fix(pack): close inventory forgery, serialize ownership changes and refuse to follow links

Names with control characters have no content digest, so a crafted name
can no longer reproduce other inventory lines and drop signed files.
Installs and uninstalls of an ID hold a per-ID lock, so a failed
concurrent install cannot remove the record of the one that won. App
data without a recorded owner goes to a new owner only with
--claim-data. Uninstall releases a record left by an interrupted
install once no data remains. Files are opened without following links
and, on Linux, must be the file that was listed.
This commit is contained in:
Marco Allegretti 2026-10-09 14:04:53 +00:00
parent d175bf012e
commit 39f7ca2a3f
No known key found for this signature in database
5 changed files with 232 additions and 31 deletions

1
Cargo.lock generated
View file

@ -10542,6 +10542,7 @@ dependencies = [
"anyhow",
"ed25519-dalek",
"hex",
"libc",
"rand 0.8.5",
"sha2",
"tar",

View file

@ -4,8 +4,9 @@
//! A package is signed over its content digest: the SHA-256 of a canonical
//! inventory listing every file except the root `signature.sig`, one
//! `<relative path>\t<hex sha-256>\n` line per file, sorted by path. Paths use
//! `/` and must be UTF-8. Symbolic links and special files are refused, so the
//! signed bytes are exactly the files a package holds.
//! `/` and must be UTF-8 without control characters, so no name can imitate
//! the separators of other lines. Symbolic links and special files are
//! refused, so the signed bytes are exactly the files a package holds.
use std::fmt;
use std::path::{Path, PathBuf};
@ -25,6 +26,8 @@ pub enum TrustError {
NotAFile(PathBuf),
/// A path in the package is not UTF-8.
NonUtf8(PathBuf),
/// A name in the package holds a control character.
ControlCharacter(PathBuf),
/// A key, signature or owner record is malformed.
Malformed(PathBuf, String),
Io(PathBuf, std::io::Error),
@ -36,6 +39,9 @@ impl fmt::Display for TrustError {
Self::Link(p) => write!(f, "{} is a symbolic link", p.display()),
Self::NotAFile(p) => write!(f, "{} is not a regular file or directory", p.display()),
Self::NonUtf8(p) => write!(f, "{} is not a UTF-8 path", p.display()),
Self::ControlCharacter(p) => {
write!(f, "{:?} has a control character in its name", p.display())
}
Self::Malformed(p, why) => write!(f, "{}: {why}", p.display()),
Self::Io(p, e) => write!(f, "{}: {e}", p.display()),
}
@ -76,6 +82,9 @@ fn collect(
.to_str()
.ok_or_else(|| TrustError::NonUtf8(path.clone()))?
.to_owned();
if relative.chars().any(char::is_control) {
return Err(TrustError::ControlCharacter(path));
}
let kind = std::fs::symlink_metadata(&path)
.map_err(io(&path))?
.file_type();
@ -295,6 +304,22 @@ pub fn write_owner(record: &Path, owner: Owner) -> Result<(), TrustError> {
.map_err(io(parent))
}
/// Takes the lock that serialises every change to the installation and
/// owner record of `app_id`, held until the returned file is dropped.
pub fn lock_owner(data_home: &Path, app_id: &str) -> Result<std::fs::File, TrustError> {
let dir = data_home.join("weft/owners");
std::fs::create_dir_all(&dir).map_err(io(&dir))?;
let path = dir.join(format!(".{app_id}.lock"));
let file = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.open(&path)
.map_err(io(&path))?;
file.lock().map_err(io(&path))?;
Ok(file)
}
#[cfg(test)]
mod tests {
use super::*;
@ -356,6 +381,39 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
#[cfg(unix)]
#[test]
fn names_cannot_imitate_other_inventory_lines() {
// With files ui/policy.txt and ui/z.css signed, a directory named
// "ui/policy.txt\t<hash>\nui" holding z.css would reproduce the
// inventory without policy.txt. Such names have no digest.
let dir = dir("forged");
std::fs::write(dir.join("ui/policy.txt"), b"default-src 'self'").unwrap();
std::fs::write(dir.join("ui/z.css"), b"p{}").unwrap();
let signed = content_digest(&dir).unwrap();
let policy_hash = hex::encode(Sha256::digest(b"default-src 'self'"));
std::fs::remove_file(dir.join("ui/policy.txt")).unwrap();
let forged = dir.join(format!("ui/policy.txt\t{policy_hash}\nui"));
std::fs::create_dir_all(&forged).unwrap();
std::fs::rename(dir.join("ui/z.css"), forged.join("z.css")).unwrap();
let refused = content_digest(&dir);
assert!(matches!(refused, Err(TrustError::ControlCharacter(_))));
assert_ne!(refused.ok(), Some(signed));
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn owner_locks_exclude_each_other() {
let home = std::env::temp_dir().join(format!("weft_trust_lock_{}", std::process::id()));
let held = lock_owner(&home, "org.weft.test.lock").unwrap();
let path = home.join("weft/owners/.org.weft.test.lock.lock");
let other = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
assert!(other.try_lock().is_err());
drop(held);
assert!(other.try_lock().is_ok());
std::fs::remove_dir_all(&home).unwrap();
}
#[cfg(target_os = "linux")]
#[test]
fn links_and_special_files_have_no_content_digest() {

View file

@ -15,5 +15,6 @@ ed25519-dalek = { version = "2", features = ["rand_core"] }
sha2 = "0.10"
rand = "0.8"
hex = "0.4"
libc = "0.2"
tar = "0.4"
zstd = "0.13"

View file

@ -20,14 +20,18 @@ fn main() -> anyhow::Result<()> {
print_info(&manifest);
}
Some("install") => {
let usage = "usage: weft-pack install <dir|archive> [--dev]";
let usage = "usage: weft-pack install <dir|archive> [--dev] [--claim-data]";
let dir = args.get(2).context(usage)?;
let mode = match args.get(3).map(String::as_str) {
None => InstallMode::Verified,
Some("--dev") => InstallMode::Development,
Some(other) => anyhow::bail!("unexpected argument '{other}'; {usage}"),
};
install_package(Path::new(dir), mode)?;
let mut mode = InstallMode::Verified;
let mut claim_data = false;
for arg in &args[3..] {
match arg.as_str() {
"--dev" => mode = InstallMode::Development,
"--claim-data" => claim_data = true,
other => anyhow::bail!("unexpected argument '{other}'; {usage}"),
}
}
install_package(Path::new(dir), mode, claim_data)?;
}
Some("uninstall") => {
let app_id = args.get(2).context("usage: weft-pack uninstall <app_id>")?;
@ -109,7 +113,10 @@ fn main() -> anyhow::Result<()> {
" weft-pack install <dir> [--dev] install a package signed by a trusted key"
);
eprintln!(
" (--dev: unsigned development content)"
" (--dev: unsigned development content;"
);
eprintln!(
" --claim-data: adopt app data with no owner)"
);
eprintln!(" weft-pack uninstall <app_id> remove installed package");
eprintln!(" weft-pack list list installed packages");
@ -257,18 +264,32 @@ enum InstallMode {
Development,
}
fn install_package(path: &Path, mode: InstallMode) -> anyhow::Result<()> {
fn install_package(path: &Path, mode: InstallMode, claim_data: bool) -> anyhow::Result<()> {
let root = resolve_install_root()?;
install_package_to(path, &root, mode)
install_into(path, &root, mode, claim_data)
}
#[cfg(test)]
fn install_package_to(path: &Path, store_root: &Path, mode: InstallMode) -> anyhow::Result<()> {
install_into(path, store_root, mode, false)
}
/// Installs the package at `path` into `store_root`. App data that exists
/// for the ID without a recorded owner, as left by an installation that
/// predates owner records, goes to this package's owner only with
/// `claim_data`.
fn install_into(
path: &Path,
store_root: &Path,
mode: InstallMode,
claim_data: bool,
) -> anyhow::Result<()> {
std::fs::create_dir_all(store_root)
.with_context(|| format!("create {}", store_root.display()))?;
if !(path.extension().is_some_and(|e| e == "zst" || e == "tar")
|| path.to_string_lossy().ends_with(".app.tar.zst"))
{
return install_dir(path, store_root, mode);
return install_dir(path, store_root, mode, claim_data);
}
let name = path
.file_name()
@ -279,7 +300,7 @@ fn install_package_to(path: &Path, store_root: &Path, mode: InstallMode) -> anyh
// nothing can be planted in it and nothing is left behind.
let unpacked = private_scratch_dir(store_root, ".unpack")?;
let result = unbundle_package(path, &unpacked)
.and_then(|()| install_dir(&unpacked.join(name), store_root, mode));
.and_then(|()| install_dir(&unpacked.join(name), store_root, mode, claim_data));
let _ = std::fs::remove_dir_all(&unpacked);
result
}
@ -300,11 +321,21 @@ fn private_scratch_dir(parent: &Path, prefix: &str) -> anyhow::Result<PathBuf> {
Ok(dir)
}
fn install_dir(dir: &Path, store_root: &Path, mode: InstallMode) -> anyhow::Result<()> {
fn install_dir(
dir: &Path,
store_root: &Path,
mode: InstallMode,
claim_data: bool,
) -> anyhow::Result<()> {
check_package(dir)?;
let manifest = load_manifest(dir)?;
let app_id = &manifest.package.id;
let dest = store_root.join(app_id);
let data_home = weft_ipc_types::package::data_home()
.context("cannot locate the data home to record who owns the app ID")?;
// Installations and uninstallations of one ID run one at a time, so the
// owner record always describes the package that is placed.
let _lock = weft_ipc_types::trust::lock_owner(&data_home, app_id)?;
// An earlier weft-appd could leave only app data, or an empty directory,
// where the package now goes; move the data to its own location so it
// neither blocks nor joins the package.
@ -329,9 +360,14 @@ fn install_dir(dir: &Path, store_root: &Path, mode: InstallMode) -> anyhow::Resu
".staging-{app_id}-{}",
hex::encode(rand::random::<[u8; 8]>())
));
let admitted = copy_dir(dir, &staging)
// Copied from the resolved source path, which every file opened during
// the copy is checked against.
let admitted = dir
.canonicalize()
.with_context(|| format!("resolve {}", dir.display()))
.and_then(|source| copy_dir(&source, &staging))
.with_context(|| format!("copy {} -> {}", dir.display(), staging.display()))
.and_then(|()| admit(&staging, app_id, mode));
.and_then(|()| admit(&staging, app_id, mode, &data_home, claim_data));
let admission = match admitted {
Ok(admission) => admission,
Err(e) => {
@ -371,7 +407,13 @@ fn place(staging: &Path, dest: &Path, admission: Admission) -> anyhow::Result<()
/// The first installation of an ID records its owner, and every later one
/// must have the same owner. The record is written before the package is
/// placed, so concurrent installations by different owners cannot both win.
fn admit(staged: &Path, app_id: &str, mode: InstallMode) -> anyhow::Result<Admission> {
fn admit(
staged: &Path,
app_id: &str,
mode: InstallMode,
data_home: &Path,
claim_data: bool,
) -> anyhow::Result<Admission> {
use weft_ipc_types::trust::{owner_record_path, read_owner, write_owner};
check_package(staged)?;
let manifest = load_manifest(staged)?;
@ -396,9 +438,7 @@ fn admit(staged: &Path, app_id: &str, mode: InstallMode) -> anyhow::Result<Admis
})?)
}
};
let data_home = weft_ipc_types::package::data_home()
.context("cannot locate the data home to record who owns the app ID")?;
let record = owner_record_path(&data_home, app_id);
let record = owner_record_path(data_home, app_id);
let created_record = match read_owner(&record)? {
Some(existing) if existing == owner => None,
Some(existing) => anyhow::bail!(
@ -406,6 +446,14 @@ fn admit(staged: &Path, app_id: &str, mode: InstallMode) -> anyhow::Result<Admis
its owner, so another publisher or a development build cannot take the ID over"
),
None => {
let data = weft_ipc_types::package::app_data_dir(data_home, app_id);
if std::fs::symlink_metadata(&data).is_ok() && !claim_data {
anyhow::bail!(
"{} holds app data for {app_id} with no recorded owner; install with \
--claim-data to give it to {owner}, or move it aside",
data.display()
);
}
write_owner(&record, owner)?;
Some(record)
}
@ -425,8 +473,22 @@ fn uninstall_package_from(app_id: &str, store_root: &Path) -> anyhow::Result<()>
if !weft_ipc_types::package::is_valid_app_id(app_id) {
anyhow::bail!("'{}' is not a valid app ID", app_id);
}
let data_home = weft_ipc_types::package::data_home();
let _lock = match &data_home {
Some(home) => Some(weft_ipc_types::trust::lock_owner(home, app_id)?),
None => None,
};
let target = store_root.join(app_id);
if !target.exists() {
// An installation interrupted between recording its owner and placing
// the package leaves a record with nothing installed; with no data
// either, it holds the ID for nothing and is released.
if let Some(home) = &data_home
&& release_owner_without_data(home, app_id)
{
println!("released {app_id}, which was not installed");
return Ok(());
}
anyhow::bail!(
"package '{}' is not installed at {}",
app_id,
@ -458,16 +520,23 @@ fn uninstall_package_from(app_id: &str, store_root: &Path) -> anyhow::Result<()>
}
// The owner record keeps the app ID, and the data with it, for its owner
// while the data remains; with no data left, the ID is free again.
if let Some(data_home) = weft_ipc_types::package::data_home()
&& std::fs::symlink_metadata(weft_ipc_types::package::app_data_dir(&data_home, app_id))
.is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound)
{
let _ = std::fs::remove_file(weft_ipc_types::trust::owner_record_path(&data_home, app_id));
if let Some(home) = &data_home {
release_owner_without_data(home, app_id);
}
println!("uninstalled {}", app_id);
Ok(())
}
/// Removes the owner record of `app_id` when the app has no data, and
/// reports whether a record was removed.
fn release_owner_without_data(data_home: &Path, app_id: &str) -> bool {
let no_data =
std::fs::symlink_metadata(weft_ipc_types::package::app_data_dir(data_home, app_id))
.is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound);
no_data
&& std::fs::remove_file(weft_ipc_types::trust::owner_record_path(data_home, app_id)).is_ok()
}
/// Whether a package directory is empty or contains nothing but `data`.
fn only_holds_app_data(package_dir: &Path) -> anyhow::Result<bool> {
let entries = std::fs::read_dir(package_dir)
@ -620,6 +689,7 @@ fn copy_dir(src: &Path, dst: &Path) -> anyhow::Result<()> {
}
fn copy_file(src: &Path, dst: &Path, metadata: &std::fs::Metadata) -> std::io::Result<()> {
let source = open_regular_file(src)?;
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
@ -631,10 +701,36 @@ fn copy_file(src: &Path, dst: &Path, metadata: &std::fs::Metadata) -> std::io::R
#[cfg(not(unix))]
let _ = metadata;
let mut target = options.open(dst)?;
std::io::copy(&mut std::fs::File::open(src)?, &mut target)?;
std::io::copy(&mut &source, &mut target)?;
Ok(())
}
/// Opens `src` for reading only if it is still the regular file it was when
/// listed: the last component is not followed, and on Linux the opened file
/// must be at `src` itself, so a link swapped in for any directory on the way
/// cannot redirect the copy outside the package.
fn open_regular_file(src: &Path) -> std::io::Result<std::fs::File> {
let mut options = std::fs::OpenOptions::new();
options.read(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, libc::O_NOFOLLOW);
let file = options.open(src)?;
let changed =
|| std::io::Error::other(format!("{} changed while it was copied", src.display()));
if !file.metadata()?.is_file() {
return Err(changed());
}
#[cfg(target_os = "linux")]
{
use std::os::fd::AsRawFd;
let opened = std::fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd()))?;
if opened != src {
return Err(changed());
}
}
Ok(file)
}
fn build_image(dir: &Path, out_path: Option<&Path>) -> anyhow::Result<()> {
let manifest = load_manifest(dir)?;
let app_id = &manifest.package.id;
@ -1121,6 +1217,43 @@ mod tests {
let _ = std::fs::remove_dir_all(&home);
}
#[test]
fn uninstall_releases_a_record_left_by_an_interrupted_install() {
let home = temp_root("interrupted");
let store = home.join("store");
let app_id = "org.weft.test.interrupted";
let record = weft_ipc_types::trust::owner_record_path(&home.join("share"), app_id);
weft_ipc_types::trust::write_owner(&record, Owner::Development).unwrap();
let data = weft_ipc_types::package::app_data_dir(&home.join("share"), app_id);
std::fs::create_dir_all(&data).unwrap();
// While data remains the record stays, and uninstall reports nothing
// installed.
assert!(with_home(&home, || uninstall_package_from(app_id, &store)).is_err());
assert!(record.exists());
std::fs::remove_dir_all(&data).unwrap();
with_home(&home, || uninstall_package_from(app_id, &store)).unwrap();
assert!(!record.exists());
let _ = std::fs::remove_dir_all(&home);
}
#[cfg(target_os = "linux")]
#[test]
fn copies_never_follow_links_swapped_in() {
let home = temp_root("swapped");
std::fs::create_dir_all(home.join("outside")).unwrap();
std::fs::write(home.join("outside/secret"), b"secret").unwrap();
std::fs::create_dir_all(home.join("pkg")).unwrap();
let root = home.canonicalize().unwrap();
// A file replaced by a link, and a directory replaced by a link.
std::os::unix::fs::symlink(root.join("outside/secret"), root.join("pkg/file")).unwrap();
std::os::unix::fs::symlink(root.join("outside"), root.join("pkg/dir")).unwrap();
assert!(open_regular_file(&root.join("pkg/file")).is_err());
assert!(open_regular_file(&root.join("pkg/dir/secret")).is_err());
assert!(open_regular_file(&root.join("outside/secret")).is_ok());
let _ = std::fs::remove_dir_all(&home);
}
#[test]
fn uninstall_keeps_app_data_from_the_user_store() {
let home = temp_root("keep");
@ -1263,8 +1396,16 @@ mod tests {
std::fs::create_dir_all(store.join(app_id).join("data")).unwrap();
std::fs::write(store.join(app_id).join("data/x"), "x").unwrap();
with_home(&home, || {
// The moved data has no recorded owner, so it is given to this
// package only when asked.
let unclaimed = with_home(&home, || {
install_package_to(&home.join("src"), &store, InstallMode::Development)
});
let message = format!("{:#}", unclaimed.unwrap_err());
assert!(message.contains("--claim-data"), "{message}");
assert!(!store.join(app_id).join("wapp.toml").exists());
with_home(&home, || {
install_into(&home.join("src"), &store, InstallMode::Development, true)
})
.unwrap();
assert!(store.join(app_id).join("wapp.toml").exists());

View file

@ -20,11 +20,11 @@ Apps access the filesystem only through WASI preopened directories. Each capabil
## Package Signing and Trust
Packages are signed with Ed25519 over their content digest: the SHA-256 of an inventory listing every file in the package except the root `signature.sig`, one `<path>\t<sha-256>` line per file sorted by path. Every file is covered, including the UI. Packages may hold only directories and regular files; a symbolic link or special file makes `weft-pack check`, `sign`, `verify` and `install` refuse the package. The committed demo signatures verify under this rule.
Packages are signed with Ed25519 over their content digest: the SHA-256 of an inventory listing every file in the package except the root `signature.sig`, one `<path>\t<sha-256>` line per file sorted by path. Every file is covered, including the UI. Names must be UTF-8 without control characters, so no name can imitate other inventory lines. Packages may hold only directories and regular files; a symbolic link or special file makes `weft-pack check`, `sign`, `verify` and `install` refuse the package. The committed demo signatures verify under this rule.
`weft-pack install` admits a package only when its signature verifies with a key in the trust store: `*.pub` files (64 hex digits) in `$XDG_CONFIG_HOME/weft/trusted-keys` and `/etc/weft/trusted-keys`, or only in `$WEFT_TRUSTED_KEYS` when that is set. A malformed key file is an error, not skipped. An unsigned or untrusted package is refused unless the developer passes `--dev`, which installs it as development content. The package is copied into the store first and checked on that copy, which is then renamed into place, so the bytes that are verified are the bytes that are installed. Installed files take fixed modes, 0644, or 0755 when the source is executable, and directories 0755, so no installed file is writable by other users whatever the source modes were. Archives are unpacked into a fresh private directory in the store, which is always removed.
`weft-pack install` admits a package only when its signature verifies with a key in the trust store: `*.pub` files (64 hex digits) in `$XDG_CONFIG_HOME/weft/trusted-keys` and `/etc/weft/trusted-keys`, or only in `$WEFT_TRUSTED_KEYS` when that is set. A malformed key file is an error, not skipped. An unsigned or untrusted package is refused unless the developer passes `--dev`, which installs it as development content. The package is copied into the store first and checked on that copy, which is then renamed into place, so the bytes that are verified are the bytes that are installed. Files are copied without following links, and on Linux each opened file must be the file the copy listed. Installed files take fixed modes, 0644, or 0755 when the source is executable, and directories 0755, so no installed file is writable by other users whatever the source modes were. Archives are unpacked into a fresh private directory in the store, which is always removed.
The first installation of an app ID records its owner in `$XDG_DATA_HOME/weft/owners/<id>`: the publisher key, or development. Every later installation of that ID must have the same owner, so neither another trusted publisher nor a development build can take over an ID, and with it the app's data. The record survives uninstall while the app's data remains; uninstalling with no data left frees the ID. A record is written under a temporary name and linked into place, so it is never partial, and a record created by an installation that then fails to place its package is removed. The demo key in `examples/keys` is a test fixture, not a signing authority.
The first installation of an app ID records its owner in `$XDG_DATA_HOME/weft/owners/<id>`: the publisher key, or development. Installations and uninstallations of one ID hold a per-ID lock, so the record always describes the package placed. Every later installation of that ID must have the same owner, so neither another trusted publisher nor a development build can take over an ID, and with it the app's data. The record survives uninstall while the app's data remains; uninstalling with no data left frees the ID. App data with no recorded owner, as left by installations from before owner records, is given to a new owner only with `--claim-data`. A record is written under a temporary name and linked into place, so it is never partial, and a record created by an installation that then fails to place its package is removed. A record left by an installation that was killed before placing its package is released by `weft-pack uninstall <id>` once no data remains. The demo key in `examples/keys` is a test fixture, not a signing authority.
Not yet covered: `weft-appd` does not check signatures or owners at launch, so the installed directory is trusted as installed; key revocation, rotation and ownership transfer have no workflow; and capabilities are granted at launch without asking the user, independently of the signature.