//! A one-time code: RFC 6238 TOTP over RFC 4226 HOTP, and the `otpauth://` //! address an authenticator hands it over in. //! //! ```text //! Totp::parse("otpauth://totp/Site:me?secret=…") the address, checked //! Totp::from_secret(base32) a secret typed by hand (SHA-1, 6 digits, 30 s) //! totp.code_at(unix) the code for that second //! totp.now(unix) the code and the seconds it has left //! totp.to_uri() the address again (what the sealed payload keeps) //! ``` //! //! SHA-1, SHA-256 and SHA-512; 6, 7 or 8 digits; any period from 1 to 300 //! seconds. A counter code (`otpauth://hotp/`) is refused in words: a counter //! kept on several devices drifts apart, and Cotton Keys keeps codes on every //! device of a person. //! //! **Pure**: the clock is the caller's (`unix`), and the secret is wiped on //! the way out. use hmac::{Hmac, Mac}; use zeroize::Zeroizing; /// The hash a code is made with. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Algorithm { Sha1, Sha256, Sha512, } impl Algorithm { pub const fn as_str(self) -> &'static str { match self { Algorithm::Sha1 => "SHA1", Algorithm::Sha256 => "SHA256", Algorithm::Sha512 => "SHA512", } } fn parse(value: &str) -> Option { match value.to_ascii_uppercase().replace('-', "").as_str() { "SHA1" => Some(Algorithm::Sha1), "SHA256" => Some(Algorithm::Sha256), "SHA512" => Some(Algorithm::Sha512), _ => None, } } } /// The longest period a code is kept for, in seconds. pub const PERIOD_MAX: u64 = 300; /// Why a code could not be read or made, in words. Never the secret. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum TotpError { #[error("this is not an otpauth:// address")] NotAnAddress, #[error("this is a counter code (hotp); Cotton Vault keeps time codes only")] CounterCode, #[error("the address has no secret")] NoSecret, #[error("the secret is not base32")] NotBase32, #[error("the code's hash {0:?} is not SHA1, SHA256 or SHA512")] BadAlgorithm(String), #[error("a code is 6, 7 or 8 digits, not {0:?}")] BadDigits(String), #[error("a code's period is 1 to {PERIOD_MAX} seconds, not {0:?}")] BadPeriod(String), } /// A time code's secret and how its codes are made. #[derive(Clone, PartialEq, Eq)] pub struct Totp { secret: Zeroizing>, pub algorithm: Algorithm, pub digits: u32, pub period: u64, /// Who issued it (`issuer=`, else the label's part before `:`). pub issuer: Option, /// The account it is for (the label's part after `:`). pub account: Option, } impl std::fmt::Debug for Totp { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Totp") .field("algorithm", &self.algorithm) .field("digits", &self.digits) .field("period", &self.period) .field("issuer", &self.issuer) .field("account", &self.account) .finish_non_exhaustive() } } /// The code for one second, and how long it stands. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Code { pub code: String, /// Seconds until the next code, 1 to `period`. pub seconds_left: u64, pub period: u64, } impl Totp { /// A secret typed by hand: SHA-1, 6 digits, 30 seconds, the defaults /// every authenticator assumes. pub fn from_secret(base32: &str) -> Result { let secret = base32_decode(base32)?; if secret.is_empty() { return Err(TotpError::NoSecret); } Ok(Totp { secret, algorithm: Algorithm::Sha1, digits: 6, period: 30, issuer: None, account: None }) } /// The raw secret bytes, for vectors and for sealing. pub fn from_bytes(secret: &[u8], algorithm: Algorithm, length: u32, period: u64) -> Result { if secret.is_empty() { return Err(TotpError::NoSecret); } if !(6..=8).contains(&length) { return Err(TotpError::BadDigits(length.to_string())); } if period == 0 || period > PERIOD_MAX { return Err(TotpError::BadPeriod(period.to_string())); } Ok(Totp { secret: Zeroizing::new(secret.to_vec()), algorithm, digits: length, period, issuer: None, account: None }) } /// An `otpauth://totp/…` address, or a bare base32 secret. pub fn parse(text: &str) -> Result { let text = text.trim(); if !text.to_ascii_lowercase().starts_with("otpauth:") { if text.contains("://") { return Err(TotpError::NotAnAddress); } return Totp::from_secret(text); } let address = url::Url::parse(text).map_err(|_| TotpError::NotAnAddress)?; match address.host_str().map(str::to_ascii_lowercase).as_deref() { Some("totp") => {} Some("hotp") => return Err(TotpError::CounterCode), _ => return Err(TotpError::NotAnAddress), } let label = percent_decode(address.path().trim_start_matches('/')); let (label_issuer, account) = match label.split_once(':') { Some((issuer, account)) => (Some(issuer.trim().to_string()), account.trim().to_string()), None => (None, label.trim().to_string()), }; let mut totp = Totp { secret: Zeroizing::new(Vec::new()), algorithm: Algorithm::Sha1, digits: 6, period: 30, issuer: label_issuer, account: None }; if !account.is_empty() { totp.account = Some(account); } let mut secret = None; for (key, value) in address.query_pairs() { match key.to_ascii_lowercase().as_str() { "secret" => secret = Some(base32_decode(&value)?), "issuer" if !value.trim().is_empty() => totp.issuer = Some(value.trim().to_string()), "algorithm" => totp.algorithm = Algorithm::parse(&value).ok_or_else(|| TotpError::BadAlgorithm(value.to_string()))?, "digits" => { totp.digits = value.parse().ok().filter(|digits| (6..=8).contains(digits)).ok_or_else(|| TotpError::BadDigits(value.to_string()))?; } "period" => { totp.period = value.parse().ok().filter(|period| (1..=PERIOD_MAX).contains(period)).ok_or_else(|| TotpError::BadPeriod(value.to_string()))?; } _ => {} } } totp.secret = secret.filter(|bytes| !bytes.is_empty()).ok_or(TotpError::NoSecret)?; if totp.issuer.as_deref() == Some("") { totp.issuer = None; } Ok(totp) } /// The secret's bytes, for an export that writes it out (behind the unlock). pub fn secret_bytes(&self) -> &[u8] { &self.secret } /// The code for the second `unix`. pub fn code_at(&self, unix: u64) -> String { let value = hotp(&self.secret, unix / self.period, self.digits, self.algorithm); format!("{value:0width$}", width = self.digits as usize) } /// The code for `unix` and the seconds it has left. pub fn now(&self, unix: u64) -> Code { Code { code: self.code_at(unix), seconds_left: self.period - unix % self.period, period: self.period } } /// The address again, unpadded base32, every parameter written out. pub fn to_uri(&self) -> String { let label = match (&self.issuer, &self.account) { (Some(issuer), Some(account)) => format!("{}:{}", percent_encode(issuer), percent_encode(account)), (Some(issuer), None) => percent_encode(issuer), (None, Some(account)) => percent_encode(account), (None, None) => String::new(), }; let mut out = format!( "otpauth://totp/{label}?secret={}&algorithm={}&digits={}&period={}", base32_encode(&self.secret), self.algorithm.as_str(), self.digits, self.period ); if let Some(issuer) = &self.issuer { out.push_str("&issuer="); out.push_str(&percent_encode(issuer)); } out } } /// RFC 4226 HOTP: the truncated HMAC of the counter, `digits` long. pub fn hotp(secret: &[u8], counter: u64, digits: u32, algorithm: Algorithm) -> u32 { let message = counter.to_be_bytes(); let mac: Vec = match algorithm { Algorithm::Sha1 => mac_of::>(secret, &message), Algorithm::Sha256 => mac_of::>(secret, &message), Algorithm::Sha512 => mac_of::>(secret, &message), }; let offset = (mac[mac.len() - 1] & 0x0f) as usize; let binary = u32::from_be_bytes([mac[offset] & 0x7f, mac[offset + 1], mac[offset + 2], mac[offset + 3]]); binary % 10u32.pow(digits) } fn mac_of(secret: &[u8], message: &[u8]) -> Vec { let mut mac = ::new_from_slice(secret).expect("HMAC takes a key of any length"); mac.update(message); mac.finalize().into_bytes().to_vec() } const BASE32: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; /// RFC 4648 base32, any case, spaces, dashes and `=` padding ignored. pub fn base32_decode(text: &str) -> Result>, TotpError> { let mut out = Zeroizing::new(Vec::with_capacity(text.len() * 5 / 8)); let mut buffer: u64 = 0; let mut bits = 0u32; for ch in text.chars() { if ch == ' ' || ch == '-' || ch == '=' || ch == '\t' { continue; } let upper = ch.to_ascii_uppercase() as u8; let value = BASE32.iter().position(|&b| b == upper).ok_or(TotpError::NotBase32)? as u64; buffer = (buffer << 5) | value; bits += 5; if bits >= 8 { bits -= 8; out.push((buffer >> bits) as u8); buffer &= (1 << bits) - 1; } } Ok(out) } /// RFC 4648 base32, upper case, unpadded (what authenticators write). pub fn base32_encode(bytes: &[u8]) -> String { let mut out = String::with_capacity(bytes.len() * 8 / 5 + 1); let mut buffer: u64 = 0; let mut bits = 0u32; for &byte in bytes { buffer = (buffer << 8) | byte as u64; bits += 8; while bits >= 5 { bits -= 5; out.push(BASE32[((buffer >> bits) & 31) as usize] as char); } buffer &= (1 << bits) - 1; } if bits > 0 { out.push(BASE32[((buffer << (5 - bits)) & 31) as usize] as char); } out } fn percent_decode(text: &str) -> String { url::form_urlencoded::parse(format!("x={}", text.replace('+', "%2B")).as_bytes()) .next() .map(|(_, value)| value.into_owned()) .unwrap_or_default() } fn percent_encode(text: &str) -> String { url::form_urlencoded::byte_serialize(text.as_bytes()).collect::().replace('+', "%20") } #[cfg(test)] #[path = "totp_tests.rs"] mod tests;