From ec298ea1fc7d2339ef44d283644d6ee2ebcd54bd Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Mon, 31 Dec 2018 00:06:06 +0100 Subject: Set the time before generating a TOTP This patch changes the otp get command to set the Nitrokey's time before generating a one-time password using the TOTP algorithm. Per default, it sets the time to the current system time. If the --time option is set, it uses its value instead. See issue #34 [0] for a discussion of this change. [0] https://github.com/d-e-s-o/nitrocli/issues/34 --- nitrocli/src/commands.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) (limited to 'nitrocli/src/commands.rs') diff --git a/nitrocli/src/commands.rs b/nitrocli/src/commands.rs index 17426cd..47a955d 100644 --- a/nitrocli/src/commands.rs +++ b/nitrocli/src/commands.rs @@ -19,6 +19,7 @@ use std::fmt; use std::result; +use std::time; use nitrokey::ConfigureOtp; use nitrokey::Device; @@ -338,9 +339,28 @@ fn get_otp(slot: u8, algorithm: args::OtpAlgorithm, device: &T) .map_err(|err| get_error("Could not generate OTP", &err)) } +fn get_unix_timestamp() -> Result { + time::SystemTime::now() + .duration_since(time::UNIX_EPOCH) + .or_else(|_| { + Err(Error::Error( + "Current system time is before the Unix epoch".to_string(), + )) + }) + .map(|duration| duration.as_secs()) +} + /// Generate a one-time password on the Nitrokey device. -pub fn otp_get(slot: u8, algorithm: args::OtpAlgorithm) -> Result<()> { +pub fn otp_get(slot: u8, algorithm: args::OtpAlgorithm, time: Option) -> Result<()> { let device = get_device()?; + if algorithm == args::OtpAlgorithm::Totp { + device + .set_time(match time { + Some(time) => time, + None => get_unix_timestamp()?, + }) + .map_err(|err| get_error("Could not set time", &err))?; + } let config = device .get_config() .map_err(|err| get_error("Could not get device configuration", &err))?; -- cgit v1.2.1