Skip to main content

kanidmd_lib/credential/
totp.rs

1use crypto_glue::{
2    hmac_s1::{HmacSha1, HmacSha1Key},
3    hmac_s256::{HmacSha256, HmacSha256Key},
4    hmac_s512::{HmacSha512, HmacSha512Key},
5    traits::{KeyInit, Mac},
6};
7use kanidm_proto::internal::{TotpAlgo as ProtoTotpAlgo, TotpSecret as ProtoTotp};
8use rand::RngExt;
9use std::{
10    convert::{TryFrom, TryInto},
11    time::{Duration, SystemTime},
12};
13
14use crate::be::dbvalue::{DbTotpAlgoV1, DbTotpV1};
15
16// This is the same size as an AES256KEY making it infeasible to bruteforce.
17const SECRET_SIZE_BYTES: usize = 32;
18pub const TOTP_DEFAULT_STEP: u64 = 30;
19
20#[derive(Debug, PartialEq, Eq)]
21pub enum TotpError {
22    InvalidKeyError,
23    HmacError,
24    TimeError,
25}
26
27#[repr(u32)]
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum TotpDigits {
30    Six = 1_000_000,
31    Eight = 100_000_000,
32}
33
34impl TryFrom<u8> for TotpDigits {
35    type Error = ();
36
37    fn try_from(value: u8) -> Result<Self, Self::Error> {
38        match value {
39            6 => Ok(TotpDigits::Six),
40            8 => Ok(TotpDigits::Eight),
41            _ => Err(()),
42        }
43    }
44}
45
46#[allow(clippy::from_over_into)]
47impl Into<u8> for TotpDigits {
48    fn into(self) -> u8 {
49        match self {
50            TotpDigits::Six => 6,
51            TotpDigits::Eight => 8,
52        }
53    }
54}
55
56#[derive(Debug, Clone, PartialEq, Eq, Copy)]
57pub enum TotpAlgo {
58    Sha1,
59    Sha256,
60    Sha512,
61}
62
63impl TotpAlgo {
64    pub(crate) fn digest(self, key_bytes: &[u8], counter: u64) -> Result<Vec<u8>, TotpError> {
65        let hmac = match self {
66            TotpAlgo::Sha1 => {
67                let mut key = HmacSha1Key::default();
68
69                if key_bytes.len() > key.as_slice().len() {
70                    return Err(TotpError::InvalidKeyError);
71                }
72
73                #[allow(clippy::indexing_slicing)]
74                let key_ref = &mut key.as_mut_slice()[..key_bytes.len()];
75                key_ref.copy_from_slice(key_bytes);
76
77                let mut hmac = HmacSha1::new(&key);
78                hmac.update(&counter.to_be_bytes());
79                hmac.finalize().into_bytes().to_vec()
80            }
81            TotpAlgo::Sha256 => {
82                let mut key = HmacSha256Key::default();
83
84                if key_bytes.len() > key.as_slice().len() {
85                    return Err(TotpError::InvalidKeyError);
86                }
87
88                #[allow(clippy::indexing_slicing)]
89                let key_ref = &mut key.as_mut_slice()[..key_bytes.len()];
90                key_ref.copy_from_slice(key_bytes);
91
92                let mut hmac = HmacSha256::new(&key);
93                hmac.update(&counter.to_be_bytes());
94                hmac.finalize().into_bytes().to_vec()
95            }
96            TotpAlgo::Sha512 => {
97                let mut key = HmacSha512Key::default();
98
99                if key_bytes.len() > key.as_slice().len() {
100                    return Err(TotpError::InvalidKeyError);
101                }
102
103                #[allow(clippy::indexing_slicing)]
104                let key_ref = &mut key.as_mut_slice()[..key_bytes.len()];
105                key_ref.copy_from_slice(key_bytes);
106
107                let mut hmac = HmacSha512::new(&key);
108                hmac.update(&counter.to_be_bytes());
109                hmac.finalize().into_bytes().to_vec()
110            }
111        };
112
113        Ok(hmac)
114    }
115}
116
117/// <https://tools.ietf.org/html/rfc6238> which relies on <https://tools.ietf.org/html/rfc4226>
118#[derive(Debug, Clone, PartialEq, Eq)]
119pub struct Totp {
120    secret: Vec<u8>,
121    pub(crate) step: u64,
122    algo: TotpAlgo,
123    digits: TotpDigits,
124}
125
126impl TryFrom<DbTotpV1> for Totp {
127    type Error = ();
128
129    fn try_from(value: DbTotpV1) -> Result<Self, Self::Error> {
130        let algo = match value.algo {
131            DbTotpAlgoV1::S1 => TotpAlgo::Sha1,
132            DbTotpAlgoV1::S256 => TotpAlgo::Sha256,
133            DbTotpAlgoV1::S512 => TotpAlgo::Sha512,
134        };
135        // Default.
136        let digits = TotpDigits::try_from(value.digits.unwrap_or(6))?;
137
138        Ok(Totp {
139            secret: value.key,
140            step: value.step,
141            algo,
142            digits,
143        })
144    }
145}
146
147impl TryFrom<ProtoTotp> for Totp {
148    type Error = ();
149
150    fn try_from(value: ProtoTotp) -> Result<Self, Self::Error> {
151        Ok(Totp {
152            secret: value.secret,
153            algo: match value.algo {
154                ProtoTotpAlgo::Sha1 => TotpAlgo::Sha1,
155                ProtoTotpAlgo::Sha256 => TotpAlgo::Sha256,
156                ProtoTotpAlgo::Sha512 => TotpAlgo::Sha512,
157            },
158            step: value.step,
159            digits: TotpDigits::try_from(value.digits)?,
160        })
161    }
162}
163
164impl Totp {
165    pub fn new(secret: Vec<u8>, step: u64, algo: TotpAlgo, digits: TotpDigits) -> Self {
166        Totp {
167            secret,
168            step,
169            algo,
170            digits,
171        }
172    }
173
174    // Create a new token with secure key and algo.
175    pub fn generate_secure(step: u64) -> Self {
176        let mut rng = rand::rng();
177        let secret: Vec<u8> = (0..SECRET_SIZE_BYTES).map(|_| rng.random()).collect();
178        let algo = TotpAlgo::Sha256;
179        let digits = TotpDigits::Six;
180        Totp {
181            secret,
182            step,
183            algo,
184            digits,
185        }
186    }
187
188    pub(crate) fn to_dbtotpv1(&self) -> DbTotpV1 {
189        DbTotpV1 {
190            label: "totp".to_string(),
191            key: self.secret.clone(),
192            step: self.step,
193            algo: match self.algo {
194                TotpAlgo::Sha1 => DbTotpAlgoV1::S1,
195                TotpAlgo::Sha256 => DbTotpAlgoV1::S256,
196                TotpAlgo::Sha512 => DbTotpAlgoV1::S512,
197            },
198            digits: Some(self.digits.into()),
199        }
200    }
201
202    fn digest(&self, counter: u64) -> Result<u32, TotpError> {
203        let hmac = self.algo.digest(&self.secret, counter)?;
204        // Now take the hmac and encode it as hotp expects.
205        // https://tools.ietf.org/html/rfc4226#page-7
206        let offset = hmac
207            .last()
208            .map(|v| (v & 0xf) as usize)
209            .ok_or(TotpError::HmacError)?;
210
211        // This is based on "dynamic truncation" where the offset into
212        // the hmac is dynamic based on the last byte of the hmac output.
213        // Since the array is u8, and we & with 0x0F, the value of offset
214        // must be in the range 0 to 15. All hmac outputs are 20 bytes
215        // or greater, so 15 + 4 == 19 as the upper bound will always
216        // be within the bounds of the hmac array.
217        // As a result, this is safe to slice.
218        #[allow(clippy::indexing_slicing)]
219        let bytes: [u8; 4] = hmac[offset..offset + 4]
220            .try_into()
221            .map_err(|_| TotpError::HmacError)?;
222
223        let otp = u32::from_be_bytes(bytes);
224        // Treat as a u31, this masks the first bit.
225        // then modulo based on the number of digits requested.
226        // * For 6 digits modulo 1_000_000
227        // * For 8 digits modulo 100_000_000
228        // Based on this 9 is max digits.
229        Ok((otp & 0x7fff_ffff) % (self.digits as u32))
230    }
231
232    pub fn do_totp_duration_from_epoch(&self, time: &Duration) -> Result<u32, TotpError> {
233        let secs = time.as_secs();
234        // do the window calculation
235        let counter = secs / self.step;
236        self.digest(counter)
237    }
238
239    pub fn do_totp(&self, time: &SystemTime) -> Result<u32, TotpError> {
240        let dur = time
241            .duration_since(SystemTime::UNIX_EPOCH)
242            .map_err(|_| TotpError::TimeError)?;
243        self.do_totp_duration_from_epoch(&dur)
244    }
245
246    pub fn verify(&self, chal: u32, time: Duration) -> bool {
247        let secs = time.as_secs();
248        let counter = secs / self.step;
249        // Any error becomes a failure.
250        self.digest(counter).map(|v1| v1 == chal).unwrap_or(false)
251            || self
252                .digest(counter - 1)
253                .map(|v2| v2 == chal)
254                .unwrap_or(false)
255    }
256
257    pub fn to_proto(&self, accountname: &str, issuer: &str) -> ProtoTotp {
258        ProtoTotp {
259            accountname: accountname.to_string(),
260            issuer: issuer.to_string(),
261            secret: self.secret.clone(),
262            step: self.step,
263            algo: match self.algo {
264                TotpAlgo::Sha1 => ProtoTotpAlgo::Sha1,
265                TotpAlgo::Sha256 => ProtoTotpAlgo::Sha256,
266                TotpAlgo::Sha512 => ProtoTotpAlgo::Sha512,
267            },
268            digits: self.digits.into(),
269        }
270    }
271
272    pub fn is_legacy_algo(&self) -> bool {
273        matches!(&self.algo, TotpAlgo::Sha1)
274    }
275
276    pub fn downgrade_to_legacy(self) -> Self {
277        Totp {
278            secret: self.secret,
279            step: self.step,
280            algo: TotpAlgo::Sha1,
281            digits: self.digits,
282        }
283    }
284}
285
286#[cfg(test)]
287mod tests {
288    use std::time::Duration;
289
290    use crate::credential::totp::{Totp, TotpAlgo, TotpDigits, TotpError, TOTP_DEFAULT_STEP};
291
292    #[test]
293    fn hotp_basic() {
294        let otp_sha1 = Totp::new(vec![0], 30, TotpAlgo::Sha1, TotpDigits::Six);
295        assert_eq!(otp_sha1.digest(0), Ok(328482));
296        let otp_sha256 = Totp::new(vec![0], 30, TotpAlgo::Sha256, TotpDigits::Six);
297        assert_eq!(otp_sha256.digest(0), Ok(356306));
298        let otp_sha512 = Totp::new(vec![0], 30, TotpAlgo::Sha512, TotpDigits::Six);
299        assert_eq!(otp_sha512.digest(0), Ok(674061));
300    }
301
302    fn do_test(
303        key: &[u8],
304        algo: TotpAlgo,
305        secs: u64,
306        step: u64,
307        digits: TotpDigits,
308        expect: &Result<u32, TotpError>,
309    ) {
310        let otp = Totp::new(key.to_vec(), step, algo, digits);
311        let d = Duration::from_secs(secs);
312        let r = otp.do_totp_duration_from_epoch(&d);
313        debug!(
314            "key: {:?}, algo: {:?}, time: {:?}, step: {:?}, expect: {:?} == {:?}",
315            key, algo, secs, step, expect, r
316        );
317        assert_eq!(&r, expect);
318    }
319
320    #[test]
321    fn totp_sha1_vectors() {
322        do_test(
323            &[0x00, 0x00, 0x00, 0x00],
324            TotpAlgo::Sha1,
325            1585368920,
326            TOTP_DEFAULT_STEP,
327            TotpDigits::Six,
328            &Ok(728926),
329        );
330        do_test(
331            &[0x00, 0x00, 0x00, 0x00],
332            TotpAlgo::Sha1,
333            1585368920,
334            TOTP_DEFAULT_STEP,
335            TotpDigits::Eight,
336            &Ok(74728926),
337        );
338        do_test(
339            &[0x00, 0xaa, 0xbb, 0xcc],
340            TotpAlgo::Sha1,
341            1585369498,
342            TOTP_DEFAULT_STEP,
343            TotpDigits::Six,
344            &Ok(985074),
345        );
346    }
347
348    #[test]
349    fn totp_sha256_vectors() {
350        do_test(
351            &[0x00, 0x00, 0x00, 0x00],
352            TotpAlgo::Sha256,
353            1585369682,
354            TOTP_DEFAULT_STEP,
355            TotpDigits::Six,
356            &Ok(795483),
357        );
358        do_test(
359            &[0x00, 0x00, 0x00, 0x00],
360            TotpAlgo::Sha256,
361            1585369682,
362            TOTP_DEFAULT_STEP,
363            TotpDigits::Eight,
364            &Ok(11795483),
365        );
366        do_test(
367            &[0x00, 0xaa, 0xbb, 0xcc],
368            TotpAlgo::Sha256,
369            1585369689,
370            TOTP_DEFAULT_STEP,
371            TotpDigits::Six,
372            &Ok(728402),
373        );
374    }
375
376    #[test]
377    fn totp_sha512_vectors() {
378        do_test(
379            &[0x00, 0x00, 0x00, 0x00],
380            TotpAlgo::Sha512,
381            1585369775,
382            TOTP_DEFAULT_STEP,
383            TotpDigits::Six,
384            &Ok(587735),
385        );
386        do_test(
387            &[0x00, 0x00, 0x00, 0x00],
388            TotpAlgo::Sha512,
389            1585369775,
390            TOTP_DEFAULT_STEP,
391            TotpDigits::Eight,
392            &Ok(14587735),
393        );
394        do_test(
395            &[0x00, 0xaa, 0xbb, 0xcc],
396            TotpAlgo::Sha512,
397            1585369780,
398            TOTP_DEFAULT_STEP,
399            TotpDigits::Six,
400            &Ok(952181),
401        );
402    }
403
404    #[test]
405    fn totp_allow_one_previous() {
406        let key = vec![0x00, 0xaa, 0xbb, 0xcc];
407        let secs = 1585369780;
408        let otp = Totp::new(key, TOTP_DEFAULT_STEP, TotpAlgo::Sha512, TotpDigits::Six);
409        let d = Duration::from_secs(secs);
410        // Step
411        assert!(otp.verify(952181, d));
412        // Step - 1
413        assert!(otp.verify(685469, d));
414        // This is step - 2
415        assert!(!otp.verify(217213, d));
416        // This is step + 1
417        assert!(!otp.verify(972806, d));
418    }
419}