From 756dad1c55210bb6f5732276b83d865b167f0818 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 07:22:39 +0000 Subject: [PATCH 1/3] deps: move zip to 9.x for RUSTSEC-2026-0367/0368/0369 cargo-audit fails on every PR: zip 2.4.2 in elastos/Cargo.lock and in capsules/object-provider/Cargo.lock (through its elastos-server path dependency) has three advisories against ZipArchive::extract and the stream extract API. The runtime calls neither; it reads each entry itself. zip 9.0.4 is the patched release. - elastos-server uses zip 9.0.4, still without default features. 9.x has no separate flate2 feature; deflate-flate2 now enables the dependency. - Both lockfiles change only for zip: nix 0.31.3 and typed-path come in, derive_arbitrary goes. `cargo update -p zip` also moved unrelated range dependencies (windows-sys, getrandom); those lines stay as they were, and `cargo metadata --locked` accepts both files. - ZipFile::name now returns a Result. The ZIP readers report an error as "invalid ZIP archive entry". - Whole-archive extract keeps its rule for entry names. zip 9 enclosed_name turns "/a.txt" into "a.txt" and folds "x/../a.txt" into "a.txt", so an entry that extract refuses today would be written. The runtime now checks the name with the rule zip 2.x applied: no NUL byte, no root or drive prefix, no climb above the archive root. test_library_provider_extract_zip_refuses_absolute_dotdot_and_symlink_entries covers absolute, "..", inner "..", backslash and symlink entries. It passes on zip 2.4.2 and with this change, and fails on the Absolute.zip case when extract uses zip 9 enclosed_name. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W6Qn9RX7LDqrwiAfNC2F2K --- capsules/object-provider/Cargo.lock | 50 ++--- elastos/Cargo.lock | 50 ++--- elastos/crates/elastos-server/Cargo.toml | 2 +- .../src/api/gateway_tests/library.rs | 199 +++++++++++++++++- elastos/crates/elastos-server/src/library.rs | 44 +++- 5 files changed, 290 insertions(+), 55 deletions(-) diff --git a/capsules/object-provider/Cargo.lock b/capsules/object-provider/Cargo.lock index d5114091d..914d1dc39 100644 --- a/capsules/object-provider/Cargo.lock +++ b/capsules/object-provider/Cargo.lock @@ -167,9 +167,6 @@ name = "arbitrary" version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] [[package]] name = "arc-swap" @@ -1190,7 +1187,7 @@ dependencies = [ "elastos-protected-content-provider-contracts", "elastos-protected-content-rights", "getrandom 0.2.17", - "nix", + "nix 0.29.0", "serde", "serde_json", "sha2 0.10.9", @@ -1274,17 +1271,6 @@ version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" -[[package]] -name = "derive_arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "derive_more" version = "2.1.1" @@ -1589,7 +1575,7 @@ dependencies = [ "elastos-common", "elastos-compute", "libc", - "nix", + "nix 0.29.0", "serde", "serde_json", "thiserror 1.0.69", @@ -1689,7 +1675,7 @@ dependencies = [ "ghash", "hkdf", "hpke", - "nix", + "nix 0.29.0", "rand 0.10.2", "rand 0.9.5", "rand_chacha 0.3.1", @@ -1734,7 +1720,7 @@ dependencies = [ "elastos-protected-content-provider-contracts", "elastos-wallet-contract", "hex", - "nix", + "nix 0.29.0", "serde", "serde_json", "sha2 0.10.9", @@ -3855,6 +3841,18 @@ dependencies = [ "libc", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nom" version = "7.1.3" @@ -6053,6 +6051,12 @@ dependencies = [ "utf-8", ] +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + [[package]] name = "typenum" version = "1.20.1" @@ -7446,18 +7450,16 @@ dependencies = [ [[package]] name = "zip" -version = "2.4.2" +version = "9.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" +checksum = "a954114b47a54df49f83d2722814e86b23d4bb1b54a1b90fb7d92b41619ddc22" dependencies = [ - "arbitrary", "crc32fast", - "crossbeam-utils", - "displaydoc", "flate2", "indexmap", "memchr", - "thiserror 2.0.20", + "nix 0.31.3", + "typed-path", ] [[package]] diff --git a/elastos/Cargo.lock b/elastos/Cargo.lock index ac82b721d..dc06da84e 100644 --- a/elastos/Cargo.lock +++ b/elastos/Cargo.lock @@ -167,9 +167,6 @@ name = "arbitrary" version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] [[package]] name = "arc-swap" @@ -1197,7 +1194,7 @@ dependencies = [ "elastos-protected-content-provider-contracts", "elastos-protected-content-rights", "getrandom 0.2.17", - "nix", + "nix 0.29.0", "serde", "serde_json", "sha2 0.10.9", @@ -1281,17 +1278,6 @@ version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" -[[package]] -name = "derive_arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "derive_more" version = "2.1.1" @@ -1598,7 +1584,7 @@ dependencies = [ "elastos-common", "elastos-compute", "libc", - "nix", + "nix 0.29.0", "serde", "serde_json", "tempfile", @@ -1706,7 +1692,7 @@ dependencies = [ "hkdf", "hpke", "k256", - "nix", + "nix 0.29.0", "rand 0.10.2", "rand 0.9.5", "rand_chacha 0.3.1", @@ -1765,7 +1751,7 @@ dependencies = [ "elastos-wallet-contract", "hex", "k256", - "nix", + "nix 0.29.0", "serde", "serde_json", "sha2 0.10.9", @@ -3925,6 +3911,18 @@ dependencies = [ "libc", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nom" version = "7.1.3" @@ -6164,6 +6162,12 @@ dependencies = [ "utf-8", ] +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + [[package]] name = "typenum" version = "1.20.1" @@ -7703,18 +7707,16 @@ dependencies = [ [[package]] name = "zip" -version = "2.4.2" +version = "9.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" +checksum = "a954114b47a54df49f83d2722814e86b23d4bb1b54a1b90fb7d92b41619ddc22" dependencies = [ - "arbitrary", "crc32fast", - "crossbeam-utils", - "displaydoc", "flate2", "indexmap", "memchr", - "thiserror 2.0.20", + "nix 0.31.3", + "typed-path", ] [[package]] diff --git a/elastos/crates/elastos-server/Cargo.toml b/elastos/crates/elastos-server/Cargo.toml index 84788f1d5..e54e95885 100644 --- a/elastos/crates/elastos-server/Cargo.toml +++ b/elastos/crates/elastos-server/Cargo.toml @@ -104,7 +104,7 @@ tempfile = "3.10" # Archive extraction (for capsule artifacts) flate2 = "1.0" tar = "0.4" -zip = { version = "2.4.2", default-features = false, features = ["deflate-flate2", "flate2"] } +zip = { version = "9.0.4", default-features = false, features = ["deflate-flate2"] } libc = "0.2" # Built-in Carrier transport (P2P for updates, gossip messaging, DHT discovery). diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/library.rs b/elastos/crates/elastos-server/src/api/gateway_tests/library.rs index d8477c0db..0253c229f 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/library.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/library.rs @@ -892,7 +892,7 @@ fn zip_text_files(bytes: &[u8]) -> std::collections::BTreeMap { if entry.is_dir() { continue; } - let name = entry.name().to_string(); + let name = entry.name().unwrap().into_owned(); let mut body = String::new(); entry.read_to_string(&mut body).unwrap(); files.insert(name, body); @@ -3870,6 +3870,203 @@ async fn test_library_provider_rejects_unsafe_zip_entries() { .contains("relative and safe")); } +/// Every path under `root` (files, folders and symlinks, not followed). +fn walk_paths(root: &std::path::Path) -> Vec { + let mut out = Vec::new(); + let mut stack = vec![root.to_path_buf()]; + while let Some(dir) = stack.pop() { + for entry in std::fs::read_dir(&dir).unwrap() { + let entry = entry.unwrap(); + let path = entry.path(); + if entry.file_type().unwrap().is_dir() { + stack.push(path.clone()); + } + out.push(path); + } + } + out +} + +#[tokio::test] +async fn test_library_provider_extract_zip_refuses_absolute_dotdot_and_symlink_entries() { + use std::io::Write as _; + + let dir = tempfile::tempdir().unwrap(); + let app = gateway_router(library_test_state(dir.path()).await); + let authority = passkey_authority_with_name(dir.path(), Some("admin")); + let token = app_token_for_authority(dir.path(), LIBRARY_CAPSULE_ID, &authority); + let root = crate::auth::principal_localhost_root(&authority.principal_id); + let documents_uri = format!("{root}/Documents"); + let imports_uri = format!("{documents_uri}/Imports"); + + let (status, _) = post_library( + app.clone(), + &token, + "mkdir", + json!({ "parent_uri": root, "name": "Documents" }), + ) + .await; + assert_eq!(status, StatusCode::OK); + let (status, _) = post_library( + app.clone(), + &token, + "mkdir", + json!({ "parent_uri": documents_uri, "name": "Imports" }), + ) + .await; + assert_eq!(status, StatusCode::OK); + + let options = + zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + // Each archive holds one hostile entry. The whole-archive extract must + // refuse it and write nothing for it, inside or outside the Library. + // (archive name, entry kind, entry name, symlink target, expected message) + let cases: [(&str, &str, &str, &str, &str); 5] = [ + ( + "Absolute.zip", + "file", + "/absolute-escape.txt", + "", + "relative and safe", + ), + ( + "DotDot.zip", + "file", + "../dotdot-escape.txt", + "", + "relative and safe", + ), + ( + "Inner.zip", + "file", + "Nested/../inner-escape.txt", + "", + "relative and safe", + ), + ( + "Backslash.zip", + "file", + "..\\backslash-escape.txt", + "", + "invalid library object name", + ), + ( + "Symlink.zip", + "symlink", + "symlink-escape.txt", + "/etc/passwd", + "non-file", + ), + ]; + for (archive_name, kind, entry_name, link_target, expected) in cases { + let archive_bytes = { + let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + if kind == "symlink" { + writer + .add_symlink(entry_name, link_target, options) + .unwrap(); + } else { + writer.start_file(entry_name, options).unwrap(); + writer.write_all(b"escape").unwrap(); + } + writer.finish().unwrap().into_inner() + }; + let zip_uri = format!("{documents_uri}/{archive_name}"); + let (write_status, write) = post_library( + app.clone(), + &token, + "write", + json!({ + "uri": zip_uri, + "mime": "application/zip", + "data": base64::engine::general_purpose::STANDARD.encode(archive_bytes), + }), + ) + .await; + assert_eq!(write_status, StatusCode::OK, "{archive_name}"); + assert_eq!(write["status"], "ok", "{archive_name}: {write}"); + + let (extract_status, extracted) = post_library( + app.clone(), + &token, + "extract_archive", + json!({ "uri": zip_uri }), + ) + .await; + assert_eq!(extract_status, StatusCode::OK, "{archive_name}"); + assert_eq!( + extracted["status"], "error", + "{archive_name}: hostile entry {entry_name:?} was not refused: {extracted}" + ); + assert!( + extracted["message"].as_str().unwrap().contains(expected), + "{archive_name}: {extracted}" + ); + + if kind == "symlink" { + // The listing marks it blocked and a selected extract refuses it. + let (list_status, listed) = post_library( + app.clone(), + &token, + "archive_entries", + json!({ "uri": zip_uri }), + ) + .await; + assert_eq!(list_status, StatusCode::OK); + let rows = listed["data"]["entries"].as_array().unwrap(); + assert!( + rows.iter().any(|entry| entry["path"] == entry_name + && entry["kind"] == "blocked" + && entry["safety"]["reason"] + .as_str() + .unwrap() + .contains("non-file")), + "{listed}" + ); + let (select_status, selected) = post_library( + app.clone(), + &token, + "archive_extract_entries", + json!({ + "uri": zip_uri, + "destination_uri": imports_uri, + "entries": [entry_name], + }), + ) + .await; + assert_eq!(select_status, StatusCode::OK); + assert_eq!(selected["status"], "ok", "{selected}"); + assert_eq!( + selected["data"]["receipt"]["progress"]["blocked_entries"], + 1 + ); + assert!(selected["data"]["blocked"][0]["reason"] + .as_str() + .unwrap() + .contains("non-file")); + } + } + + // Nothing from any hostile entry exists anywhere under the data dir, and + // no symlink was created. + for path in walk_paths(dir.path()) { + let name = path.file_name().unwrap().to_string_lossy().to_string(); + assert!( + !name.contains("escape"), + "hostile entry was written: {}", + path.display() + ); + assert!( + !std::fs::symlink_metadata(&path) + .unwrap() + .file_type() + .is_symlink(), + "symlink was created: {}", + path.display() + ); + } +} + #[tokio::test] async fn test_library_gateway_reads_webspace_files_through_runtime_provider() { let dir = tempfile::tempdir().unwrap(); diff --git a/elastos/crates/elastos-server/src/library.rs b/elastos/crates/elastos-server/src/library.rs index 9e537d229..84c791d0a 100644 --- a/elastos/crates/elastos-server/src/library.rs +++ b/elastos/crates/elastos-server/src/library.rs @@ -4239,7 +4239,10 @@ fn preview_zip_archive_entry( let mut file = archive .by_index(index) .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))?; - let raw_name = file.name().to_string(); + let raw_name = file + .name() + .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))? + .into_owned(); let Ok(normalized) = normalized_archive_entry_path(Path::new(&raw_name)) else { continue; }; @@ -4457,7 +4460,10 @@ fn list_zip_archive_entries(bytes: Vec) -> anyhow::Result<(Vec, bool) let file = archive .by_index(index) .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))?; - let raw_name = file.name().to_string(); + let raw_name = file + .name() + .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))? + .into_owned(); let path = Path::new(&raw_name); let normalized = match normalized_archive_entry_path(path) { Ok(path) => path, @@ -4939,7 +4945,10 @@ fn collect_selected_zip_writes( let mut file = archive .by_index(index) .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))?; - let raw_name = file.name().to_string(); + let raw_name = file + .name() + .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))? + .into_owned(); let normalized = match normalized_archive_entry_path(Path::new(&raw_name)) { Ok(path) => path, Err(err) => { @@ -5429,8 +5438,10 @@ fn extract_zip_archive( let mut file = archive .by_index(index) .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))?; - let entry_path = file - .enclosed_name() + let raw_name = file + .name() + .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))?; + let entry_path = zip_entry_enclosed_path(&raw_name) .ok_or_else(|| anyhow!("library archive entry path must be relative and safe"))?; let entry_uri = archive_entry_uri(&destination.uri, &entry_path)?; if entry_uri == destination.uri { @@ -5461,6 +5472,29 @@ fn extract_zip_archive( Ok(()) } +/// The path a whole-archive ZIP extract writes for an entry name, or `None` +/// when the name holds a NUL byte, is absolute (a root or a drive prefix), or +/// climbs above the archive root. `archive_entry_uri` then refuses any `..` +/// that is left. This keeps the rule in the runtime: zip 9 `enclosed_name` +/// strips a leading `/` or drive prefix and folds `..` instead, which would +/// write entries that this extract refuses. +fn zip_entry_enclosed_path(name: &str) -> Option { + if name.contains('\0') { + return None; + } + let path = PathBuf::from(name); + let mut depth = 0usize; + for component in path.components() { + match component { + Component::Prefix(_) | Component::RootDir => return None, + Component::ParentDir => depth = depth.checked_sub(1)?, + Component::Normal(_) => depth += 1, + Component::CurDir => {} + } + } + Some(path) +} + fn archive_entry_uri(destination_uri: &str, path: &Path) -> anyhow::Result { let mut uri = destination_uri.trim_end_matches('/').to_string(); for component in path.components() { From 6ef7073d509aba94ab42dac4699341cf833edd57 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 08:39:57 +0000 Subject: [PATCH 2/3] fix(setup): Linux setup names the removal command for an earlier release's Browser host access An earlier installer could run scripts/browser-vm-linux-network.py setup with sudo. That setup left a root-owned helper copy, a boot service, a KVM udev rule, a KVM ACL and private network devices for the account. Linux setup now removes only the user-owned Browser files, and nothing told the user that the root-owned access was still there. retire_host now checks this account's files read-only. When the helper and its access record are present, it prints the helper's own removal command. Otherwise it names the files that are left. Setup changes nothing outside the data directory and does not ask for sudo. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W6Qn9RX7LDqrwiAfNC2F2K --- .../src/setup/browser_config.rs | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/elastos/crates/elastos-server/src/setup/browser_config.rs b/elastos/crates/elastos-server/src/setup/browser_config.rs index 54b6b466a..07df8b08a 100644 --- a/elastos/crates/elastos-server/src/setup/browser_config.rs +++ b/elastos/crates/elastos-server/src/setup/browser_config.rs @@ -352,9 +352,52 @@ fn retire_host(data: &Path, manifest: &super::ComponentsManifest) -> anyhow::Res if browser_installed { println!("Browser is not available on this computer yet."); } + #[cfg(target_os = "linux")] + if let Some(notice) = earlier_linux_host_access(Path::new("/"), unsafe { libc::getuid() }) { + println!("{notice}"); + } Ok(()) } +/// The root-owned copy of scripts/browser-vm-linux-network.py that an earlier +/// release's installer ran with sudo. +#[cfg(target_os = "linux")] +const LINUX_HOST_HELPER: &str = "/usr/local/lib/elastos/browser-vm-linux-network.py"; + +/// An earlier installer could set up root-owned Browser host access for this +/// account (KVM access, private network devices, a udev rule and a boot +/// service). Setup runs as the Home user, so it does not remove that access. +/// It tells the user the exact removal command, and it changes nothing. +#[cfg(target_os = "linux")] +fn earlier_linux_host_access(root: &Path, uid: u32) -> Option { + let at = |path: &str| root.join(path.trim_start_matches('/')); + let state = format!("/var/lib/elastos-browser/{uid}.json"); + let leftovers: Vec = [ + format!("/etc/systemd/system/elastos-browser-network-{uid}.service"), + format!("/etc/udev/rules.d/70-elastos-browser-kvm-{uid}.rules"), + state.clone(), + ] + .into_iter() + .filter(|path| at(path).symlink_metadata().is_ok()) + .collect(); + if leftovers.is_empty() { + return None; + } + let helper = at(LINUX_HOST_HELPER) + .symlink_metadata() + .is_ok_and(|meta| meta.is_file()); + // The helper's removal needs its saved KVM access record (the state file). + if helper && at(&state).symlink_metadata().is_ok() { + return Some(format!( + "An earlier ElastOS release set up Browser access for your account on this computer: KVM access, private network devices and a boot service. Browser is not available on this computer yet, so this access is not in use. To remove it, run this command and confirm:\n sudo /usr/bin/python3 -I {LINUX_HOST_HELPER} remove --user \"$(id -un)\"" + )); + } + Some(format!( + "An earlier ElastOS release left Browser access files for your account on this computer: {}. Browser is not available on this computer yet. An administrator can remove these files.", + leftovers.join(", ") + )) +} + /// True when the data directory and every folder from it down to `relative`'s /// parent are real directories, so a removal stays inside the data directory. fn parents_are_real_directories(data: &Path, relative: &Path) -> bool { @@ -935,6 +978,46 @@ mod tests { assert!(!data.join("scripts/browser-vm-linux-network.py").exists()); } + #[cfg(target_os = "linux")] + #[test] + fn earlier_linux_host_access_names_its_exact_removal_command() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let place = |path: &str| { + let path = root.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"root-owned fixture").unwrap(); + }; + // A fresh host, or another account's setup, needs no notice. + assert_eq!(earlier_linux_host_access(root, 1000), None); + place("usr/local/lib/elastos/browser-vm-linux-network.py"); + place("etc/udev/rules.d/70-elastos-browser-kvm-1001.rules"); + place("var/lib/elastos-browser/1001.json"); + assert_eq!(earlier_linux_host_access(root, 1000), None); + // This account's setup gets the helper's own removal command. + place("etc/systemd/system/elastos-browser-network-1000.service"); + place("etc/udev/rules.d/70-elastos-browser-kvm-1000.rules"); + place("var/lib/elastos-browser/1000.json"); + let notice = earlier_linux_host_access(root, 1000).unwrap(); + assert!(notice.contains("Browser is not available on this computer yet")); + assert!(notice.ends_with( + "\n sudo /usr/bin/python3 -I /usr/local/lib/elastos/browser-vm-linux-network.py remove --user \"$(id -un)\"" + )); + // The notice only reads; every file stays. + assert!(root.join("var/lib/elastos-browser/1000.json").is_file()); + // Without the root-owned helper or its access record the command would + // fail, so the notice names the files instead. + fs::remove_file(root.join("var/lib/elastos-browser/1000.json")).unwrap(); + let notice = earlier_linux_host_access(root, 1000).unwrap(); + assert!(!notice.contains("sudo")); + assert!(notice.contains("/etc/systemd/system/elastos-browser-network-1000.service, /etc/udev/rules.d/70-elastos-browser-kvm-1000.rules")); + place("var/lib/elastos-browser/1000.json"); + fs::remove_file(root.join("usr/local/lib/elastos/browser-vm-linux-network.py")).unwrap(); + assert!(!earlier_linux_host_access(root, 1000) + .unwrap() + .contains("sudo")); + } + #[test] fn removal_never_goes_through_a_linked_data_directory() { use std::os::unix::fs::symlink; From 4bf4b26afe59b28dcaaa4d8b5d7f58df590cadbe Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 14:25:28 +0000 Subject: [PATCH 3/3] fix(setup): name the sudo removal command only for root-owned paths The leftover Browser host access notice printed a sudo command when the helper copy and its access record merely existed. A file that another account can write, a link, or a link in a folder on the path could then put a command that runs that account's code as root in front of the user. The notice now checks each path with lstat, as the helper's own trusted_path does: the helper, its access record and /usr/bin/python3 (through root-owned links) must be root-owned regular files with no set-id bit and no group or other write, in real folders that only root can change. Otherwise the notice names the files and no command. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W6Qn9RX7LDqrwiAfNC2F2K --- .../src/setup/browser_config.rs | 363 ++++++++++++++++-- 1 file changed, 332 insertions(+), 31 deletions(-) diff --git a/elastos/crates/elastos-server/src/setup/browser_config.rs b/elastos/crates/elastos-server/src/setup/browser_config.rs index 07df8b08a..7417d8a86 100644 --- a/elastos/crates/elastos-server/src/setup/browser_config.rs +++ b/elastos/crates/elastos-server/src/setup/browser_config.rs @@ -353,23 +353,35 @@ fn retire_host(data: &Path, manifest: &super::ComponentsManifest) -> anyhow::Res println!("Browser is not available on this computer yet."); } #[cfg(target_os = "linux")] - if let Some(notice) = earlier_linux_host_access(Path::new("/"), unsafe { libc::getuid() }) { + if let Some(notice) = + earlier_linux_host_access(Path::new("/"), unsafe { libc::getuid() }, ROOT_UID) + { println!("{notice}"); } Ok(()) } /// The root-owned copy of scripts/browser-vm-linux-network.py that an earlier -/// release's installer ran with sudo. +/// release's installer ran with sudo (scripts/install.sh, prepare_browser_linux_host). #[cfg(target_os = "linux")] const LINUX_HOST_HELPER: &str = "/usr/local/lib/elastos/browser-vm-linux-network.py"; +/// The interpreter the earlier installer ran the helper with. +#[cfg(target_os = "linux")] +const LINUX_HOST_PYTHON: &str = "/usr/bin/python3"; + +/// The owner every path in the removal command must have. +#[cfg(target_os = "linux")] +const ROOT_UID: u32 = 0; + /// An earlier installer could set up root-owned Browser host access for this /// account (KVM access, private network devices, a udev rule and a boot /// service). Setup runs as the Home user, so it does not remove that access. -/// It tells the user the exact removal command, and it changes nothing. +/// It changes nothing. It names the sudo removal command only when every path +/// in that command, and the access record the removal reads, is a file that +/// only `owner` (root) can change. Otherwise it names the files and no command. #[cfg(target_os = "linux")] -fn earlier_linux_host_access(root: &Path, uid: u32) -> Option { +fn earlier_linux_host_access(root: &Path, uid: u32, owner: u32) -> Option { let at = |path: &str| root.join(path.trim_start_matches('/')); let state = format!("/var/lib/elastos-browser/{uid}.json"); let leftovers: Vec = [ @@ -383,13 +395,13 @@ fn earlier_linux_host_access(root: &Path, uid: u32) -> Option { if leftovers.is_empty() { return None; } - let helper = at(LINUX_HOST_HELPER) - .symlink_metadata() - .is_ok_and(|meta| meta.is_file()); // The helper's removal needs its saved KVM access record (the state file). - if helper && at(&state).symlink_metadata().is_ok() { + if root_only_file(root, &at(LINUX_HOST_HELPER), owner) + && root_only_file(root, &at(&state), owner) + && root_only_program(root, LINUX_HOST_PYTHON, owner) + { return Some(format!( - "An earlier ElastOS release set up Browser access for your account on this computer: KVM access, private network devices and a boot service. Browser is not available on this computer yet, so this access is not in use. To remove it, run this command and confirm:\n sudo /usr/bin/python3 -I {LINUX_HOST_HELPER} remove --user \"$(id -un)\"" + "An earlier ElastOS release set up Browser access for your account on this computer: KVM access, private network devices and a boot service. Browser is not available on this computer yet, so this access is not in use. To remove it, run this command and confirm:\n sudo {LINUX_HOST_PYTHON} -I {LINUX_HOST_HELPER} remove --user \"$(id -un)\"" )); } Some(format!( @@ -398,6 +410,79 @@ fn earlier_linux_host_access(root: &Path, uid: u32) -> Option { )) } +/// True when `meta` belongs to `owner` and no group or other user can write it. +/// The helper's own trusted_path applies the same rule. +#[cfg(target_os = "linux")] +fn only_owner_writes(meta: &fs::Metadata, owner: u32) -> bool { + use std::os::unix::fs::MetadataExt; + meta.uid() == owner && meta.mode() & 0o022 == 0 +} + +/// True when every folder above `path`, up to and including `root`, is a real +/// folder (not a link) that only `owner` can change. +#[cfg(target_os = "linux")] +fn root_only_folders(root: &Path, path: &Path, owner: u32) -> bool { + path.ancestors() + .skip(1) + .take_while(|folder| folder.starts_with(root)) + .all(|folder| { + folder + .symlink_metadata() + .is_ok_and(|meta| meta.is_dir() && only_owner_writes(&meta, owner)) + }) +} + +/// True when `path` is a regular file (not a link) with no set-id or sticky +/// bit that only `owner` can change, in folders only `owner` can change. +#[cfg(target_os = "linux")] +fn root_only_file(root: &Path, path: &Path, owner: u32) -> bool { + use std::os::unix::fs::MetadataExt; + root_only_folders(root, path, owner) + && path.symlink_metadata().is_ok_and(|meta| { + meta.is_file() && meta.mode() & 0o7000 == 0 && only_owner_writes(&meta, owner) + }) +} + +/// True when `program` resolves, through at most eight links that `owner` +/// owns in folders only `owner` can change, to an executable regular file +/// that only `owner` can change. A link target with `..` is refused. +#[cfg(target_os = "linux")] +fn root_only_program(root: &Path, program: &str, owner: u32) -> bool { + use std::os::unix::fs::MetadataExt; + let mut path = root.join(program.trim_start_matches('/')); + for _ in 0..8 { + if !root_only_folders(root, &path, owner) { + return false; + } + let Ok(meta) = path.symlink_metadata() else { + return false; + }; + if !meta.file_type().is_symlink() { + return root_only_file(root, &path, owner) && meta.mode() & 0o100 != 0; + } + if meta.uid() != owner { + return false; + } + let Ok(target) = fs::read_link(&path) else { + return false; + }; + if target + .components() + .any(|part| matches!(part, std::path::Component::ParentDir)) + { + return false; + } + path = match target.strip_prefix("/") { + Ok(absolute) => root.join(absolute), + Err(_) => match path.parent() { + Some(folder) => folder.join(target), + None => return false, + }, + }; + } + false +} + /// True when the data directory and every folder from it down to `relative`'s /// parent are real directories, so a removal stays inside the data directory. fn parents_are_real_directories(data: &Path, relative: &Path) -> bool { @@ -978,44 +1063,260 @@ mod tests { assert!(!data.join("scripts/browser-vm-linux-network.py").exists()); } + /// Lays out an earlier release's Browser host access for uid 1000 under + /// `root`, as its installer and helper wrote it: folders 0755, the helper + /// and the interpreter 0755, the access record 0644, and /usr/bin/python3 a + /// link to the interpreter. Everything belongs to the test process. + #[cfg(target_os = "linux")] + fn earlier_linux_host_layout(root: &Path) { + use std::os::unix::fs::{symlink, PermissionsExt}; + let place = |path: &str, mode: u32| { + let path = root.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, b"root-owned fixture").unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(mode)).unwrap(); + }; + place("usr/local/lib/elastos/browser-vm-linux-network.py", 0o755); + place("usr/bin/python3.12", 0o755); + symlink("python3.12", root.join("usr/bin/python3")).unwrap(); + place( + "etc/systemd/system/elastos-browser-network-1000.service", + 0o644, + ); + place("etc/udev/rules.d/70-elastos-browser-kvm-1000.rules", 0o644); + place("var/lib/elastos-browser/1000.json", 0o644); + // The umask must not decide the folder modes. + for folder in [ + "usr", + "usr/local", + "usr/local/lib", + "usr/local/lib/elastos", + "usr/bin", + "etc", + "etc/systemd", + "etc/systemd/system", + "etc/udev", + "etc/udev/rules.d", + "var", + "var/lib", + "var/lib/elastos-browser", + ] { + fs::set_permissions(root.join(folder), fs::Permissions::from_mode(0o755)).unwrap(); + } + } + + /// A named change to `earlier_linux_host_layout`. + #[cfg(target_os = "linux")] + type LayoutChange = (&'static str, fn(&Path)); + + #[cfg(target_os = "linux")] + fn set_mode(root: &Path, path: &str, mode: u32) { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(root.join(path), fs::Permissions::from_mode(mode)).unwrap(); + } + + #[cfg(target_os = "linux")] + fn test_owner() -> u32 { + unsafe { libc::geteuid() } + } + + #[cfg(target_os = "linux")] + fn names_sudo(root: &Path, owner: u32) -> bool { + earlier_linux_host_access(root, 1000, owner) + .unwrap() + .contains("sudo") + } + #[cfg(target_os = "linux")] #[test] fn earlier_linux_host_access_names_its_exact_removal_command() { let temp = tempfile::tempdir().unwrap(); let root = temp.path(); - let place = |path: &str| { - let path = root.join(path); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(path, b"root-owned fixture").unwrap(); - }; + let owner = test_owner(); // A fresh host, or another account's setup, needs no notice. - assert_eq!(earlier_linux_host_access(root, 1000), None); - place("usr/local/lib/elastos/browser-vm-linux-network.py"); - place("etc/udev/rules.d/70-elastos-browser-kvm-1001.rules"); - place("var/lib/elastos-browser/1001.json"); - assert_eq!(earlier_linux_host_access(root, 1000), None); - // This account's setup gets the helper's own removal command. - place("etc/systemd/system/elastos-browser-network-1000.service"); - place("etc/udev/rules.d/70-elastos-browser-kvm-1000.rules"); - place("var/lib/elastos-browser/1000.json"); - let notice = earlier_linux_host_access(root, 1000).unwrap(); + assert_eq!(earlier_linux_host_access(root, 1000, owner), None); + earlier_linux_host_layout(root); + assert_eq!(earlier_linux_host_access(root, 1001, owner), None); + // This account's setup, with every path owned by `owner`, gets the + // helper's own removal command. + let notice = earlier_linux_host_access(root, 1000, owner).unwrap(); assert!(notice.contains("Browser is not available on this computer yet")); assert!(notice.ends_with( "\n sudo /usr/bin/python3 -I /usr/local/lib/elastos/browser-vm-linux-network.py remove --user \"$(id -un)\"" )); // The notice only reads; every file stays. assert!(root.join("var/lib/elastos-browser/1000.json").is_file()); - // Without the root-owned helper or its access record the command would - // fail, so the notice names the files instead. + // Without the helper or its access record the command would fail, so + // the notice names the files instead. fs::remove_file(root.join("var/lib/elastos-browser/1000.json")).unwrap(); - let notice = earlier_linux_host_access(root, 1000).unwrap(); + let notice = earlier_linux_host_access(root, 1000, owner).unwrap(); assert!(!notice.contains("sudo")); assert!(notice.contains("/etc/systemd/system/elastos-browser-network-1000.service, /etc/udev/rules.d/70-elastos-browser-kvm-1000.rules")); - place("var/lib/elastos-browser/1000.json"); + fs::write(root.join("var/lib/elastos-browser/1000.json"), b"{}").unwrap(); + fs::set_permissions( + root.join("var/lib/elastos-browser/1000.json"), + std::os::unix::fs::PermissionsExt::from_mode(0o644), + ) + .unwrap(); + assert!(names_sudo(root, owner)); fs::remove_file(root.join("usr/local/lib/elastos/browser-vm-linux-network.py")).unwrap(); - assert!(!earlier_linux_host_access(root, 1000) - .unwrap() - .contains("sudo")); + assert!(!names_sudo(root, owner)); + } + + #[cfg(target_os = "linux")] + #[test] + fn earlier_linux_host_access_names_no_sudo_command_for_files_root_does_not_own() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + earlier_linux_host_layout(root); + let owner = test_owner(); + assert!(names_sudo(root, owner)); + if owner == ROOT_UID { + // Each path in turn, given to uid 1000, loses the command. + let named_sudo: Vec = [ + "usr/local/lib/elastos/browser-vm-linux-network.py", + "usr/local/lib/elastos", + "usr/local", + "var/lib/elastos-browser/1000.json", + "var/lib/elastos-browser", + "usr/bin/python3", + "usr/bin/python3.12", + "usr/bin", + "", + ] + .into_iter() + .filter(|path| { + let path = root.join(path); + std::os::unix::fs::lchown(&path, Some(1000), None).unwrap(); + let named = names_sudo(root, ROOT_UID); + std::os::unix::fs::lchown(&path, Some(ROOT_UID), None).unwrap(); + named + }) + .map(|path| format!("/{path}")) + .collect(); + assert!(named_sudo.is_empty(), "sudo command named: {named_sudo:?}"); + assert!(names_sudo(root, ROOT_UID)); + } else { + // The test's files are ordinary user files: no sudo command. + assert!(!names_sudo(root, ROOT_UID)); + eprintln!( + "skipped the per-path chown cases: only uid 0 can give a file to another account" + ); + } + // Files that belong to another account get no sudo command. + assert!(!names_sudo(root, owner.wrapping_add(1))); + } + + #[cfg(target_os = "linux")] + #[test] + fn earlier_linux_host_access_names_no_sudo_command_through_a_link() { + use std::os::unix::fs::symlink; + let owner = test_owner(); + let cases: [LayoutChange; 6] = [ + ("helper is a link", |root| { + let helper = root.join("usr/local/lib/elastos/browser-vm-linux-network.py"); + fs::rename(&helper, root.join("usr/local/lib/elastos/real.py")).unwrap(); + symlink("real.py", &helper).unwrap(); + }), + ("access record is a link", |root| { + let state = root.join("var/lib/elastos-browser/1000.json"); + fs::rename(&state, root.join("var/lib/elastos-browser/real.json")).unwrap(); + symlink("real.json", &state).unwrap(); + }), + ("helper folder is a link", |root| { + fs::rename( + root.join("usr/local/lib/elastos"), + root.join("usr/local/lib/real"), + ) + .unwrap(); + symlink("real", root.join("usr/local/lib/elastos")).unwrap(); + }), + ("a higher helper folder is a link", |root| { + fs::rename(root.join("usr/local"), root.join("usr/real")).unwrap(); + symlink("real", root.join("usr/local")).unwrap(); + }), + ("interpreter link leaves its folder with ..", |root| { + fs::remove_file(root.join("usr/bin/python3")).unwrap(); + symlink("../bin/python3.12", root.join("usr/bin/python3")).unwrap(); + }), + ("interpreter links in a loop", |root| { + fs::remove_file(root.join("usr/bin/python3")).unwrap(); + symlink("python3", root.join("usr/bin/python3")).unwrap(); + }), + ]; + let named_sudo: Vec<&str> = cases + .into_iter() + .filter(|(_, change)| { + let temp = tempfile::tempdir().unwrap(); + earlier_linux_host_layout(temp.path()); + change(temp.path()); + names_sudo(temp.path(), owner) + }) + .map(|(name, _)| name) + .collect(); + assert!(named_sudo.is_empty(), "sudo command named: {named_sudo:?}"); + } + + #[cfg(target_os = "linux")] + #[test] + fn earlier_linux_host_access_names_no_sudo_command_for_a_wrong_type_or_mode() { + let owner = test_owner(); + let cases: [LayoutChange; 9] = [ + ("helper is a folder", |root| { + let helper = root.join("usr/local/lib/elastos/browser-vm-linux-network.py"); + fs::remove_file(&helper).unwrap(); + fs::create_dir(&helper).unwrap(); + }), + ("access record is a folder", |root| { + let state = root.join("var/lib/elastos-browser/1000.json"); + fs::remove_file(&state).unwrap(); + fs::create_dir(&state).unwrap(); + }), + ("helper is group-writable", |root| { + set_mode( + root, + "usr/local/lib/elastos/browser-vm-linux-network.py", + 0o775, + ) + }), + ("helper is writable by others", |root| { + set_mode( + root, + "usr/local/lib/elastos/browser-vm-linux-network.py", + 0o757, + ) + }), + ("helper is set-user-id", |root| { + set_mode( + root, + "usr/local/lib/elastos/browser-vm-linux-network.py", + 0o4755, + ) + }), + ("access record is writable by others", |root| { + set_mode(root, "var/lib/elastos-browser/1000.json", 0o666) + }), + ("helper folder is writable by others", |root| { + set_mode(root, "usr/local/lib/elastos", 0o777) + }), + ("interpreter is not executable", |root| { + set_mode(root, "usr/bin/python3.12", 0o644) + }), + ("interpreter folder is group-writable", |root| { + set_mode(root, "usr/bin", 0o775) + }), + ]; + let named_sudo: Vec<&str> = cases + .into_iter() + .filter(|(_, change)| { + let temp = tempfile::tempdir().unwrap(); + earlier_linux_host_layout(temp.path()); + change(temp.path()); + names_sudo(temp.path(), owner) + }) + .map(|(name, _)| name) + .collect(); + assert!(named_sudo.is_empty(), "sudo command named: {named_sudo:?}"); } #[test]