Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 56 additions & 7 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,25 @@ jobs:
- target: aarch64-unknown-linux-gnu
os: ubuntu-latest
cross: true
# macOS and Windows build on their own runners rather than by
# cross-compiling. `ring` and `blake3` compile C and assembly, so
# each target needs a C toolchain for *that* target — a Linux host
# feeds them its own `cc`, which does not understand
# `-mmacosx-version-min` or `/arch:AVX512`. Cross-compiling all of
# this from one box does not work, and finding that out at release
# time is expensive.
# The same labels the `cross-platform` job in favonius.yml uses,
# and pinned for the same reason it pins them: `macos-13` was
# retired on 2025-12-04, and a job naming a label that no longer
# resolves does not fail — it queues, for ever, reporting nothing.
# Three real failures once sat behind that for fourteen hours.
# `macos-latest` would move under us the same way.
- target: aarch64-apple-darwin
os: macos-14
- target: x86_64-apple-darwin
os: macos-15-intel # the last x86_64 image; retires autumn 2027
- target: x86_64-pc-windows-msvc
os: windows-latest
steps:
- uses: actions/checkout@v4

Expand All @@ -49,24 +68,47 @@ jobs:
# emits the texts for exactly what is linked into this target's
# binaries, and fails the job rather than write an empty file.
- name: Generate third-party licence notices
shell: bash
run: python3 packaging/gen-attribution.py ${{ matrix.target }} THIRD-PARTY-LICENSES.md

# `shell: bash` on every runner, Windows included: GitHub's Windows
# image ships Git Bash, and one packaging script that works everywhere
# is worth more than three that drift.
- name: Package
shell: bash
run: |
set -euo pipefail
d=favonius-${{ github.ref_name }}-${{ matrix.target }}
exe=""
case "${{ matrix.target }}" in *windows*) exe=".exe" ;; esac
mkdir -p "$d"
cp target/${{ matrix.target }}/release/favonius "$d"/
cp target/${{ matrix.target }}/release/favonius-daemon "$d"/
cp "target/${{ matrix.target }}/release/favonius$exe" "$d"/
cp "target/${{ matrix.target }}/release/favonius-daemon$exe" "$d"/
# `fvn` is an alias, not a second binary: a relative symlink, so it
# resolves wherever the directory is unpacked and costs no extra
# compile time or bytes. Both release targets are Linux and tar
# stores symlinks as symlinks, so it survives the round trip.
ln -s favonius "$d"/fvn
# compile time or bytes. Unix only — creating a symlink on Windows
# needs a privilege the runner does not have, and a copy would be a
# second megabyte pretending to be an alias. Windows users get
# `favonius.exe`.
case "${{ matrix.target }}" in
*windows*) : ;;
*) ln -s favonius "$d"/fvn ;;
esac
cp README.md LICENSE NOTICE SECURITY.md CHANGELOG.md "$d"/
cp THIRD-PARTY-LICENSES.md "$d"/
cp packaging/favonius-daemon.service "$d"/
# A systemd unit is meaningless off Linux, and shipping one is a
# small lie about what this platform's install looks like.
case "${{ matrix.target }}" in
*linux*) cp packaging/favonius-daemon.service "$d"/ ;;
esac
tar czf "$d".tar.gz "$d"
sha256sum "$d".tar.gz > "$d".tar.gz.sha256
# macOS has `shasum`, Linux and Git Bash have `sha256sum`, and
# neither has both.
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "$d".tar.gz > "$d".tar.gz.sha256
else
shasum -a 256 "$d".tar.gz > "$d".tar.gz.sha256
fi

