use crate::error::{Error, Result};
pub const USER_VAR: &str = "ECLIPSE_WEB_USER";
pub const HASH_VAR: &str = "ECLIPSE_WEB_PASSWORD_HASH";
pub const ITERATIONS: u32 = 600_000;
pub const SCHEME: &str = "pbkdf2-sha256";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Stored {
pub iterations: u32,
pub salt: Vec<u8>,
pub digest: Vec<u8>,
}
impl Stored {
pub fn hash(password: &str) -> Result<Stored> {
let mut salt = vec![0u8; 16];
getrandom::getrandom(&mut salt)
.map_err(|e| Error::Config(format!("cannot read a random salt: {e}")))?;
let digest = derive(password, &salt, ITERATIONS)?;
Ok(Stored {
iterations: ITERATIONS,
salt,
digest,
})
}
pub fn parse(text: &str) -> std::result::Result<Stored, String> {
let text = text.trim();
let mut parts = text.split('$');
let (Some(scheme), Some(iterations), Some(salt), Some(digest), None) = (
parts.next(),
parts.next(),
parts.next(),
parts.next(),
parts.next(),
) else {
return Err(format!(
"expected {SCHEME}$<iterations>$<salt>$<digest>, got {} field(s)",
text.split('$').count()
));
};
if scheme != SCHEME {
return Err(format!(
"unknown scheme {scheme:?}: this build only reads {SCHEME}"
));
}
let iterations: u32 = iterations
.parse()
.map_err(|_| format!("iterations {iterations:?} is not a number"))?;
if !(1_000..=100_000_000).contains(&iterations) {
return Err(format!(
"iterations {iterations} is outside 1,000–100,000,000: a hash nobody can afford to \
check, or one nobody needs to"
));
}
let salt = unhex(salt).map_err(|e| format!("salt: {e}"))?;
let digest = unhex(digest).map_err(|e| format!("digest: {e}"))?;
if salt.is_empty() {
return Err(
"salt is empty: a hash without one is a rainbow table with extra steps".into(),
);
}
if digest.len() != 32 {
return Err(format!(
"digest is {} bytes, and PBKDF2-HMAC-SHA256 produces 32",
digest.len()
));
}
Ok(Stored {
iterations,
salt,
digest,
})
}
pub fn verify(&self, password: &str) -> bool {
let Some(count) = std::num::NonZeroU32::new(self.iterations) else {
return false;
};
ring::pbkdf2::verify(
ring::pbkdf2::PBKDF2_HMAC_SHA256,
count,
&self.salt,
password.as_bytes(),
&self.digest,
)
.is_ok()
}
}
impl std::fmt::Display for Stored {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{SCHEME}${}${}${}",
self.iterations,
hex(&self.salt),
hex(&self.digest)
)
}
}
pub fn hash_password(password: &str) -> Result<String> {
Ok(Stored::hash(password)?.to_string())
}
pub fn verify_password(password: &str, stored: &str) -> bool {
match Stored::parse(stored) {
Ok(stored) => stored.verify(password),
Err(_) => false,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Credentials {
Password { user: String, hash: Stored },
Token,
}
impl Credentials {
pub fn resolve(lookup: impl Fn(&str) -> Option<String>) -> std::result::Result<Self, String> {
let hash = lookup(HASH_VAR).filter(|v| !v.trim().is_empty());
let user = lookup(USER_VAR).filter(|v| !v.trim().is_empty());
match (user, hash) {
(None, None) => Ok(Credentials::Token),
(None, Some(_)) => Err(format!(
"{HASH_VAR} is set but {USER_VAR} is not: a password with no username is half a \
login. Run `eclipse web passwd <name>`."
)),
(Some(user), None) => Err(format!(
"{USER_VAR} is {:?} but {HASH_VAR} is not set, so there is no password to check \
it against. Run `eclipse web passwd`.",
user.trim()
)),
(Some(user), Some(hash)) => Ok(Credentials::Password {
user: user.trim().to_string(),
hash: Stored::parse(&hash).map_err(|e| format!("{HASH_VAR}: {e}"))?,
}),
}
}
pub fn mode(&self) -> &'static str {
match self {
Credentials::Password { .. } => "password",
Credentials::Token => "token",
}
}
pub fn check(&self, user: &str, secret: &str, token: &str) -> bool {
if secret.is_empty() {
return false;
}
match self {
Credentials::Password {
user: expected,
hash,
} => {
let user_ok = crate::token::constant_time_eq(user.trim(), expected);
let pass_ok = hash.verify(secret);
user_ok & pass_ok
}
Credentials::Token => crate::token::constant_time_eq(secret.trim(), token),
}
}
}
fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for b in bytes {
out.push(char::from_digit((b >> 4) as u32, 16).unwrap_or('0'));
out.push(char::from_digit((b & 0xf) as u32, 16).unwrap_or('0'));
}
out
}
fn unhex(text: &str) -> std::result::Result<Vec<u8>, String> {
let chars: Vec<char> = text.chars().collect();
if !chars.len().is_multiple_of(2) {
return Err(format!(
"{} hex digits is not a whole number of bytes",
chars.len()
));
}
let mut out = Vec::with_capacity(chars.len() / 2);
for pair in chars.chunks(2) {
let hi = pair[0]
.to_digit(16)
.ok_or_else(|| format!("{:?} is not hex", pair[0]))?;
let lo = pair[1]
.to_digit(16)
.ok_or_else(|| format!("{:?} is not hex", pair[1]))?;
out.push((hi * 16 + lo) as u8);
}
Ok(out)
}
pub fn write_env_vars(path: &std::path::Path, pairs: &[(&str, &str)]) -> Result<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
}
let existing = match std::fs::read_to_string(path) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => return Err(Error::io(path, e)),
};
let mut lines: Vec<String> = existing.lines().map(|l| l.to_string()).collect();
for (key, value) in pairs {
let prefix = format!("{key}=");
let mut found = false;
for line in lines.iter_mut() {
let body = line.trim_start();
let body = body.strip_prefix("export ").unwrap_or(body);
if body.starts_with(&prefix) {
*line = format!("{key}={value}");
found = true;
}
}
if !found {
lines.push(format!("{key}={value}"));
}
}
let mut body = lines.join("\n");
if !body.ends_with('\n') {
body.push('\n');
}
crate::config::write_private(path, &body)
}
fn derive(password: &str, salt: &[u8], iterations: u32) -> Result<Vec<u8>> {
let count = std::num::NonZeroU32::new(iterations)
.ok_or_else(|| Error::Config("zero iterations is not a hash".into()))?;
let mut digest = vec![0u8; 32];
ring::pbkdf2::derive(
ring::pbkdf2::PBKDF2_HMAC_SHA256,
count,
salt,
password.as_bytes(),
&mut digest,
);
Ok(digest)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
let map: BTreeMap<String, String> = pairs
.iter()
.map(|(k, v)| ((*k).to_string(), (*v).to_string()))
.collect();
move |name| map.get(name).cloned()
}
#[test]
fn a_hash_carries_its_own_parameters_and_reads_back() {
let mut stored = Stored::hash("correct horse").unwrap();
assert_eq!(stored.iterations, ITERATIONS);
let text = stored.to_string();
assert!(text.starts_with("pbkdf2-sha256$600000$"), "{text}");
let parsed = Stored::parse(&text).unwrap();
assert_eq!(parsed, stored);
assert!(parsed.verify("correct horse"));
assert!(
!parsed.verify("correct horse "),
"never trimmed, never normalised"
);
stored.iterations = 1_000;
let older = Stored {
digest: derive("hunter2", &stored.salt, 1_000).unwrap(),
..stored
};
assert!(Stored::parse(&older.to_string()).unwrap().verify("hunter2"));
assert!(!Stored::parse(&older.to_string())
.unwrap()
.verify("hunter2!"));
}
#[test]
fn a_salt_makes_two_identical_passwords_hash_differently() {
let a = Stored::hash("same password").unwrap();
let b = Stored::hash("same password").unwrap();
assert_ne!(a.salt, b.salt, "a fresh salt every time");
assert_ne!(a.to_string(), b.to_string());
assert!(a.verify("same password") && b.verify("same password"));
}
#[test]
fn a_hash_this_build_cannot_read_is_refused_by_name() {
let cases = [
("", "field"),
("pbkdf2-sha256$600000$abcd", "field"),
("sha256$600000$aabb$ccdd", "unknown scheme"),
("pbkdf2-sha256$lots$aabb$ccdd", "not a number"),
("pbkdf2-sha256$10$aabb$ccdd", "outside"),
("pbkdf2-sha256$600000$$ccdd", "empty"),
("pbkdf2-sha256$600000$aabb$ccdd", "32"),
("pbkdf2-sha256$600000$aazb$ccdd", "not hex"),
("pbkdf2-sha256$600000$aabb$ccdd$ee", "field"),
];
for (text, needle) in cases {
let err = Stored::parse(text).unwrap_err();
assert!(err.contains(needle), "{text:?} → {err}");
assert!(!verify_password("whatever", text), "{text:?}");
}
}
#[test]
fn credentials_are_password_or_the_old_token_never_a_downgrade() {
assert_eq!(Credentials::resolve(env(&[])).unwrap(), Credentials::Token);
let half = Credentials::resolve(env(&[(USER_VAR, " max ")])).unwrap_err();
assert!(
half.contains(USER_VAR) && half.contains(HASH_VAR) && half.contains("web passwd"),
"{half}"
);
assert!(
half.contains("\"max\""),
"the name is named, and trimmed: {half}"
);
assert!(
Credentials::resolve(env(&[(HASH_VAR, "pbkdf2-sha256$600000$aabb$ccdd")]))
.unwrap_err()
.contains(USER_VAR)
);
let hash = hash_password("s3cret").unwrap();
let creds = Credentials::resolve(env(&[(USER_VAR, "max"), (HASH_VAR, &hash)])).unwrap();
assert_eq!(creds.mode(), "password");
assert_eq!(
creds,
Credentials::Password {
user: "max".into(),
hash: Stored::parse(&hash).unwrap()
}
);
let bad = Credentials::resolve(env(&[(USER_VAR, "max"), (HASH_VAR, "nonsense")]));
assert!(bad.unwrap_err().contains(HASH_VAR));
}
#[test]
fn a_right_pair_signs_in_and_nothing_else_does() {
let hash = hash_password("open sesame").unwrap();
let creds = Credentials::resolve(env(&[(USER_VAR, "max"), (HASH_VAR, &hash)])).unwrap();
assert!(creds.check("max", "open sesame", "token"));
assert!(!creds.check("max", "open sesam", "token"));
assert!(!creds.check("mor", "open sesame", "token"));
assert!(!creds.check("", "open sesame", "token"));
assert!(!creds.check("max", "", "token"));
let token = Credentials::Token;
assert!(token.check("", "the-token", "the-token"));
assert!(token.check("ignored", "the-token", "the-token"));
assert!(!token.check("", "the-toke", "the-token"));
assert_eq!(token.mode(), "token");
}
}