From e97ccf213eec4e2d056c2f72079e4eeb7ac66f3f Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Mon, 28 Jan 2019 12:05:42 +0000 Subject: Implement DerefMut for User and Admin As we want to change some methods to take a mutable reference to a Device, we implement DerefMut for User and Admin so that users can obtain a mutable reference to the wrapped device. --- src/auth.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) (limited to 'src/auth.rs') diff --git a/src/auth.rs b/src/auth.rs index 8978f32..8cec49c 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -1,7 +1,7 @@ // Copyright (C) 2018-2019 Robin Krahl // SPDX-License-Identifier: MIT -use std::ops::Deref; +use std::ops; use std::os::raw::c_char; use std::os::raw::c_int; @@ -211,7 +211,7 @@ impl User { } } -impl Deref for User { +impl ops::Deref for User { type Target = T; fn deref(&self) -> &Self::Target { @@ -219,6 +219,12 @@ impl Deref for User { } } +impl ops::DerefMut for User { + fn deref_mut(&mut self) -> &mut T { + &mut self.device + } +} + impl GenerateOtp for User { fn get_hotp_code(&self, slot: u8) -> Result { result_from_string(unsafe { @@ -246,7 +252,7 @@ impl AuthenticatedDevice for User { } } -impl Deref for Admin { +impl ops::Deref for Admin { type Target = T; fn deref(&self) -> &Self::Target { @@ -254,6 +260,12 @@ impl Deref for Admin { } } +impl ops::DerefMut for Admin { + fn deref_mut(&mut self) -> &mut T { + &mut self.device + } +} + impl Admin { /// Forgets the user authentication and returns an unauthenticated device. This method /// consumes the authenticated device. It does not perform any actual commands on the -- cgit v1.2.1 From f49e61589e32217f97c94aa86d826f6b65170fba Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Mon, 28 Jan 2019 12:27:15 +0000 Subject: Require mutable reference if method changes device state Previously, all methods that access a Nitrokey device took a reference to the device as input. This method changes methods that change the device state to require a mutable reference instead. In most case, this is straightforward as the method writes data to the device (for example write_config or change_user_pin). But there are two edge cases: - Authenticating with a PIN changes the device state as it may decrease the PIN retry counter if the authentication fails. - Generating an HOTP code changes the device state as it increases the HOTP counter. --- src/auth.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'src/auth.rs') diff --git a/src/auth.rs b/src/auth.rs index 8cec49c..f9f50fa 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -226,7 +226,7 @@ impl ops::DerefMut for User { } impl GenerateOtp for User { - fn get_hotp_code(&self, slot: u8) -> Result { + fn get_hotp_code(&mut self, slot: u8) -> Result { result_from_string(unsafe { nitrokey_sys::NK_get_hotp_code_PIN(slot, self.temp_password_ptr()) }) @@ -290,7 +290,7 @@ impl Admin { /// let device = nitrokey::connect()?; /// let config = Config::new(None, None, None, false); /// match device.authenticate_admin("12345678") { - /// Ok(admin) => { + /// Ok(mut admin) => { /// admin.write_config(config); /// () /// }, @@ -301,7 +301,7 @@ impl Admin { /// ``` /// /// [`InvalidSlot`]: enum.LibraryError.html#variant.InvalidSlot - pub fn write_config(&self, config: Config) -> Result<(), Error> { + pub fn write_config(&mut self, config: Config) -> Result<(), Error> { let raw_config = RawConfig::try_from(config)?; get_command_result(unsafe { nitrokey_sys::NK_write_config( @@ -317,7 +317,7 @@ impl Admin { } impl ConfigureOtp for Admin { - fn write_hotp_slot(&self, data: OtpSlotData, counter: u64) -> Result<(), Error> { + fn write_hotp_slot(&mut self, data: OtpSlotData, counter: u64) -> Result<(), Error> { let raw_data = RawOtpSlotData::new(data)?; get_command_result(unsafe { nitrokey_sys::NK_write_hotp_slot( @@ -334,7 +334,7 @@ impl ConfigureOtp for Admin { }) } - fn write_totp_slot(&self, data: OtpSlotData, time_window: u16) -> Result<(), Error> { + fn write_totp_slot(&mut self, data: OtpSlotData, time_window: u16) -> Result<(), Error> { let raw_data = RawOtpSlotData::new(data)?; get_command_result(unsafe { nitrokey_sys::NK_write_totp_slot( @@ -351,13 +351,13 @@ impl ConfigureOtp for Admin { }) } - fn erase_hotp_slot(&self, slot: u8) -> Result<(), Error> { + fn erase_hotp_slot(&mut self, slot: u8) -> Result<(), Error> { get_command_result(unsafe { nitrokey_sys::NK_erase_hotp_slot(slot, self.temp_password_ptr()) }) } - fn erase_totp_slot(&self, slot: u8) -> Result<(), Error> { + fn erase_totp_slot(&mut self, slot: u8) -> Result<(), Error> { get_command_result(unsafe { nitrokey_sys::NK_erase_totp_slot(slot, self.temp_password_ptr()) }) -- cgit v1.2.1 From 0972bbe82623c3d9649b6023d8f50d304aa0cde6 Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Mon, 28 Jan 2019 14:24:12 +0000 Subject: Refactor User and Admin to use a mutable reference MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In the initial nitrokey-rs implementation, the Admin and the User struct take the Device by value to make sure that the user cannot initiate a second authentication while this first is still active (which would invalidate the temporary password). Now we realized that this is not necessary – taking a mutable reference has the same effect, but leads to a much cleaner API. This patch refactors the Admin and User structs – and all dependent code – to use a mutable reference instead of a Device value. --- src/auth.rs | 183 ++++++++++++++++++------------------------------------------ 1 file changed, 53 insertions(+), 130 deletions(-) (limited to 'src/auth.rs') diff --git a/src/auth.rs b/src/auth.rs index f9f50fa..573fed3 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -42,16 +42,10 @@ pub trait Authenticate { /// fn perform_other_task(device: &DeviceWrapper) {} /// /// # fn try_main() -> Result<(), Error> { - /// let device = nitrokey::connect()?; - /// let device = match device.authenticate_user("123456") { - /// Ok(user) => { - /// perform_user_task(&user); - /// user.device() - /// }, - /// Err((device, err)) => { - /// eprintln!("Could not authenticate as user: {}", err); - /// device - /// }, + /// let mut device = nitrokey::connect()?; + /// match device.authenticate_user("123456") { + /// Ok(user) => perform_user_task(&user), + /// Err(err) => eprintln!("Could not authenticate as user: {}", err), /// }; /// perform_other_task(&device); /// # Ok(()) @@ -61,9 +55,9 @@ pub trait Authenticate { /// [`InvalidString`]: enum.LibraryError.html#variant.InvalidString /// [`RngError`]: enum.CommandError.html#variant.RngError /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword - fn authenticate_user(self, password: &str) -> Result, (Self, Error)> + fn authenticate_user(&mut self, password: &str) -> Result, Error> where - Self: Device + Sized; + Self: Device + std::marker::Sized; /// Performs admin authentication. This method consumes the device. If successful, an /// authenticated device is returned. Otherwise, the current unauthenticated device and the @@ -88,16 +82,10 @@ pub trait Authenticate { /// fn perform_other_task(device: &DeviceWrapper) {} /// /// # fn try_main() -> Result<(), Error> { - /// let device = nitrokey::connect()?; - /// let device = match device.authenticate_admin("123456") { - /// Ok(admin) => { - /// perform_admin_task(&admin); - /// admin.device() - /// }, - /// Err((device, err)) => { - /// eprintln!("Could not authenticate as admin: {}", err); - /// device - /// }, + /// let mut device = nitrokey::connect()?; + /// match device.authenticate_admin("123456") { + /// Ok(admin) => perform_admin_task(&admin), + /// Err(err) => eprintln!("Could not authenticate as admin: {}", err), /// }; /// perform_other_task(&device); /// # Ok(()) @@ -107,13 +95,13 @@ pub trait Authenticate { /// [`InvalidString`]: enum.LibraryError.html#variant.InvalidString /// [`RngError`]: enum.CommandError.html#variant.RngError /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword - fn authenticate_admin(self, password: &str) -> Result, (Self, Error)> + fn authenticate_admin(&mut self, password: &str) -> Result, Error> where - Self: Device + Sized; + Self: Device + std::marker::Sized; } -trait AuthenticatedDevice { - fn new(device: T, temp_password: Vec) -> Self; +trait AuthenticatedDevice<'a, T> { + fn new(device: &'a mut T, temp_password: Vec) -> Self; fn temp_password_ptr(&self) -> *const c_char; } @@ -128,8 +116,8 @@ trait AuthenticatedDevice { /// [`authenticate_admin`]: trait.Authenticate.html#method.authenticate_admin /// [`device`]: #method.device #[derive(Debug)] -pub struct User { - device: T, +pub struct User<'a, T: Device> { + device: &'a mut T, temp_password: Vec, } @@ -143,89 +131,42 @@ pub struct User { /// [`authenticate_admin`]: trait.Authenticate.html#method.authenticate_admin /// [`device`]: #method.device #[derive(Debug)] -pub struct Admin { - device: T, +pub struct Admin<'a, T: Device> { + device: &'a mut T, temp_password: Vec, } -fn authenticate(device: D, password: &str, callback: T) -> Result +fn authenticate<'a, D, A, T>(device: &'a mut D, password: &str, callback: T) -> Result where D: Device, - A: AuthenticatedDevice, + A: AuthenticatedDevice<'a, D>, T: Fn(*const c_char, *const c_char) -> c_int, { - let temp_password = match generate_password(TEMPORARY_PASSWORD_LENGTH) { - Ok(temp_password) => temp_password, - Err(err) => return Err((device, err)), - }; - let password = match get_cstring(password) { - Ok(password) => password, - Err(err) => return Err((device, err)), - }; + let temp_password = generate_password(TEMPORARY_PASSWORD_LENGTH)?; + let password = get_cstring(password)?; let password_ptr = password.as_ptr(); let temp_password_ptr = temp_password.as_ptr() as *const c_char; match callback(password_ptr, temp_password_ptr) { 0 => Ok(A::new(device, temp_password)), - rv => Err((device, Error::from(rv))), + rv => Err(Error::from(rv)), } } -fn authenticate_user_wrapper( - device: T, - constructor: C, - password: &str, -) -> Result, (DeviceWrapper, Error)> -where - T: Device, - C: Fn(T) -> DeviceWrapper, -{ - let result = device.authenticate_user(password); - match result { - Ok(user) => Ok(User::new(constructor(user.device), user.temp_password)), - Err((device, err)) => Err((constructor(device), err)), - } -} - -fn authenticate_admin_wrapper( - device: T, - constructor: C, - password: &str, -) -> Result, (DeviceWrapper, Error)> -where - T: Device, - C: Fn(T) -> DeviceWrapper, -{ - let result = device.authenticate_admin(password); - match result { - Ok(user) => Ok(Admin::new(constructor(user.device), user.temp_password)), - Err((device, err)) => Err((constructor(device), err)), - } -} - -impl User { - /// Forgets the user authentication and returns an unauthenticated device. This method - /// consumes the authenticated device. It does not perform any actual commands on the - /// Nitrokey. - pub fn device(self) -> T { - self.device - } -} - -impl ops::Deref for User { +impl<'a, T: Device> ops::Deref for User<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { - &self.device + self.device } } -impl ops::DerefMut for User { +impl<'a, T: Device> ops::DerefMut for User<'a, T> { fn deref_mut(&mut self) -> &mut T { - &mut self.device + self.device } } -impl GenerateOtp for User { +impl<'a, T: Device> GenerateOtp for User<'a, T> { fn get_hotp_code(&mut self, slot: u8) -> Result { result_from_string(unsafe { nitrokey_sys::NK_get_hotp_code_PIN(slot, self.temp_password_ptr()) @@ -239,8 +180,8 @@ impl GenerateOtp for User { } } -impl AuthenticatedDevice for User { - fn new(device: T, temp_password: Vec) -> Self { +impl<'a, T: Device> AuthenticatedDevice<'a, T> for User<'a, T> { + fn new(device: &'a mut T, temp_password: Vec) -> Self { User { device, temp_password, @@ -252,28 +193,21 @@ impl AuthenticatedDevice for User { } } -impl ops::Deref for Admin { +impl<'a, T: Device> ops::Deref for Admin<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { - &self.device + self.device } } -impl ops::DerefMut for Admin { +impl<'a, T: Device> ops::DerefMut for Admin<'a, T> { fn deref_mut(&mut self) -> &mut T { - &mut self.device - } -} - -impl Admin { - /// Forgets the user authentication and returns an unauthenticated device. This method - /// consumes the authenticated device. It does not perform any actual commands on the - /// Nitrokey. - pub fn device(self) -> T { self.device } +} +impl<'a, T: Device> Admin<'a, T> { /// Writes the given configuration to the Nitrokey device. /// /// # Errors @@ -287,14 +221,11 @@ impl Admin { /// # use nitrokey::Error; /// /// # fn try_main() -> Result<(), Error> { - /// let device = nitrokey::connect()?; + /// let mut device = nitrokey::connect()?; /// let config = Config::new(None, None, None, false); /// match device.authenticate_admin("12345678") { - /// Ok(mut admin) => { - /// admin.write_config(config); - /// () - /// }, - /// Err((_, err)) => eprintln!("Could not authenticate as admin: {}", err), + /// Ok(mut admin) => admin.write_config(config)?, + /// Err(err) => eprintln!("Could not authenticate as admin: {}", err), /// }; /// # Ok(()) /// # } @@ -316,7 +247,7 @@ impl Admin { } } -impl ConfigureOtp for Admin { +impl<'a, T: Device> ConfigureOtp for Admin<'a, T> { fn write_hotp_slot(&mut self, data: OtpSlotData, counter: u64) -> Result<(), Error> { let raw_data = RawOtpSlotData::new(data)?; get_command_result(unsafe { @@ -364,8 +295,8 @@ impl ConfigureOtp for Admin { } } -impl AuthenticatedDevice for Admin { - fn new(device: T, temp_password: Vec) -> Self { +impl<'a, T: Device> AuthenticatedDevice<'a, T> for Admin<'a, T> { + fn new(device: &'a mut T, temp_password: Vec) -> Self { Admin { device, temp_password, @@ -378,35 +309,27 @@ impl AuthenticatedDevice for Admin { } impl Authenticate for DeviceWrapper { - fn authenticate_user(self, password: &str) -> Result, (Self, Error)> { - match self { - DeviceWrapper::Storage(storage) => { - authenticate_user_wrapper(storage, DeviceWrapper::Storage, password) - } - DeviceWrapper::Pro(pro) => authenticate_user_wrapper(pro, DeviceWrapper::Pro, password), - } + fn authenticate_user(&mut self, password: &str) -> Result, Error> { + authenticate(self, password, |password_ptr, temp_password_ptr| unsafe { + nitrokey_sys::NK_user_authenticate(password_ptr, temp_password_ptr) + }) } - fn authenticate_admin(self, password: &str) -> Result, (Self, Error)> { - match self { - DeviceWrapper::Storage(storage) => { - authenticate_admin_wrapper(storage, DeviceWrapper::Storage, password) - } - DeviceWrapper::Pro(pro) => { - authenticate_admin_wrapper(pro, DeviceWrapper::Pro, password) - } - } + fn authenticate_admin(&mut self, password: &str) -> Result, Error> { + authenticate(self, password, |password_ptr, temp_password_ptr| unsafe { + nitrokey_sys::NK_user_authenticate(password_ptr, temp_password_ptr) + }) } } impl Authenticate for Pro { - fn authenticate_user(self, password: &str) -> Result, (Self, Error)> { + fn authenticate_user(&mut self, password: &str) -> Result, Error> { authenticate(self, password, |password_ptr, temp_password_ptr| unsafe { nitrokey_sys::NK_user_authenticate(password_ptr, temp_password_ptr) }) } - fn authenticate_admin(self, password: &str) -> Result, (Self, Error)> { + fn authenticate_admin(&mut self, password: &str) -> Result, Error> { authenticate(self, password, |password_ptr, temp_password_ptr| unsafe { nitrokey_sys::NK_first_authenticate(password_ptr, temp_password_ptr) }) @@ -414,13 +337,13 @@ impl Authenticate for Pro { } impl Authenticate for Storage { - fn authenticate_user(self, password: &str) -> Result, (Self, Error)> { + fn authenticate_user(&mut self, password: &str) -> Result, Error> { authenticate(self, password, |password_ptr, temp_password_ptr| unsafe { nitrokey_sys::NK_user_authenticate(password_ptr, temp_password_ptr) }) } - fn authenticate_admin(self, password: &str) -> Result, (Self, Error)> { + fn authenticate_admin(&mut self, password: &str) -> Result, Error> { authenticate(self, password, |password_ptr, temp_password_ptr| unsafe { nitrokey_sys::NK_first_authenticate(password_ptr, temp_password_ptr) }) -- cgit v1.2.1