- uses: actions/upload-artifact@v4
with:
Expand All @@ -78,6 +120,13 @@ jobs:
release:
needs: build
runs-on: ubuntu-latest
# Only for a tag. `workflow_dispatch` exists to prove the matrix builds —
# five targets, three operating systems, and the first run of any of them
# is the one that finds the packaging assumption nobody noticed. Attaching
# that to a release would publish something nobody asked to publish, named
# after a branch. A dispatch leaves its artefacts on the run and nothing
# else.
if: startsWith(github.ref, 'refs/tags/')
steps:
- uses: actions/download-artifact@v4
with:
Expand Down
2 changes: 1 addition & 1 deletion crates/ahp-cli/tests/peer_auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ async fn start_daemon_inner(policy: PeerPolicy, identity: SigningIdentity) -> Op
4,
None,
None,
Some(root),
vec![root],
Some(identity),
policy,
)
Expand Down
2 changes: 1 addition & 1 deletion crates/ahp-cli/tests/per_stream_ports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ async fn start_daemon(data_ports: u16) -> Option<Daemon> {
let root = dest_root.clone();
tokio::spawn(async move {
let _ = ahp_daemon::net_receiver::run_protocol_listener(
control, data, 4, range, None, Some(root), None, Default::default(),
control, data, 4, range, None, vec![root], None, Default::default(),
)
.await;
});
Expand Down
31 changes: 23 additions & 8 deletions crates/ahp-daemon/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,17 @@ struct Args {
#[arg(long, default_value_t = 0)]
max_file_size_mb: u64,
/// Confine every transfer destination under this directory. Required
/// unless --allow-any-dest is passed (S1)
#[arg(long)]
dest_root: Option<std::path::PathBuf>,
/// unless --allow-any-dest is passed (S1).
///
/// Repeatable. A machine legitimately exposes several trees — media on
/// one volume, archives on another — and one root can only cover them by
/// being their common ancestor, which is frequently `/`. Confinement that
/// has to widen to `/` to be usable is not confinement, so the flag
/// repeats and a destination must fall under one of the roots given:
///
/// --dest-root /srv/media --dest-root /mnt/archive
#[arg(long = "dest-root")]
dest_roots: Vec<std::path::PathBuf>,

/// Do not listen for TCP fallback transfers.
///
Expand Down Expand Up @@ -279,7 +287,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// host with cron, requiring no key and no --encrypt. The daemon warned
// and continued, which is not enough: the insecure mode was reachable
// by running the documented command line with a flag left off.
if args.dest_root.is_none() && !args.allow_any_dest {
if args.dest_roots.is_empty() && !args.allow_any_dest {
eprintln!(
"favonius-daemon: refusing to start without --dest-root.\n\
\n\
Expand All @@ -289,6 +297,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
\n\
Confine incoming transfers:\n --dest-root /srv/incoming\n\
\n\
The flag repeats if this machine exposes more than one tree:\n\
\x20\x20\x20--dest-root /srv/media --dest-root /mnt/archive\n\
\n\
If you genuinely intend a daemon that accepts arbitrary paths\n\
from any peer that can reach it, say so explicitly:\n --allow-any-dest"
);
Expand Down Expand Up @@ -318,7 +329,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
);
}
if !args.no_tcp_fallback && !args.require_peer_auth && !args.require_grant {
let fb_root = args.dest_root.clone();
// The fallback confines against the first root only: it predates
// multiple roots, carries no manifest, and is disabled outright
// whenever peer authentication or grants are required — which is
// every deployment that would have several.
let fb_root = args.dest_roots.first().cloned();
match tokio::net::TcpListener::bind(control_addr).await {
Ok(l) => {
tokio::spawn(async move {
Expand Down Expand Up @@ -358,10 +373,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
} else {
None
};
let dest_root = args.dest_root.clone();
let dest_roots = args.dest_roots.clone();
tokio::spawn(async move {
if let Err(e) = ahp_daemon::net_receiver::run_protocol_listener(
control_addr, data_addr, max_concurrent, data_port_range, max_file_size, dest_root,
control_addr, data_addr, max_concurrent, data_port_range, max_file_size, dest_roots,
identity, peer_policy,
).await {
tracing::error!("protocol listener failed: {}", e);
Expand All @@ -374,7 +389,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let mut state = AppState::new(if args.max_concurrent > 0 { args.max_concurrent } else { 1024 });
// The filesystem endpoints (used by `favonius sync` to diff against the
// destination) are only enabled when a root confines them.
if let Some(ref root) = args.dest_root {
if let Some(root) = args.dest_roots.first() {
state = state.with_dest_root(root);
}
let listener = TcpListener::bind(&args.listen).await?;
Expand Down
113 changes: 96 additions & 17 deletions crates/ahp-daemon/src/net_receiver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,35 @@ pub(crate) fn confine_dest_path(root: &std::path::Path, dest: &str) -> Result<st
Ok(joined)
}

/// Confine against several roots: the destination must be under one of them.
///
/// A machine legitimately exposes more than one tree — media on one volume,
/// archives on another — and a single confinement root can only cover them by
/// being their common ancestor, which for `/srv/archive` and `/mnt/media` is
/// `/`. That is the opposite of confinement, so the flag repeats instead.
///
/// The first root that accepts the path wins; the error names them all,
/// because "escapes the configured root" is unhelpful when there are three
/// and the reader cannot see which they missed.
pub(crate) fn confine_dest_path_any(
roots: &[std::path::PathBuf],
dest: &str,
) -> Result<std::path::PathBuf, String> {
for root in roots {
if let Ok(path) = confine_dest_path(root, dest) {
return Ok(path);
}
}
Err(format!(
"destination path {dest} is under none of the configured --dest-root directories ({})",
roots
.iter()
.map(|r| r.display().to_string())
.collect::<Vec<_>>()
.join(", ")
))
}

/// Control-plane datagrams routed to one transfer, by `connection_id`.
///
/// `handle_transfer` used to read MANIFEST and FINISH straight off the
Expand Down Expand Up @@ -842,9 +871,14 @@ fn bind_transfer_data_socket(
/// to the bitmap recv thread during transfers. This prevents the bitmap thread
/// from consuming HELLOs intended for the control port.
///
/// `dest_root`, when set, confines every transfer destination under that
/// directory (S1); when unset the daemon honors arbitrary sender-controlled
/// destination paths (a loud warning is logged at startup).
/// `dest_roots`, when non-empty, confines every transfer destination under
/// one of those directories (S1); when empty the daemon honors arbitrary
/// sender-controlled destination paths (a loud warning is logged at startup).
///
/// A list rather than one directory because a machine legitimately exposes
/// several trees — media on one volume, archives on another — and a single
/// root can only cover them by being their common ancestor, which is often
/// `/`. Confinement that has to widen to `/` to be usable is not confinement.
///
/// `identity`, when set, makes the daemon sign every full handshake with its
/// Ed25519 identity key and carry the signature in HELLO_ACK (S5, RFC §12.2)
Expand All @@ -857,27 +891,30 @@ pub async fn run_protocol_listener(
// keeps the daemon serial on the single `data_addr` port.
data_port_range: Option<(u16, u16)>,
max_file_size: Option<u64>,
dest_root: Option<std::path::PathBuf>,
dest_roots: Vec<std::path::PathBuf>,
identity: Option<ahp_crypto::signatures::SigningIdentity>,
peer_policy: crate::peer_auth::PeerPolicy,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// Canonicalize the confinement root once: it must exist, and the
// canonical form is what lexical `starts_with` checks compare against.
let dest_root = match dest_root {
Some(root) => {
let dest_roots: Vec<std::path::PathBuf> = if !dest_roots.is_empty() {
let mut canonical = Vec::with_capacity(dest_roots.len());
for root in dest_roots {
let canon = root.canonicalize().map_err(|e| {
format!("--dest-root {} cannot be canonicalized: {e}", root.display())
})?;
tracing::info!(dest_root = %canon.display(), "destination confinement enabled");
Some(canon)
canonical.push(canon);
}
None => {
canonical
} else {
{
tracing::warn!(
"no --dest-root configured: the daemon accepts ARBITRARY \
destination paths from any peer that can reach the control \
port — set --dest-root to confine incoming transfers"
);
None
Vec::new()
}
};
// Socket family follows the bind address. These were hardcoded to
Expand Down Expand Up @@ -1087,7 +1124,7 @@ split, about (concurrent transfers) x (streams per transfer)",
// HELLO its receive thread saw mid-flight.
let new_tx_accept = new_tx.clone();
// Shared, read-only, for the life of the daemon.
let dest_root = dest_root.map(std::sync::Arc::new);
let dest_roots = std::sync::Arc::new(dest_roots);
let identity = std::sync::Arc::new(identity);
let peer_policy = std::sync::Arc::new(peer_policy);
{
Expand Down Expand Up @@ -1250,7 +1287,7 @@ split, about (concurrent transfers) x (streams per transfer)",
max_file_size,
ticket_key.clone(),
used_tickets.clone(),
dest_root.clone(),
dest_roots.clone(),
identity.clone(),
peer_policy.clone(),
free_data_socks.clone(),
Expand Down Expand Up @@ -1297,7 +1334,7 @@ async fn run_transfer_slot(
max_file_size: Option<u64>,
ticket_key: std::sync::Arc<std::sync::Mutex<ahp_crypto::session_ticket::TicketKey>>,
used_tickets: std::sync::Arc<std::sync::Mutex<ahp_crypto::session_ticket::UsedTicketCache>>,
dest_root: Option<std::sync::Arc<std::path::PathBuf>>,
dest_roots: std::sync::Arc<Vec<std::path::PathBuf>>,
identity: std::sync::Arc<Option<ahp_crypto::signatures::SigningIdentity>>,
peer_policy: std::sync::Arc<crate::peer_auth::PeerPolicy>,
// Where to return the data socket. Returning it is what bounds the
Expand Down Expand Up @@ -1327,7 +1364,7 @@ async fn run_transfer_slot(
max_file_size,
&ticket_key,
&used_tickets,
dest_root.as_deref().map(|p| p.as_path()),
dest_roots.as_slice(),
identity.as_ref().as_ref(),
&peer_policy,
),
Expand Down Expand Up @@ -1895,7 +1932,7 @@ async fn handle_transfer(
max_file_size: Option<u64>,
ticket_key: &std::sync::Arc<std::sync::Mutex<ahp_crypto::session_ticket::TicketKey>>,
used_tickets: &std::sync::Arc<std::sync::Mutex<ahp_crypto::session_ticket::UsedTicketCache>>,
dest_root: Option<&std::path::Path>,
dest_roots: &[std::path::PathBuf],
identity: Option<&ahp_crypto::signatures::SigningIdentity>,
peer_policy: &crate::peer_auth::PeerPolicy,
) -> Result<Option<(u64, SocketAddr)>, Box<dyn std::error::Error + Send + Sync>> {
Expand Down Expand Up @@ -2095,8 +2132,8 @@ async fn handle_transfer(
// Without this the manifest makes the daemon create/truncate/write any
// path it can reach. The rewritten (absolute, confined) path is used by
// every consumer below — resume probes, merkle cache, output file.
if let Some(root) = dest_root {
match confine_dest_path(root, &manifest.dest_path) {
if !dest_roots.is_empty() {
match confine_dest_path_any(dest_roots, &manifest.dest_path) {
Ok(confined) => manifest.dest_path = confined.to_string_lossy().into_owned(),
Err(e) => {
tracing::warn!(error = %e, "rejecting transfer: destination escapes dest-root");
Expand Down Expand Up @@ -3708,7 +3745,8 @@ fn authenticate_ctrl(
mod tests {
use super::{
apply_resume_bitmap, authenticate_ctrl, build_merkle_resume, build_recv_streams,
confine_dest_path, content_fingerprint, decode_resume_bitmap, encode_merkle_cache,
confine_dest_path, confine_dest_path_any, content_fingerprint, decode_resume_bitmap,
encode_merkle_cache,
finalize_transfer, hex, lexical_normalize, local_chunk_index, make_header,
merkle_cache_path, read_merkle_cache, recv_manifest_packet, resume_from_ticket,
should_rotate, validate_manifest, write_chunk,
Expand Down Expand Up @@ -3766,6 +3804,47 @@ mod tests {
);
}

#[test]
fn several_roots_each_admit_their_own_paths() {
// The case the flag became repeatable for: two trees that share no
// useful ancestor.
let media = std::path::PathBuf::from("/srv/media");
let archive = std::path::PathBuf::from("/mnt/archive");
let roots = vec![media.clone(), archive.clone()];

assert_eq!(
confine_dest_path_any(&roots, "show/ep1.mkv").unwrap(),
media.join("show/ep1.mkv")
);
assert_eq!(
confine_dest_path_any(&roots, "/mnt/archive/2024/tape.tar").unwrap(),
archive.join("2024/tape.tar")
);
}

#[test]
fn a_path_under_none_of_the_roots_is_refused_and_the_message_names_them() {
let roots = vec![
std::path::PathBuf::from("/srv/media"),
std::path::PathBuf::from("/mnt/archive"),
];
let err = confine_dest_path_any(&roots, "/etc/cron.d/pwn").unwrap_err();
assert!(err.contains("/srv/media"), "{err}");
assert!(err.contains("/mnt/archive"), "{err}");
}

/// Escapes are still escapes when there are several roots: `..` must not
/// climb out of one root and into another's parent.
#[test]
fn an_escape_is_refused_by_every_root() {
let roots = vec![
std::path::PathBuf::from("/srv/media"),
std::path::PathBuf::from("/mnt/archive"),
];
assert!(confine_dest_path_any(&roots, "../../etc/passwd").is_err());
assert!(confine_dest_path_any(&roots, "/etc/passwd").is_err());
}

#[test]
fn dest_root_rejects_escapes() {
let root = std::path::Path::new("/srv/incoming");
Expand Down
Loading