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:
1 parent
f1d659965b
commit
646fbfd46b
5 files changed
+152
-10
No files matched your search
@@ -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 } => {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user