Token CLI owner check, 0600 pre-created DB, never chmod existing state dir; README updates

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YShymaPrXmc3KYRUg2HMSs
This commit is contained in:
ariandClaude Sonnet 5.5 committed 2026-10-16 10:02:15 -04:00
1 parent f1d659965b
commit 646fbfd46b
5 files changed
+152 -10

No files matched your search

Generated
+1
View File
@@ -2820,6 +2820,7 @@ dependencies = [
"futures",
"hyper-util",
"jiff",
"libc",
"opentelemetry",
"opentelemetry-otlp",
"opentelemetry_sdk",
+1
View File
@@ -22,6 +22,7 @@ futures = "0.3.34"
async-trait = "0.1.92"
anyhow = "1.0.104"
thiserror = "2.0.21"
libc = "0.2"
# HTTP
axum = "0.8.9"
+3 -2
View File
@@ -40,7 +40,7 @@ Startup refuses `auth.enabled = false` on a non-loopback `server.bind`.
All `/api/v1/*` and `/mcp` requests need `Authorization: Bearer <token>`. `/healthz` is public. Tokens are stored hashed (sha256) in SQLite, and the plaintext is shown once.
Run the token CLI **as the service user** so the database keeps the right owner and mode:
Run the token CLI **as the service user** (the unit's `User=skyg`), i.e. `sudo -u <service user> slinuxm token create <name>`. The CLI refuses to run (with the matching `sudo -u <owner> ...` hint) when the effective uid, root included, does not own the database file or, if it does not exist yet, its existing state directory, so it cannot create or modify state owned by another user:
```sh
sudo -u skyg slinuxm token create my-laptop --config /etc/skyg-linux-tracker.toml
@@ -54,6 +54,7 @@ Notes:
- `auth.db_path` must stay under the unit's `StateDirectory` (`/var/lib/skyg-linux-tracker`). The unit uses `ProtectSystem=strict`, so any other location needs a matching `ReadWritePaths=`.
- `token create` needs the state directory to exist, so start the service once first (systemd creates it with the right owner), then run the CLI as `skyg`.
- A state directory the server creates itself is made 0700 and the database file 0600 from creation. An existing directory is never chmod'd; a group/world-accessible one only logs a warning.
## REST
@@ -135,7 +136,7 @@ openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days
curl --cacert cert.pem -H "Authorization: Bearer $TOKEN" https://localhost:9109/api/v1/systemd/units
```
Rotation: replace the files and send `SIGHUP` (`kill -HUP $(pidof slinuxm)`, or `systemctl kill -s HUP <unit>`). New connections get the new certificate; established ones are not dropped. The certificate and key are read as two separate files, so rotation tooling must send SIGHUP only after BOTH are in place; if the pair is unreadable or mismatched (for example the cert was replaced but the key not yet), the old certificate stays, an error is logged, and you send SIGHUP again once the files are consistent. Any intermediate certificates must be in the `cert_file` chain. The TLS listener is HTTP/1.1 only, caps concurrent connections at 1024 and closes connections that send no request header within 30 seconds. SIGHUP is harmless when TLS is disabled (it is logged and ignored). For ACME, point `cert_file` and `key_file` at the client's output (for example certbot's `live/<name>/fullchain.pem` and `privkey.pem`, or the NixOS `security.acme` directory) and send SIGHUP from the renewal hook. For sops-nix or systemd `LoadCredential`, point at the decrypted or credential path (`/run/credentials/<unit>/...`) so the service user needs no access to the original key file.
Rotation: replace the files and send `SIGHUP` (`kill -HUP $(pidof slinuxm)`, or `systemctl kill -s HUP <unit>`). New connections get the new certificate; established ones are not dropped. The certificate and key are read as two separate files, so rotation tooling must send SIGHUP only after BOTH are in place; if the pair is unreadable or mismatched (for example the cert was replaced but the key not yet), the old certificate stays, an error is logged, and you send SIGHUP again once the files are consistent. Any intermediate certificates must be in the `cert_file` chain. Both the TLS and the plain listener are HTTP/1.1 only, share one accept loop, cap concurrent connections at 1024 and close connections that send no request header within 30 seconds. SIGHUP is harmless when TLS is disabled (it is logged and ignored). For ACME, point `cert_file` and `key_file` at the client's output (for example certbot's `live/<name>/fullchain.pem` and `privkey.pem`, or the NixOS `security.acme` directory) and send SIGHUP from the renewal hook. For sops-nix or systemd `LoadCredential`, point at the decrypted or credential path (`/run/credentials/<unit>/...`) so the service user needs no access to the original key file.
## Docker access
+2
View File
@@ -148,6 +148,8 @@ pub async fn verify(pool: &SqlitePool, token: &str) -> Result<bool> {
}
pub async fn run(cmd: TokenCmd, config: &Config) -> Result<()> {
#[cfg(unix)]
crate::db::ensure_token_cli_owner(&config.auth.db_path)?;
let pool = crate::db::open(config).await?;
match cmd {
TokenCmd::Create { name } => {
+145 -8
View File
@@ -14,6 +14,7 @@ pub async fn open(config: &Config) -> Result<SqlitePool> {
if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
create_private_dir(dir)?;
}
precreate_private_file(path)?;
let opts = SqliteConnectOptions::new()
.filename(path)
.create_if_missing(true)
@@ -57,6 +58,9 @@ pub async fn migrate(pool: &SqlitePool) -> Result<()> {
.context("running database migrations")
}
/// Create `dir` (and missing parents) as 0700. A directory that already
/// exists is never chmod'd (it may be systemd's `StateDirectory` or an
/// admin's choice); a group/world-accessible one only draws a warning.
fn create_private_dir(dir: &Path) -> Result<()> {
if dir.exists() {
#[cfg(unix)]
@@ -64,12 +68,8 @@ fn create_private_dir(dir: &Path) -> Result<()> {
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(dir)?.permissions().mode();
if mode & 0o077 != 0 {
if let Err(e) =
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
{
tracing::warn!(dir = %dir.display(), mode = format!("{:o}", mode & 0o777), error = %e,
"state directory is accessible to others and could not be tightened");
}
tracing::warn!(dir = %dir.display(), mode = format!("{:o}", mode & 0o777),
"state directory is accessible to group/others; consider chmod 0700");
}
}
return Ok(());
@@ -85,6 +85,72 @@ fn create_private_dir(dir: &Path) -> Result<()> {
.with_context(|| format!("creating {}", dir.display()))
}
/// Create the database file as 0600 if missing, so it never exists with
/// umask-default permissions (sqlx would create it 0644 under umask 022).
fn precreate_private_file(path: &Path) -> Result<()> {
let mut o = std::fs::OpenOptions::new();
o.write(true).create(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
o.mode(0o600);
}
o.open(path)
.map(drop)
.with_context(|| format!("creating token database {}", path.display()))
}
/// Effective uid of this process.
#[cfg(unix)]
pub fn effective_uid() -> u32 {
// SAFETY: geteuid has no preconditions and cannot fail.
unsafe { libc::geteuid() }
}
/// Pure ownership rule: the caller must own the state it is about to touch.
/// Root gets no exemption: it must not create or modify root-owned state next
/// to a service user's.
pub fn check_owner(euid: u32, owner: u32, path: &Path) -> Result<()> {
if euid == owner {
return Ok(());
}
let who = user_name(owner).unwrap_or_else(|| format!("#{owner}"));
anyhow::bail!(
"{} is owned by uid {owner} but slinuxm is running as uid {euid}; \
run it as the owner instead: sudo -u {who} slinuxm token ...",
path.display()
)
}
fn user_name(uid: u32) -> Option<String> {
let passwd = std::fs::read_to_string("/etc/passwd").ok()?;
passwd.lines().find_map(|l| {
let mut f = l.split(':');
let name = f.next()?;
(f.nth(1)? == uid.to_string()).then(|| name.to_owned())
})
}
/// For the token CLI: refuse to run unless the effective uid owns the
/// database file, or (when it does not exist yet) its existing parent
/// directory. A missing directory is fine; we will create it as ourselves.
#[cfg(unix)]
pub fn ensure_token_cli_owner(db_path: &Path) -> Result<()> {
use std::os::unix::fs::MetadataExt;
let euid = effective_uid();
if let Ok(m) = std::fs::metadata(db_path) {
return check_owner(euid, m.uid(), db_path);
}
let parent = match db_path.parent() {
Some(p) if !p.as_os_str().is_empty() => p,
_ => Path::new("."),
};
match std::fs::metadata(parent) {
Ok(m) => check_owner(euid, m.uid(), parent),
Err(_) => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -120,7 +186,7 @@ mod tests {
}
assert!(tmp.join("state/db.sqlite").exists());
}
// a looser existing dir is tightened on reopen
// a looser existing dir is left alone (warn only), never chmod'd
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
@@ -129,11 +195,82 @@ mod tests {
drop(pool);
open(&c).await.unwrap();
let m = std::fs::metadata(&d).unwrap().permissions().mode();
assert_eq!(m & 0o777, 0o700);
assert_eq!(m & 0o777, 0o755);
}
#[cfg(not(unix))]
drop(pool);
open(&c).await.unwrap();
std::fs::remove_dir_all(tmp).ok();
}
fn tmpdir(tag: &str) -> std::path::PathBuf {
use rand::TryRng;
let mut r = [0u8; 8];
rand::rngs::SysRng.try_fill_bytes(&mut r).unwrap();
let p = std::env::temp_dir().join(format!(
"slinuxm-{tag}-{}",
r.iter().map(|b| format!("{b:02x}")).collect::<String>()
));
std::fs::create_dir_all(&p).unwrap();
p
}
#[cfg(unix)]
#[test]
fn precreated_file_is_0600() {
use std::os::unix::fs::PermissionsExt;
let d = tmpdir("precreate");
let f = d.join("db.sqlite");
precreate_private_file(&f).unwrap();
assert_eq!(
std::fs::metadata(&f).unwrap().permissions().mode() & 0o777,
0o600
);
// An existing file is neither truncated nor re-moded.
std::fs::write(&f, b"keep").unwrap();
precreate_private_file(&f).unwrap();
assert_eq!(std::fs::read(&f).unwrap(), b"keep");
std::fs::remove_dir_all(d).ok();
}
#[cfg(unix)]
#[test]
fn new_dir_is_0700_existing_dir_untouched() {
use std::os::unix::fs::PermissionsExt;
let d = tmpdir("privdir");
let fresh = d.join("a/b");
create_private_dir(&fresh).unwrap();
let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
assert_eq!(mode(&fresh), 0o700);
std::fs::set_permissions(&fresh, std::fs::Permissions::from_mode(0o750)).unwrap();
create_private_dir(&fresh).unwrap();
assert_eq!(mode(&fresh), 0o750);
std::fs::remove_dir_all(d).ok();
}
#[test]
fn owner_check_pure() {
let p = Path::new("/var/lib/x/db.sqlite");
assert!(check_owner(1000, 1000, p).is_ok());
let e = check_owner(0, 1000, p).unwrap_err().to_string();
assert!(e.contains("sudo -u"), "{e}");
assert!(check_owner(1000, 0, p).is_err());
// root is not exempt
assert!(check_owner(0, 5, p).is_err());
}
#[cfg(unix)]
#[test]
fn cli_owner_check_uses_file_then_parent_and_allows_missing_dir() {
let d = tmpdir("owner");
assert!(ensure_token_cli_owner(&d.join("db.sqlite")).is_ok());
assert!(ensure_token_cli_owner(&d.join("missing/db.sqlite")).is_ok());
std::fs::write(d.join("db.sqlite"), b"").unwrap();
assert!(ensure_token_cli_owner(&d.join("db.sqlite")).is_ok());
// A root-owned location seen from a non-root uid fails.
if effective_uid() != 0 {
assert!(ensure_token_cli_owner(Path::new("/usr/db.sqlite")).is_err());
}
std::fs::remove_dir_all(d).ok();
}
}