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/storage.rs | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) (limited to 'src/device/storage.rs') diff --git a/src/device/storage.rs b/src/device/storage.rs index 370ce36..64e6848 100644 --- a/src/device/storage.rs +++ b/src/device/storage.rs @@ -1,11 +1,11 @@ -// Copyright (C) 2018-2019 Robin Krahl +// Copyright (C) 2019-2019 Robin Krahl // SPDX-License-Identifier: MIT use std::fmt; use nitrokey_sys; -use crate::device::{Device, FirmwareVersion, Model}; +use crate::device::{Device, FirmwareVersion, Model, Status}; use crate::error::Error; use crate::otp::GenerateOtp; use crate::util::{get_command_result, get_cstring}; @@ -678,6 +678,33 @@ impl<'a> Device<'a> for Storage<'a> { fn get_model(&self) -> Model { Model::Storage } + + fn get_status(&self) -> Result { + // Currently, the GET_STATUS command does not report the correct firmware version and + // serial number on the Nitrokey Storage, see [0]. Until this is fixed in libnitrokey, we + // have to manually execute the GET_DEVICE_STATUS command (Storage::get_status) and + // complete the missing data, see [1]. + // [0] https://github.com/Nitrokey/nitrokey-storage-firmware/issues/96 + // [1] https://github.com/Nitrokey/libnitrokey/issues/166 + + let mut raw_status = nitrokey_sys::NK_status { + firmware_version_major: 0, + firmware_version_minor: 0, + serial_number_smart_card: 0, + config_numlock: 0, + config_capslock: 0, + config_scrolllock: 0, + otp_user_password: false, + }; + get_command_result(unsafe { nitrokey_sys::NK_get_status(&mut raw_status) })?; + let mut status = Status::from(raw_status); + + let storage_status = Storage::get_status(&self)?; + status.firmware_version = storage_status.firmware_version; + status.serial_number = storage_status.serial_number_smart_card; + + Ok(status) + } } impl<'a> GenerateOtp for Storage<'a> {} -- 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/storage.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src/device/storage.rs') diff --git a/src/device/storage.rs b/src/device/storage.rs index 64e6848..08ec4e9 100644 --- a/src/device/storage.rs +++ b/src/device/storage.rs @@ -525,7 +525,7 @@ impl<'a> Storage<'a> { /// # fn try_main() -> Result<(), Error> { /// let mut manager = nitrokey::take()?; /// let device = manager.connect_storage()?; - /// match device.get_status() { + /// match device.get_storage_status() { /// Ok(status) => { /// println!("SD card ID: {:#x}", status.serial_number_sd_card); /// }, @@ -534,7 +534,7 @@ impl<'a> Storage<'a> { /// # Ok(()) /// # } /// ``` - pub fn get_status(&self) -> Result { + pub fn get_storage_status(&self) -> Result { let mut raw_status = nitrokey_sys::NK_storage_status { unencrypted_volume_read_only: false, unencrypted_volume_active: false, @@ -682,8 +682,8 @@ impl<'a> Device<'a> for Storage<'a> { fn get_status(&self) -> Result { // Currently, the GET_STATUS command does not report the correct firmware version and // serial number on the Nitrokey Storage, see [0]. Until this is fixed in libnitrokey, we - // have to manually execute the GET_DEVICE_STATUS command (Storage::get_status) and - // complete the missing data, see [1]. + // have to manually execute the GET_DEVICE_STATUS command (get_storage_status) and complete + // the missing data, see [1]. // [0] https://github.com/Nitrokey/nitrokey-storage-firmware/issues/96 // [1] https://github.com/Nitrokey/libnitrokey/issues/166 @@ -699,7 +699,7 @@ impl<'a> Device<'a> for Storage<'a> { get_command_result(unsafe { nitrokey_sys::NK_get_status(&mut raw_status) })?; let mut status = Status::from(raw_status); - let storage_status = Storage::get_status(&self)?; + let storage_status = self.get_storage_status()?; status.firmware_version = storage_status.firmware_version; status.serial_number = storage_status.serial_number_smart_card; -- cgit v1.2.1 From 73c8aebac338d3454d7e345ffd687324317077ec Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Tue, 14 Jan 2020 12:00:15 +0100 Subject: Add the get_sd_card_usage function to the Storage struct This patch adds support for the NK_get_SD_usage_data function. It returns a range of the SD card that has not been accessed during this power cycle. --- src/device/storage.rs | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) (limited to 'src/device/storage.rs') diff --git a/src/device/storage.rs b/src/device/storage.rs index 08ec4e9..a2c598b 100644 --- a/src/device/storage.rs +++ b/src/device/storage.rs @@ -1,7 +1,8 @@ -// Copyright (C) 2019-2019 Robin Krahl +// Copyright (C) 2019-2020 Robin Krahl // SPDX-License-Identifier: MIT use std::fmt; +use std::ops; use nitrokey_sys; @@ -635,6 +636,45 @@ impl<'a> Storage<'a> { }) } + /// Returns a range of the SD card that has not been used to during this power cycle. + /// + /// The Nitrokey Storage tracks read and write access to the SD card during a power cycle. + /// This method returns a range of the SD card that has not been accessed during this power + /// cycle. The range is relative to the total size of the SD card, so both values are less + /// than or equal to 100. This can be used as a guideline when creating a hidden volume. + /// + /// # Example + /// + /// ```no_run + /// let mut manager = nitrokey::take()?; + /// let storage = manager.connect_storage()?; + /// let usage = storage.get_sd_card_usage()?; + /// println!("SD card usage: {}..{}", usage.start, usage.end); + /// # Ok::<(), nitrokey::Error>(()) + /// ``` + pub fn get_sd_card_usage(&self) -> Result, Error> { + let mut usage_data = nitrokey_sys::NK_SD_usage_data { + write_level_min: 0, + write_level_max: 0, + }; + let result = unsafe { nitrokey_sys::NK_get_SD_usage_data(&mut usage_data) }; + match get_command_result(result) { + Ok(_) => { + if usage_data.write_level_min > usage_data.write_level_max + || usage_data.write_level_max > 100 + { + Err(Error::UnexpectedError) + } else { + Ok(ops::Range { + start: usage_data.write_level_min, + end: usage_data.write_level_max, + }) + } + } + Err(err) => Err(err), + } + } + /// Blinks the red and green LED alternatively and infinitely until the device is reconnected. pub fn wink(&mut self) -> Result<(), Error> { get_command_result(unsafe { nitrokey_sys::NK_wink() }) -- 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/storage.rs | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) (limited to 'src/device/storage.rs') diff --git a/src/device/storage.rs b/src/device/storage.rs index a2c598b..8d45763 100644 --- a/src/device/storage.rs +++ b/src/device/storage.rs @@ -1,6 +1,7 @@ // Copyright (C) 2019-2020 Robin Krahl // SPDX-License-Identifier: MIT +use std::convert::TryFrom as _; use std::fmt; use std::ops; @@ -9,7 +10,7 @@ use nitrokey_sys; use crate::device::{Device, FirmwareVersion, Model, Status}; use crate::error::Error; use crate::otp::GenerateOtp; -use crate::util::{get_command_result, get_cstring}; +use crate::util::{get_command_result, get_cstring, get_last_error}; /// A Nitrokey Storage device without user or admin authentication. /// @@ -142,6 +143,20 @@ pub struct StorageStatus { pub stick_initialized: bool, } +/// The progress of a background operation on the Nitrokey. +/// +/// Some commands may start a background operation during which no other commands can be executed. +/// This enum stores the status of a background operation: Ongoing with a relative progress (up to +/// 100), or idle, i. e. no background operation has been started or the last one has been +/// finished. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum OperationStatus { + /// A background operation with its progress value (less than or equal to 100). + Ongoing(u8), + /// No backgrund operation. + Idle, +} + impl<'a> Storage<'a> { pub(crate) fn new(manager: &'a mut crate::Manager) -> Storage<'a> { Storage { @@ -680,6 +695,24 @@ impl<'a> Storage<'a> { get_command_result(unsafe { nitrokey_sys::NK_wink() }) } + /// Returns the status of an ongoing background operation on the Nitrokey Storage. + /// + /// Some commands may start a background operation during which no other commands can be + /// executed. This method can be used to check whether such an operation is ongoing. + /// + /// Currently, this is only used by the `fill_sd_card` method. + pub fn get_operation_status(&self) -> Result { + let status = unsafe { nitrokey_sys::NK_get_progress_bar_value() }; + match status { + 0..=100 => u8::try_from(status) + .map(OperationStatus::Ongoing) + .map_err(|_| Error::UnexpectedError), + -1 => Ok(OperationStatus::Idle), + -2 => Err(get_last_error()), + _ => Err(Error::UnexpectedError), + } + } + /// Exports the firmware to the unencrypted volume. /// /// This command requires the admin PIN. The unencrypted volume must be in read-write mode -- cgit v1.2.1 From 2e543445c3059fa9decdbef718caf84696bb8786 Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Tue, 14 Jan 2020 16:15:40 +0100 Subject: Add the fill_sd_card function to Storage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This patch adds support for libnitrokey’s NK_fill_SD_card_with_random_data function. It is executed by the fill_sd_card function of the Storage struct. We also add a new test case that is set to ignore because it takes between 30 and 60 minutes to run. --- src/device/storage.rs | 53 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) (limited to 'src/device/storage.rs') diff --git a/src/device/storage.rs b/src/device/storage.rs index 8d45763..deb2844 100644 --- a/src/device/storage.rs +++ b/src/device/storage.rs @@ -8,7 +8,7 @@ use std::ops; use nitrokey_sys; use crate::device::{Device, FirmwareVersion, Model, Status}; -use crate::error::Error; +use crate::error::{CommandError, Error}; use crate::otp::GenerateOtp; use crate::util::{get_command_result, get_cstring, get_last_error}; @@ -700,7 +700,9 @@ impl<'a> Storage<'a> { /// Some commands may start a background operation during which no other commands can be /// executed. This method can be used to check whether such an operation is ongoing. /// - /// Currently, this is only used by the `fill_sd_card` method. + /// Currently, this is only used by the [`fill_sd_card`][] method. + /// + /// [`fill_sd_card`]: #method.fill_sd_card pub fn get_operation_status(&self) -> Result { let status = unsafe { nitrokey_sys::NK_get_progress_bar_value() }; match status { @@ -713,6 +715,53 @@ impl<'a> Storage<'a> { } } + /// Overwrites the SD card with random data. + /// + /// Ths method starts a background operation that overwrites the SD card with random data. + /// While this operation is ongoing, no other commands can be executed. Use the + /// [`get_operation_status`][] function to check the progress of the operation. + /// + /// # Errors + /// + /// - [`InvalidString`][] if one of the provided passwords contains a null byte + /// - [`WrongPassword`][] if the admin password is wrong + /// + /// # Example + /// + /// ```no_run + /// use nitrokey::OperationStatus; + /// + /// let mut manager = nitrokey::take()?; + /// let mut storage = manager.connect_storage()?; + /// storage.fill_sd_card("12345678")?; + /// loop { + /// match storage.get_operation_status()? { + /// OperationStatus::Ongoing(progress) => println!("{}/100", progress), + /// OperationStatus::Idle => { + /// println!("Done!"); + /// break; + /// } + /// } + /// } + /// # Ok::<(), nitrokey::Error>(()) + /// ``` + /// + /// [`get_operation_status`]: #method.get_operation_status + /// [`InvalidString`]: enum.LibraryError.html#variant.InvalidString + /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword + pub fn fill_sd_card(&mut self, admin_pin: &str) -> Result<(), Error> { + let admin_pin_string = get_cstring(admin_pin)?; + get_command_result(unsafe { + nitrokey_sys::NK_fill_SD_card_with_random_data(admin_pin_string.as_ptr()) + }) + .or_else(|err| match err { + // libnitrokey’s C API returns a LongOperationInProgressException with the same error + // code as the WrongCrc command error, so we cannot distinguish them. + Error::CommandError(CommandError::WrongCrc) => Ok(()), + err => Err(err), + }) + } + /// Exports the firmware to the unencrypted volume. /// /// This command requires the admin PIN. The unencrypted volume must be in read-write mode -- cgit v1.2.1