diff --git a/apps/rocm/src/driver_plan.rs b/apps/rocm/src/driver_plan.rs index 1ef2804685..7c3b2bf6b8 100644 --- a/apps/rocm/src/driver_plan.rs +++ b/apps/rocm/src/driver_plan.rs @@ -1156,7 +1156,7 @@ pub(crate) mod tests { #[cfg(unix)] use std::process::Command as ProcessCommand; - use super::rocdxg::scoped_rocdxg_env; + use super::rocdxg::{ROCDXG_STAGING_DIR, scoped_rocdxg_env}; use super::*; use crate::tests::ScopedTestEnv; @@ -3061,7 +3061,7 @@ VERSION_ID="41" // assertions below hold against a plan that installs nothing at all. // Only a real install plan carries this command. assert!( - rendered.contains("apt-get install -y '/tmp/"), + rendered.contains(&format!("apt-get install -y '{ROCDXG_STAGING_DIR}/")), "expected a real install plan, got:\n{rendered}" ); assert!(rendered.contains("post_install_checks:")); diff --git a/apps/rocm/src/driver_plan/rocdxg.rs b/apps/rocm/src/driver_plan/rocdxg.rs index 26c828b994..5d0799c66a 100644 --- a/apps/rocm/src/driver_plan/rocdxg.rs +++ b/apps/rocm/src/driver_plan/rocdxg.rs @@ -6,7 +6,7 @@ //! package that bridges the Windows host driver into the distro, and refusing to //! build a plan when the package cannot be authenticated. //! -//! Relocated from `driver_install.rs` with no behavior change. +//! Relocated from `driver_install.rs`; the move itself changed no behavior. //! `ROCDXG_PINNED_DIGESTS` is the trust anchor: the digests an unattended root //! install is checked against. It moved byte for byte. //! @@ -115,6 +115,23 @@ const ROCDXG_PINNED_DIGESTS: &[(&str, &str)] = &[ ), ]; +/// `concat!` takes only literals, so the parent path is a macro to let +/// `ROCDXG_STAGING_DIR` be derived from it rather than repeat it. +macro_rules! rocdxg_staging_parent { + () => { + "/var/cache/rocm-cli" + }; +} + +/// Parent of `ROCDXG_STAGING_DIR`, reserved for root-owned driver staging: the +/// plan resets its owner and mode on every run, so another user cannot rename +/// the staging directory out from under it. +const ROCDXG_STAGING_PARENT: &str = rocdxg_staging_parent!(); +/// Root-only directory the ROCDXG package is placed in before it is verified +/// and installed. `/var/cache` is writable only by root, so no other user can +/// create, replace or redirect anything under it; see `wsl_rocdxg_driver_plan`. +pub(super) const ROCDXG_STAGING_DIR: &str = concat!(rocdxg_staging_parent!(), "/rocdxg"); + /// Whether a resolved ROCDXG version is safe to place in the plan's commands. /// /// The driver plan is a list of shell lines run through `sh -c`, and the @@ -143,8 +160,8 @@ fn sha256_digest_is_well_formed(digest: &str) -> bool { /// installed as root. #[derive(Debug, Clone, Eq, PartialEq)] enum RocdxgVerification { - /// Check the download against this digest and abort the install on a - /// mismatch. + /// Check the root-placed copy against this digest and abort the install + /// on a mismatch. Digest(String), /// Install without checking, because the caller explicitly asked for it. OptedOut, @@ -256,7 +273,17 @@ pub(crate) fn wsl_rocdxg_driver_plan(escalation: PrivilegeEscalation) -> DriverI let sudo = escalation.prefix(); let deb = format!("rocdxg-roct_{version}_amd64.deb"); let url = format!("https://github.com/ROCm/librocdxg/releases/download/v{version}/{deb}"); - let deb_path = format!("/tmp/{deb}"); + // Where root installs the package from. Never a fixed name in a shared, + // world-writable directory such as `/tmp`: another local user could + // pre-create that file, let the genuine download land in it so it passes + // the digest check, then replace its contents before `apt-get install` + // reads it — and the maintainer scripts run as root. A directory only root + // can write closes that: once the file is in place, nothing but root can + // change it between the check and the install, so the bytes checked are + // the bytes installed. A fixed name is fine there for the same reason, and + // it lets each step below name the file without passing state between + // separate shell invocations. + let deb_path = format!("{ROCDXG_STAGING_DIR}/{deb}"); // `version` is validated above and the digest is hex, so neither can carry // shell metacharacters; the quotes keep that guarantee local to the command // rather than resting on a check several functions away. @@ -325,19 +352,50 @@ pub(crate) fn wsl_rocdxg_driver_plan(escalation: PrivilegeEscalation) -> DriverI DriverCommandPhase::Prepare, &format!("{sudo}apt-get install -y ca-certificates curl"), ), + // Re-asserted on every run rather than trusted from a previous + // one: `install -d` also resets the owner and mode of a directory + // that already exists. So `/var/cache/rocm-cli` is reserved for + // root-owned driver staging: whatever owner and mode it or its + // `rocdxg` subdirectory had, both are root:root 0755 again the + // next time this plan runs (their contents are left as they are). + driver_command( + DriverCommandPhase::Execute, + &format!( + "{sudo}install -d -m 0755 -o root -g root '{ROCDXG_STAGING_PARENT}' '{ROCDXG_STAGING_DIR}'" + ), + ), + // The download runs without `sudo` — with the privileges of + // whoever runs the plan, so as root only when the CLI itself is + // root — into a fresh `mktemp -d` directory (unpredictable name, + // mode 0700, removed on exit), never a shared location. Only a + // root `install` copies it into the root-only directory. + // One shell line because each plan step is its own `sh -c`, and the + // temporary directory's name exists only in this one. driver_command( DriverCommandPhase::Execute, - &format!("curl -L --fail --show-error --output '{deb_path}' '{url}'"), + &format!( + "d=\"$(mktemp -d)\" && trap 'rm -rf \"$d\"' EXIT && curl -L --fail --show-error --output \"$d/{deb}\" '{url}' && {sudo}install -m 0644 \"$d/{deb}\" '{deb_path}'" + ), ), // Authenticating the download is the whole trust anchor for this // plan: everything after it runs the package's maintainer scripts // as root. `sha256sum -c -` exits non-zero on a mismatch, which - // aborts the plan before the install step. + // aborts the plan before the install step. It checks the root-owned + // copy, not the download, so what passed is what root installs. verify_download, driver_command( DriverCommandPhase::Execute, &format!("{sudo}apt-get install -y '{deb_path}'"), ), + // Reached only after a successful install: the executor stops at + // the first failing step, so a package rejected by the digest + // check or by `apt-get` stays in the root-only directory, out of + // reach of other users, until the next run of the same version + // replaces it (the file name carries the version). + driver_command( + DriverCommandPhase::Execute, + &format!("{sudo}rm -f '{deb_path}'"), + ), driver_command(DriverCommandPhase::Execute, &format!("{sudo}ldconfig")), driver_command( DriverCommandPhase::Verify, @@ -386,8 +444,11 @@ mod tests { use crate::tests::test_paths; #[cfg(unix)] use std::fs; - #[cfg(unix)] use std::path::Path; + #[cfg(unix)] + use std::path::PathBuf; + #[cfg(unix)] + use std::process::Stdio; #[test] fn wsl_rocdxg_plan_installs_the_library_and_publishes_it() { @@ -402,7 +463,9 @@ mod tests { // it. Any one of these missing leaves `wsl_rocdxg_ready` unreachable. assert!(commands.contains("https://github.com/ROCm/librocdxg/releases/download/")); assert!(commands.contains("rocdxg-roct_")); - assert!(commands.contains("sudo apt-get install -y '/tmp/rocdxg-roct_")); + assert!(commands.contains(&format!( + "sudo apt-get install -y '{ROCDXG_STAGING_DIR}/rocdxg-roct_" + ))); assert!(commands.contains("sudo ldconfig")); // And in that order. `ldconfig` refreshes the cache from what is on @@ -416,7 +479,7 @@ mod tests { let steps = plan.execution_commands(); let install = steps .iter() - .position(|c| c.contains("apt-get install -y '/tmp/")) + .position(|c| c.contains(&format!("apt-get install -y '{ROCDXG_STAGING_DIR}/"))) .expect("plan installs the package"); let publish = steps .iter() @@ -512,11 +575,156 @@ mod tests { .expect("plan verifies the download"); let install = commands .iter() - .position(|c| c.contains("apt-get install -y '/tmp/")) + .position(|c| c.contains(&format!("apt-get install -y '{ROCDXG_STAGING_DIR}/"))) .expect("plan installs the package"); assert!(check < install, "digest must be checked before install"); } + /// System directories whose standard permissions let only root create + /// entries in them. Spelled out here rather than derived from + /// `ROCDXG_STAGING_PARENT`, so moving the staging directory somewhere + /// world-writable fails the tests instead of moving the expectation too. + const ROOT_ONLY_STAGING_ROOTS: &[&str] = &["/var/cache/"]; + + /// The single-quoted path `apt-get install -y` is handed in a ROCDXG plan. + fn rocdxg_installed_path(commands: &[String]) -> String { + let install = commands + .iter() + .find(|c| c.contains("apt-get install -y '") && c.contains("rocdxg-roct_")) + .expect("plan installs the package"); + install + .split('\'') + .nth(1) + .expect("installed path is single-quoted") + .to_owned() + } + + #[test] + fn wsl_rocdxg_plan_never_installs_from_a_path_another_user_can_write() { + // `apt-get install` runs the package's maintainer scripts as root, and + // the digest check is the only thing authenticating those bytes. If the + // file lives somewhere another local user can create or replace it — + // a fixed name in the world-writable `/tmp` — they can pre-create it, + // let the genuine download land in it and pass the check, then swap + // the contents before root installs it. So the file root installs must + // sit in a directory only root can write, and be the very file that + // was checked. + let _env = scoped_rocdxg_env(); + for escalation in [PrivilegeEscalation::Sudo, PrivilegeEscalation::AlreadyRoot] { + let plan = wsl_rocdxg_driver_plan(escalation); + let commands = plan.execution_commands(); + let joined = commands.join("\n"); + assert!( + !joined.contains("/tmp/") && !joined.contains("/tmp'"), + "{escalation:?}: the plan stages the package in shared /tmp:\n{joined}" + ); + + let installed = rocdxg_installed_path(&commands); + // Ruling out `/tmp` is not enough: `/dev/shm` and `/var/tmp` are + // world-writable too, and another user can pre-create a symlink + // there. The path must sit under a system directory only root can + // write, with no `..` to climb back out of it. + assert!( + ROOT_ONLY_STAGING_ROOTS + .iter() + .any(|root| installed.starts_with(root)) + && !installed.contains("/../"), + "{escalation:?}: {installed} is not under a root-only system directory \ + ({ROOT_ONLY_STAGING_ROOTS:?})" + ); + let staging_dir = Path::new(&installed) + .parent() + .expect("installed path has a directory") + .display() + .to_string(); + let staging_parent = Path::new(&staging_dir) + .parent() + .expect("staging dir has a parent") + .display() + .to_string(); + let sudo = escalation.prefix(); + + // The staging directory and its parent are both (re)asserted + // root-only before anything is placed in them, by a privileged + // command. The parent matters as much as the directory: whoever + // can write the parent can rename the staging directory away and + // put their own in its place. + // + // The `-o root -g root` owner reset is pinned only by this string: + // the test does not run as root, so the stand-in `install` in + // `wsl_rocdxg_generated_steps_install_exactly_the_verified_file` + // drops `-o`/`-g` and that test proves the mode reset alone. + let make_dir = commands + .iter() + .position(|c| { + *c == format!( + "{sudo}install -d -m 0755 -o root -g root '{staging_parent}' '{staging_dir}'" + ) + }) + .unwrap_or_else(|| panic!("{escalation:?}: no root-only staging dir:\n{joined}")); + // The download itself is unprivileged, into a private `mktemp -d` + // directory, and only a root `install` places it at the final path. + let stage = commands + .iter() + .position(|c| c.contains("curl ")) + .expect("plan downloads the package"); + assert!( + commands[stage].contains("mktemp -d") + && !commands[stage].contains(&format!("--output '{installed}'")) + && commands[stage].contains(&format!("{sudo}install -m 0644 ")) + && commands[stage].ends_with(&format!("'{installed}'")), + "{escalation:?}: download is not staged through a private dir:\n{}", + commands[stage] + ); + // The digest is checked on the copy root will install, after it is + // in place, and before the install. + let check = commands + .iter() + .position(|c| c.contains("sha256sum -c -")) + .expect("plan verifies the download"); + assert!( + commands[check].contains(&format!("'{installed}'")), + "{escalation:?}: the checked file is not the installed file:\n{joined}" + ); + let install = commands + .iter() + .position(|c| c.contains("apt-get install -y '")) + .expect("plan installs the package"); + assert!( + make_dir < stage && stage < check && check < install, + "{escalation:?}: steps out of order:\n{joined}" + ); + // The installed file is root-owned, so removing it needs the same + // escalation as the install; without it the `rm` fails as the + // invoking user and the plan stops before `ldconfig`. + let remove = commands + .iter() + .position(|c| *c == format!("{sudo}rm -f '{installed}'")) + .unwrap_or_else(|| { + panic!("{escalation:?}: no `{sudo}rm -f '{installed}'` step:\n{joined}") + }); + let ldconfig = commands + .iter() + .position(|c| *c == format!("{sudo}ldconfig")) + .expect("plan runs ldconfig"); + assert!( + install < remove && remove < ldconfig, + "{escalation:?}: the staged package is not removed between install and ldconfig:\n{joined}" + ); + } + + // And the plan `--dry-run` shows the user is the same one. + let plan = wsl_rocdxg_driver_plan(PrivilegeEscalation::Sudo); + let rendered = render_driver_install_plan(&plan, false, true); + assert!(rendered.contains("dry_run: true"), "{rendered}"); + assert!(rendered.contains("sha256sum -c -"), "{rendered}"); + assert!( + rendered.contains(&format!("apt-get install -y '{ROCDXG_STAGING_DIR}/")), + "{rendered}" + ); + assert!(!rendered.contains("/tmp/"), "{rendered}"); + } + #[test] fn wsl_rocdxg_refuses_a_version_whose_digest_is_unknown() { // An unpinned version is the case where silently falling back to "no @@ -668,7 +876,10 @@ mod tests { let plan = wsl_rocdxg_driver_plan(PrivilegeEscalation::AlreadyRoot); let joined = plan.execution_commands().join("\n"); assert!(!joined.contains("sudo "), "{joined}"); - assert!(joined.contains("apt-get install -y '/tmp/"), "{joined}"); + assert!( + joined.contains(&format!("apt-get install -y '{ROCDXG_STAGING_DIR}/")), + "{joined}" + ); // And it must not demand a binary it no longer uses. assert!(!joined.contains("command -v sudo"), "{joined}"); assert!( @@ -681,6 +892,23 @@ mod tests { ); } + /// The SHA-256 of `path` as `sha256sum` prints it, so the ROCDXG tests + /// compare against the same tool the plan runs. + #[cfg(unix)] + fn sha256sum_of(path: &Path) -> String { + let out = std::process::Command::new("sha256sum") + .arg(path) + .output() + .expect("sha256sum runs"); + assert!(out.status.success()); + String::from_utf8(out.stdout) + .expect("utf8") + .split_whitespace() + .next() + .expect("digest field") + .to_owned() + } + /// Runs the digest step the plan actually generates, rather than asserting /// that it contains some substrings. /// @@ -711,7 +939,7 @@ mod tests { (*pinned_version == version.as_str()).then_some(*digest) }) .expect("the default version is pinned"); - let deb_path = format!("/tmp/rocdxg-roct_{version}_amd64.deb"); + let deb_path = format!("{ROCDXG_STAGING_DIR}/rocdxg-roct_{version}_amd64.deb"); let generated = plan .execution_commands() .into_iter() @@ -731,20 +959,7 @@ mod tests { let payload = root.join(format!("rocdxg-roct_{version}_amd64.deb")); fs::write(&payload, b"pretend this is a .deb\n").expect("write payload"); - let digest_of = |path: &Path| -> String { - let out = Command::new("sha256sum") - .arg(path) - .output() - .expect("sha256sum runs"); - assert!(out.status.success()); - String::from_utf8(out.stdout) - .expect("utf8") - .split_whitespace() - .next() - .expect("digest field") - .to_owned() - }; - let good = digest_of(&payload); + let good = sha256sum_of(&payload); // The command under test is the generated one; the only edits are the // digest being checked and the path being checked, so a regression in @@ -774,6 +989,361 @@ mod tests { let _ = fs::remove_dir_all(&root); } + /// Runs the plan's generated Execute steps, each as its own `sh -c` exactly + /// as `run_driver_shell_command` does, against stand-ins for `sudo`, + /// `curl`, `install`, `apt-get` and `ldconfig`. + /// + /// The private-staging step depends on shell state (the `mktemp -d` name) + /// never having to cross from one step to the next, which only executing + /// the steps separately can show. The `curl` stand-in refuses to run under + /// `sudo` and refuses any `--output` that is not in a 0700 directory + /// directly under `$TMPDIR`, and records that directory so the test can + /// check it is gone afterwards — so a plan that downloaded as root, or + /// straight into the staging directory, fails here. Only the root-only + /// staging path and the digest are redirected; every other byte of each + /// command is production's. + #[cfg(unix)] + #[test] + fn wsl_rocdxg_generated_steps_install_exactly_the_verified_file() { + use std::os::unix::fs::PermissionsExt; + use std::process::Command; + + let _env = scoped_rocdxg_env(); + let plan = wsl_rocdxg_driver_plan(PrivilegeEscalation::Sudo); + let pinned = ROCDXG_PINNED_DIGESTS + .iter() + .find_map(|(version, digest)| (*version == plan.repo_version_expr).then_some(*digest)) + .expect("the default version is pinned"); + + let (root, _paths) = test_paths("wsl-rocdxg-staging"); + let bin = root.join("bin"); + let tmp = root.join("tmp"); + let staging_parent = root.join("var-cache-rocm-cli"); + let log = root.join("apt.log"); + let download_dirs = root.join("download-dirs.log"); + // While this file exists the `apt-get` stand-in fails the install. + let apt_fails = root.join("apt-fails"); + let installed_copy = root.join("installed.deb"); + let served = root.join("served.deb"); + for dir in [&bin, &tmp] { + fs::create_dir_all(dir).expect("test dir"); + } + let shim = |name: &str, body: &str| { + let path = bin.join(name); + fs::write(&path, format!("#!/bin/sh\n{body}\n")).expect("write shim"); + fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).expect("chmod shim"); + }; + // Not root here, so `sudo` just runs the command — marking it, so the + // `curl` stand-in can tell it was elevated — and `install` drops the + // ownership flags it could not honour; everything else is real. + shim("sudo", "ROCDXG_TEST_UNDER_SUDO=1 exec \"$@\""); + shim( + "install", + "args=''\nwhile [ $# -gt 0 ]; do\n case \"$1\" in\n -o|-g) shift 2 ;;\n *) args=\"$args '$1'\"; shift ;;\n esac\ndone\neval \"exec /usr/bin/install $args\"", + ); + shim( + "curl", + &[ + r#"[ -z "$ROCDXG_TEST_UNDER_SUDO" ] || { echo 'curl ran under sudo' >&2; exit 1; }"#, + "while [ $# -gt 0 ]; do", + r#" if [ "$1" = --output ]; then"#, + r#" d="$(dirname "$2")""#, + r#" [ "$(dirname "$d")" = "$TMPDIR" ] || { echo "download not in a private directory: $2" >&2; exit 1; }"#, + r#" [ "$(stat -c %a "$d")" = 700 ] || { echo "download directory is not 0700: $d" >&2; exit 1; }"#, + &format!(r#" echo "$d" >> '{}'"#, download_dirs.display()), + &format!(r#" cp '{}' "$2"; exit $?"#, served.display()), + " fi", + " shift", + "done", + "exit 1", + ] + .join("\n"), + ); + shim( + "apt-get", + &format!( + "for last; do :; done\necho \"$last\" >> '{}'\n[ ! -e '{}' ] || exit 100\ncp \"$last\" '{}'", + log.display(), + apt_fails.display(), + installed_copy.display() + ), + ); + shim("ldconfig", "exit 0"); + + let run_plan = |payload: &[u8], digest: &str| -> bool { + fs::write(&served, payload).expect("write payload"); + let _ = fs::remove_file(&log); + let path = format!( + "{}:{}", + bin.display(), + std::env::var("PATH").unwrap_or_default() + ); + plan.commands + .iter() + .filter(|c| c.phase == DriverCommandPhase::Execute) + .all(|c| { + let command = c + .command + .replace(ROCDXG_STAGING_PARENT, &staging_parent.display().to_string()) + .replace(pinned, digest); + Command::new("sh") + .arg("-c") + .arg(&command) + .env("PATH", &path) + .env("TMPDIR", &tmp) + .stdin(Stdio::null()) + .output() + .expect("sh runs") + .status + .success() + }) + }; + // The same substitution `run_plan` makes in each command. + let staging_dir = PathBuf::from( + ROCDXG_STAGING_DIR + .replace(ROCDXG_STAGING_PARENT, &staging_parent.display().to_string()), + ); + // Both staging directories already exist with a mode anyone can write, + // as a stale or tampered leftover would, so the 0755 asserted below + // has to come from the plan resetting each of them rather than from + // `install -d` creating them under the default umask. + for dir in [&staging_parent, &staging_dir] { + fs::create_dir_all(dir).expect("pre-existing staging dir"); + fs::set_permissions(dir, fs::Permissions::from_mode(0o777)) + .expect("loosen pre-existing staging dir"); + } + let genuine = b"genuine package\n"; + let genuine_digest = { + let file = root.join("digest-input"); + fs::write(&file, genuine).expect("write digest input"); + sha256sum_of(&file) + }; + assert!( + run_plan(genuine, &genuine_digest), + "a genuine package must install" + ); + let staged = staging_dir.join(format!("rocdxg-roct_{}_amd64.deb", plan.repo_version_expr)); + assert_eq!( + fs::read_to_string(&log).expect("apt-get ran").trim(), + staged.display().to_string(), + "apt-get must install the staged copy" + ); + assert_eq!(fs::read(&installed_copy).expect("installed"), genuine); + assert!( + !staged.exists(), + "the staged package is removed after install" + ); + // Ownership needs root and is pinned as a string elsewhere; the mode + // is what `install -d -m 0755` resets here too, from the 0777 both + // directories started with. + for dir in [&staging_parent, &staging_dir] { + assert_eq!( + fs::metadata(dir).expect("staging dir").permissions().mode() & 0o777, + 0o755, + "{} must be writable only by its owner", + dir.display() + ); + } + let recorded = fs::read_to_string(&download_dirs).expect("curl ran"); + let recorded: Vec<&str> = recorded.lines().collect(); + assert_eq!( + recorded.len(), + 1, + "exactly one download, into a private directory: {recorded:?}" + ); + assert!( + !Path::new(recorded[0]).exists(), + "the private download directory is removed" + ); + assert_eq!(fs::read_dir(&tmp).expect("tmp").count(), 0); + + // A download that does not match stops the plan before apt-get. + assert!(!run_plan(b"tampered\n", &genuine_digest)); + assert!( + !log.exists(), + "apt-get must not run after a digest mismatch" + ); + assert_eq!(fs::read_dir(&tmp).expect("tmp").count(), 0); + // The plan stops at the failing step, so the rejected package stays + // in the root-only directory; the next run replaces it. + assert_eq!( + fs::read(&staged).expect("a package the check rejected stays staged"), + b"tampered\n" + ); + + // The same holds when `apt-get` itself fails the install. + fs::write(&apt_fails, b"").expect("apt-get failure marker"); + assert!( + !run_plan(genuine, &genuine_digest), + "an apt-get failure must fail the plan" + ); + assert_eq!( + fs::read_to_string(&log).expect("apt-get ran").trim(), + staged.display().to_string() + ); + assert_eq!( + fs::read(&staged).expect("a package apt-get rejected stays staged"), + genuine + ); + assert_eq!(fs::read_dir(&tmp).expect("tmp").count(), 0); + + // And the next run replaces what was left and cleans up after itself. + fs::remove_file(&apt_fails).expect("clear apt-get failure marker"); + fs::write(&staged, b"left over\n").expect("leftover staged package"); + let _ = fs::remove_file(&installed_copy); + assert!( + run_plan(genuine, &genuine_digest), + "a run after a failed one must install" + ); + assert_eq!(fs::read(&installed_copy).expect("installed"), genuine); + assert!(!staged.exists()); + + let _ = fs::remove_dir_all(&root); + } + + /// The manual steps in `docs/wsl.md`, from the `ROCDXG_DEB=` line to the + /// end of that fenced block, with the version, digest and staging root + /// filled in for the test. + #[cfg(unix)] + fn wsl_doc_manual_rocdxg_block(digest: &str, staging_root: &Path) -> String { + // Read at run time rather than embedded with `include_str!`: the + // embedded-data ASCII contract would then cover this doc, whose + // licence header is not ASCII. + let doc = + fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/wsl.md")) + .expect("read docs/wsl.md"); + let start = doc + .find("ROCDXG_DEB=\"rocdxg-roct_") + .expect("docs/wsl.md has the manual ROCDXG steps"); + let end = start + + doc[start..] + .find("\n```") + .expect("the manual ROCDXG block is fenced"); + format!( + "ROCDXG_VERSION=1.0\nROCDXG_SHA256={digest}\n{}\n", + doc[start..end].replace(ROCDXG_STAGING_PARENT, &staging_root.display().to_string()) + ) + } + + /// The manual steps are pasted into a shell, where a failed line does not + /// stop the next. Every step up to `ldconfig` is therefore one `&&` chain: + /// a download that fails must stop the block before the digest check, or a + /// copy an earlier run left staged passes that check and is reinstalled as + /// though this run had downloaded it. The private download directory is + /// removed either way, and the block's exit status is the chain's, so a + /// failed install is not reported as success. + #[cfg(unix)] + #[test] + fn wsl_doc_manual_steps_stop_before_the_check_when_the_download_fails() { + use std::os::unix::fs::PermissionsExt; + use std::process::Command; + + let (root, _paths) = test_paths("wsl-doc-rocdxg-manual"); + let bin = root.join("bin"); + let tmp = root.join("tmp"); + let stage_root = root.join("var-cache-rocm-cli"); + let apt_log = root.join("apt.log"); + let served = root.join("served.deb"); + for dir in [&bin, &tmp] { + fs::create_dir_all(dir).expect("test dir"); + } + let shim = |name: &str, body: &str| { + let path = bin.join(name); + fs::write(&path, format!("#!/bin/sh\n{body}\n")).expect("write shim"); + fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).expect("chmod shim"); + }; + // Not root here: `sudo` just runs the command, and `install` drops the + // ownership flags it could not honour. + shim("sudo", "exec \"$@\""); + shim( + "install", + "args=''\nwhile [ $# -gt 0 ]; do\n case \"$1\" in\n -o|-g) shift 2 ;;\n *) args=\"$args '$1'\"; shift ;;\n esac\ndone\neval \"exec /usr/bin/install $args\"", + ); + // Fails while `$CURL_FAILS` is set, else serves `served.deb`. + shim( + "curl", + &format!( + "[ -z \"$CURL_FAILS\" ] || exit 22\nwhile [ $# -gt 0 ]; do\n [ \"$1\" = -o ] && cp '{}' \"$2\"\n shift\ndone", + served.display() + ), + ); + // Records each install, and fails it while `$APT_FAILS` is set. + shim( + "apt", + &format!( + "echo \"$*\" >> '{}'\n[ -z \"$APT_FAILS\" ] || exit 100", + apt_log.display() + ), + ); + shim("ldconfig", "exit 0"); + + fs::write(&served, b"genuine package\n").expect("served package"); + let block = wsl_doc_manual_rocdxg_block(&sha256sum_of(&served), &stage_root); + let staged = stage_root.join("rocdxg").join("rocdxg-roct_1.0_amd64.deb"); + let path = format!( + "{}:{}", + bin.display(), + std::env::var("PATH").unwrap_or_default() + ); + let run_block = |curl_fails: bool, apt_fails: bool| -> bool { + let mut command = Command::new("sh"); + command + .arg("-c") + .arg(&block) + .env("PATH", &path) + .env("TMPDIR", &tmp) + .stdin(Stdio::null()); + if curl_fails { + command.env("CURL_FAILS", "1"); + } + if apt_fails { + command.env("APT_FAILS", "1"); + } + command.output().expect("sh runs").status.success() + }; + + // A copy that passed the check on an earlier run is still staged, and + // this run's download fails: nothing may be installed. + fs::create_dir_all(staged.parent().expect("staging dir")).expect("staging dir"); + fs::copy(&served, &staged).expect("leftover staged copy"); + assert!( + !run_block(true, false), + "a failed download must fail the block, not report success" + ); + assert!( + !apt_log.exists(), + "a failed download must stop the block before the check and the install:\n{block}" + ); + assert_eq!( + fs::read_dir(&tmp).expect("tmp").count(), + 0, + "the private download directory is removed after a failed download" + ); + + // A failure at the end of the chain fails the block too, and still + // removes the private download directory. + assert!( + !run_block(false, true), + "a failed install must fail the block, not report success" + ); + assert_eq!(fs::read_dir(&tmp).expect("tmp").count(), 0); + fs::remove_file(&apt_log).expect("clear apt log"); + + // A good download installs the staged copy once and cleans up. + assert!(run_block(false, false), "a good download must succeed"); + assert_eq!( + fs::read_to_string(&apt_log).expect("apt ran").trim(), + format!("install -y {}", staged.display()) + ); + assert!( + !staged.exists(), + "the staged package is removed after install" + ); + assert_eq!(fs::read_dir(&tmp).expect("tmp").count(), 0); + + let _ = fs::remove_dir_all(&root); + } + #[test] fn wsl_rocdxg_version_is_overridable_and_reaches_every_reference() { // One resolved value drives the archive name, the release tag and the diff --git a/crates/rocm-core/src/diagnose/wsl.rs b/crates/rocm-core/src/diagnose/wsl.rs index 2edd502a6b..88eec4d26a 100644 --- a/crates/rocm-core/src/diagnose/wsl.rs +++ b/crates/rocm-core/src/diagnose/wsl.rs @@ -176,7 +176,7 @@ pub(super) fn check_wsl_3_rocdxg_missing(e: &Examination, symptom: &str) -> Diag fix_id: "fix-wsl-3-rocdxg-missing".to_owned(), verify: "ldconfig -p | grep librocdxg".to_owned(), notes: vec![ - "This downloads and installs a .deb with sudo, so `rocm fix` prints it rather than running it. `rocm install driver` shows the full plan, and checks the download against a digest pinned for that ROCDXG release.".to_owned(), + "This downloads and installs a .deb with sudo, so `rocm fix` prints it rather than running it. `rocm install driver` shows the full plan, and checks the package against a digest pinned for that ROCDXG release after root has placed it where only root can write, so the file checked is the file installed.".to_owned(), ], ..Fix::default() }; @@ -531,10 +531,21 @@ mod tests { // Verification is no longer something the user has to remember to turn // on: `rocm install driver` pins a digest per release. The note has to // say so, because a print-only recipe is all the user sees here. + // + // This pins the wording only. That the plan really checks the copy + // root installs, from a directory only root can write, is proved by + // `wsl_rocdxg_generated_steps_install_exactly_the_verified_file` in + // `apps/rocm/src/driver_plan/rocdxg.rs`, which executes the generated + // steps. + let note = fix + .notes + .iter() + .find(|n| n.contains("digest")) + .unwrap_or_else(|| panic!("must state that the package is verified: {:?}", fix.notes)); assert!( - fix.notes.iter().any(|n| n.contains("digest")), - "must state that the download is verified: {:?}", - fix.notes + note.contains("only root can write") + && note.contains("the file checked is the file installed"), + "must state that the checked file is the root-placed copy that is installed: {note}" ); assert!( fix.commands diff --git a/crates/rocm-core/src/fix/catalog.rs b/crates/rocm-core/src/fix/catalog.rs index 5c4d587a26..92a263c35d 100644 --- a/crates/rocm-core/src/fix/catalog.rs +++ b/crates/rocm-core/src/fix/catalog.rs @@ -714,7 +714,7 @@ pub(super) const RECIPES: &[FixRecipe] = &[ verify_linux: None, notes: &[ "Print-only on purpose: this downloads a .deb from a release page and installs it with sudo. `rocm install driver` prints the plan first so the URL and the package are reviewable before anything runs.", - "The download is checked against a digest pinned for that ROCDXG release. To install a release rocm-cli has no digest for, set ROCM_CLI_ROCDXG_SHA256 to the one published with it.", + "The package is checked against a digest pinned for that ROCDXG release, on the copy root installs from a directory only root can write. To install a release rocm-cli has no digest for, set ROCM_CLI_ROCDXG_SHA256 to the one published with it.", ], doc_url: None, applies_on: PRINT_ON_WSL, @@ -1449,6 +1449,22 @@ mod tests { .collect() } + #[test] + fn rocdxg_missing_note_says_the_checked_copy_is_the_installed_one() { + // Pins the wording only. That the plan really checks the copy root + // installs, from a directory only root can write, is proved by + // `wsl_rocdxg_generated_steps_install_exactly_the_verified_file` in + // `apps/rocm/src/driver_plan/rocdxg.rs`, which executes the generated + // steps. + let recipe = find_recipe("fix-wsl-3-rocdxg-missing").expect("recipe exists"); + assert!( + recipe.notes.iter().any(|n| n.contains("digest") + && n.contains("on the copy root installs from a directory only root can write")), + "{:?}", + recipe.notes + ); + } + // Ubuntu 26.04 gets the DKMS driver plan (`dkms_driver_plan_is_supported`), // so no recipe may still describe it as in-tree or unplanned. #[test] diff --git a/docs/architecture.md b/docs/architecture.md index b929c31659..540733f72b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -66,7 +66,7 @@ The `rocm` binary: the clap command tree, a handler module for most commands, an | [`diagnose_model.rs`](../apps/rocm/src/diagnose_model.rs) | The binary's side of `rocm diagnose --model`'s GGUF context estimate: the `--kv-cache-type` and model flags, the `--report` note, and the device-visibility-mask caveat. | domain | | [`driver_install.rs`](../apps/rocm/src/driver_install.rs) | `rocm install driver` (`install_driver`, `reconcile_driver_install`): runs an approved plan's commands and persists the driver install state. It re-exports `host_install_driver_only_reports` from [`driver_plan.rs`](../apps/rocm/src/driver_plan.rs) for its callers, [`tool_policy.rs`](../apps/rocm/src/tool_policy.rs) and [`freeform_planner.rs`](../apps/rocm/src/freeform_planner.rs). | relocation | | [`driver_plan.rs`](../apps/rocm/src/driver_plan.rs) | The `rocm install driver` plan: its model, its printed text, and the per-distro builders (apt, dnf, zypper) from the host's examination and os-release. | domain | -| [`driver_plan/rocdxg.rs`](../apps/rocm/src/driver_plan/rocdxg.rs) | The WSL2 rocDXG driver plan, which installs the digest-pinned `rocdxg-roct` package or refuses when the download cannot be authenticated. | domain | +| [`driver_plan/rocdxg.rs`](../apps/rocm/src/driver_plan/rocdxg.rs) | The WSL2 rocDXG driver plan, which stages the digest-pinned `rocdxg-roct` package in a root-only directory, checks and installs that same file, or refuses when the download cannot be authenticated. | domain | | [`endpoint_keys.rs`](../apps/rocm/src/endpoint_keys.rs) | Per-service inference-endpoint API keys, stored in owner-only files under the services directory, keyed by service id. | relocation | | [`engine_install_env.rs`](../apps/rocm/src/engine_install_env.rs) | Which runtime an engine installs into and where its environment lives (`engine_manages_own_runtime`, `env_root_for_engine_install`), shared by the engine and SDK install paths. | relocation | | [`engine_ipc.rs`](../apps/rocm/src/engine_ipc.rs) | Locating an engine's plugin binary, the engine request entry points (answering from the in-process built-in handler, or running the resolved engine binary with `stdio`), and the in-process built-in engine path. `engine_stdio_child_request` hands the child to the stdio client `rocm` shares with `rocmd`, [`stdio_client.rs`](../crates/rocm-engine-protocol/src/stdio_client.rs), and chooses what `rocm` asks of it: the app paths and engine environments root for the child, progress for an install, and the child's stderr forwarded to the terminal. | relocation | diff --git a/docs/release-trust.md b/docs/release-trust.md index 8f9f4678ad..23e86e299f 100644 --- a/docs/release-trust.md +++ b/docs/release-trust.md @@ -179,8 +179,12 @@ All of those checks happen before activation. Run the current host's set with The ROCDXG `.deb` is fetched over plain HTTPS from a release page and handed to `apt-get install`, which runs its maintainer scripts as root. rocm-cli therefore carries a SHA-256 digest for each published ROCDXG release and checks the -download against it before the install step; on a mismatch the plan stops before -anything runs as root. Verification is on by default and needs nothing set. +package against it before the install step; on a mismatch the plan stops before +the package's maintainer scripts run. The check is made on a copy root has +placed in `/var/cache/rocm-cli/rocdxg/`, which only root can write, and that +same file is what `apt-get install` reads, so no other local user can change +the package between the check and the install. Verification is on by default +and needs nothing set. `ROCM_CLI_ROCDXG_SHA256` supplies a digest for a release rocm-cli has none for, and overrides the pinned digest for one it does: diff --git a/docs/testing.md b/docs/testing.md index f2e1139620..cd6af86bf6 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -3858,6 +3858,8 @@ Release trust checks: cargo test -p rocm --bin rocm metadata_signature_verification_accepts_generated_key_and_rejects_tamper cargo test -p rocm-core model_recipe_index_signature_accepts_generated_key_and_rejects_tamper cargo test -p rocm --bin rocm wsl_rocdxg_generated_digest_step_accepts_only_the_matching_file +cargo test -p rocm --bin rocm wsl_rocdxg_generated_steps_install_exactly_the_verified_file +cargo test -p rocm --bin rocm wsl_doc_manual_steps_stop_before_the_check_when_the_download_fails python scripts/release_readiness.py --self-test bash scripts/setup-wsl-portable-build-deps.sh --self-test bash scripts/reclaim-gpu.sh --self-test @@ -3892,6 +3894,30 @@ that is then installed as root, and this replaces the self-test that shipped with the removed `scripts/wsl_setup_rocdxg.sh`. It needs a POSIX shell and `sha256sum`, so it is Unix-only. +`wsl_rocdxg_generated_steps_install_exactly_the_verified_file` runs every +Execute step of that plan, each in its own `sh -c` as the CLI does, against +stand-ins for `sudo`, `curl`, `install`, `apt-get` and `ldconfig`. It proves the +file `apt-get` installs is the root-staged copy the digest was checked against, +that a tampered download stops the plan before `apt-get`, and that the private +download directory and the staged copy are both removed after a successful +install. When the check or `apt-get` fails, it checks the rejected package is +left in the root-only directory and that the next run of the same version +replaces it. It also checks the staging directories end up mode 0755. The +`curl` stand-in fails if it is run under `sudo` or asked to write anywhere but +a 0700 directory directly under `$TMPDIR`, so a plan that downloads as root or +straight into the staging directory fails the test. It is Unix-only too. +`wsl_rocdxg_plan_never_installs_from_a_path_another_user_can_write` checks the +same layout on the plan text for both the `sudo` and the already-root plan, and +scenario `@id:driver-install-wsl-dry-run-plan` checks it on the `--dry-run` +output on the `@requires-wsl` lane. +`wsl_doc_manual_steps_stop_before_the_check_when_the_download_fails` runs the +manual steps from [wsl.md](wsl.md) against the same kind of stand-ins. With a +copy an earlier run left staged and a download that fails, it checks that the +block stops before the digest check, installs nothing and exits non-zero, and +that the private download directory is removed. A failed install also exits +non-zero and removes that directory, and a good download installs once and +exits zero. It is Unix-only. + The eight native Linux GPU preflights are one script, [`gpu-preflight.sh`](../.github/scripts/gpu-preflight.sh), which each lane runs with its own `GPU_PREFLIGHT_MIN_FREE_GIB` (16 on the discrete lanes, 8 on diff --git a/docs/wsl.md b/docs/wsl.md index 6cae3199d5..b5a18170a1 100644 --- a/docs/wsl.md +++ b/docs/wsl.md @@ -57,6 +57,16 @@ SHA-256 digest for each published ROCDXG release and checks the `.deb` against it; on a mismatch the plan stops before `apt install` runs the package's maintainer scripts as root. Nothing needs to be set for this. +The check covers the exact file root installs. The `.deb` is downloaded without +`sudo`, as whoever runs `rocm`, into a private `mktemp -d` directory, copied by +root into `/var/cache/rocm-cli/rocdxg/` (which only root can write), checked +there, then installed from there and removed. It is never staged under a fixed +name in a shared directory such as `/tmp`, where another local user could +replace it between the check and the install. A package that fails the check, +or that `apt` fails to install, is left in that root-only directory; the next +run for the same version replaces it, and `sudo rm -f +/var/cache/rocm-cli/rocdxg/*.deb` clears what an abandoned version left. + To install a release other than the pinned one, set `ROCM_CLI_ROCDXG_VERSION`. Because ROCm CLI has no digest for a release it predates, supply one: @@ -80,9 +90,15 @@ unverified. ### Doing it by hand The equivalent manual steps, for reference or for a host where the CLI is not -installed yet. Do not skip the `sha256sum -c` line, because `apt install` runs -the package's maintainer scripts as root. `rocm install driver` checks the -download against a digest pinned in the ROCm CLI source +installed yet. Do not skip the `sha256sum -c` check, because `apt install` +runs the package's maintainer scripts as root, and run it on the root-owned +copy rather than on a file in `/tmp` that another user could swap after it is +checked. Each command in the chain runs only if the one before it succeeded, +so a failed download stops the block before the check rather than letting it +check and reinstall a copy an earlier run left staged. The chain runs in a +subshell whose exit removes the private download directory either way, and the +block's exit status is the chain's, so a failed download, check or install +does not report success. `rocm install driver` checks the root-owned copy against a digest pinned in the ROCm CLI source (`ROCDXG_PINNED_DIGESTS` in `apps/rocm/src/driver_plan/rocdxg.rs`), which also catches a replaced release asset. A digest read from the release page at install time catches only a corrupted download. For a version listed in @@ -94,12 +110,19 @@ ROCDXG_VERSION= ROCDXG_SHA256=<64-hex-sha256> sudo apt-get update sudo apt-get install -y ca-certificates curl -curl -L -o "/tmp/rocdxg-roct_${ROCDXG_VERSION}_amd64.deb" \ - "https://github.com/ROCm/librocdxg/releases/download/v${ROCDXG_VERSION}/rocdxg-roct_${ROCDXG_VERSION}_amd64.deb" -printf '%s %s\n' "${ROCDXG_SHA256}" \ - "/tmp/rocdxg-roct_${ROCDXG_VERSION}_amd64.deb" | sha256sum -c - -sudo apt install -y "/tmp/rocdxg-roct_${ROCDXG_VERSION}_amd64.deb" -sudo ldconfig +ROCDXG_DEB="rocdxg-roct_${ROCDXG_VERSION}_amd64.deb" +ROCDXG_STAGED="/var/cache/rocm-cli/rocdxg/${ROCDXG_DEB}" +( + d="$(mktemp -d)" && trap 'rm -rf "$d"' EXIT && + sudo install -d -m 0755 -o root -g root /var/cache/rocm-cli /var/cache/rocm-cli/rocdxg && + curl -L --fail -o "$d/${ROCDXG_DEB}" \ + "https://github.com/ROCm/librocdxg/releases/download/v${ROCDXG_VERSION}/${ROCDXG_DEB}" && + sudo install -m 0644 "$d/${ROCDXG_DEB}" "${ROCDXG_STAGED}" && + printf '%s %s\n' "${ROCDXG_SHA256}" "${ROCDXG_STAGED}" | sha256sum -c - && + sudo apt install -y "${ROCDXG_STAGED}" && + sudo rm -f "${ROCDXG_STAGED}" && + sudo ldconfig +) ``` Source-build alternative. Set `win_sdk` to the Windows SDK version installed on diff --git a/skills/rocm-doctor/evals/fixtures/rocm-no-vendor-wsl-host-gpu-hidden-asks-which-gpu/replies.json b/skills/rocm-doctor/evals/fixtures/rocm-no-vendor-wsl-host-gpu-hidden-asks-which-gpu/replies.json index 4e8ee964fb..459c9d45b1 100644 --- a/skills/rocm-doctor/evals/fixtures/rocm-no-vendor-wsl-host-gpu-hidden-asks-which-gpu/replies.json +++ b/skills/rocm-doctor/evals/fixtures/rocm-no-vendor-wsl-host-gpu-hidden-asks-which-gpu/replies.json @@ -10,12 +10,12 @@ "rc": 0 }, "diagnose_json": { - "stdout": "{\n \"matched\": [\n {\n \"id\": \"fix-wsl-3-rocdxg-missing\",\n \"title\": \"ROCDXG not installed in the distro\",\n \"score\": 65,\n \"evidence\": [\n \"librocdxg.so was not found under any ROCm install or on LD_LIBRARY_PATH\",\n \"the WSL DXCore handoff is present, so only the distro-side ROCDXG is missing\"\n ],\n \"fix\": {\n \"summary\": \"Install ROCDXG inside the distro: it is the ROCm-to-DXCore shim the WSL path runs on.\",\n \"commands\": [\n \"rocm install driver\",\n \"# Then, once the plan looks right:\",\n \"# rocm install driver --yes\"\n ],\n \"needs_sudo\": true,\n \"needs_reboot\": false,\n \"needs_relogin\": false,\n \"fix_id\": \"fix-wsl-3-rocdxg-missing\",\n \"auto_applicable\": false,\n \"class\": \"print-only\",\n \"notes\": [\n \"This downloads and installs a .deb with sudo, so `rocm fix` prints it rather than running it. `rocm install driver` shows the full plan, and checks the download against a digest pinned for that ROCDXG release.\"\n ],\n \"verify\": \"ldconfig -p | grep librocdxg\"\n },\n \"symptom_matched\": false\n }\n ],\n \"has_match\": true,\n \"min_score_for_match\": 50,\n \"high_confidence_threshold\": 75,\n \"route_when_no_match\": {\n \"target\": \"rocm-core\",\n \"url\": \"https://github.com/ROCm/ROCm/issues\"\n },\n \"out_of_scope\": null,\n \"model\": null\n}\n", + "stdout": "{\n \"matched\": [\n {\n \"id\": \"fix-wsl-3-rocdxg-missing\",\n \"title\": \"ROCDXG not installed in the distro\",\n \"score\": 65,\n \"evidence\": [\n \"librocdxg.so was not found under any ROCm install or on LD_LIBRARY_PATH\",\n \"the WSL DXCore handoff is present, so only the distro-side ROCDXG is missing\"\n ],\n \"fix\": {\n \"summary\": \"Install ROCDXG inside the distro: it is the ROCm-to-DXCore shim the WSL path runs on.\",\n \"commands\": [\n \"rocm install driver\",\n \"# Then, once the plan looks right:\",\n \"# rocm install driver --yes\"\n ],\n \"needs_sudo\": true,\n \"needs_reboot\": false,\n \"needs_relogin\": false,\n \"fix_id\": \"fix-wsl-3-rocdxg-missing\",\n \"auto_applicable\": false,\n \"class\": \"print-only\",\n \"notes\": [\n \"This downloads and installs a .deb with sudo, so `rocm fix` prints it rather than running it. `rocm install driver` shows the full plan, and checks the package against a digest pinned for that ROCDXG release after root has placed it where only root can write, so the file checked is the file installed.\"\n ],\n \"verify\": \"ldconfig -p | grep librocdxg\"\n },\n \"symptom_matched\": false\n }\n ],\n \"has_match\": true,\n \"min_score_for_match\": 50,\n \"high_confidence_threshold\": 75,\n \"route_when_no_match\": {\n \"target\": \"rocm-core\",\n \"url\": \"https://github.com/ROCm/ROCm/issues\"\n },\n \"out_of_scope\": null,\n \"model\": null\n}\n", "stderr": "", "rc": 0 }, "diagnose_text": { - "stdout": "#1 (fix-wsl-3-rocdxg-missing) [LIKELY score=65/100] ROCDXG not installed in the distro\n id: fix-wsl-3-rocdxg-missing\n - librocdxg.so was not found under any ROCm install or on LD_LIBRARY_PATH\n - the WSL DXCore handoff is present, so only the distro-side ROCDXG is missing\n plan: Install ROCDXG inside the distro: it is the ROCm-to-DXCore shim the WSL path runs on.\n $ rocm install driver\n $ # Then, once the plan looks right:\n $ # rocm install driver --yes\n flags: requires sudo, manual only (`rocm fix` will NOT run it automatically)\n note: This downloads and installs a .deb with sudo, so `rocm fix` prints it rather than running it. `rocm install driver` shows the full plan, and checks the download against a digest pinned for that ROCDXG release.\n verify after fix: ldconfig -p | grep librocdxg\n apply with: rocm fix fix-wsl-3-rocdxg-missing\n\nHighest-scoring match is below the HIGH_CONFIDENCE threshold. Confirm one more piece of evidence before applying.\nWhen you are ready, run `rocm fix fix-wsl-3-rocdxg-missing` (the highest-scoring match), or use the `apply with:` line of whichever cause fits.\n", + "stdout": "#1 (fix-wsl-3-rocdxg-missing) [LIKELY score=65/100] ROCDXG not installed in the distro\n id: fix-wsl-3-rocdxg-missing\n - librocdxg.so was not found under any ROCm install or on LD_LIBRARY_PATH\n - the WSL DXCore handoff is present, so only the distro-side ROCDXG is missing\n plan: Install ROCDXG inside the distro: it is the ROCm-to-DXCore shim the WSL path runs on.\n $ rocm install driver\n $ # Then, once the plan looks right:\n $ # rocm install driver --yes\n flags: requires sudo, manual only (`rocm fix` will NOT run it automatically)\n note: This downloads and installs a .deb with sudo, so `rocm fix` prints it rather than running it. `rocm install driver` shows the full plan, and checks the package against a digest pinned for that ROCDXG release after root has placed it where only root can write, so the file checked is the file installed.\n verify after fix: ldconfig -p | grep librocdxg\n apply with: rocm fix fix-wsl-3-rocdxg-missing\n\nHighest-scoring match is below the HIGH_CONFIDENCE threshold. Confirm one more piece of evidence before applying.\nWhen you are ready, run `rocm fix fix-wsl-3-rocdxg-missing` (the highest-scoring match), or use the `apply with:` line of whichever cause fits.\n", "stderr": "", "rc": 0 }, diff --git a/tests/e2e-cucumber/features/driver_install.feature b/tests/e2e-cucumber/features/driver_install.feature index 9271bdeecd..65366e353e 100644 --- a/tests/e2e-cucumber/features/driver_install.feature +++ b/tests/e2e-cucumber/features/driver_install.feature @@ -15,6 +15,7 @@ Feature: Driver installation planning Then the driver plan is supported and mutating And the dry-run driver plan requires no approval and previews no execution And the driver plan verifies the download before installing it + And the driver plan installs only a package no other local user could have replaced And the driver plan does not direct the user to the removed WSL setup script @id:driver-install-wsl-review-requires-approval @requires-wsl diff --git a/tests/e2e-cucumber/tests/e2e/driver_steps.rs b/tests/e2e-cucumber/tests/e2e/driver_steps.rs index cdb0d7debf..082236d68d 100644 --- a/tests/e2e-cucumber/tests/e2e/driver_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/driver_steps.rs @@ -190,7 +190,7 @@ async fn assert_driver_plan_verifies_download(world: &mut E2eWorld) { .expect("plan verifies the download"); let install = commands .iter() - .position(|line| line.contains("apt-get install -y '/tmp/")) + .position(|line| line.contains("apt-get install -y '") && line.contains("rocdxg-roct_")) .expect("plan installs the package"); assert!( check < install, @@ -198,6 +198,58 @@ async fn assert_driver_plan_verifies_download(world: &mut E2eWorld) { ); } +#[then("the driver plan installs only a package no other local user could have replaced")] +async fn assert_driver_plan_stages_privately(world: &mut E2eWorld) { + // The package's maintainer scripts run as root. A fixed name in the shared, + // world-writable `/tmp` lets another local user pre-create the file, let + // the genuine download pass the digest check, and swap it before the + // install reads it. The file root installs has to sit in a directory only + // root can write, and be the very file the digest was checked against. + let output = world.cli_output.as_ref().expect("no driver plan output"); + assert!( + !output.contains("/tmp/"), + "the plan stages the package in shared /tmp:\n{output}" + ); + let lines: Vec<&str> = output.lines().map(str::trim).collect(); + let install = lines + .iter() + .find(|line| line.contains("apt-get install -y '") && line.contains("rocdxg-roct_")) + .expect("plan installs the package"); + let installed = install + .split('\'') + .nth(1) + .expect("installed path is single-quoted"); + // Ruling out `/tmp` is not enough: `/dev/shm` and `/var/tmp` are + // world-writable too. Only root can create entries under `/var/cache`. + assert!( + installed.starts_with("/var/cache/") && !installed.contains("/../"), + "the package is not staged under a root-only system directory: {installed}\n{output}" + ); + let staging_dir = installed + .rsplit_once('/') + .map(|(dir, _)| dir) + .expect("installed path has a directory"); + assert!( + lines + .iter() + .any(|line| line.contains("install -d -m 0755 -o root -g root") + && line.contains(&format!("'{staging_dir}'"))), + "the install directory is not made root-only first:\n{output}" + ); + assert!( + lines.iter().any(|line| line.contains("mktemp -d") + && line.contains("curl ") + && line.ends_with(&format!("'{installed}'"))), + "the download is not staged through a private directory:\n{output}" + ); + assert!( + lines + .iter() + .any(|line| line.contains("sha256sum -c -") && line.contains(&format!("'{installed}'"))), + "the digest is not checked on the file root installs:\n{output}" + ); +} + #[when("the user previews driver installation for a ROCDXG release with no known digest")] async fn preview_wsl_driver_install_unpinned(world: &mut E2eWorld) { let (stdout, stderr, rc) = crate::run_rocm_with_env(