use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use subtle::ConstantTimeEq;
use zeroize::Zeroizing;
use crate::auth::factors::AuthFactors;
use crate::auth::second_factor::SecondFactor;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TotpAlgorithm {
Sha1,
Sha256,
Sha512,
}
impl TotpAlgorithm {
fn uri_name(self) -> &'static str {
match self {
Self::Sha1 => "SHA1",
Self::Sha256 => "SHA256",
Self::Sha512 => "SHA512",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum TotpError {
#[error("a TOTP code is required")]
NotPresented,
#[error("the presented code is not {expected} decimal digits")]
Malformed {
expected: u32,
},
#[error("the enrolled TOTP secret is not valid base32")]
UndecodableSecret,
#[error("the presented code is not valid now")]
NoMatch,
#[error("this code has already been used")]
Replayed,
#[error("the system clock is unreadable, so no TOTP code can be verified")]
ClockUnreadable,
#[error("the TOTP replay guard is unusable")]
GuardPoisoned,
}
pub struct TotpSecret(Zeroizing<Vec<u8>>);
impl TotpSecret {
pub fn from_bytes(bytes: Vec<u8>) -> Self {
Self(Zeroizing::new(bytes))
}
pub fn from_base32(encoded: &str) -> Result<Self, TotpError> {
let normalized: String = encoded
.chars()
.filter(|c| !c.is_whitespace() && *c != '=')
.flat_map(char::to_uppercase)
.collect();
data_encoding::BASE32_NOPAD
.decode(normalized.as_bytes())
.map(Self::from_bytes)
.map_err(|_| TotpError::UndecodableSecret)
}
pub fn generate() -> Self {
use rand_core::RngCore;
let mut bytes = vec![0u8; 20];
rand_core::OsRng.fill_bytes(&mut bytes);
Self::from_bytes(bytes)
}
fn expose(&self) -> &[u8] {
&self.0
}
}
impl std::fmt::Debug for TotpSecret {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("TotpSecret(<redacted>)")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TotpParams {
pub algorithm: TotpAlgorithm,
pub digits: u32,
pub step_secs: u64,
pub skew_steps: u64,
}
impl Default for TotpParams {
fn default() -> Self {
Self {
algorithm: TotpAlgorithm::Sha1,
digits: 6,
step_secs: 30,
skew_steps: 1,
}
}
}
pub trait TimeSource: Send + Sync {
fn unix_seconds(&self) -> Result<u64, TotpError>;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemTimeSource;
impl TimeSource for SystemTimeSource {
fn unix_seconds(&self) -> Result<u64, TotpError> {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.map_err(|_| TotpError::ClockUnreadable)
}
}
fn code_at_counter(secret: &[u8], params: &TotpParams, counter: u64) -> String {
let seconds = counter.saturating_mul(params.step_secs);
let (step, digits) = (params.step_secs, params.digits);
match params.algorithm {
TotpAlgorithm::Sha1 => {
totp_lite::totp_custom::<totp_lite::Sha1>(step, digits, secret, seconds)
}
TotpAlgorithm::Sha256 => {
totp_lite::totp_custom::<totp_lite::Sha256>(step, digits, secret, seconds)
}
TotpAlgorithm::Sha512 => {
totp_lite::totp_custom::<totp_lite::Sha512>(step, digits, secret, seconds)
}
}
}
pub struct TotpFactor {
secret: TotpSecret,
params: TotpParams,
time: Box<dyn TimeSource>,
last_consumed: Mutex<Option<u64>>,
}
impl TotpFactor {
pub fn new(secret: TotpSecret, params: TotpParams, time: Box<dyn TimeSource>) -> Self {
Self {
secret,
params,
time,
last_consumed: Mutex::new(None),
}
}
pub fn with_defaults(secret: TotpSecret) -> Self {
Self::new(secret, TotpParams::default(), Box::new(SystemTimeSource))
}
pub fn enrollment_uri(&self, issuer: &str, account_label: &str) -> String {
let secret = data_encoding::BASE32_NOPAD.encode(self.secret.expose());
format!(
"otpauth://totp/{}:{}?secret={}&issuer={}&algorithm={}&digits={}&period={}",
urlencode(issuer),
urlencode(account_label),
secret,
urlencode(issuer),
self.params.algorithm.uri_name(),
self.params.digits,
self.params.step_secs,
)
}
pub fn check(&self, presented: &str) -> Result<(), TotpError> {
if presented.len() != self.params.digits as usize
|| !presented.bytes().all(|b| b.is_ascii_digit())
{
return Err(TotpError::Malformed {
expected: self.params.digits,
});
}
let now = self.time.unix_seconds()?;
let current = now / self.params.step_secs;
let skew = self.params.skew_steps;
let mut matched: Option<u64> = None;
for counter in current.saturating_sub(skew)..=current.saturating_add(skew) {
let expected = code_at_counter(self.secret.expose(), &self.params, counter);
if bool::from(expected.as_bytes().ct_eq(presented.as_bytes())) {
matched = Some(counter);
}
}
let counter = matched.ok_or(TotpError::NoMatch)?;
let mut guard = self
.last_consumed
.lock()
.map_err(|_| TotpError::GuardPoisoned)?;
if guard.is_some_and(|last| counter <= last) {
return Err(TotpError::Replayed);
}
*guard = Some(counter);
Ok(())
}
}
impl SecondFactor for TotpFactor {
fn name(&self) -> &str {
"TOTP"
}
fn verify(&self, factors: &AuthFactors) -> Result<(), String> {
let Some(presented) = factors.totp.as_deref() else {
return Err(TotpError::NotPresented.to_string());
};
self.check(presented).map_err(|e| e.to_string())
}
}
fn urlencode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}