From d9adac05dfa5de83465fde3479df4fd898ebd8bd Mon Sep 17 00:00:00 2001 From: Daniel Mueller Date: Sat, 5 Jan 2019 16:04:49 -0800 Subject: Update nitrokey crate to 0.3.0 This change updates the nitrokey crate to version 0.3.0. Import subrepo nitrokey/:nitrokey at 3593df8844b80741e2d33c8e5af80e65760dc058 --- nitrokey/src/auth.rs | 5 +- nitrokey/src/device.rs | 153 +++++++++++++++++++++++++++++++++++++++++++++++-- nitrokey/src/otp.rs | 33 ++++++----- nitrokey/src/pws.rs | 24 ++++++-- nitrokey/src/util.rs | 70 ++++++++++++---------- 5 files changed, 228 insertions(+), 57 deletions(-) (limited to 'nitrokey/src') diff --git a/nitrokey/src/auth.rs b/nitrokey/src/auth.rs index 017cdbb..a129bd8 100644 --- a/nitrokey/src/auth.rs +++ b/nitrokey/src/auth.rs @@ -149,10 +149,7 @@ where A: AuthenticatedDevice, T: Fn(*const i8, *const i8) -> c_int, { - let temp_password = match generate_password(TEMPORARY_PASSWORD_LENGTH) { - Ok(pw) => pw, - Err(_) => return Err((device, CommandError::RngError)), - }; + let temp_password = generate_password(TEMPORARY_PASSWORD_LENGTH); let password = match get_cstring(password) { Ok(password) => password, Err(err) => return Err((device, err)), diff --git a/nitrokey/src/device.rs b/nitrokey/src/device.rs index 9c6608d..78d0d82 100644 --- a/nitrokey/src/device.rs +++ b/nitrokey/src/device.rs @@ -510,6 +510,74 @@ pub trait Device: Authenticate + GetPasswordSafe + GenerateOtp { fn lock(&self) -> Result<(), CommandError> { unsafe { get_command_result(nitrokey_sys::NK_lock_device()) } } + + /// Performs a factory reset on the Nitrokey device. + /// + /// This commands performs a factory reset on the smart card (like the factory reset via `gpg + /// --card-edit`) and then clears the flash memory (password safe, one-time passwords etc.). + /// After a factory reset, [`build_aes_key`][] has to be called before the password safe or the + /// encrypted volume can be used. + /// + /// # Errors + /// + /// - [`InvalidString`][] if the provided password contains a null byte + /// - [`WrongPassword`][] if the admin password is wrong + /// + /// # Example + /// + /// ```no_run + /// use nitrokey::Device; + /// # use nitrokey::CommandError; + /// + /// # fn try_main() -> Result<(), CommandError> { + /// let device = nitrokey::connect()?; + /// match device.factory_reset("12345678") { + /// Ok(()) => println!("Performed a factory reset."), + /// Err(err) => println!("Could not perform a factory reset: {}", err), + /// }; + /// # Ok(()) + /// # } + /// ``` + /// + /// [`build_aes_key`]: #method.build_aes_key + fn factory_reset(&self, admin_pin: &str) -> Result<(), CommandError> { + let admin_pin_string = get_cstring(admin_pin)?; + unsafe { get_command_result(nitrokey_sys::NK_factory_reset(admin_pin_string.as_ptr())) } + } + + /// Builds a new AES key on the Nitrokey. + /// + /// The AES key is used to encrypt the password safe and the encrypted volume. You may need + /// to call this method after a factory reset, either using [`factory_reset`][] or using `gpg + /// --card-edit`. You can also use it to destory the data stored in the password safe or on + /// the encrypted volume. + /// + /// # Errors + /// + /// - [`InvalidString`][] if the provided password contains a null byte + /// - [`WrongPassword`][] if the admin password is wrong + /// + /// # Example + /// + /// ```no_run + /// use nitrokey::Device; + /// # use nitrokey::CommandError; + /// + /// # fn try_main() -> Result<(), CommandError> { + /// let device = nitrokey::connect()?; + /// match device.build_aes_key("12345678") { + /// Ok(()) => println!("New AES keys have been built."), + /// Err(err) => println!("Could not build new AES keys: {}", err), + /// }; + /// # Ok(()) + /// # } + /// ``` + /// + /// [`factory_reset`]: #method.factory_reset + fn build_aes_key(&self, admin_pin: &str) -> Result<(), CommandError> { + let admin_pin_string = get_cstring(admin_pin)?; + unsafe { get_command_result(nitrokey_sys::NK_build_aes_key(admin_pin_string.as_ptr())) } + } } /// Connects to a Nitrokey device. This method can be used to connect to any connected device, @@ -532,9 +600,9 @@ pub fn connect() -> Result { match nitrokey_sys::NK_login_auto() { 1 => match get_connected_device() { Some(wrapper) => Ok(wrapper), - None => Err(CommandError::Unknown), + None => Err(CommandError::Undefined), }, - _ => Err(CommandError::Unknown), + _ => Err(CommandError::Undefined), } } } @@ -623,7 +691,7 @@ impl Pro { // TODO: maybe Option instead of Result? match connect_model(Model::Pro) { true => Ok(Pro {}), - false => Err(CommandError::Unknown), + false => Err(CommandError::Undefined), } } } @@ -663,7 +731,84 @@ impl Storage { // TODO: maybe Option instead of Result? match connect_model(Model::Storage) { true => Ok(Storage {}), - false => Err(CommandError::Unknown), + false => Err(CommandError::Undefined), + } + } + + /// Changes the update PIN. + /// + /// The update PIN is used to enable firmware updates. Unlike the user and the admin PIN, the + /// update PIN is not managed by the OpenPGP smart card but by the Nitrokey firmware. There is + /// no retry counter as with the other PIN types. + /// + /// # Errors + /// + /// - [`InvalidString`][] if one of the provided passwords contains a null byte + /// - [`WrongPassword`][] if the current update password is wrong + /// + /// # Example + /// + /// ```no_run + /// # use nitrokey::CommandError; + /// + /// # fn try_main() -> Result<(), CommandError> { + /// let device = nitrokey::Storage::connect()?; + /// match device.change_update_pin("12345678", "87654321") { + /// Ok(()) => println!("Updated update PIN."), + /// Err(err) => println!("Failed to update update PIN: {}", err), + /// }; + /// # Ok(()) + /// # } + /// ``` + /// + /// [`InvalidString`]: enum.CommandError.html#variant.InvalidString + /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword + pub fn change_update_pin(&self, current: &str, new: &str) -> Result<(), CommandError> { + let current_string = get_cstring(current)?; + let new_string = get_cstring(new)?; + unsafe { + get_command_result(nitrokey_sys::NK_change_update_password( + current_string.as_ptr(), + new_string.as_ptr(), + )) + } + } + + /// Enables the firmware update mode. + /// + /// During firmware update mode, the Nitrokey can no longer be accessed using HID commands. + /// To resume normal operation, run `dfu-programmer at32uc3a3256s launch`. In order to enter + /// the firmware update mode, you need the update password that can be changed using the + /// [`change_update_pin`][] method. + /// + /// # Errors + /// + /// - [`InvalidString`][] if one of the provided passwords contains a null byte + /// - [`WrongPassword`][] if the current update password is wrong + /// + /// # Example + /// + /// ```no_run + /// # use nitrokey::CommandError; + /// + /// # fn try_main() -> Result<(), CommandError> { + /// let device = nitrokey::Storage::connect()?; + /// match device.enable_firmware_update("12345678") { + /// Ok(()) => println!("Nitrokey entered update mode."), + /// Err(err) => println!("Could not enter update mode: {}", err), + /// }; + /// # Ok(()) + /// # } + /// ``` + /// + /// [`InvalidString`]: enum.CommandError.html#variant.InvalidString + /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword + pub fn enable_firmware_update(&self, update_pin: &str) -> Result<(), CommandError> { + let update_pin_string = get_cstring(update_pin)?; + unsafe { + get_command_result(nitrokey_sys::NK_enable_firmware_update( + update_pin_string.as_ptr(), + )) } } diff --git a/nitrokey/src/otp.rs b/nitrokey/src/otp.rs index 6f6bd80..9f0a388 100644 --- a/nitrokey/src/otp.rs +++ b/nitrokey/src/otp.rs @@ -151,27 +151,27 @@ pub trait ConfigureOtp { /// Provides methods to generate OTP codes and to query OTP slots on a Nitrokey /// device. pub trait GenerateOtp { - /// Sets the time on the Nitrokey. This command may set the time to arbitrary values. `time` - /// is the number of seconds since January 1st, 1970 (Unix timestamp). + /// Sets the time on the Nitrokey. + /// + /// `time` is the number of seconds since January 1st, 1970 (Unix timestamp). Unless `force` + /// is set to `true`, this command fails if the timestamp on the device is larger than the + /// given timestamp or if it is zero. /// /// The time is used for TOTP generation (see [`get_totp_code`][]). /// /// # Example /// - /// ```ignore - /// extern crate chrono; - /// - /// use chrono::Utc; - /// use nitrokey::Device; + /// ```no_run + /// use std::time; + /// use nitrokey::GenerateOtp; /// # use nitrokey::CommandError; /// /// # fn try_main() -> Result<(), CommandError> { /// let device = nitrokey::connect()?; - /// let time = Utc::now().timestamp(); - /// if time < 0 { - /// println!("Timestamps before 1970-01-01 are not supported!"); - /// } else { - /// device.set_time(time as u64); + /// let time = time::SystemTime::now().duration_since(time::UNIX_EPOCH); + /// match time { + /// Ok(time) => device.set_time(time.as_secs(), false)?, + /// Err(_) => println!("The system time is before the Unix epoch!"), /// } /// # Ok(()) /// # } @@ -183,8 +183,13 @@ pub trait GenerateOtp { /// /// [`get_totp_code`]: #method.get_totp_code /// [`Timestamp`]: enum.CommandError.html#variant.Timestamp - fn set_time(&self, time: u64) -> Result<(), CommandError> { - unsafe { get_command_result(nitrokey_sys::NK_totp_set_time(time)) } + fn set_time(&self, time: u64, force: bool) -> Result<(), CommandError> { + let result = if force { + unsafe { nitrokey_sys::NK_totp_set_time(time) } + } else { + unsafe { nitrokey_sys::NK_totp_set_time_soft(time) } + }; + get_command_result(result) } /// Returns the name of the given HOTP slot. diff --git a/nitrokey/src/pws.rs b/nitrokey/src/pws.rs index 08ac365..ebd5fcd 100644 --- a/nitrokey/src/pws.rs +++ b/nitrokey/src/pws.rs @@ -71,9 +71,18 @@ pub trait GetPasswordSafe { /// has been used. Otherwise, other applications can access the password store without /// authentication. /// + /// If this method returns an `AesDecryptionFailed` (Nitrokey Pro) or `Unknown` (Nitrokey + /// Storage) error, the AES data object on the smart card could not be accessed. This problem + /// occurs after a factory reset using `gpg --card-edit` and can be fixed using the + /// [`Device::build_aes_key`][] command. + /// /// # Errors /// + /// - [`AesDecryptionFailed`][] if the secret for the password safe could not be decrypted + /// (Nitrokey Pro only) /// - [`InvalidString`][] if one of the provided passwords contains a null byte + /// - [`Unknown`][] if the secret for the password safe could not be decrypted (Nitrokey + /// Storage only) /// - [`WrongPassword`][] if the current user password is wrong /// /// # Example @@ -99,7 +108,10 @@ pub trait GetPasswordSafe { /// /// [`device`]: struct.PasswordSafe.html#method.device /// [`lock`]: trait.Device.html#method.lock + /// [`AesDecryptionFailed`]: enum.CommandError.html#variant.AesDecryptionFailed + /// [`Device::build_aes_key`]: trait.Device.html#method.build_aes_key /// [`InvalidString`]: enum.CommandError.html#variant.InvalidString + /// [`Unknown`]: enum.CommandError.html#variant.Unknown /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword fn get_password_safe(&self, user_pin: &str) -> Result, CommandError>; } @@ -163,7 +175,7 @@ impl<'a> PasswordSafe<'a> { /// # Errors /// /// - [`InvalidSlot`][] if the given slot is out of range - /// - [`Unknown`][] if the slot is not programmed + /// - [`Undefined`][] if the slot is not programmed /// /// # Example /// @@ -187,7 +199,7 @@ impl<'a> PasswordSafe<'a> { /// ``` /// /// [`InvalidSlot`]: enum.CommandError.html#variant.InvalidSlot - /// [`Unknown`]: enum.CommandError.html#variant.Unknown + /// [`Undefined`]: enum.CommandError.html#variant.Undefined pub fn get_slot_name(&self, slot: u8) -> Result { unsafe { result_from_string(nitrokey_sys::NK_get_password_safe_slot_name(slot)) } } @@ -197,7 +209,7 @@ impl<'a> PasswordSafe<'a> { /// # Errors /// /// - [`InvalidSlot`][] if the given slot is out of range - /// - [`Unknown`][] if the slot is not programmed + /// - [`Undefined`][] if the slot is not programmed /// /// # Example /// @@ -217,7 +229,7 @@ impl<'a> PasswordSafe<'a> { /// ``` /// /// [`InvalidSlot`]: enum.CommandError.html#variant.InvalidSlot - /// [`Unknown`]: enum.CommandError.html#variant.Unknown + /// [`Undefined`]: enum.CommandError.html#variant.Undefined pub fn get_slot_login(&self, slot: u8) -> Result { unsafe { result_from_string(nitrokey_sys::NK_get_password_safe_slot_login(slot)) } } @@ -227,7 +239,7 @@ impl<'a> PasswordSafe<'a> { /// # Errors /// /// - [`InvalidSlot`][] if the given slot is out of range - /// - [`Unknown`][] if the slot is not programmed + /// - [`Undefined`][] if the slot is not programmed /// /// # Example /// @@ -247,7 +259,7 @@ impl<'a> PasswordSafe<'a> { /// ``` /// /// [`InvalidSlot`]: enum.CommandError.html#variant.InvalidSlot - /// [`Unknown`]: enum.CommandError.html#variant.Unknown + /// [`Undefined`]: enum.CommandError.html#variant.Undefined pub fn get_slot_password(&self, slot: u8) -> Result { unsafe { result_from_string(nitrokey_sys::NK_get_password_safe_slot_password(slot)) } } diff --git a/nitrokey/src/util.rs b/nitrokey/src/util.rs index a2e957e..1ecc0b7 100644 --- a/nitrokey/src/util.rs +++ b/nitrokey/src/util.rs @@ -1,3 +1,4 @@ +use std::borrow; use std::ffi::{CStr, CString}; use std::fmt; use std::os::raw::{c_char, c_int}; @@ -19,7 +20,7 @@ pub enum CommandError { /// You are not authorized for this command or provided a wrong temporary /// password. NotAuthorized, - /// An error occured when getting or setting the time. + /// An error occurred when getting or setting the time. Timestamp, /// You did not provide a name for the OTP slot. NoName, @@ -29,14 +30,14 @@ pub enum CommandError { UnknownCommand, /// AES decryption failed. AesDecryptionFailed, - /// An unknown error occured. - Unknown, + /// An unknown error occurred. + Unknown(i64), + /// An unspecified error occurred. + Undefined, /// You passed a string containing a null byte. InvalidString, /// You passed an invalid slot. InvalidSlot, - /// An error occured during random number generation. - RngError, } /// Log level for libnitrokey. @@ -68,7 +69,7 @@ pub fn owned_str_from_ptr(ptr: *const c_char) -> String { pub fn result_from_string(ptr: *const c_char) -> Result { if ptr.is_null() { - return Err(CommandError::Unknown); + return Err(CommandError::Undefined); } unsafe { let s = owned_str_from_ptr(ptr); @@ -94,42 +95,53 @@ pub fn get_last_result() -> Result<(), CommandError> { pub fn get_last_error() -> CommandError { return match get_last_result() { - Ok(()) => CommandError::Unknown, + Ok(()) => CommandError::Undefined, Err(err) => err, }; } -pub fn generate_password(length: usize) -> std::io::Result> { +pub fn generate_password(length: usize) -> Vec { let mut data = vec![0u8; length]; rand::thread_rng().fill(&mut data[..]); - return Ok(data); + return data; } pub fn get_cstring>>(s: T) -> Result { CString::new(s).or(Err(CommandError::InvalidString)) } -impl fmt::Display for CommandError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let msg = match *self { - CommandError::WrongCrc => "A packet with a wrong checksum has been sent or received", - CommandError::WrongSlot => "The given OTP slot does not exist", - CommandError::SlotNotProgrammed => "The given OTP slot is not programmed", - CommandError::WrongPassword => "The given password is wrong", +impl CommandError { + fn as_str(&self) -> borrow::Cow<'static, str> { + match *self { + CommandError::WrongCrc => { + "A packet with a wrong checksum has been sent or received".into() + } + CommandError::WrongSlot => "The given OTP slot does not exist".into(), + CommandError::SlotNotProgrammed => "The given OTP slot is not programmed".into(), + CommandError::WrongPassword => "The given password is wrong".into(), CommandError::NotAuthorized => { - "You are not authorized for this command or provided a wrong temporary password" + "You are not authorized for this command or provided a wrong temporary \ + password" + .into() } - CommandError::Timestamp => "An error occured when getting or setting the time", - CommandError::NoName => "You did not provide a name for the OTP slot", - CommandError::NotSupported => "This command is not supported by this device", - CommandError::UnknownCommand => "This command is unknown", - CommandError::AesDecryptionFailed => "AES decryption failed", - CommandError::Unknown => "An unknown error occured", - CommandError::InvalidString => "You passed a string containing a null byte", - CommandError::InvalidSlot => "The given slot is invalid", - CommandError::RngError => "An error occured during random number generation", - }; - write!(f, "{}", msg) + CommandError::Timestamp => "An error occurred when getting or setting the time".into(), + CommandError::NoName => "You did not provide a name for the OTP slot".into(), + CommandError::NotSupported => "This command is not supported by this device".into(), + CommandError::UnknownCommand => "This command is unknown".into(), + CommandError::AesDecryptionFailed => "AES decryption failed".into(), + CommandError::Unknown(x) => { + borrow::Cow::from(format!("An unknown error occurred ({})", x)) + } + CommandError::Undefined => "An unspecified error occurred".into(), + CommandError::InvalidString => "You passed a string containing a null byte".into(), + CommandError::InvalidSlot => "The given slot is invalid".into(), + } + } +} + +impl fmt::Display for CommandError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.as_str()) } } @@ -147,7 +159,7 @@ impl From for CommandError { 9 => CommandError::UnknownCommand, 10 => CommandError::AesDecryptionFailed, 201 => CommandError::InvalidSlot, - _ => CommandError::Unknown, + x => CommandError::Unknown(x.into()), } } } -- cgit v1.2.3