Add local password-TOTP sessions and scoped revocable MCP tokens

This commit is contained in:
2026-11-17 20:05:28 +01:00
parent 7fe20df34f
commit 9fa0fb81ff
17 changed files with 1804 additions and 27 deletions
+538
View File
@@ -0,0 +1,538 @@
//! Password and TOTP authentication for explicitly provisioned local human users.
use anyhow::{Result, ensure};
use axum::http::StatusCode;
use openssl::{hash::MessageDigest, pkey::PKey, sign::Signer};
use rmm_domain::jobs::hash;
use serde::Deserialize;
use sqlx::PgPool;
use std::{
collections::BTreeSet,
fs::OpenOptions,
io::Read,
os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt},
path::Path,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
use tokio::sync::Semaphore;
use uuid::Uuid;
const SCRYPT_N: u64 = 1 << 17;
const SCRYPT_MAX_MEMORY: u64 = 256 * 1024 * 1024;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct FileConfig {
schema_version: u32,
users: Vec<FileUser>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct FileUser {
username: String,
principal: String,
tenant_id: Uuid,
disabled: bool,
password_scrypt: PasswordHash,
totp_secret_base32: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PasswordHash {
salt_hex: String,
hash_hex: String,
}
#[derive(Clone)]
struct Account {
username: String,
principal: String,
tenant: Uuid,
disabled: bool,
salt: Vec<u8>,
password_hash: Vec<u8>,
secret: Vec<u8>,
}
pub struct LocalAuth {
users: Vec<Account>,
attempts: Mutex<Vec<Vec<Instant>>>,
workers: Arc<Semaphore>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Login {
username: String,
password: String,
totp_code: String,
}
fn username_valid(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 64
&& value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"_.@-".contains(&b))
}
fn decode_secret(value: &str) -> Result<Vec<u8>> {
ensure!(
value.len() == 32,
"TOTP requires exactly 160 bits in unpadded uppercase base32"
);
let mut bytes = Vec::with_capacity(20);
let mut buffer = 0u16;
let mut bits = 0;
for b in value.bytes() {
let digit = match b {
b'A'..=b'Z' => b - b'A',
b'2'..=b'7' => b - b'2' + 26,
_ => anyhow::bail!("Invalid TOTP base32"),
};
buffer = (buffer << 5) | u16::from(digit);
bits += 5;
if bits >= 8 {
bits -= 8;
bytes.push((buffer >> bits) as u8);
buffer &= (1 << bits) - 1;
}
}
ensure!(bytes.len() == 20 && bits == 0, "Invalid TOTP secret length");
Ok(bytes)
}
fn derive_password(password: &[u8], salt: &[u8]) -> Result<[u8; 64]> {
let mut derived = [0; 64];
openssl::pkcs5::scrypt(
password,
salt,
SCRYPT_N,
8,
1,
SCRYPT_MAX_MEMORY,
&mut derived,
)?;
Ok(derived)
}
fn code(secret: &[u8], step: u64) -> Result<u32> {
let key = PKey::hmac(secret)?;
let mut signer = Signer::new(MessageDigest::sha1(), &key)?;
signer.update(&step.to_be_bytes())?;
let mac = signer.sign_to_vec()?;
let offset = usize::from(mac[19] & 15);
let value = u32::from_be_bytes(mac[offset..offset + 4].try_into()?) & 0x7fff_ffff;
Ok(value % 1_000_000)
}
fn matching_step(secret: &[u8], supplied: &str, now: i64) -> Result<Option<i64>> {
if supplied.len() != 6 || !supplied.bytes().all(|b| b.is_ascii_digit()) || now < 30 {
return Ok(None);
}
let current = now / 30;
let mut matched = None;
for step in current - 1..=current + 1 {
let expected = format!("{:06}", code(secret, step as u64)?);
if openssl::memcmp::eq(expected.as_bytes(), supplied.as_bytes()) {
// If adjacent timesteps happen to collide, consume the highest one.
matched = Some(step);
}
}
Ok(matched)
}
impl LocalAuth {
pub fn configured() -> Result<Option<Self>> {
let Some(path) = std::env::var_os("RMM_LOCAL_AUTH_FILE") else {
return Ok(None);
};
let path = Path::new(&path);
ensure!(path.is_absolute(), "Local auth path must be absolute");
let mut file = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW)
.open(path)
.map_err(|_| anyhow::anyhow!("Local authentication file unavailable"))?;
let metadata = file.metadata()?;
ensure!(
metadata.is_file()
&& metadata.uid() == 10001
&& metadata.permissions().mode() & 0o777 == 0o600
&& metadata.nlink() == 1
&& metadata.len() <= 65536,
"Unsafe local authentication file"
);
let mut content = Vec::new();
file.by_ref().take(65537).read_to_end(&mut content)?;
ensure!(
content.len() <= 65536,
"Oversized local authentication file"
);
Self::parse(&content).map(Some)
}
fn parse(content: &[u8]) -> Result<Self> {
let config: FileConfig = serde_json::from_slice(content)
.map_err(|_| anyhow::anyhow!("Invalid local authentication configuration"))?;
ensure!(
config.schema_version == 1 && !config.users.is_empty() && config.users.len() <= 100,
"Invalid local authentication schema or user limit"
);
let mut usernames = BTreeSet::new();
let mut principals = BTreeSet::new();
let mut users = Vec::new();
for user in config.users {
let id = user
.principal
.strip_prefix("local:")
.and_then(|s| Uuid::parse_str(s).ok())
.filter(|id| !id.is_nil() && user.principal == format!("local:{id}"));
ensure!(
id.is_some()
&& !user.tenant_id.is_nil()
&& username_valid(&user.username)
&& usernames.insert(user.username.clone())
&& principals.insert(user.principal.clone()),
"Invalid or duplicate local identity"
);
let salt = hex::decode(&user.password_scrypt.salt_hex)?;
let password_hash = hex::decode(&user.password_scrypt.hash_hex)?;
ensure!(
salt.len() == 32 && password_hash.len() == 64,
"Invalid scrypt credential"
);
users.push(Account {
username: user.username,
principal: user.principal,
tenant: user.tenant_id,
disabled: user.disabled,
salt,
password_hash,
secret: decode_secret(&user.totp_secret_base32)?,
});
}
Ok(Self {
attempts: Mutex::new(vec![vec![]; users.len() + 1]),
users,
workers: Arc::new(Semaphore::new(1)),
})
}
pub fn enabled(&self, principal: &str, tenant: Uuid) -> bool {
self.users
.iter()
.any(|u| !u.disabled && u.principal == principal && u.tenant == tenant)
}
fn limit(&self, index: usize) -> Result<(), StatusCode> {
let mut buckets = self
.attempts
.lock()
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
let attempts = &mut buckets[index];
attempts.retain(|t| t.elapsed() < Duration::from_secs(60));
if attempts.len() >= 6 {
return Err(StatusCode::TOO_MANY_REQUESTS);
}
attempts.push(Instant::now());
Ok(())
}
pub async fn authenticate(
&self,
pool: &PgPool,
input: Login,
) -> Result<crate::auth::Principal, StatusCode> {
if !username_valid(&input.username)
|| input.password.is_empty()
|| input.password.len() > 1024
|| input.totp_code.len() != 6
|| !input.totp_code.bytes().all(|b| b.is_ascii_digit())
{
return Err(StatusCode::UNAUTHORIZED);
}
let index = self.users.iter().position(|u| u.username == input.username);
self.limit(index.unwrap_or(self.users.len()))?;
let permit = self
.workers
.clone()
.try_acquire_owned()
.map_err(|_| StatusCode::TOO_MANY_REQUESTS)?;
// Unknown usernames perform the same expensive derivation against a fixed dummy record.
let account = index.map(|i| self.users[i].clone());
let checking = account.clone().unwrap_or(Account {
username: String::new(),
principal: String::new(),
tenant: Uuid::nil(),
disabled: true,
salt: vec![0; 32],
password_hash: vec![0; 64],
secret: vec![0; 20],
});
let matched = tokio::task::spawn_blocking(move || -> Result<Option<i64>> {
let _permit = permit; // Held until computation ends, including a disconnected HTTP caller.
let password = derive_password(input.password.as_bytes(), &checking.salt)?;
let matches = openssl::memcmp::eq(&password, &checking.password_hash);
let step = matching_step(
&checking.secret,
&input.totp_code,
chrono::Utc::now().timestamp(),
)?;
Ok(step.filter(|_| matches && !checking.disabled))
})
.await
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
let account = account.ok_or(StatusCode::UNAUTHORIZED)?;
let step = matched.ok_or(StatusCode::UNAUTHORIZED)?;
consume(pool, &account, step).await?;
Ok(crate::auth::Principal {
tenant: account.tenant,
name: account.principal,
operator: true,
session_hash: None,
csrf: None,
scopes: None,
testsimulation: false,
identity: None,
tenants: vec![account.tenant],
})
}
}
async fn consume(pool: &PgPool, account: &Account, step: i64) -> Result<(), StatusCode> {
let mut tx = rmm_persistence::tenant_tx(pool, account.tenant)
.await
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
let consumed: bool = sqlx::query_scalar("SELECT local_totp_consume($1,$2,$3)")
.bind(&account.principal)
.bind(hash(&account.secret))
.bind(step)
.fetch_one(&mut *tx)
.await
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
if !consumed {
return Err(StatusCode::UNAUTHORIZED);
}
tx.commit()
.await
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::Utc;
use serde_json::json;
fn sample(principal: &str, tenant: Uuid, password_hash: &str) -> serde_json::Value {
json!({"schema_version":1,"users":[{
"username":"kevin","principal":principal,"tenant_id":tenant,"disabled":false,
"password_scrypt":{"salt_hex":hex::encode([7;32]),"hash_hex":password_hash},
"totp_secret_base32":"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
}]})
}
fn configured(data: &serde_json::Value) -> LocalAuth {
LocalAuth::parse(&serde_json::to_vec(data).unwrap()).unwrap()
}
fn input(password: &str, secret: &[u8]) -> Login {
Login {
username: "kevin".into(),
password: password.into(),
totp_code: format!(
"{:06}",
code(secret, (Utc::now().timestamp() / 30) as u64).unwrap()
),
}
}
#[test]
fn rfc6238_and_strict_adjacent_steps() {
let secret = decode_secret("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ").unwrap();
assert_eq!(secret, b"12345678901234567890");
for (now, expected) in [
(59, 287082),
(1111111109, 81804),
(1111111111, 50471),
(1234567890, 5924),
(2000000000, 279037),
(20000000000, 353130),
] {
let text = format!("{expected:06}");
assert_eq!(code(&secret, (now / 30) as u64).unwrap(), expected);
assert_eq!(matching_step(&secret, &text, now).unwrap(), Some(now / 30));
}
let now = 1_234_567_890;
for offset in [-1, 0, 1] {
let text = format!("{:06}", code(&secret, (now / 30 + offset) as u64).unwrap());
assert_eq!(
matching_step(&secret, &text, now).unwrap(),
Some(now / 30 + offset)
);
}
let old = format!("{:06}", code(&secret, (now / 30 - 2) as u64).unwrap());
assert_eq!(matching_step(&secret, &old, now).unwrap(), None);
for text in ["", "12345", "1234567", "12 456", "123456"] {
assert_eq!(matching_step(&secret, text, now).unwrap(), None);
}
}
#[test]
fn rejects_ambiguous_configuration_and_bounds_rate_limit() {
let p = format!("local:{}", Uuid::new_v4());
let tenant = Uuid::new_v4();
let good = sample(&p, tenant, &hex::encode([1; 64]));
let local = configured(&good);
assert!(local.enabled(&p, tenant));
assert!(!local.enabled(&p, Uuid::new_v4()));
for _ in 0..6 {
assert!(local.limit(0).is_ok());
}
assert_eq!(local.limit(0), Err(StatusCode::TOO_MANY_REQUESTS));
let mut disabled = good.clone();
disabled["users"][0]["disabled"] = json!(true);
assert!(!configured(&disabled).enabled(&p, tenant));
for (key, value) in [
("principal", json!("simulated-testprincipal-a")),
("tenant_id", json!(Uuid::nil())),
("totp_secret_base32", json!("short")),
("username", json!("../kevin")),
] {
let mut bad = good.clone();
bad["users"][0][key] = value;
assert!(LocalAuth::parse(&serde_json::to_vec(&bad).unwrap()).is_err());
}
let mut duplicate = good.clone();
duplicate["users"]
.as_array_mut()
.unwrap()
.push(good["users"][0].clone());
assert!(LocalAuth::parse(&serde_json::to_vec(&duplicate).unwrap()).is_err());
}
#[tokio::test]
#[ignore = "requires isolated PostgreSQL with current migrations"]
async fn local_password_totp_database() {
let admin = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
.await
.unwrap();
let pool = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
.await
.unwrap();
rmm_persistence::verify_application_role(&pool)
.await
.unwrap();
let tenant = Uuid::new_v4();
let p = format!("local:{}", Uuid::new_v4());
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,'local auth test')")
.bind(tenant)
.execute(&admin)
.await
.unwrap();
sqlx::query("INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES($1,$2,'human',ARRAY['inventory:read'])")
.bind(tenant).bind(&p).execute(&admin).await.unwrap();
let password = "isolated unit test password";
let derived = derive_password(password.as_bytes(), &[7; 32]).unwrap();
let data = sample(&p, tenant, &hex::encode(derived));
let local = configured(&data);
let secret = &local.users[0].secret;
let held = local.workers.clone().acquire_owned().await.unwrap();
assert_eq!(
local
.authenticate(&pool, input(password, secret))
.await
.err(),
Some(StatusCode::TOO_MANY_REQUESTS)
);
drop(held);
assert_eq!(
local
.authenticate(&pool, input("wrong password", secret))
.await
.err(),
Some(StatusCode::UNAUTHORIZED)
);
let mut incorrect = input(password, secret);
incorrect.totp_code = "x".repeat(6);
assert_eq!(
local.authenticate(&pool, incorrect).await.err(),
Some(StatusCode::UNAUTHORIZED)
);
let mut wrong_code = input(password, secret);
let current = Utc::now().timestamp();
wrong_code.totp_code = (0..1_000_000)
.map(|n| format!("{n:06}"))
.find(|v| matching_step(secret, v, current).unwrap().is_none())
.unwrap();
assert_eq!(
local.authenticate(&pool, wrong_code).await.err(),
Some(StatusCode::UNAUTHORIZED)
);
let valid_input = input(password, secret);
let consumed_code = valid_input.totp_code.clone();
let valid = local.authenticate(&pool, valid_input).await.unwrap();
assert_eq!(valid.name, p);
assert_eq!(valid.tenant, tenant);
assert!(!valid.testsimulation);
assert!(valid.session_hash.is_none());
assert_eq!(
local
.authenticate(
&pool,
Login {
username: "kevin".into(),
password: password.into(),
totp_code: consumed_code.clone()
}
)
.await
.err(),
Some(StatusCode::UNAUTHORIZED)
);
// Replay remains rejected by the database after constructing a fresh auth provider.
let restarted = configured(&data);
assert_eq!(
restarted
.authenticate(
&pool,
Login {
username: "kevin".into(),
password: password.into(),
totp_code: consumed_code
}
)
.await
.err(),
Some(StatusCode::UNAUTHORIZED)
);
let mut disabled = data.clone();
disabled["users"][0]["disabled"] = json!(true);
assert_eq!(
configured(&disabled)
.authenticate(&pool, input(password, secret))
.await
.err(),
Some(StatusCode::UNAUTHORIZED)
);
let step = Utc::now().timestamp() / 30 + 1;
let a = consume(&pool, &local.users[0], step);
let b = consume(&pool, &local.users[0], step);
let (one, two) = tokio::join!(a, b);
assert_eq!(usize::from(one.is_ok()) + usize::from(two.is_ok()), 1);
assert_eq!(one.err().or(two.err()), Some(StatusCode::UNAUTHORIZED));
let foreign = Account {
tenant: Uuid::new_v4(),
..local.users[0].clone()
};
assert_eq!(
consume(&pool, &foreign, step + 1).await,
Err(StatusCode::UNAUTHORIZED)
);
sqlx::query("UPDATE memberships SET revoked_at=now() WHERE tenant_id=$1 AND principal=$2")
.bind(tenant)
.bind(&p)
.execute(&admin)
.await
.unwrap();
assert_eq!(
consume(&pool, &local.users[0], step + 1).await,
Err(StatusCode::UNAUTHORIZED)
);
sqlx::query("UPDATE memberships SET revoked_at=NULL,kind='automation' WHERE tenant_id=$1 AND principal=$2")
.bind(tenant).bind(&p).execute(&admin).await.unwrap();
assert_eq!(
consume(&pool, &local.users[0], step + 1).await,
Err(StatusCode::UNAUTHORIZED)
);
pool.close().await;
admin.close().await;
}
}