From 6b439950c3c856f1b0eb6df2c9e89387b1697608 Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Sat, 28 Dec 2019 23:34:58 +0100 Subject: Implement conversion traits for Model and NK_device_model A nitrokey_sys::NK_device_model (= u32) value may correspond to a nitrokey::Model, and vice versa. This patch adds the appropriate From and TryFrom implementations. --- src/device/mod.rs | 44 +++++++++++++++++++++++++++++--------------- 1 file changed, 29 insertions(+), 15 deletions(-) (limited to 'src/device/mod.rs') diff --git a/src/device/mod.rs b/src/device/mod.rs index 5e15f08..a3a0255 100644 --- a/src/device/mod.rs +++ b/src/device/mod.rs @@ -5,6 +5,7 @@ mod pro; mod storage; mod wrapper; +use std::convert::TryFrom; use std::fmt; use libc; @@ -43,6 +44,30 @@ impl fmt::Display for Model { } } +impl From for nitrokey_sys::NK_device_model { + fn from(model: Model) -> Self { + match model { + Model::Storage => nitrokey_sys::NK_device_model_NK_STORAGE, + Model::Pro => nitrokey_sys::NK_device_model_NK_PRO, + } + } +} + +impl TryFrom for Model { + type Error = Error; + + fn try_from(model: nitrokey_sys::NK_device_model) -> Result { + match model { + nitrokey_sys::NK_device_model_NK_DISCONNECTED => { + Err(CommunicationError::NotConnected.into()) + } + nitrokey_sys::NK_device_model_NK_PRO => Ok(Model::Pro), + nitrokey_sys::NK_device_model_NK_STORAGE => Ok(Model::Storage), + _ => Err(Error::UnsupportedModelError), + } + } +} + /// A firmware version for a Nitrokey device. #[derive(Clone, Copy, Debug, PartialEq)] pub struct FirmwareVersion { @@ -428,12 +453,8 @@ pub trait Device<'a>: Authenticate<'a> + GetPasswordSafe<'a> + GenerateOtp + fmt } } -fn get_connected_model() -> Option { - match unsafe { nitrokey_sys::NK_get_device_model() } { - nitrokey_sys::NK_device_model_NK_PRO => Some(Model::Pro), - nitrokey_sys::NK_device_model_NK_STORAGE => Some(Model::Storage), - _ => None, - } +fn get_connected_model() -> Result { + Model::try_from(unsafe { nitrokey_sys::NK_get_device_model() }) } pub(crate) fn create_device_wrapper( @@ -449,16 +470,9 @@ pub(crate) fn create_device_wrapper( pub(crate) fn get_connected_device( manager: &mut crate::Manager, ) -> Result, Error> { - match get_connected_model() { - Some(model) => Ok(create_device_wrapper(manager, model)), - None => Err(CommunicationError::NotConnected.into()), - } + Ok(create_device_wrapper(manager, get_connected_model()?)) } pub(crate) fn connect_enum(model: Model) -> bool { - let model = match model { - Model::Storage => nitrokey_sys::NK_device_model_NK_STORAGE, - Model::Pro => nitrokey_sys::NK_device_model_NK_PRO, - }; - unsafe { nitrokey_sys::NK_login_enum(model) == 1 } + unsafe { nitrokey_sys::NK_login_enum(model.into()) == 1 } } -- cgit v1.2.1 From bcad061ed3e7777547c1b6fc9223dd65f752d94e Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Sat, 28 Dec 2019 23:53:24 +0100 Subject: Add the DeviceInfo struct In the next patch, we will add support for the NK_list_devices functions that returns a list of NK_device_info structs with information about the connected devices. This patch introduces the DeviceInfo struct that holds the information returned by NK_list_devices and that can be created from a NK_device_info struct. --- src/device/mod.rs | 105 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 103 insertions(+), 2 deletions(-) (limited to 'src/device/mod.rs') diff --git a/src/device/mod.rs b/src/device/mod.rs index a3a0255..e015886 100644 --- a/src/device/mod.rs +++ b/src/device/mod.rs @@ -5,7 +5,9 @@ mod pro; mod storage; mod wrapper; -use std::convert::TryFrom; +use std::cmp; +use std::convert::{TryFrom, TryInto}; +use std::ffi; use std::fmt; use libc; @@ -17,7 +19,8 @@ use crate::error::{CommunicationError, Error}; use crate::otp::GenerateOtp; use crate::pws::GetPasswordSafe; use crate::util::{ - get_command_result, get_cstring, get_last_error, result_from_string, result_or_error, + get_command_result, get_cstring, get_last_error, owned_str_from_ptr, result_from_string, + result_or_error, }; pub use pro::Pro; @@ -68,6 +71,73 @@ impl TryFrom for Model { } } +/// Connection information for a Nitrokey device. +#[derive(Clone, Debug, PartialEq)] +pub struct DeviceInfo { + /// The model of the Nitrokey device, or `None` if the model is not supported by this crate. + pub model: Option, + /// The USB device path. + pub path: String, + /// The serial number as a 8-character hex string, or `None` if the device does not expose its + /// serial number. + pub serial_number: Option, +} + +impl TryFrom<&nitrokey_sys::NK_device_info> for DeviceInfo { + type Error = Error; + + fn try_from(device_info: &nitrokey_sys::NK_device_info) -> Result { + let model_result = device_info.model.try_into(); + let model_option = model_result.map(Some).or_else(|err| match err { + Error::UnsupportedModelError => Ok(None), + _ => Err(err), + })?; + let serial_number = unsafe { ffi::CStr::from_ptr(device_info.serial_number) } + .to_str() + .map_err(Error::from)?; + Ok(DeviceInfo { + model: model_option, + path: owned_str_from_ptr(device_info.path)?, + serial_number: get_hidapi_serial_number(serial_number), + }) + } +} + +impl fmt::Display for DeviceInfo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.model { + Some(model) => write!(f, "Nitrokey {}", model)?, + None => write!(f, "Unsupported Nitrokey model")?, + } + write!(f, " at {} with ", self.path)?; + match &self.serial_number { + Some(ref serial_number) => write!(f, "serial no. {}", serial_number), + None => write!(f, "an unknown serial number"), + } + } +} + +/// Parses a serial number returned by hidapi and transforms it to the Nitrokey format. +/// +/// If the serial number is all zero, this function returns `None`. Otherwise, all leading zeros +/// (except the last eight characters) are stripped and `Some(_)` is returned. If the serial +/// number has less than eight characters, leading zeros are added. +fn get_hidapi_serial_number(serial_number: &str) -> Option { + let mut iter = serial_number.char_indices().skip_while(|(_, c)| *c == '0'); + let first_non_null = iter.next(); + if let Some((i, _)) = first_non_null { + // keep at least the last 8 characters + let len = serial_number.len(); + let cut = cmp::min(len.saturating_sub(8), i); + let (_, suffix) = serial_number.split_at(cut); + // if necessary, add leading zeros to reach 8 characters + let fill = 8usize.saturating_sub(len); + Some("0".repeat(fill) + suffix) + } else { + None + } +} + /// A firmware version for a Nitrokey device. #[derive(Clone, Copy, Debug, PartialEq)] pub struct FirmwareVersion { @@ -476,3 +546,34 @@ pub(crate) fn get_connected_device( pub(crate) fn connect_enum(model: Model) -> bool { unsafe { nitrokey_sys::NK_login_enum(model.into()) == 1 } } + +#[cfg(test)] +mod tests { + use super::get_hidapi_serial_number; + + #[test] + fn hidapi_serial_number() { + assert_eq!(None, get_hidapi_serial_number("")); + assert_eq!(None, get_hidapi_serial_number("00000000000000000")); + assert_eq!( + Some("00001234".to_string()), + get_hidapi_serial_number("1234") + ); + assert_eq!( + Some("00001234".to_string()), + get_hidapi_serial_number("00001234") + ); + assert_eq!( + Some("00001234".to_string()), + get_hidapi_serial_number("000000001234") + ); + assert_eq!( + Some("100000001234".to_string()), + get_hidapi_serial_number("100000001234") + ); + assert_eq!( + Some("10000001234".to_string()), + get_hidapi_serial_number("010000001234") + ); + } +} -- cgit v1.2.1 From dbee55efa41496c8a683bfab96163facc93d6639 Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Sat, 11 Jan 2020 20:05:39 +0100 Subject: Add support for the GET_STATUS command This patch adds support for the GET_STATUS command that returns the status information common to all Nitrokey devices. It can be accessed using the Device::get_status function and is stored in a Status struct. Due to a bug in the Storage firmware [0], the GET_STATUS command returns wrong firmware versions and serial numbers. Until this is fixed in libnitrokey [1], we have to manually execute the GET_DEVICE_STATUS command to fix these values for the Nitrokey Storage. Also, this leads to a name clash with the existing Storage::get_status function, which will be renamed in an upcoming patch. [0] https://github.com/Nitrokey/nitrokey-storage-firmware/issues/96 [1] https://github.com/Nitrokey/libnitrokey/issues/166 --- src/device/mod.rs | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) (limited to 'src/device/mod.rs') diff --git a/src/device/mod.rs b/src/device/mod.rs index e015886..668c230 100644 --- a/src/device/mod.rs +++ b/src/device/mod.rs @@ -153,6 +153,35 @@ impl fmt::Display for FirmwareVersion { } } +/// The status information common to all Nitrokey devices. +pub struct Status { + /// The firmware version of the device. + pub firmware_version: FirmwareVersion, + /// The serial number of the device. + pub serial_number: u32, + /// The configuration of the device. + pub config: Config, +} + +impl From for Status { + fn from(status: nitrokey_sys::NK_status) -> Self { + Self { + firmware_version: FirmwareVersion { + major: status.firmware_version_major, + minor: status.firmware_version_minor, + }, + serial_number: status.serial_number_smart_card, + config: RawConfig { + numlock: status.config_numlock, + capslock: status.config_capslock, + scrollock: status.config_scrolllock, + user_password: status.otp_user_password, + } + .into(), + } + } +} + /// A Nitrokey device. /// /// This trait provides the commands that can be executed without authentication and that are @@ -197,6 +226,35 @@ pub trait Device<'a>: Authenticate<'a> + GetPasswordSafe<'a> + GenerateOtp + fmt /// # } fn get_model(&self) -> Model; + /// Returns the status of the Nitrokey device. + /// + /// This methods returns the status information common to all Nitrokey devices as a + /// [`Status`][] struct. Some models may provide more information, for example + /// [`Storage::get_status`][] returns the [`StorageStatus`][] struct. + /// + /// # Errors + /// + /// - [`NotConnected`][] if the Nitrokey device has been disconnected + /// + /// # Example + /// + /// ```no_run + /// use nitrokey::Device; + /// + /// let mut manager = nitrokey::take()?; + /// let device = manager.connect()?; + /// let status = device.get_status()?; + /// println!("Firmware version: {}", status.firmware_version); + /// println!("Serial number: {:x}", status.serial_number); + /// # Ok::<(), nitrokey::Error>(()) + /// ``` + /// + /// [`NotConnected`]: enum.CommunicationError.html#variant.NotConnected + /// [`Status`]: struct.Status.html + /// [`Storage::get_status`]: struct.Storage.html#method.get_status + /// [`StorageStatus`]: struct.StorageStatus.html + fn get_status(&self) -> Result; + /// Returns the serial number of the Nitrokey device. The serial number is the string /// representation of a hex number. /// -- cgit v1.2.1 From 6142752da1563c1ab873dc7069aeec72522cca99 Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Sat, 11 Jan 2020 20:13:22 +0100 Subject: Rename Status::get_status to get_storage_status MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In the last patch, we added the get_status function to the Device trait. This patch renames the Storage::get_status function to get_storage_status to resolve the name clash – though allowed by the compiler, it is rather confusing for the end user. --- src/device/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/device/mod.rs') diff --git a/src/device/mod.rs b/src/device/mod.rs index 668c230..ef9f018 100644 --- a/src/device/mod.rs +++ b/src/device/mod.rs @@ -230,7 +230,7 @@ pub trait Device<'a>: Authenticate<'a> + GetPasswordSafe<'a> + GenerateOtp + fmt /// /// This methods returns the status information common to all Nitrokey devices as a /// [`Status`][] struct. Some models may provide more information, for example - /// [`Storage::get_status`][] returns the [`StorageStatus`][] struct. + /// [`get_storage_status`][] returns the [`StorageStatus`][] struct. /// /// # Errors /// @@ -249,9 +249,9 @@ pub trait Device<'a>: Authenticate<'a> + GetPasswordSafe<'a> + GenerateOtp + fmt /// # Ok::<(), nitrokey::Error>(()) /// ``` /// + /// [`get_storage_status`]: struct.Storage.html#method.get_storage_status /// [`NotConnected`]: enum.CommunicationError.html#variant.NotConnected /// [`Status`]: struct.Status.html - /// [`Storage::get_status`]: struct.Storage.html#method.get_status /// [`StorageStatus`]: struct.StorageStatus.html fn get_status(&self) -> Result; -- cgit v1.2.1 From eb04dafce313ff5349b1c93d8d87cb53ba320e7e Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Tue, 14 Jan 2020 16:18:02 +0100 Subject: Derive Clone, Copy, Debug, PartialEq for Status Somehow I forgot to derive the common traits for the new Status struct. This patch adds the missing derive attribute for Clone, Copy, Debug and PartialEq. --- src/device/mod.rs | 1 + 1 file changed, 1 insertion(+) (limited to 'src/device/mod.rs') diff --git a/src/device/mod.rs b/src/device/mod.rs index ef9f018..8b7f1c6 100644 --- a/src/device/mod.rs +++ b/src/device/mod.rs @@ -154,6 +154,7 @@ impl fmt::Display for FirmwareVersion { } /// The status information common to all Nitrokey devices. +#[derive(Clone, Copy, Debug, PartialEq)] pub struct Status { /// The firmware version of the device. pub firmware_version: FirmwareVersion, -- cgit v1.2.1 From f266ea63039c87886f871b068ef3dcdf851a1eca Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Tue, 14 Jan 2020 13:48:56 +0100 Subject: Add the get_operation_status function to the Storage struct This patch adds support for the NK_get_progress_bar_value function: It adds the OperationStatus enum that stores the return value of this command and adds the get_operation_status function to the Storage struct that executes the command. --- src/device/mod.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src/device/mod.rs') diff --git a/src/device/mod.rs b/src/device/mod.rs index 8b7f1c6..16d6b11 100644 --- a/src/device/mod.rs +++ b/src/device/mod.rs @@ -25,7 +25,8 @@ use crate::util::{ pub use pro::Pro; pub use storage::{ - SdCardData, Storage, StorageProductionInfo, StorageStatus, VolumeMode, VolumeStatus, + OperationStatus, SdCardData, Storage, StorageProductionInfo, StorageStatus, VolumeMode, + VolumeStatus, }; pub use wrapper::DeviceWrapper; -- cgit v1.2.1