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
8 changes: 8 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,14 @@ jobs:
- name: make test
run: make test

- name: Check root PAM audit ownership in a disposable directory
run: |
for test_binary in target/debug/deps/pam_audit_ownership-*; do
if test -x "$test_binary"; then
sudo "$test_binary" --ignored --exact pam_first_log_is_owned_by_store_account
fi
done

- name: Test pacman update checker
run: python3 -m unittest discover -s tests -p test_pam_update_check.py

Expand Down
2 changes: 1 addition & 1 deletion crates/syauth-pam/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ time = { version = "0.3", features = ["formatting", "parsing"] }
thiserror = "2"
# `nix::unistd::geteuid` for the `/run/user/$UID` fallback when
# `XDG_RUNTIME_DIR` is unset (SPEC §8 Risks row).
nix = { version = "0.29", features = ["user"] }
nix = { version = "0.29", features = ["user", "fs"] }

[dev-dependencies]
# Tests bind ephemeral Unix-domain sockets under tempdirs.
Expand Down
48 changes: 46 additions & 2 deletions crates/syauth-pam/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,21 @@
//!
//! Every step is a flat early-return; no helper hides a branch.

use std::{fs::OpenOptions, io::Write, os::unix::net::UnixStream, path::Path, time::Duration};
use std::{
fs::OpenOptions,
io::Write,
os::{
fd::AsRawFd as _,
unix::{
fs::{MetadataExt as _, OpenOptionsExt as _},
net::UnixStream,
},
},
path::Path,
time::Duration,
};

