| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | | pub mod roles; |
| 6 | | pub mod totp; |
| 7 | | pub mod viewer; |
| 8 | |
|
| 9 | | pub use roles::{Access, Role}; |
| 10 | | pub use viewer::{Viewer, ViewerAccount}; |
| 11 | |
|
| 12 | | use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString}; |
| 13 | | use argon2::Argon2; |
| 14 | | use rand::RngCore; |
| 15 | | use std::path::Path; |
| 16 | | use subtle::ConstantTimeEq; |
| 17 | |
|
| 18 | |
|
| 19 | | #[derive(Clone)] |
| 20 | | pub struct CookieKey([u8; 32]); |
| 21 | |
|
| 22 | | impl CookieKey { |
| 23 | 196× | pub fn load_or_create(keys: &Path) -> anyhow::Result<CookieKey> { |
| 24 | 196× | std::fs::create_dir_all(keys)?; |
| 25 | 196× | let path = keys.join("cookie.key"); |
| 26 | 196× | if let Ok(bytes) = std::fs::read(&path) { |
| 27 | 1× | if bytes.len() == 32 { |
| 28 | 1× | return Ok(CookieKey(bytes.try_into().unwrap())); |
| 29 | 0× | } |
| 30 | 195× | } |
| 31 | 195× | let mut k = [0u8; 32]; |
| 32 | 195× | rand::rngs::OsRng.fill_bytes(&mut k); |
| 33 | 195× | std::fs::write(&path, k)?; |
| 34 | | #[cfg(unix)] |
| 35 | | { |
| 36 | | use std::os::unix::fs::PermissionsExt; |
| 37 | 195× | std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?; |
| 38 | | } |
| 39 | 195× | Ok(CookieKey(k)) |
| 40 | 196× | } |
| 41 | |
|
| 42 | | |
| 43 | 1172× | pub fn mac(&self, message: &[u8]) -> String { |
| 44 | 1172× | hex::encode(blake3::keyed_hash(&self.0, message).as_bytes()) |
| 45 | 1172× | } |
| 46 | | } |
| 47 | |
|
| 48 | |
|
| 49 | 1951× | pub fn mac_equal(a: &str, b: &str) -> bool { |
| 50 | 1951× | a.len() == b.len() && a.as_bytes().ct_eq(b.as_bytes()).into() |
| 51 | 1951× | } |
| 52 | |
|
| 53 | 130× | pub fn hash_password(password: &str) -> anyhow::Result<String> { |
| 54 | 130× | let salt = SaltString::generate(&mut rand::rngs::OsRng); |
| 55 | 130× | Ok(Argon2::default().hash_password(password.as_bytes(), &salt).map_err(|e| anyhow::anyhow!("{e}"))?.to_string()) |
| 56 | 130× | } |
| 57 | |
|
| 58 | 19× | pub fn verify_password(hash: &str, password: &str) -> bool { |
| 59 | 19× | match PasswordHash::new(hash) { |
| 60 | 18× | Ok(parsed) => Argon2::default().verify_password(password.as_bytes(), &parsed).is_ok(), |
| 61 | 1× | Err(_) => false, |
| 62 | | } |
| 63 | 19× | } |
| 64 | |
|
| 65 | |
|
| 66 | 133× | pub fn password_ok(password: &str) -> Result<(), &'static str> { |
| 67 | 133× | if password.chars().count() < 10 { |
| 68 | 2× | return Err("a password is at least 10 characters"); |
| 69 | 131× | } |
| 70 | 131× | if password.len() > 256 { |
| 71 | 0× | return Err("a password is at most 256 bytes"); |
| 72 | 131× | } |
| 73 | 131× | Ok(()) |
| 74 | 133× | } |
| 75 | |
|
| 76 | 877× | pub fn random_hex(bytes: usize) -> String { |
| 77 | 877× | let mut b = vec![0u8; bytes]; |
| 78 | 877× | rand::rngs::OsRng.fill_bytes(&mut b); |
| 79 | 877× | hex::encode(b) |
| 80 | 877× | } |
| 81 | |
|
| 82 | |
|
| 83 | |
|
| 84 | 42× | pub fn new_token() -> (String, String) { |
| 85 | 42× | let secret = format!("oxyhub_{}", random_hex(32)); |
| 86 | 42× | (secret.clone(), token_hash(&secret)) |
| 87 | 42× | } |
| 88 | |
|
| 89 | 3678× | pub fn token_hash(secret: &str) -> String { |
| 90 | 3678× | hex::encode(blake3::hash(secret.as_bytes()).as_bytes()) |
| 91 | 3678× | } |
| 92 | |
|
| 93 | |
|
| 94 | |
|
| 95 | 139× | pub fn new_session_id() -> String { |
| 96 | 139× | random_hex(32) |
| 97 | 139× | } |
| 98 | |
|
| 99 | |
|
| 100 | |
|
| 101 | |
|
| 102 | |
|
| 103 | |
|
| 104 | 21× | pub fn pending_login(key: &CookieKey, username: &str, session_salt: &str, until: i64) -> String { |
| 105 | 21× | format!("{until}.{}", key.mac(format!("pending-login:{username}:{session_salt}:{until}").as_bytes())) |
| 106 | 21× | } |
| 107 | |
|
| 108 | |
|
| 109 | 2× | pub fn pending_login_ok(key: &CookieKey, username: &str, session_salt: &str, token: &str, now: i64) -> bool { |
| 110 | 2× | let Some((until, _)) = token.split_once('.') else { return false }; |
| 111 | 2× | let Ok(until) = until.parse::<i64>() else { return false }; |
| 112 | 2× | until > now && mac_equal(token, &pending_login(key, username, session_salt, until)) |
| 113 | 2× | } |
| 114 | |
|
| 115 | |
|
| 116 | 1068× | pub fn csrf_token(key: &CookieKey, session_value: &str) -> String { |
| 117 | 1068× | key.mac(format!("csrf:{session_value}").as_bytes()) |
| 118 | 1068× | } |
| 119 | |
|
| 120 | | pub const SESSION_COOKIE: &str = "oxyhub"; |
| 121 | |
|
| 122 | | #[cfg(test)] |
| 123 | | mod tests { |
| 124 | | use super::*; |
| 125 | |
|
| 126 | | #[test] |
| 127 | 1× | fn passwords_and_tokens() { |
| 128 | 1× | let h = hash_password("correct horse battery").unwrap(); |
| 129 | 1× | assert!(verify_password(&h, "correct horse battery")); |
| 130 | 1× | assert!(!verify_password(&h, "wrong")); |
| 131 | 1× | assert!(!verify_password("garbage", "x")); |
| 132 | 1× | assert!(password_ok("short").is_err()); |
| 133 | 1× | let (secret, hash) = new_token(); |
| 134 | 1× | assert!(secret.starts_with("oxyhub_")); |
| 135 | 1× | assert_eq!(token_hash(&secret), hash); |
| 136 | 1× | assert!(mac_equal("ab", "ab") && !mac_equal("ab", "ac") && !mac_equal("a", "ab")); |
| 137 | 1× | } |
| 138 | |
|
| 139 | | #[test] |
| 140 | 1× | fn cookie_key_persists() { |
| 141 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 142 | 1× | let a = CookieKey::load_or_create(dir.path()).unwrap(); |
| 143 | 1× | let b = CookieKey::load_or_create(dir.path()).unwrap(); |
| 144 | 1× | assert_eq!(a.mac(b"x"), b.mac(b"x")); |
| 145 | 1× | let v = new_session_id(); |
| 146 | 1× | assert_eq!(v.len(), 64); |
| 147 | 1× | assert_ne!(v, new_session_id()); |
| 148 | 1× | assert_ne!(csrf_token(&a, &v), csrf_token(&a, "other")); |
| 149 | 1× | } |
| 150 | | } |