//! Symmetric protection for the credentials the server stores: provider //! API keys and ssh private keys. The key comes from a 0600 file. use std::io::Write; use std::path::Path; use base64::Engine; use chacha20poly1305::aead::{Aead, KeyInit}; use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce}; use crate::error::AppError; /// The server's secret box. #[derive(Clone)] pub struct Secrets { cipher: ChaCha20Poly1305, sign_key: [u8; 32], } impl Secrets { /// Loads the key at `path`, creating a 32-byte key with mode 0600 /// when the file does not exist. A key file that is neither 32 raw /// bytes nor base64 for 32 bytes is refused. pub fn load_or_create(path: &Path) -> anyhow::Result { let key = if path.exists() { #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)); } let raw = std::fs::read(path)?; decode_key(&raw)? } else { if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } use rand::RngCore; let mut key = [0u8; 32]; rand::rngs::OsRng.fill_bytes(&mut key); let mut options = std::fs::OpenOptions::new(); options.write(true).create_new(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); } let mut file = options.open(path)?; file.write_all(&key)?; key }; use sha2::{Digest, Sha256}; let mut derive = Sha256::new(); derive.update(key); derive.update(b"rhema-together preview signatures"); let sign_key: [u8; 32] = derive.finalize().into(); Ok(Self { cipher: ChaCha20Poly1305::new(Key::from_slice(&key)), sign_key, }) } /// A short, stable signature over `message`. Used to sign preview /// hosts so a preview URL cannot be guessed from a room id alone. pub fn sign(&self, message: &str) -> String { use hmac::{Hmac, Mac}; let mut mac = as Mac>::new_from_slice(&self.sign_key) .expect("hmac accepts any key length"); mac.update(message.as_bytes()); hex::encode(mac.finalize().into_bytes())[..24].to_owned() } /// Encrypts `plaintext` into `base64(nonce || ciphertext)`. pub fn seal(&self, plaintext: &[u8]) -> Result { use rand::RngCore; let mut nonce = [0u8; 12]; rand::rngs::OsRng.fill_bytes(&mut nonce); let ciphertext = self .cipher .encrypt(Nonce::from_slice(&nonce), plaintext) .map_err(|_| AppError::internal("could not encrypt a secret"))?; let mut out = nonce.to_vec(); out.extend_from_slice(&ciphertext); Ok(base64::engine::general_purpose::STANDARD.encode(out)) } /// The inverse of [`Secrets::seal`]. pub fn open(&self, sealed: &str) -> Result, AppError> { let raw = base64::engine::general_purpose::STANDARD .decode(sealed) .map_err(|_| AppError::internal("stored secret is not valid base64"))?; if raw.len() < 13 { return Err(AppError::internal("stored secret is truncated")); } let (nonce, ciphertext) = raw.split_at(12); self.cipher .decrypt(Nonce::from_slice(nonce), ciphertext) .map_err(|_| AppError::internal("stored secret could not be decrypted")) } /// Seals a string. pub fn seal_str(&self, plaintext: &str) -> Result { self.seal(plaintext.as_bytes()) } /// Opens a sealed string as UTF-8. pub fn open_str(&self, sealed: &str) -> Result { String::from_utf8(self.open(sealed)?) .map_err(|_| AppError::internal("stored secret is not UTF-8")) } } fn decode_key(raw: &[u8]) -> anyhow::Result<[u8; 32]> { if raw.len() == 32 { let mut key = [0u8; 32]; key.copy_from_slice(raw); return Ok(key); } let text = String::from_utf8_lossy(raw); let decoded = base64::engine::general_purpose::STANDARD .decode(text.trim()) .map_err(|_| anyhow::anyhow!("secret key file is neither 32 bytes nor base64"))?; if decoded.len() != 32 { anyhow::bail!("secret key must be 32 bytes, found {}", decoded.len()); } let mut key = [0u8; 32]; key.copy_from_slice(&decoded); Ok(key) }