use nix::unistd::{Gid, Uid, fchown};
use syauth_core::{Bond, BondError, BondStatus, BondStore, NONCE_LEN};
use syauth_presenced::{
OUTCOME_REASON_BAD_SIGNATURE, OUTCOME_REASON_BUSY, OUTCOME_REASON_DENIED, OUTCOME_REASON_OK, OUTCOME_REASON_REPLAY,
Expand Down Expand Up @@ -89,6 +102,8 @@ const LAST_LOG_VERB_SUCCESS: &str = "success";
/// `last.log` verb for any failure outcome.
const LAST_LOG_VERB_FAILURE: &str = "failure";

const LAST_LOG_FILE_MODE: u32 = 0o600;

/// Placeholder peer id used in the `last.log` line when authentication
/// failed before a peer could be identified (e.g. empty bond store).
pub const LAST_LOG_UNKNOWN_PEER: &str = "unknown";
Expand Down Expand Up @@ -422,7 +437,20 @@ fn append_last_log(cfg: &Config, outcome: &AuthOutcome) -> std::io::Result<()> {
if let Some(parent) = cfg.last_log_path().parent() {
let _ = std::fs::create_dir_all(parent);
}
let mut f = OpenOptions::new().create(true).append(true).open(cfg.last_log_path())?;
let path = cfg.last_log_path();
let mut options = OpenOptions::new();
options.append(true).mode(LAST_LOG_FILE_MODE).custom_flags(libc::O_NOFOLLOW);
let mut f = match options.create_new(true).open(&path) {
Ok(file) => {
// PAM may run as root before the desktop daemon creates the log.
// Assign only our exclusively created inode, never an existing path.
let owner = std::fs::metadata(&cfg.bond_dir)?;
fchown(file.as_raw_fd(), Some(Uid::from_raw(owner.uid())), Some(Gid::from_raw(owner.gid())))?;
file
}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => options.create_new(false).open(&path)?,
Err(error) => return Err(error),
};
writeln!(f, "{ts} {verb} {peer_id}")?;
Ok(())
}
Expand Down Expand Up @@ -765,6 +793,9 @@ mod tests {
peer_id: "deadbeef".to_string(),
};
append_last_log(&cfg, &outcome).expect("append ok");
// BUG-20261108-audit-ownership: a PAM-first log stays private.
use std::os::unix::fs::MetadataExt as _;
assert_eq!(std::fs::metadata(cfg.last_log_path()).expect("stat").mode() & 0o777, 0o600);
let content = std::fs::read_to_string(cfg.last_log_path()).expect("read");
assert!(content.contains(" success deadbeef"), "got: {content}");
let lines: Vec<_> = content.lines().collect();
Expand All @@ -785,6 +816,19 @@ mod tests {
assert!(content.contains(&format!(" failure {LAST_LOG_UNKNOWN_PEER}")), "got: {content}");
}

/// A user-controlled symlink must not redirect privileged audit writes.
#[test]
fn last_log_rejects_a_symbolic_link() {
let tmp = tempfile::tempdir().expect("tempdir");
let target = tmp.path().join("untouched");
std::fs::write(&target, "original\n").expect("target");
let cfg = Config::for_tests(tmp.path());
std::os::unix::fs::symlink(&target, cfg.last_log_path()).expect("symlink");
let outcome = AuthOutcome::Success { peer_id: "test".into() };
assert!(append_last_log(&cfg, &outcome).is_err());
assert_eq!(std::fs::read_to_string(target).expect("read target"), "original\n");
}

/// first_bonded prefers the first non-revoked peer.
#[test]
fn first_bonded_picks_first_bonded_peer() {
Expand Down
30 changes: 30 additions & 0 deletions crates/syauth-pam/tests/pam_audit_ownership.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//! BUG-20261108-audit-ownership: root-run PAM must not lock out daemon auditing.

use std::{
fs,
os::unix::fs::{MetadataExt as _, chown},
};

use pam_syauth::{auth::authenticate, config::Config};

const STORE_UID: u32 = 65534;
const STORE_GID: u32 = 65534;

// Run explicitly as root against a tempdir; no host PAM stack is accessed.
#[test]
#[ignore = "requires root; run in an isolated container or the CI tempdir test step"]
fn pam_first_log_is_owned_by_store_account() {
assert!(nix::unistd::geteuid().is_root(), "run this test as root");
let store = tempfile::tempdir().expect("store");
chown(store.path(), Some(STORE_UID), Some(STORE_GID)).expect("store owner");
let config = Config::for_tests(store.path());
assert!(!authenticate(&config).is_success());
let log = config.last_log_path();
let metadata = fs::metadata(&log).expect("PAM created log");
assert_eq!((metadata.uid(), metadata.gid()), (STORE_UID, STORE_GID));
assert_eq!(metadata.mode() & 0o777, 0o600);
let first = fs::read_to_string(&log).expect("first record");
assert!(!authenticate(&config).is_success());
assert!(fs::read_to_string(&log).expect("second record").starts_with(&first));
assert_eq!(fs::read_to_string(&log).expect("records").lines().count(), 2);
}
6 changes: 6 additions & 0 deletions docs/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ does not establish that the desktop is advertising or the phone is subscribed.

The intended default desktop store belongs to the desktop account running the daemon. Keep directories private (`0700`) and key files private (`0600`). The shared default path is not a separate store for each Linux account. Changing the daemon's storage flags alone does not change the PAM module's fixed bond directory.

When PAM creates `last.log` before the daemon starts, it uses mode `0600` and
the bond-store directory's owner and group. Existing records are preserved.
For a log created by an older version with root ownership, have an administrator
restore its ownership to the desktop account and its mode to `0600`; upgrading
does not change ownership of existing files.

Android's signing private key is represented by its Keystore alias. It is not a raw Ed25519 seed stored in that TOML file. See [storage boundaries](../explanation/security.md#implementation-and-design) for the difference between a Keystore signing key and the application's bond material.

## PAM socket resolution
Expand Down
58 changes: 58 additions & 0 deletions specs/bugs/BUG-20261108-audit-ownership.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# BUG-20261108-audit-ownership: PAM-first audit files block the user daemon

## Summary

Root-run PAM can create the shared audit file before the desktop user's daemon,
leaving the daemon unable to append transaction records.

## Reproduction

- Method: isolated NixOS KVM guest, PR #7 head `41c262e`.
- Run sudo while Bluetooth is unavailable, then start the installed daemon with
a synthetic signed phone response.
- Evidence: `last.log` becomes `644 root users`; the daemon logs
`audit log open failed; orchestrator will run without audit appends` with
`Permission denied (os error 13)`. Authentication succeeds without its detailed
audit record. Correcting ownership in the guest restores logging.
- Automated regressions: `auth::tests::last_log_append_writes_one_line` and
`crates/syauth-pam/tests/pam_audit_ownership.rs`.

## Expected Behavior

A new PAM audit file is private and owned by the bond-store account, allowing
the desktop daemon to append regardless of startup order. Existing records
survive subsequent PAM calls.

## Actual Behavior

The file inherits the root caller's ownership and the default creation mode.
The later unprivileged daemon cannot open it for append.

## Root Cause Analysis

PAM and the user daemon both append to `last.log`. PAM uses plain `O_CREAT`
without specifying its mode or assigning the bond-store account ownership.
The daemon's mode-on-create cannot change an already existing root-owned file.

## Fix

Create the PAM log exclusively with mode 0600, then assign the newly created
file descriptor the parent directory's UID and GID before writing. Open an
existing file for append without changing its ownership or truncating it.
Reject a final-component symbolic link, including during concurrent creation.
Authentication outcomes and PAM control policy remain unchanged.

## Stressors

PAM starts first; daemon starts first; simultaneous file creation; restrictive
umask; existing records; non-root PAM caller; a different desktop UID; a
symbolic-link destination; missing directory; unwritable directory; ownership
assignment failure; repeated authentication.

## Traceability

- Failing test: `last_log_append_writes_one_line` checks mode 0600.
- Privileged regression: `pam_first_log_is_owned_by_store_account` checks a
disposable account's UID/GID and subsequent appends.
- Fixed in: `crates/syauth-pam/src/auth.rs`.
- No authentication-policy or protocol changes.
1 change: 1 addition & 0 deletions specs/syauth/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -1060,4 +1060,5 @@ These are explicitly **not** part of v0.1 per SPEC §3.3; tracked here so they a

## Changelog

- 2026-11-08: [PAM-first audit ownership regression](../bugs/BUG-20261108-audit-ownership.md): private creation owned by the bond-store account, with a privileged tempdir regression test.
- 2026-05-14: Initial roadmap drafted from SPEC.md by `/roadmap`. All items pending.
Loading