256 lines
9.2 KiB
Rust
256 lines
9.2 KiB
Rust
use super::{set_mode, DirLock, KEY_FILE, STATE_FILE};
|
|
use crate::error::{AcauaError, AuthFailure, Result};
|
|
use aes_gcm::aead::{rand_core::RngCore, Aead, AeadCore, KeyInit, OsRng};
|
|
use aes_gcm::{Aes256Gcm, Key, Nonce};
|
|
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
|
|
use base64::Engine;
|
|
use sha2::{Digest, Sha256};
|
|
use std::fs::{self, OpenOptions};
|
|
use std::io::Write;
|
|
use std::path::Path;
|
|
|
|
const KEY_LEN: usize = 32;
|
|
const NONCE_LEN: usize = 12;
|
|
|
|
/// AES-256-GCM sealing of small secrets (TOTP seeds and similar).
|
|
pub struct Secrets {
|
|
cipher: Aes256Gcm,
|
|
}
|
|
|
|
impl std::fmt::Debug for Secrets {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
f.write_str("Secrets(<redacted>)")
|
|
}
|
|
}
|
|
|
|
impl Secrets {
|
|
/// Loads the key from `key_file` (e.g. a Docker secret) or from
|
|
/// `<auth_dir>/secret.key`. A new key is generated only when no auth state
|
|
/// exists yet; a missing key next to existing state is an error.
|
|
pub fn open(auth_dir: &Path, key_file: Option<&Path>) -> Result<Secrets> {
|
|
if let Some(path) = key_file {
|
|
let raw = fs::read(path).map_err(|e| {
|
|
if e.kind() == std::io::ErrorKind::NotFound {
|
|
AcauaError::Auth(AuthFailure::KeyMissing)
|
|
} else {
|
|
AcauaError::Io(e)
|
|
}
|
|
})?;
|
|
return Self::from_bytes(&raw);
|
|
}
|
|
let path = auth_dir.join(KEY_FILE);
|
|
match fs::read(&path) {
|
|
Ok(raw) => Self::from_bytes(&raw),
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
|
if auth_dir.join(STATE_FILE).exists() {
|
|
return Err(AuthFailure::KeyMissing.into());
|
|
}
|
|
Self::create_key(auth_dir, &path)
|
|
}
|
|
Err(e) => Err(e.into()),
|
|
}
|
|
}
|
|
|
|
/// First-run key creation, serialized by the dir lock. The key appears
|
|
/// atomically (temp file, fsync, hard link that never overwrites).
|
|
fn create_key(auth_dir: &Path, path: &Path) -> Result<Secrets> {
|
|
let _lock = DirLock::acquire(auth_dir, true)?;
|
|
// Recheck under the lock: another process may have won the race.
|
|
match fs::read(path) {
|
|
Ok(raw) => return Self::from_bytes(&raw),
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
|
Err(e) => return Err(e.into()),
|
|
}
|
|
if auth_dir.join(STATE_FILE).exists() {
|
|
return Err(AuthFailure::KeyMissing.into());
|
|
}
|
|
let mut key = [0u8; KEY_LEN];
|
|
OsRng.fill_bytes(&mut key);
|
|
let tmp = auth_dir.join(format!("{KEY_FILE}.tmp"));
|
|
let _ = fs::remove_file(&tmp);
|
|
let mut opts = OpenOptions::new();
|
|
opts.write(true).create_new(true);
|
|
set_mode(&mut opts, 0o600);
|
|
let mut file = opts.open(&tmp)?;
|
|
let written = file
|
|
.write_all(STANDARD.encode(key).as_bytes())
|
|
.and_then(|_| file.sync_all());
|
|
drop(file);
|
|
let linked = written.and_then(|_| fs::hard_link(&tmp, path));
|
|
let _ = fs::remove_file(&tmp);
|
|
linked?;
|
|
if let Ok(d) = fs::File::open(auth_dir) {
|
|
let _ = d.sync_all();
|
|
}
|
|
Self::from_bytes(&key)
|
|
}
|
|
|
|
/// Accepts the key as raw 32 bytes or as base64 text (whitespace trimmed).
|
|
fn from_bytes(raw: &[u8]) -> Result<Secrets> {
|
|
let key: Vec<u8> = if raw.len() == KEY_LEN {
|
|
raw.to_vec()
|
|
} else {
|
|
let text = std::str::from_utf8(raw)
|
|
.map_err(|_| AuthFailure::KeyInvalid("not raw 32 bytes nor base64 text"))?;
|
|
STANDARD
|
|
.decode(text.trim())
|
|
.map_err(|_| AuthFailure::KeyInvalid("not raw 32 bytes nor base64 text"))?
|
|
};
|
|
if key.len() != KEY_LEN {
|
|
return Err(AuthFailure::KeyInvalid("must be 32 bytes").into());
|
|
}
|
|
Ok(Secrets {
|
|
cipher: Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&key)),
|
|
})
|
|
}
|
|
|
|
/// Returns base64(nonce || ciphertext+tag) with a fresh random nonce.
|
|
pub fn seal(&self, plain: &[u8]) -> Result<String> {
|
|
let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
|
|
let ct = self
|
|
.cipher
|
|
.encrypt(&nonce, plain)
|
|
.map_err(|_| AuthFailure::SealInvalid)?;
|
|
let mut out = nonce.to_vec();
|
|
out.extend_from_slice(&ct);
|
|
Ok(STANDARD.encode(out))
|
|
}
|
|
|
|
pub fn open_sealed(&self, sealed: &str) -> Result<Vec<u8>> {
|
|
let raw = STANDARD
|
|
.decode(sealed.trim())
|
|
.map_err(|_| AuthFailure::SealInvalid)?;
|
|
if raw.len() < NONCE_LEN + 16 {
|
|
return Err(AuthFailure::SealInvalid.into());
|
|
}
|
|
let (nonce, ct) = raw.split_at(NONCE_LEN);
|
|
self.cipher
|
|
.decrypt(Nonce::from_slice(nonce), ct)
|
|
.map_err(|_| AuthFailure::SealInvalid.into())
|
|
}
|
|
}
|
|
|
|
/// URL-safe base64 (no padding) of `bytes` random bytes from the OS CSPRNG.
|
|
/// An OS RNG failure is unrecoverable and aborts, as in `OsRng::fill_bytes`.
|
|
pub fn random_token(bytes: usize) -> String {
|
|
let mut buf = vec![0u8; bytes];
|
|
OsRng.fill_bytes(&mut buf);
|
|
URL_SAFE_NO_PAD.encode(buf)
|
|
}
|
|
|
|
/// Hex SHA-256 of a token; only this digest is ever stored.
|
|
pub fn hash_token(token: &str) -> String {
|
|
Sha256::digest(token.as_bytes())
|
|
.iter()
|
|
.map(|b| format!("{b:02x}"))
|
|
.collect()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::os::unix::fs::PermissionsExt;
|
|
|
|
#[test]
|
|
fn seal_roundtrip_and_tamper_rejected() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let s = Secrets::open(dir.path(), None).unwrap();
|
|
let sealed = s.seal(b"totp-seed").unwrap();
|
|
assert_ne!(sealed, s.seal(b"totp-seed").unwrap(), "nonce must vary");
|
|
assert_eq!(s.open_sealed(&sealed).unwrap(), b"totp-seed");
|
|
|
|
let mut raw = STANDARD.decode(&sealed).unwrap();
|
|
let last = raw.len() - 1;
|
|
raw[last] ^= 1;
|
|
assert!(s.open_sealed(&STANDARD.encode(raw)).is_err());
|
|
assert!(s.open_sealed("not base64!").is_err());
|
|
assert!(s.open_sealed("").is_err());
|
|
let other = Secrets::open(tempfile::tempdir().unwrap().path(), None).unwrap();
|
|
assert!(other.open_sealed(&sealed).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn key_file_created_0600_and_missing_key_with_state_fails() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let a = Secrets::open(dir.path(), None).unwrap();
|
|
let mode = fs::metadata(dir.path().join(KEY_FILE))
|
|
.unwrap()
|
|
.permissions()
|
|
.mode();
|
|
assert_eq!(mode & 0o777, 0o600);
|
|
// Reopen yields the same key.
|
|
let sealed = a.seal(b"x").unwrap();
|
|
assert_eq!(
|
|
Secrets::open(dir.path(), None)
|
|
.unwrap()
|
|
.open_sealed(&sealed)
|
|
.unwrap(),
|
|
b"x"
|
|
);
|
|
|
|
let dir2 = tempfile::tempdir().unwrap();
|
|
fs::write(dir2.path().join(STATE_FILE), r#"{"version":1}"#).unwrap();
|
|
let err = Secrets::open(dir2.path(), None).unwrap_err();
|
|
assert!(matches!(err, AcauaError::Auth(AuthFailure::KeyMissing)));
|
|
assert!(
|
|
!dir2.path().join(KEY_FILE).exists(),
|
|
"must not recreate the key"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn concurrent_first_open_agrees_on_one_key() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let path = dir.path().join("auth");
|
|
let sealed: Vec<(String, Secrets)> = std::thread::scope(|sc| {
|
|
let hs: Vec<_> = (0..8)
|
|
.map(|_| {
|
|
sc.spawn(|| {
|
|
let s = Secrets::open(&path, None).unwrap();
|
|
(s.seal(b"v").unwrap(), s)
|
|
})
|
|
})
|
|
.collect();
|
|
hs.into_iter().map(|h| h.join().unwrap()).collect()
|
|
});
|
|
let reopened = Secrets::open(&path, None).unwrap();
|
|
for (sl, s) in &sealed {
|
|
assert_eq!(reopened.open_sealed(sl).unwrap(), b"v");
|
|
assert_eq!(s.open_sealed(sl).unwrap(), b"v");
|
|
}
|
|
assert!(!path.join("secret.key.tmp").exists());
|
|
}
|
|
|
|
#[test]
|
|
fn external_key_file_is_used_and_validated() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let kf = dir.path().join("docker-secret");
|
|
fs::write(&kf, format!("{}\n", STANDARD.encode([7u8; 32]))).unwrap();
|
|
let s = Secrets::open(dir.path(), Some(&kf)).unwrap();
|
|
assert_eq!(s.open_sealed(&s.seal(b"a").unwrap()).unwrap(), b"a");
|
|
assert!(!dir.path().join(KEY_FILE).exists());
|
|
|
|
fs::write(&kf, "short").unwrap();
|
|
assert!(Secrets::open(dir.path(), Some(&kf)).is_err());
|
|
let missing = dir.path().join("nope");
|
|
assert!(Secrets::open(dir.path(), Some(&missing)).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn tokens_are_random_and_hash_is_stable() {
|
|
assert_ne!(random_token(32), random_token(32));
|
|
assert_eq!(random_token(32).len(), 43);
|
|
assert_eq!(
|
|
hash_token("abc"),
|
|
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
|
|
);
|
|
assert_eq!(
|
|
format!(
|
|
"{:?}",
|
|
Secrets::open(tempfile::tempdir().unwrap().path(), None).unwrap()
|
|
),
|
|
"Secrets(<redacted>)"
|
|
);
|
|
}
|
|
}
|