222 lines
7.8 KiB
Rust
222 lines
7.8 KiB
Rust
//! TOTP (RFC 6238) and HOTP (RFC 4226) on RustCrypto's HMAC, and `otpauth://` URIs.
|
|
//!
|
|
//! ```
|
|
//! use custos_totp::Totp;
|
|
//! let t = Totp::parse("otpauth://totp/GitHub:mark?secret=JBSWY3DPEHPK3PXP&issuer=GitHub")?;
|
|
//! assert_eq!(t.code_at(1_700_000_000).len(), 6);
|
|
//! # Ok::<(), custos_totp::TotpError>(())
|
|
//! ```
|
|
|
|
use data_encoding::BASE32_NOPAD;
|
|
use hmac::{Hmac, KeyInit, Mac};
|
|
use percent_encoding::{NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
|
|
use std::fmt;
|
|
use zeroize::Zeroizing;
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum Algorithm {
|
|
Sha1,
|
|
Sha256,
|
|
Sha512,
|
|
}
|
|
|
|
impl Algorithm {
|
|
fn name(self) -> &'static str {
|
|
match self {
|
|
Algorithm::Sha1 => "SHA1",
|
|
Algorithm::Sha256 => "SHA256",
|
|
Algorithm::Sha512 => "SHA512",
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct TotpError(String);
|
|
|
|
impl fmt::Display for TotpError {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
f.write_str(&self.0)
|
|
}
|
|
}
|
|
|
|
impl std::error::Error for TotpError {}
|
|
|
|
fn err<T>(msg: &str) -> Result<T, TotpError> {
|
|
Err(TotpError(msg.into()))
|
|
}
|
|
|
|
fn mac(alg: Algorithm, key: &[u8], msg: &[u8]) -> Vec<u8> {
|
|
// HMAC accepts keys of any length; `new_from_slice` cannot fail for it.
|
|
match alg {
|
|
Algorithm::Sha1 => {
|
|
let mut m = <Hmac<sha1::Sha1> as KeyInit>::new_from_slice(key).expect("any key length");
|
|
m.update(msg);
|
|
m.finalize().into_bytes().to_vec()
|
|
}
|
|
Algorithm::Sha256 => {
|
|
let mut m = <Hmac<sha2::Sha256> as KeyInit>::new_from_slice(key).expect("any key length");
|
|
m.update(msg);
|
|
m.finalize().into_bytes().to_vec()
|
|
}
|
|
Algorithm::Sha512 => {
|
|
let mut m = <Hmac<sha2::Sha512> as KeyInit>::new_from_slice(key).expect("any key length");
|
|
m.update(msg);
|
|
m.finalize().into_bytes().to_vec()
|
|
}
|
|
}
|
|
}
|
|
|
|
/// RFC 4226: HMAC of the 8-byte big-endian counter, dynamic truncation, `digits` decimal digits.
|
|
pub fn hotp(secret: &[u8], counter: u64, digits: u32, alg: Algorithm) -> String {
|
|
let h = mac(alg, secret, &counter.to_be_bytes());
|
|
let off = (h[h.len() - 1] & 0x0f) as usize;
|
|
let bin = u32::from_be_bytes([h[off] & 0x7f, h[off + 1], h[off + 2], h[off + 3]]);
|
|
format!("{:0width$}", bin % 10u32.pow(digits), width = digits as usize)
|
|
}
|
|
|
|
/// A TOTP generator. The secret is wiped on drop and never printed.
|
|
#[derive(Clone)]
|
|
pub struct Totp {
|
|
secret: Zeroizing<Vec<u8>>,
|
|
algorithm: Algorithm,
|
|
digits: u32,
|
|
period: u64,
|
|
issuer: Option<String>,
|
|
account: Option<String>,
|
|
}
|
|
|
|
impl fmt::Debug for Totp {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
f.debug_struct("Totp")
|
|
.field("secret", &"[redacted]")
|
|
.field("algorithm", &self.algorithm)
|
|
.field("digits", &self.digits)
|
|
.field("period", &self.period)
|
|
.field("issuer", &self.issuer)
|
|
.finish_non_exhaustive()
|
|
}
|
|
}
|
|
|
|
fn decode_base32(s: &str) -> Result<Zeroizing<Vec<u8>>, TotpError> {
|
|
let clean: Zeroizing<String> = Zeroizing::new(
|
|
s.chars().filter(|c| !c.is_whitespace() && *c != '-' && *c != '=').collect::<String>().to_uppercase(),
|
|
);
|
|
if clean.is_empty() {
|
|
return err("the 2FA secret is empty");
|
|
}
|
|
BASE32_NOPAD
|
|
.decode(clean.as_bytes())
|
|
.map(Zeroizing::new)
|
|
.map_err(|_| TotpError("the 2FA secret is not valid base32".into()))
|
|
}
|
|
|
|
impl Totp {
|
|
/// `digits` 6..=8, `period` in seconds (at least 1).
|
|
pub fn new(secret: Vec<u8>, algorithm: Algorithm, digits: u32, period: u64) -> Result<Totp, TotpError> {
|
|
if !(6..=8).contains(&digits) {
|
|
return err("a 2FA code has 6 to 8 digits");
|
|
}
|
|
if period == 0 {
|
|
return err("the 2FA period must be at least one second");
|
|
}
|
|
if secret.is_empty() {
|
|
return err("the 2FA secret is empty");
|
|
}
|
|
Ok(Totp { secret: Zeroizing::new(secret), algorithm, digits, period, issuer: None, account: None })
|
|
}
|
|
|
|
/// An `otpauth://totp/…` URI, or a bare base32 secret (spaces, lower case and `=` are fine).
|
|
pub fn parse(input: &str) -> Result<Totp, TotpError> {
|
|
let input = input.trim();
|
|
let Some(rest) = input.strip_prefix("otpauth://") else {
|
|
return Totp::new(decode_base32(input)?.to_vec(), Algorithm::Sha1, 6, 30);
|
|
};
|
|
let Some(rest) = rest.strip_prefix("totp/") else {
|
|
return err("only time-based codes (otpauth://totp) are supported");
|
|
};
|
|
let (label, query) = rest.split_once('?').unwrap_or((rest, ""));
|
|
let label = percent_decode_str(label).decode_utf8_lossy().into_owned();
|
|
let (mut issuer, account) = match label.split_once(':') {
|
|
Some((i, a)) => (Some(i.trim().to_owned()), Some(a.trim().to_owned())),
|
|
None if label.is_empty() => (None, None),
|
|
None => (None, Some(label.trim().to_owned())),
|
|
};
|
|
let (mut secret, mut alg, mut digits, mut period) = (None, Algorithm::Sha1, 6u32, 30u64);
|
|
for pair in query.split('&').filter(|p| !p.is_empty()) {
|
|
let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
|
|
let v = Zeroizing::new(percent_decode_str(v).decode_utf8_lossy().into_owned());
|
|
match k.to_ascii_lowercase().as_str() {
|
|
"secret" => secret = Some(decode_base32(&v)?),
|
|
"issuer" => issuer = Some(v.to_string()),
|
|
"algorithm" => {
|
|
alg = match v.to_ascii_uppercase().as_str() {
|
|
"SHA1" => Algorithm::Sha1,
|
|
"SHA256" => Algorithm::Sha256,
|
|
"SHA512" => Algorithm::Sha512,
|
|
_ => return err("unsupported 2FA algorithm (use SHA1, SHA256 or SHA512)"),
|
|
}
|
|
}
|
|
"digits" => digits = v.parse().map_err(|_| TotpError("digits is not a number".into()))?,
|
|
"period" => period = v.parse().map_err(|_| TotpError("period is not a number".into()))?,
|
|
_ => {}
|
|
}
|
|
}
|
|
let secret = secret.ok_or_else(|| TotpError("the otpauth URI has no secret".into()))?;
|
|
let mut t = Totp::new(secret.to_vec(), alg, digits, period)?;
|
|
t.issuer = issuer.filter(|s| !s.is_empty());
|
|
t.account = account.filter(|s| !s.is_empty());
|
|
Ok(t)
|
|
}
|
|
|
|
/// The code for Unix time `unix_secs`.
|
|
pub fn code_at(&self, unix_secs: u64) -> String {
|
|
hotp(&self.secret, unix_secs / self.period, self.digits, self.algorithm)
|
|
}
|
|
|
|
/// Seconds until the code at `unix_secs` changes (1..=period).
|
|
pub fn seconds_left(&self, unix_secs: u64) -> u64 {
|
|
self.period - unix_secs % self.period
|
|
}
|
|
|
|
pub fn to_uri(&self) -> String {
|
|
let enc = |s: &str| utf8_percent_encode(s, NON_ALPHANUMERIC).to_string();
|
|
let label = match (&self.issuer, &self.account) {
|
|
(Some(i), Some(a)) => format!("{}:{}", enc(i), enc(a)),
|
|
(None, Some(a)) => enc(a),
|
|
(Some(i), None) => enc(i),
|
|
(None, None) => String::new(),
|
|
};
|
|
let mut uri = format!(
|
|
"otpauth://totp/{label}?secret={}&algorithm={}&digits={}&period={}",
|
|
BASE32_NOPAD.encode(&self.secret),
|
|
self.algorithm.name(),
|
|
self.digits,
|
|
self.period
|
|
);
|
|
if let Some(i) = &self.issuer {
|
|
uri.push_str(&format!("&issuer={}", enc(i)));
|
|
}
|
|
uri
|
|
}
|
|
|
|
pub fn issuer(&self) -> Option<&str> {
|
|
self.issuer.as_deref()
|
|
}
|
|
|
|
pub fn account(&self) -> Option<&str> {
|
|
self.account.as_deref()
|
|
}
|
|
|
|
pub fn digits(&self) -> u32 {
|
|
self.digits
|
|
}
|
|
|
|
pub fn period(&self) -> u64 {
|
|
self.period
|
|
}
|
|
|
|
pub fn algorithm(&self) -> Algorithm {
|
|
self.algorithm
|
|
}
|
|
}
|