1use base32;
2use hmac::{Hmac, KeyInit, Mac};
3use sha1::Sha1;
4use sha2::{Sha256, Sha512};
5use std::time::{Duration, SystemTime, SystemTimeError, UNIX_EPOCH};
6use thiserror::Error;
7use url::Url;
8use zeroize::{Zeroize, ZeroizeOnDrop};
9
10use crate::db::Entry;
11
12const DEFAULT_PERIOD: u64 = 30;
13const DEFAULT_DIGITS: u32 = 8;
14const MAX_GENERATED_DIGITS: u32 = 20;
15
16#[derive(Debug, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
18#[non_exhaustive]
19pub enum TOTPAlgorithm {
20 Sha1,
22 Sha256,
24 Sha512,
26}
27
28impl std::str::FromStr for TOTPAlgorithm {
29 type Err = TOTPError;
30
31 fn from_str(s: &str) -> Result<Self, Self::Err> {
32 match s {
33 "SHA1" => Ok(Self::Sha1),
34 "SHA256" => Ok(Self::Sha256),
35 "SHA512" => Ok(Self::Sha512),
36 _ => Err(TOTPError::BadAlgorithm(s.to_string())),
37 }
38 }
39}
40
41#[derive(Debug, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
43pub struct TOTP {
44 pub label: String,
46
47 pub issuer: Option<String>,
49
50 pub period: u64,
52
53 pub digits: u32,
55
56 pub algorithm: TOTPAlgorithm,
58
59 secret: Vec<u8>,
61}
62
63pub struct OTPCode {
65 pub code: String,
67
68 pub valid_for: Duration,
70
71 pub period: Duration,
73}
74
75impl std::fmt::Display for OTPCode {
76 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77 write!(f, "Code: {}, valid for: {}/{}s", self.code, self.valid_for.as_secs(), self.period.as_secs(),)
78 }
79}
80
81#[derive(Debug, Error)]
83#[non_exhaustive]
84pub enum TOTPError {
85 #[error(transparent)]
87 UrlFormat(#[from] url::ParseError),
88
89 #[error(transparent)]
91 IntFormat(#[from] std::num::ParseIntError),
92
93 #[error("Missing TOTP field: {}", _0)]
95 MissingField(&'static str),
96
97 #[error(transparent)]
99 Time(#[from] SystemTimeError),
100
101 #[error("Base32 decoding error")]
103 Base32,
104
105 #[error("No OTP record found")]
107 NoRecord,
108
109 #[error("Bad URL scheme: '{}'", _0)]
111 BadScheme(String),
112
113 #[error("Bad hash algorithm: '{}'", _0)]
115 BadAlgorithm(String),
116}
117
118impl std::str::FromStr for TOTP {
119 type Err = TOTPError;
120
121 fn from_str(s: &str) -> Result<Self, Self::Err> {
122 let parsed = Url::parse(s)?;
123
124 if parsed.scheme() != "otpauth" {
125 return Err(TOTPError::BadScheme(parsed.scheme().to_string()));
126 }
127
128 let label = parsed.path().trim_start_matches('/').to_string();
130
131 let mut secret: Option<String> = None;
132 let mut issuer: Option<String> = None;
133 let mut period = DEFAULT_PERIOD;
134 let mut digits = DEFAULT_DIGITS;
135 let mut algorithm = TOTPAlgorithm::Sha1;
136
137 for (key, value) in parsed.query_pairs() {
138 match key.as_ref() {
139 "secret" => secret = Some(value.to_string()),
140 "issuer" => issuer = Some(value.to_string()),
141 "period" => period = value.parse()?,
142 "digits" => digits = value.parse()?,
143 "algorithm" => algorithm = value.parse()?,
144 _ => {}
145 }
146 }
147
148 let secret = secret.ok_or(TOTPError::MissingField("secret"))?;
149 let secret = base32::decode(base32::Alphabet::Rfc4648 { padding: true }, &secret).ok_or(TOTPError::Base32)?;
150
151 Ok(Self { label, secret, issuer, period, digits, algorithm })
152 }
153}
154
155impl TOTP {
156 fn generate_code(&self, time: u64, digits: u32) -> String {
160 let counter = time / self.period;
161 let counter_bytes = counter.to_be_bytes();
162
163 let hash = match self.algorithm {
164 TOTPAlgorithm::Sha1 => {
165 let mut mac = Hmac::<Sha1>::new_from_slice(&self.secret).unwrap_or_else(|_| unreachable!("HMAC accepts keys of any length"));
166 mac.update(&counter_bytes);
167 mac.finalize().into_bytes().to_vec()
168 }
169 TOTPAlgorithm::Sha256 => {
170 let mut mac = Hmac::<Sha256>::new_from_slice(&self.secret).unwrap_or_else(|_| unreachable!("HMAC accepts keys of any length"));
171 mac.update(&counter_bytes);
172 mac.finalize().into_bytes().to_vec()
173 }
174 TOTPAlgorithm::Sha512 => {
175 let mut mac = Hmac::<Sha512>::new_from_slice(&self.secret).unwrap_or_else(|_| unreachable!("HMAC accepts keys of any length"));
176 mac.update(&counter_bytes);
177 mac.finalize().into_bytes().to_vec()
178 }
179 };
180
181 let offset = (hash.last().copied().unwrap_or_default() & 0x0f) as usize;
182
183 let binary = hash
184 .get(offset..offset + 4)
185 .and_then(|bytes| <&[u8; 4]>::try_from(bytes).ok())
186 .map(|bytes| u32::from_be_bytes(*bytes) & 0x7fff_ffff)
187 .unwrap_or_default();
188
189 let code = if digits >= 10 { u64::from(binary) } else { u64::from(binary) % 10_u64.pow(digits) };
190
191 format!("{code:0width$}", width = digits as usize)
192 }
193
194 pub fn value_at(&self, time: u64) -> OTPCode {
196 let period = Duration::from_secs(self.period);
197
198 if self.period == 0 {
199 return OTPCode { code: String::new(), valid_for: Duration::ZERO, period };
200 }
201
202 let valid_for = Duration::from_secs(self.period - (time % self.period));
203
204 if self.digits == 0 {
205 return OTPCode { code: "0".to_string(), valid_for, period };
206 }
207
208 let digits = self.digits.min(MAX_GENERATED_DIGITS);
209 let code = self.generate_code(time, digits);
210
211 OTPCode { code, valid_for, period }
212 }
213
214 pub fn value_now(&self) -> Result<OTPCode, SystemTimeError> {
216 let time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
217 Ok(self.value_at(time))
218 }
219
220 pub fn get_secret(&self) -> String {
222 base32::encode(base32::Alphabet::Rfc4648 { padding: true }, &self.secret)
223 }
224}
225
226impl Entry {
227 pub fn get_otp(&self) -> Result<TOTP, TOTPError> {
229 self.get_raw_otp_value().ok_or(TOTPError::NoRecord)?.parse()
230 }
231}
232
233#[cfg(test)]
234mod kdbx4_otp_tests {
235 use super::{TOTP, TOTPAlgorithm, TOTPError};
236 use crate::{db::Database, key::DatabaseKey};
237 use std::{fs::File, path::Path};
238
239 #[test]
240 fn kdbx4_entry() -> Result<(), Box<dyn std::error::Error>> {
241 let path = Path::new("tests/resources/test_db_kdbx4_with_totp_entry.kdbx");
242 let db = Database::open(&mut File::open(path)?, DatabaseKey::new().with_password("test"))?;
243
244 let otp_str = "otpauth://totp/KeePassXC:none?secret=JBSWY3DPEHPK3PXP&period=30&digits=6&issuer=KeePassXC";
245
246 let root = db.root();
247 let entry = root.entries().find(|e| e.get_title().is_some_and(|title| title.eq_ignore_ascii_case("this entry has totp"))).unwrap();
248
249 assert_eq!(entry.get_title(), Some("this entry has totp"));
250 assert_eq!(entry.get_raw_otp_value(), Some(otp_str));
251
252 Ok(())
253 }
254
255 #[test]
256 fn totp_default() -> Result<(), TOTPError> {
257 let otp_str = "otpauth://totp/KeePassXC:none?secret=JBSWY3DPEHPK3PXP&period=30&digits=6&issuer=KeePassXC";
258
259 let expected = TOTP {
260 label: "KeePassXC:none".to_string(),
261 secret: b"Hello!\xDE\xAD\xBE\xEF".to_vec(),
262 issuer: Some("KeePassXC".to_string()),
263 period: 30,
264 digits: 6,
265 algorithm: TOTPAlgorithm::Sha1,
266 };
267
268 assert_eq!(otp_str.parse::<TOTP>()?, expected);
269 Ok(())
270 }
271
272 #[test]
273 fn totp_get_secret() -> Result<(), TOTPError> {
274 let otp_str = "otpauth://totp/KeePassXC:none?secret=JBSWY3DPEHPK3PXP&period=30&digits=6&issuer=KeePassXC";
275
276 let otp = otp_str.parse::<TOTP>()?;
277 assert_eq!(otp.get_secret(), "JBSWY3DPEHPK3PXP");
278 Ok(())
279 }
280
281 #[test]
282 fn totp_sha512() -> Result<(), TOTPError> {
283 let otp_str = "otpauth://totp/sha512%20totp:none?secret=GEZDGNBVGY%3D%3D%3D%3D%3D%3D&period=30&digits=6&issuer=sha512%20totp&algorithm=SHA512";
284
285 let expected = TOTP {
286 label: "sha512%20totp:none".to_string(),
287 secret: b"123456".to_vec(),
288 issuer: Some("sha512 totp".to_string()),
289 period: 30,
290 digits: 6,
291 algorithm: TOTPAlgorithm::Sha512,
292 };
293
294 assert_eq!(otp_str.parse::<TOTP>()?, expected);
295 Ok(())
296 }
297
298 #[test]
299 fn totp_value() {
300 let totp = TOTP {
301 label: "KeePassXC:none".to_string(),
302 secret: b"Hello!\xDE\xAD\xBE\xEF".to_vec(),
303 issuer: Some("KeePassXC".to_string()),
304 period: 30,
305 digits: 6,
306 algorithm: TOTPAlgorithm::Sha1,
307 };
308
309 assert_eq!(totp.value_at(1234).code, "806863");
310 }
311
312 #[test]
313 fn totp_zero_period() {
314 let totp = TOTP {
315 label: "KeePassXC:none".to_string(),
316 secret: b"Hello!\xDE\xAD\xBE\xEF".to_vec(),
317 issuer: Some("KeePassXC".to_string()),
318 period: 0,
319 digits: 6,
320 algorithm: TOTPAlgorithm::Sha1,
321 };
322
323 assert_eq!(totp.value_at(1234).code, "");
324 }
325
326 #[test]
327 fn totp_zero_digits() {
328 let totp = TOTP {
329 label: "KeePassXC:none".to_string(),
330 secret: b"Hello!\xDE\xAD\xBE\xEF".to_vec(),
331 issuer: Some("KeePassXC".to_string()),
332 period: 30,
333 digits: 0,
334 algorithm: TOTPAlgorithm::Sha1,
335 };
336
337 assert_eq!(totp.value_at(1234).code, "0");
338 }
339
340 #[test]
341 fn totp_ten_digits() {
342 let totp = TOTP {
343 label: "KeePassXC:none".to_string(),
344 secret: b"Hello!\xDE\xAD\xBE\xEF".to_vec(),
345 issuer: Some(TOTPAlgorithm::Sha1).map(|_| "KeePassXC".to_string()),
346 period: 30,
347 digits: 10,
348 algorithm: TOTPAlgorithm::Sha1,
349 };
350
351 assert_eq!(totp.value_at(1234).code, "0638806863");
352 }
353
354 #[test]
355 fn totp_twentyone_digits() {
356 let totp = TOTP {
357 label: "KeePassXC:none".to_string(),
358 secret: b"Hello!\xDE\xAD\xBE\xEF".to_vec(),
359 issuer: Some(TOTPAlgorithm::Sha1).map(|_| "KeePassXC".to_string()),
360 period: 30,
361 digits: 21,
362 algorithm: TOTPAlgorithm::Sha1,
363 };
364
365 assert_eq!(totp.value_at(1234).code, "00000000000638806863");
366 }
367
368 #[test]
369 fn totp_bad() {
370 assert!(matches!("not a totp string".parse::<TOTP>(), Err(TOTPError::UrlFormat(_))));
371
372 assert!(matches!(
373 "http://totp/sha512%20totp:none?secret=GEZDGNBVGY%3D%3D%3D%3D%3D%3D&period=30&digits=6&issuer=sha512%20totp&algorithm=SHA512".parse::<TOTP>(),
374 Err(TOTPError::BadScheme(_))
375 ));
376
377 assert!(matches!(
378 "otpauth://totp/sha512%20totp:none?secret=GEZDGNBVGY%3D%3D%3D%3D%3D%3D&period=30&digits=6&issuer=sha512%20totp&algorithm=SHA123".parse::<TOTP>(),
379 Err(TOTPError::BadAlgorithm(_))
380 ));
381
382 assert!(matches!("otpauth://missing_fields".parse::<TOTP>(), Err(TOTPError::MissingField("secret"))));
383 }
384
385 #[test]
386 fn totp_minimal() -> Result<(), TOTPError> {
387 let otp_str = "otpauth://totp/KeePassXC:none?secret=JBSWY3DPEHPK3PXP&period=30&digits=6";
388
389 let expected = TOTP {
390 label: "KeePassXC:none".to_string(),
391 secret: b"Hello!\xDE\xAD\xBE\xEF".to_vec(),
392 issuer: None,
393 period: 30,
394 digits: 6,
395 algorithm: TOTPAlgorithm::Sha1,
396 };
397
398 assert_eq!(otp_str.parse::<TOTP>()?, expected);
399 Ok(())
400 }
401}