diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/arg_util.rs | 168 | ||||
-rw-r--r-- | src/args.rs | 436 | ||||
-rw-r--r-- | src/commands.rs | 1008 | ||||
-rw-r--r-- | src/error.rs | 118 | ||||
-rw-r--r-- | src/main.rs | 239 | ||||
-rw-r--r-- | src/pinentry.rs | 395 | ||||
-rw-r--r-- | src/redefine.rs | 38 | ||||
-rw-r--r-- | src/tests/config.rs | 84 | ||||
-rw-r--r-- | src/tests/encrypted.rs | 95 | ||||
-rw-r--r-- | src/tests/hidden.rs | 49 | ||||
-rw-r--r-- | src/tests/list.rs | 42 | ||||
-rw-r--r-- | src/tests/lock.rs | 44 | ||||
-rw-r--r-- | src/tests/mod.rs | 188 | ||||
-rw-r--r-- | src/tests/otp.rs | 130 | ||||
-rw-r--r-- | src/tests/pin.rs | 84 | ||||
-rw-r--r-- | src/tests/pws.rs | 123 | ||||
-rw-r--r-- | src/tests/reset.rs | 60 | ||||
-rw-r--r-- | src/tests/run.rs | 110 | ||||
-rw-r--r-- | src/tests/status.rs | 81 | ||||
-rw-r--r-- | src/tests/unencrypted.rs | 46 |
20 files changed, 3538 insertions, 0 deletions
diff --git a/src/arg_util.rs b/src/arg_util.rs new file mode 100644 index 0000000..3a4c001 --- /dev/null +++ b/src/arg_util.rs @@ -0,0 +1,168 @@ +// arg_util.rs + +// ************************************************************************* +// * Copyright (C) 2019-2020 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +macro_rules! count { + ($head:ident) => { 1 }; + ($head:ident, $($tail:ident),*) => { + 1 + count!($($tail),*) + } +} + +/// Translate an optional source into an optional destination. +macro_rules! tr { + ($dst:tt, $src:tt) => { + $dst + }; + ($dst:tt) => {}; +} + +macro_rules! Command { + ( $(#[$docs:meta])* $name:ident, [ + $( $(#[$doc:meta])* $var:ident$(($inner:ty))? => $exec:expr, ) * + ] ) => { + $(#[$docs])* + #[derive(Debug, PartialEq, structopt::StructOpt)] + pub enum $name { + $( + $(#[$doc])* + $var$(($inner))?, + )* + } + + #[allow(unused_qualifications)] + impl $name { + pub fn execute( + self, + ctx: &mut crate::ExecCtx<'_>, + ) -> crate::Result<()> { + match self { + $( + $name::$var$((tr!(args, $inner)))? => $exec(ctx $(,tr!(args, $inner))?), + )* + } + } + } + }; +} + +/// A macro for generating an enum with a set of simple (i.e., no +/// parameters) variants and their textual representations. +// TODO: Right now we hard code the derives we create. We may want to +// make this set configurable. +macro_rules! Enum { + ( $(#[$docs:meta])* $name:ident, [ $( $var:ident => $str:expr, ) *] ) => { + $(#[$docs])* + #[derive(Clone, Copy, Debug, PartialEq)] + pub enum $name { + $( + $var, + )* + } + + enum_int! {$name, [ + $( $var => $str, )* + ]} + }; +} + +macro_rules! enum_int { + ( $name:ident, [ $( $var:ident => $str:expr, ) *] ) => { + impl $name { + #[allow(unused)] + pub fn all(&self) -> [$name; count!($($var),*) ] { + $name::all_variants() + } + + pub fn all_variants() -> [$name; count!($($var),*) ] { + [ + $( + $name::$var, + )* + ] + } + + #[allow(unused)] + pub fn all_str() -> [&'static str; count!($($var),*)] { + [ + $( + $str, + )* + ] + } + } + + impl ::std::convert::AsRef<str> for $name { + fn as_ref(&self) -> &'static str { + match *self { + $( + $name::$var => $str, + )* + } + } + } + + impl ::std::fmt::Display for $name { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + write!(f, "{}", self.as_ref()) + } + } + + impl ::std::str::FromStr for $name { + type Err = ::std::string::String; + + fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> { + match s { + $( + $str => Ok($name::$var), + )* + _ => Err( + format!( + "expected one of {}", + $name::all_str().join(", "), + ) + ) + } + } + } + }; +} + +#[cfg(test)] +mod tests { + Enum! {Command, [ + Var1 => "var1", + Var2 => "2", + Var3 => "crazy", + ]} + + #[test] + fn all_variants() { + assert_eq!( + Command::all_variants(), + [Command::Var1, Command::Var2, Command::Var3] + ) + } + + #[test] + fn text_representations() { + assert_eq!(Command::Var1.as_ref(), "var1"); + assert_eq!(Command::Var2.as_ref(), "2"); + assert_eq!(Command::Var3.as_ref(), "crazy"); + } +} diff --git a/src/args.rs b/src/args.rs new file mode 100644 index 0000000..91b340c --- /dev/null +++ b/src/args.rs @@ -0,0 +1,436 @@ +// args.rs + +// ************************************************************************* +// * Copyright (C) 2020 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +/// Provides access to a Nitrokey device +#[derive(structopt::StructOpt)] +#[structopt(name = "nitrocli")] +pub struct Args { + /// Increases the log level (can be supplied multiple times) + #[structopt(short, long, global = true, parse(from_occurrences))] + pub verbose: u8, + /// Selects the device model to connect to + #[structopt(short, long, global = true, possible_values = &DeviceModel::all_str())] + pub model: Option<DeviceModel>, + #[structopt(subcommand)] + pub cmd: Command, +} + +Enum! { + /// The available Nitrokey models. + DeviceModel, [ + Pro => "pro", + Storage => "storage", + ] +} + +impl DeviceModel { + pub fn as_user_facing_str(&self) -> &str { + match self { + DeviceModel::Pro => "Pro", + DeviceModel::Storage => "Storage", + } + } +} + +impl From<DeviceModel> for nitrokey::Model { + fn from(model: DeviceModel) -> nitrokey::Model { + match model { + DeviceModel::Pro => nitrokey::Model::Pro, + DeviceModel::Storage => nitrokey::Model::Storage, + } + } +} + +Command! { + /// A top-level command for nitrocli. + Command, [ + /// Reads or writes the device configuration + Config(ConfigArgs) => |ctx, args: ConfigArgs| args.subcmd.execute(ctx), + /// Interacts with the device's encrypted volume + Encrypted(EncryptedArgs) => |ctx, args: EncryptedArgs| args.subcmd.execute(ctx), + /// Interacts with the device's hidden volume + Hidden(HiddenArgs) => |ctx, args: HiddenArgs| args.subcmd.execute(ctx), + /// Lists the attached Nitrokey devices + List(ListArgs) => |ctx, args: ListArgs| crate::commands::list(ctx, args.no_connect), + /// Locks the connected Nitrokey device + Lock => crate::commands::lock, + /// Accesses one-time passwords + Otp(OtpArgs) => |ctx, args: OtpArgs| args.subcmd.execute(ctx), + /// Manages the Nitrokey PINs + Pin(PinArgs) => |ctx, args: PinArgs| args.subcmd.execute(ctx), + /// Accesses the password safe + Pws(PwsArgs) => |ctx, args: PwsArgs| args.subcmd.execute(ctx), + /// Performs a factory reset + Reset => crate::commands::reset, + /// Prints the status of the connected Nitrokey device + Status => crate::commands::status, + /// Interacts with the device's unencrypted volume + Unencrypted(UnencryptedArgs) => |ctx, args: UnencryptedArgs| args.subcmd.execute(ctx), + ] +} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct ConfigArgs { + #[structopt(subcommand)] + subcmd: ConfigCommand, +} + +Command! {ConfigCommand, [ + /// Prints the Nitrokey configuration + Get => crate::commands::config_get, + /// Changes the Nitrokey configuration + Set(ConfigSetArgs) => crate::commands::config_set, +]} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct ConfigSetArgs { + /// Sets the numlock option to the given HOTP slot + #[structopt(short = "n", long)] + pub numlock: Option<u8>, + /// Unsets the numlock option + #[structopt(short = "N", long, conflicts_with("numlock"))] + pub no_numlock: bool, + /// Sets the capslock option to the given HOTP slot + #[structopt(short = "c", long)] + pub capslock: Option<u8>, + /// Unsets the capslock option + #[structopt(short = "C", long, conflicts_with("capslock"))] + pub no_capslock: bool, + /// Sets the scrollock option to the given HOTP slot + #[structopt(short = "s", long)] + pub scrollock: Option<u8>, + /// Unsets the scrollock option + #[structopt(short = "S", long, conflicts_with("scrollock"))] + pub no_scrollock: bool, + /// Requires the user PIN to generate one-time passwords + #[structopt(short = "o", long)] + pub otp_pin: bool, + /// Allows one-time password generation without PIN + #[structopt(short = "O", long, conflicts_with("otp-pin"))] + pub no_otp_pin: bool, +} + +#[derive(Clone, Copy, Debug)] +pub enum ConfigOption<T> { + Enable(T), + Disable, + Ignore, +} + +impl<T> ConfigOption<T> { + pub fn try_from(disable: bool, value: Option<T>, name: &'static str) -> Result<Self, String> { + if disable { + if value.is_some() { + Err(format!( + "--{name} and --no-{name} are mutually exclusive", + name = name + )) + } else { + Ok(ConfigOption::Disable) + } + } else { + match value { + Some(value) => Ok(ConfigOption::Enable(value)), + None => Ok(ConfigOption::Ignore), + } + } + } + + pub fn or(self, default: Option<T>) -> Option<T> { + match self { + ConfigOption::Enable(value) => Some(value), + ConfigOption::Disable => None, + ConfigOption::Ignore => default, + } + } +} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct EncryptedArgs { + #[structopt(subcommand)] + subcmd: EncryptedCommand, +} + +Command! {EncryptedCommand, [ + /// Closes the encrypted volume on a Nitrokey Storage + Close => crate::commands::encrypted_close, + /// Opens the encrypted volume on a Nitrokey Storage + Open => crate::commands::encrypted_open, +]} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct HiddenArgs { + #[structopt(subcommand)] + subcmd: HiddenCommand, +} + +Command! {HiddenCommand, [ + /// Closes the hidden volume on a Nitrokey Storage + Close => crate::commands::hidden_close, + /// Creates a hidden volume on a Nitrokey Storage + Create(HiddenCreateArgs) => |ctx, args: HiddenCreateArgs| { + crate::commands::hidden_create(ctx, args.slot, args.start, args.end) + }, + /// Opens the hidden volume on a Nitrokey Storage + Open => crate::commands::hidden_open, +]} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct HiddenCreateArgs { + /// The hidden volume slot to use + pub slot: u8, + /// The start location of the hidden volume as a percentage of the encrypted volume's size (0-99) + pub start: u8, + /// The end location of the hidden volume as a percentage of the encrypted volume's size (1-100) + pub end: u8, +} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct ListArgs { + /// Only print the information that is available without connecting to a device + #[structopt(short, long)] + pub no_connect: bool, +} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct OtpArgs { + #[structopt(subcommand)] + subcmd: OtpCommand, +} + +Command! {OtpCommand, [ + /// Clears a one-time password slot + Clear(OtpClearArgs) => |ctx, args: OtpClearArgs| { + crate::commands::otp_clear(ctx, args.slot, args.algorithm) + }, + /// Generates a one-time password + Get(OtpGetArgs) => |ctx, args: OtpGetArgs| { + crate::commands::otp_get(ctx, args.slot, args.algorithm, args.time) + }, + /// Configures a one-time password slot + Set(OtpSetArgs) => crate::commands::otp_set, + /// Prints the status of the one-time password slots + Status(OtpStatusArgs) => |ctx, args: OtpStatusArgs| crate::commands::otp_status(ctx, args.all), +]} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct OtpClearArgs { + /// The OTP algorithm to use + #[structopt(short, long, default_value = OtpAlgorithm::Totp.as_ref(), + possible_values = &OtpAlgorithm::all_str())] + pub algorithm: OtpAlgorithm, + /// The OTP slot to clear + pub slot: u8, +} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct OtpGetArgs { + /// The OTP algorithm to use + #[structopt(short, long, default_value = OtpAlgorithm::Totp.as_ref(), + possible_values = &OtpAlgorithm::all_str())] + pub algorithm: OtpAlgorithm, + /// The time to use for TOTP generation (Unix timestamp) [default: system time] + #[structopt(short, long)] + pub time: Option<u64>, + /// The OTP slot to use + pub slot: u8, +} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct OtpSetArgs { + /// The OTP algorithm to use + #[structopt(short, long, default_value = OtpAlgorithm::Totp.as_ref(), + possible_values = &OtpAlgorithm::all_str())] + pub algorithm: OtpAlgorithm, + /// The number of digits to use for the one-time password + #[structopt(short, long, default_value = OtpMode::SixDigits.as_ref(), + possible_values = &OtpMode::all_str())] + pub digits: OtpMode, + /// The counter value for HOTP + #[structopt(short, long, default_value = "0")] + pub counter: u64, + /// The time window for TOTP + #[structopt(short, long, default_value = "30")] + pub time_window: u16, + /// The format of the secret + #[structopt(short, long, default_value = OtpSecretFormat::Hex.as_ref(), + possible_values = &OtpSecretFormat::all_str())] + pub format: OtpSecretFormat, + /// The OTP slot to use + pub slot: u8, + /// The name of the slot + pub name: String, + /// The secret to store on the slot as a hexadecimal string (or in the format set with the + /// --format option) + pub secret: String, +} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct OtpStatusArgs { + /// Shows slots that are not programmed + #[structopt(short, long)] + pub all: bool, +} + +Enum! {OtpAlgorithm, [ + Hotp => "hotp", + Totp => "totp", +]} + +Enum! {OtpMode, [ + SixDigits => "6", + EightDigits => "8", +]} + +impl From<OtpMode> for nitrokey::OtpMode { + fn from(mode: OtpMode) -> Self { + match mode { + OtpMode::SixDigits => nitrokey::OtpMode::SixDigits, + OtpMode::EightDigits => nitrokey::OtpMode::EightDigits, + } + } +} + +Enum! {OtpSecretFormat, [ + Ascii => "ascii", + Base32 => "base32", + Hex => "hex", +]} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct PinArgs { + #[structopt(subcommand)] + subcmd: PinCommand, +} + +Command! {PinCommand, [ + /// Clears the cached PINs + Clear => crate::commands::pin_clear, + /// Changes a PIN + Set(PinSetArgs) => |ctx, args: PinSetArgs| crate::commands::pin_set(ctx, args.pintype), + /// Unblocks and resets the user PIN + Unblock => crate::commands::pin_unblock, +]} + +Enum! { + /// PIN type requested from pinentry. + /// + /// The available PIN types correspond to the PIN types used by the + /// Nitrokey devices: user and admin. + PinType, [ + Admin => "admin", + User => "user", + ] +} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct PinSetArgs { + /// The PIN type to change + #[structopt(name = "type", possible_values = &PinType::all_str())] + pub pintype: PinType, +} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct PwsArgs { + #[structopt(subcommand)] + subcmd: PwsCommand, +} + +Command! {PwsCommand, [ + /// Clears a password safe slot + Clear(PwsClearArgs) => |ctx, args: PwsClearArgs| crate::commands::pws_clear(ctx, args.slot), + /// Reads a password safe slot + Get(PwsGetArgs) => |ctx, args: PwsGetArgs| { + crate::commands::pws_get(ctx, args.slot, args.name, args.login, args.password, args.quiet) + }, + /// Writes a password safe slot + Set(PwsSetArgs) => |ctx, args: PwsSetArgs| { + crate::commands::pws_set(ctx, args.slot, &args.name, &args.login, &args.password) + }, + /// Prints the status of the password safe slots + Status(PwsStatusArgs) => |ctx, args: PwsStatusArgs| crate::commands::pws_status(ctx, args.all), +]} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct PwsClearArgs { + /// The PWS slot to clear + pub slot: u8, +} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct PwsGetArgs { + /// Shows the name stored on the slot + #[structopt(short, long)] + pub name: bool, + /// Shows the login stored on the slot + #[structopt(short, long)] + pub login: bool, + /// Shows the password stored on the slot + #[structopt(short, long)] + pub password: bool, + /// Prints the stored data without description + #[structopt(short, long)] + pub quiet: bool, + /// The PWS slot to read + pub slot: u8, +} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct PwsSetArgs { + /// The PWS slot to write + pub slot: u8, + /// The name to store on the slot + pub name: String, + /// The login to store on the slot + pub login: String, + /// The password to store on the slot + pub password: String, +} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct PwsStatusArgs { + /// Shows slots that are not programmed + #[structopt(short, long)] + pub all: bool, +} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct UnencryptedArgs { + #[structopt(subcommand)] + subcmd: UnencryptedCommand, +} + +Command! {UnencryptedCommand, [ + /// Changes the configuration of the unencrypted volume on a Nitrokey Storage + Set(UnencryptedSetArgs) => |ctx, args: UnencryptedSetArgs| { + crate::commands::unencrypted_set(ctx, args.mode) + }, +]} + +#[derive(Debug, PartialEq, structopt::StructOpt)] +pub struct UnencryptedSetArgs { + /// The mode to change to + #[structopt(name = "type", possible_values = &UnencryptedVolumeMode::all_str())] + pub mode: UnencryptedVolumeMode, +} + +Enum! {UnencryptedVolumeMode, [ + ReadWrite => "read-write", + ReadOnly => "read-only", +]} diff --git a/src/commands.rs b/src/commands.rs new file mode 100644 index 0000000..a2b6004 --- /dev/null +++ b/src/commands.rs @@ -0,0 +1,1008 @@ +// commands.rs + +// ************************************************************************* +// * Copyright (C) 2018-2020 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +use std::fmt; +use std::mem; +use std::result; +use std::thread; +use std::time; +use std::u8; + +use libc::sync; + +use nitrokey::ConfigureOtp; +use nitrokey::Device; +use nitrokey::GenerateOtp; +use nitrokey::GetPasswordSafe; + +use crate::args; +use crate::error; +use crate::error::Error; +use crate::pinentry; +use crate::ExecCtx; +use crate::Result; + +/// Create an `error::Error` with an error message of the format `msg: err`. +fn get_error(msg: &'static str, err: nitrokey::Error) -> Error { + Error::NitrokeyError(Some(msg), err) +} + +/// Set `libnitrokey`'s log level based on the execution context's verbosity. +fn set_log_level(ctx: &mut ExecCtx<'_>) { + let log_lvl = match ctx.verbosity { + // The error log level is what libnitrokey uses by default. As such, + // there is no harm in us setting that as well when the user did not + // ask for higher verbosity. + 0 => nitrokey::LogLevel::Error, + 1 => nitrokey::LogLevel::Warning, + 2 => nitrokey::LogLevel::Info, + 3 => nitrokey::LogLevel::DebugL1, + 4 => nitrokey::LogLevel::Debug, + _ => nitrokey::LogLevel::DebugL2, + }; + nitrokey::set_log_level(log_lvl); +} + +/// Connect to any Nitrokey device and do something with it. +fn with_device<F>(ctx: &mut ExecCtx<'_>, op: F) -> Result<()> +where + F: FnOnce(&mut ExecCtx<'_>, nitrokey::DeviceWrapper<'_>) -> Result<()>, +{ + let mut manager = nitrokey::take()?; + set_log_level(ctx); + + let device = match ctx.model { + Some(model) => manager.connect_model(model.into()).map_err(|_| { + let error = format!("Nitrokey {} device not found", model.as_user_facing_str()); + Error::Error(error) + })?, + None => manager + .connect() + .map_err(|_| Error::from("Nitrokey device not found"))?, + }; + + op(ctx, device) +} + +/// Connect to a Nitrokey Storage device and do something with it. +fn with_storage_device<F>(ctx: &mut ExecCtx<'_>, op: F) -> Result<()> +where + F: FnOnce(&mut ExecCtx<'_>, nitrokey::Storage<'_>) -> Result<()>, +{ + let mut manager = nitrokey::take()?; + set_log_level(ctx); + + if let Some(model) = ctx.model { + if model != args::DeviceModel::Storage { + return Err(Error::from( + "This command is only available on the Nitrokey Storage", + )); + } + } + + let device = manager + .connect_storage() + .map_err(|_| Error::from("Nitrokey Storage device not found"))?; + op(ctx, device) +} + +/// Connect to any Nitrokey device, retrieve a password safe handle, and +/// do something with it. +fn with_password_safe<F>(ctx: &mut ExecCtx<'_>, mut op: F) -> Result<()> +where + F: FnMut(&mut ExecCtx<'_>, nitrokey::PasswordSafe<'_, '_>) -> Result<()>, +{ + with_device(ctx, |ctx, mut device| { + let pin_entry = pinentry::PinEntry::from(args::PinType::User, &device)?; + try_with_pin_and_data( + ctx, + &pin_entry, + "Could not access the password safe", + (), + move |ctx, _, pin| { + let pws = device + .get_password_safe(pin) + .map_err(|err| ((), Error::from(err)))?; + + op(ctx, pws).map_err(|err| ((), err)) + }, + ) + })?; + Ok(()) +} + +/// Authenticate the given device using the given PIN type and operation. +/// +/// If an error occurs, the error message `msg` is used. +fn authenticate<'mgr, D, A, F>( + ctx: &mut ExecCtx<'_>, + device: D, + pin_type: args::PinType, + msg: &'static str, + op: F, +) -> Result<A> +where + D: Device<'mgr>, + F: FnMut(&mut ExecCtx<'_>, D, &str) -> result::Result<A, (D, nitrokey::Error)>, +{ + let pin_entry = pinentry::PinEntry::from(pin_type, &device)?; + + try_with_pin_and_data(ctx, &pin_entry, msg, device, op) +} + +/// Authenticate the given device with the user PIN. +fn authenticate_user<'mgr, T>(ctx: &mut ExecCtx<'_>, device: T) -> Result<nitrokey::User<'mgr, T>> +where + T: Device<'mgr>, +{ + authenticate( + ctx, + device, + args::PinType::User, + "Could not authenticate as user", + |_ctx, device, pin| device.authenticate_user(pin), + ) +} + +/// Authenticate the given device with the admin PIN. +fn authenticate_admin<'mgr, T>(ctx: &mut ExecCtx<'_>, device: T) -> Result<nitrokey::Admin<'mgr, T>> +where + T: Device<'mgr>, +{ + authenticate( + ctx, + device, + args::PinType::Admin, + "Could not authenticate as admin", + |_ctx, device, pin| device.authenticate_admin(pin), + ) +} + +/// Return a string representation of the given volume status. +fn get_volume_status(status: &nitrokey::VolumeStatus) -> &'static str { + if status.active { + if status.read_only { + "read-only" + } else { + "active" + } + } else { + "inactive" + } +} + +/// Try to execute the given function with a pin queried using pinentry. +/// +/// This function will query the pin of the given type from the user +/// using pinentry. It will then execute the given function. If this +/// function returns a result, the result will be passed on. If it +/// returns a `CommandError::WrongPassword`, the user will be asked +/// again to enter the pin. Otherwise, this function returns an error +/// containing the given error message. The user will have at most +/// three tries to get the pin right. +/// +/// The data argument can be used to pass on data between the tries. At +/// the first try, this function will call `op` with `data`. At the +/// second or third try, it will call `op` with the data returned by the +/// previous call to `op`. +fn try_with_pin_and_data_with_pinentry<D, F, R, E>( + ctx: &mut ExecCtx<'_>, + pin_entry: &pinentry::PinEntry, + msg: &'static str, + data: D, + mut op: F, +) -> Result<R> +where + F: FnMut(&mut ExecCtx<'_>, D, &str) -> result::Result<R, (D, E)>, + E: error::TryInto<nitrokey::Error>, +{ + let mut data = data; + let mut retry = 3; + let mut error_msg = None; + loop { + let pin = pinentry::inquire(ctx, pin_entry, pinentry::Mode::Query, error_msg)?; + match op(ctx, data, &pin) { + Ok(result) => return Ok(result), + Err((new_data, err)) => match err.try_into() { + Ok(err) => match err { + nitrokey::Error::CommandError(nitrokey::CommandError::WrongPassword) => { + pinentry::clear(pin_entry)?; + retry -= 1; + + if retry > 0 { + error_msg = Some("Wrong password, please reenter"); + data = new_data; + continue; + } + return Err(get_error(msg, err)); + } + err => return Err(get_error(msg, err)), + }, + Err(err) => return Err(err), + }, + }; + } +} + +/// Try to execute the given function with a PIN. +fn try_with_pin_and_data<D, F, R, E>( + ctx: &mut ExecCtx<'_>, + pin_entry: &pinentry::PinEntry, + msg: &'static str, + data: D, + mut op: F, +) -> Result<R> +where + F: FnMut(&mut ExecCtx<'_>, D, &str) -> result::Result<R, (D, E)>, + E: Into<Error> + error::TryInto<nitrokey::Error>, +{ + let pin = match pin_entry.pin_type() { + // Ideally we would not clone here, but that would require us to + // restrict op to work with an immutable ExecCtx, which is not + // possible given that some clients print data. + args::PinType::Admin => ctx.admin_pin.clone(), + args::PinType::User => ctx.user_pin.clone(), + }; + + if let Some(pin) = pin { + let pin = pin.to_str().ok_or_else(|| { + Error::Error(format!( + "{}: Failed to read PIN due to invalid Unicode data", + msg + )) + })?; + op(ctx, data, &pin).map_err(|(_, err)| err.into()) + } else { + try_with_pin_and_data_with_pinentry(ctx, pin_entry, msg, data, op) + } +} + +/// Try to execute the given function with a pin queried using pinentry. +/// +/// This function behaves exactly as `try_with_pin_and_data`, but +/// it refrains from passing any data to it. +fn try_with_pin<F, E>( + ctx: &mut ExecCtx<'_>, + pin_entry: &pinentry::PinEntry, + msg: &'static str, + mut op: F, +) -> Result<()> +where + F: FnMut(&str) -> result::Result<(), E>, + E: Into<Error> + error::TryInto<nitrokey::Error>, +{ + try_with_pin_and_data(ctx, pin_entry, msg, (), |_ctx, data, pin| { + op(pin).map_err(|err| (data, err)) + }) +} + +/// Pretty print the status of a Nitrokey Storage. +fn print_storage_status(ctx: &mut ExecCtx<'_>, status: &nitrokey::StorageStatus) -> Result<()> { + println!( + ctx, + r#" Storage: + SD card ID: {id:#x} + firmware: {fw} + storage keys: {sk} + volumes: + unencrypted: {vu} + encrypted: {ve} + hidden: {vh}"#, + id = status.serial_number_sd_card, + fw = if status.firmware_locked { + "locked" + } else { + "unlocked" + }, + sk = if status.stick_initialized { + "created" + } else { + "not created" + }, + vu = get_volume_status(&status.unencrypted_volume), + ve = get_volume_status(&status.encrypted_volume), + vh = get_volume_status(&status.hidden_volume), + )?; + Ok(()) +} + +/// Query and pretty print the status that is common to all Nitrokey devices. +fn print_status( + ctx: &mut ExecCtx<'_>, + model: &'static str, + device: &nitrokey::DeviceWrapper<'_>, +) -> Result<()> { + let serial_number = device + .get_serial_number() + .map_err(|err| get_error("Could not query the serial number", err))?; + + println!( + ctx, + r#"Status: + model: {model} + serial number: {id} + firmware version: {fwv} + user retry count: {urc} + admin retry count: {arc}"#, + model = model, + id = serial_number, + fwv = device.get_firmware_version()?, + urc = device.get_user_retry_count()?, + arc = device.get_admin_retry_count()?, + )?; + + if let nitrokey::DeviceWrapper::Storage(device) = device { + let status = device + .get_storage_status() + .map_err(|err| get_error("Getting Storage status failed", err))?; + + print_storage_status(ctx, &status) + } else { + Ok(()) + } +} + +/// Inquire the status of the nitrokey. +pub fn status(ctx: &mut ExecCtx<'_>) -> Result<()> { + with_device(ctx, |ctx, device| { + let model = match device { + nitrokey::DeviceWrapper::Pro(_) => "Pro", + nitrokey::DeviceWrapper::Storage(_) => "Storage", + }; + print_status(ctx, model, &device) + }) +} + +/// List the attached Nitrokey devices. +pub fn list(ctx: &mut ExecCtx<'_>, no_connect: bool) -> Result<()> { + set_log_level(ctx); + + let device_infos = nitrokey::list_devices()?; + if device_infos.is_empty() { + println!(ctx, "No Nitrokey device connected")?; + } else { + println!(ctx, "device path\tmodel\tserial number")?; + let mut manager = nitrokey::take()?; + + for device_info in device_infos { + let model = device_info + .model + .map(|m| m.to_string()) + .unwrap_or_else(|| "unknown".into()); + let serial_number = match device_info.serial_number { + Some(serial_number) => serial_number.to_string(), + None => { + // Storage devices do not have the serial number present in + // the device information. We have to connect to them to + // retrieve the information. + if no_connect { + "N/A".to_string() + } else { + let device = manager.connect_path(device_info.path.clone())?; + device.get_serial_number()?.to_string() + } + } + }; + + println!(ctx, "{}\t{}\t{}", device_info.path, model, serial_number)?; + } + } + + Ok(()) +} + +/// Perform a factory reset. +pub fn reset(ctx: &mut ExecCtx<'_>) -> Result<()> { + with_device(ctx, |ctx, mut device| { + let pin_entry = pinentry::PinEntry::from(args::PinType::Admin, &device)?; + + // To force the user to enter the admin PIN before performing a + // factory reset, we clear the pinentry cache for the admin PIN. + pinentry::clear(&pin_entry)?; + + try_with_pin(ctx, &pin_entry, "Factory reset failed", |pin| { + device.factory_reset(&pin)?; + // Work around for a timing issue between factory_reset and + // build_aes_key, see + // https://github.com/Nitrokey/nitrokey-storage-firmware/issues/80 + thread::sleep(time::Duration::from_secs(3)); + // Another work around for spurious WrongPassword returns of + // build_aes_key after a factory reset on Pro devices. + // https://github.com/Nitrokey/nitrokey-pro-firmware/issues/57 + let _ = device.get_user_retry_count(); + device.build_aes_key(nitrokey::DEFAULT_ADMIN_PIN) + }) + }) +} + +/// Change the configuration of the unencrypted volume. +pub fn unencrypted_set(ctx: &mut ExecCtx<'_>, mode: args::UnencryptedVolumeMode) -> Result<()> { + with_storage_device(ctx, |ctx, mut device| { + let pin_entry = pinentry::PinEntry::from(args::PinType::Admin, &device)?; + let mode = match mode { + args::UnencryptedVolumeMode::ReadWrite => nitrokey::VolumeMode::ReadWrite, + args::UnencryptedVolumeMode::ReadOnly => nitrokey::VolumeMode::ReadOnly, + }; + + // The unencrypted volume may reconnect, so be sure to flush caches to + // disk. + unsafe { sync() }; + + try_with_pin( + ctx, + &pin_entry, + "Changing unencrypted volume mode failed", + |pin| device.set_unencrypted_volume_mode(&pin, mode), + ) + }) +} + +/// Open the encrypted volume on the Nitrokey. +pub fn encrypted_open(ctx: &mut ExecCtx<'_>) -> Result<()> { + with_storage_device(ctx, |ctx, mut device| { + let pin_entry = pinentry::PinEntry::from(args::PinType::User, &device)?; + + // We may forcefully close a hidden volume, if active, so be sure to + // flush caches to disk. + unsafe { sync() }; + + try_with_pin(ctx, &pin_entry, "Opening encrypted volume failed", |pin| { + device.enable_encrypted_volume(&pin) + }) + }) +} + +/// Close the previously opened encrypted volume. +pub fn encrypted_close(ctx: &mut ExecCtx<'_>) -> Result<()> { + with_storage_device(ctx, |_ctx, mut device| { + // Flush all filesystem caches to disk. We are mostly interested in + // making sure that the encrypted volume on the Nitrokey we are + // about to close is not closed while not all data was written to + // it. + unsafe { sync() }; + + device + .disable_encrypted_volume() + .map_err(|err| get_error("Closing encrypted volume failed", err)) + }) +} + +/// Create a hidden volume. +pub fn hidden_create(ctx: &mut ExecCtx<'_>, slot: u8, start: u8, end: u8) -> Result<()> { + with_storage_device(ctx, |ctx, mut device| { + let pwd_entry = pinentry::PwdEntry::from(&device)?; + let pwd = if let Some(pwd) = &ctx.password { + pwd + .to_str() + .ok_or_else(|| Error::from("Failed to read password: invalid Unicode data found")) + .map(ToOwned::to_owned) + } else { + pinentry::choose(ctx, &pwd_entry) + }?; + + device + .create_hidden_volume(slot, start, end, &pwd) + .map_err(|err| get_error("Creating hidden volume failed", err)) + }) +} + +/// Open a hidden volume. +pub fn hidden_open(ctx: &mut ExecCtx<'_>) -> Result<()> { + with_storage_device(ctx, |ctx, mut device| { + let pwd_entry = pinentry::PwdEntry::from(&device)?; + let pwd = if let Some(pwd) = &ctx.password { + pwd + .to_str() + .ok_or_else(|| Error::from("Failed to read password: invalid Unicode data found")) + .map(ToOwned::to_owned) + } else { + pinentry::inquire(ctx, &pwd_entry, pinentry::Mode::Query, None) + }?; + + // We may forcefully close an encrypted volume, if active, so be sure + // to flush caches to disk. + unsafe { sync() }; + + device + .enable_hidden_volume(&pwd) + .map_err(|err| get_error("Opening hidden volume failed", err)) + }) +} + +/// Close a previously opened hidden volume. +pub fn hidden_close(ctx: &mut ExecCtx<'_>) -> Result<()> { + with_storage_device(ctx, |_ctx, mut device| { + unsafe { sync() }; + + device + .disable_hidden_volume() + .map_err(|err| get_error("Closing hidden volume failed", err)) + }) +} + +/// Return a String representation of the given Option. +fn format_option<T: fmt::Display>(option: Option<T>) -> String { + match option { + Some(value) => format!("{}", value), + None => "not set".to_string(), + } +} + +/// Read the Nitrokey configuration. +pub fn config_get(ctx: &mut ExecCtx<'_>) -> Result<()> { + with_device(ctx, |ctx, device| { + let config = device + .get_config() + .map_err(|err| get_error("Could not get configuration", err))?; + println!( + ctx, + r#"Config: + numlock binding: {nl} + capslock binding: {cl} + scrollock binding: {sl} + require user PIN for OTP: {otp}"#, + nl = format_option(config.numlock), + cl = format_option(config.capslock), + sl = format_option(config.scrollock), + otp = config.user_password, + )?; + Ok(()) + }) +} + +/// Write the Nitrokey configuration. +pub fn config_set(ctx: &mut ExecCtx<'_>, args: args::ConfigSetArgs) -> Result<()> { + let numlock = args::ConfigOption::try_from(args.no_numlock, args.numlock, "numlock")?; + let capslock = args::ConfigOption::try_from(args.no_capslock, args.capslock, "capslock")?; + let scrollock = args::ConfigOption::try_from(args.no_scrollock, args.scrollock, "scrollock")?; + let otp_pin = if args.otp_pin { + Some(true) + } else if args.no_otp_pin { + Some(false) + } else { + None + }; + + with_device(ctx, |ctx, device| { + let mut device = authenticate_admin(ctx, device)?; + let config = device + .get_config() + .map_err(|err| get_error("Could not get configuration", err))?; + let config = nitrokey::Config { + numlock: numlock.or(config.numlock), + capslock: capslock.or(config.capslock), + scrollock: scrollock.or(config.scrollock), + user_password: otp_pin.unwrap_or(config.user_password), + }; + device + .write_config(config) + .map_err(|err| get_error("Could not set configuration", err)) + }) +} + +/// Lock the Nitrokey device. +pub fn lock(ctx: &mut ExecCtx<'_>) -> Result<()> { + with_device(ctx, |_ctx, mut device| { + device + .lock() + .map_err(|err| get_error("Could not lock the device", err)) + }) +} + +fn get_otp<T>(slot: u8, algorithm: args::OtpAlgorithm, device: &mut T) -> Result<String> +where + T: GenerateOtp, +{ + match algorithm { + args::OtpAlgorithm::Hotp => device.get_hotp_code(slot), + args::OtpAlgorithm::Totp => device.get_totp_code(slot), + } + .map_err(|err| get_error("Could not generate OTP", err)) +} + +fn get_unix_timestamp() -> Result<u64> { + time::SystemTime::now() + .duration_since(time::UNIX_EPOCH) + .map_err(|_| Error::from("Current system time is before the Unix epoch")) + .map(|duration| duration.as_secs()) +} + +/// Generate a one-time password on the Nitrokey device. +pub fn otp_get( + ctx: &mut ExecCtx<'_>, + slot: u8, + algorithm: args::OtpAlgorithm, + time: Option<u64>, +) -> Result<()> { + with_device(ctx, |ctx, mut device| { + if algorithm == args::OtpAlgorithm::Totp { + device + .set_time( + match time { + Some(time) => time, + None => get_unix_timestamp()?, + }, + true, + ) + .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))?; + let otp = if config.user_password { + let mut user = authenticate_user(ctx, device)?; + get_otp(slot, algorithm, &mut user) + } else { + get_otp(slot, algorithm, &mut device) + }?; + println!(ctx, "{}", otp)?; + Ok(()) + }) +} + +/// Format a byte vector as a hex string. +fn format_bytes(bytes: &[u8]) -> String { + bytes + .iter() + .map(|c| format!("{:02x}", c)) + .collect::<Vec<_>>() + .join("") +} + +/// Prepare an ASCII secret string for libnitrokey. +/// +/// libnitrokey expects secrets as hexadecimal strings. This function transforms an ASCII string +/// into a hexadecimal string or returns an error if the given string contains non-ASCII +/// characters. +fn prepare_ascii_secret(secret: &str) -> Result<String> { + if secret.is_ascii() { + Ok(format_bytes(&secret.as_bytes())) + } else { + Err(Error::from( + "The given secret is not an ASCII string despite --format ascii being set", + )) + } +} + +/// Prepare a base32 secret string for libnitrokey. +fn prepare_base32_secret(secret: &str) -> Result<String> { + base32::decode(base32::Alphabet::RFC4648 { padding: false }, secret) + .map(|vec| format_bytes(&vec)) + .ok_or_else(|| Error::from("Could not parse base32 secret")) +} + +/// Configure a one-time password slot on the Nitrokey device. +pub fn otp_set(ctx: &mut ExecCtx<'_>, mut args: args::OtpSetArgs) -> Result<()> { + let mut data = nitrokey::OtpSlotData { + number: args.slot, + name: mem::take(&mut args.name), + secret: mem::take(&mut args.secret), + mode: args.digits.into(), + use_enter: false, + token_id: None, + }; + + with_device(ctx, |ctx, device| { + let secret = match args.format { + args::OtpSecretFormat::Ascii => prepare_ascii_secret(&data.secret)?, + args::OtpSecretFormat::Base32 => prepare_base32_secret(&data.secret)?, + args::OtpSecretFormat::Hex => { + // We need to ensure to provide a string with an even number of + // characters in it, just because that's what libnitrokey + // expects. So prepend a '0' if that is not the case. + // TODO: This code can be removed once upstream issue #164 + // (https://github.com/Nitrokey/libnitrokey/issues/164) is + // addressed. + if data.secret.len() % 2 != 0 { + data.secret.insert(0, '0') + } + data.secret + } + }; + let data = nitrokey::OtpSlotData { secret, ..data }; + let mut device = authenticate_admin(ctx, device)?; + match args.algorithm { + args::OtpAlgorithm::Hotp => device.write_hotp_slot(data, args.counter), + args::OtpAlgorithm::Totp => device.write_totp_slot(data, args.time_window), + } + .map_err(|err| get_error("Could not write OTP slot", err))?; + Ok(()) + }) +} + +/// Clear an OTP slot. +pub fn otp_clear(ctx: &mut ExecCtx<'_>, slot: u8, algorithm: args::OtpAlgorithm) -> Result<()> { + with_device(ctx, |ctx, device| { + let mut device = authenticate_admin(ctx, device)?; + match algorithm { + args::OtpAlgorithm::Hotp => device.erase_hotp_slot(slot), + args::OtpAlgorithm::Totp => device.erase_totp_slot(slot), + } + .map_err(|err| get_error("Could not clear OTP slot", err))?; + Ok(()) + }) +} + +fn print_otp_status( + ctx: &mut ExecCtx<'_>, + algorithm: args::OtpAlgorithm, + device: &nitrokey::DeviceWrapper<'_>, + all: bool, +) -> Result<()> { + let mut slot: u8 = 0; + loop { + let result = match algorithm { + args::OtpAlgorithm::Hotp => device.get_hotp_slot_name(slot), + args::OtpAlgorithm::Totp => device.get_totp_slot_name(slot), + }; + slot = match slot.checked_add(1) { + Some(slot) => slot, + None => { + return Err(Error::from("Integer overflow when iterating OTP slots")); + } + }; + let name = match result { + Ok(name) => name, + Err(nitrokey::Error::LibraryError(nitrokey::LibraryError::InvalidSlot)) => return Ok(()), + Err(nitrokey::Error::CommandError(nitrokey::CommandError::SlotNotProgrammed)) => { + if all { + "[not programmed]".to_string() + } else { + continue; + } + } + Err(err) => return Err(get_error("Could not check OTP slot", err)), + }; + println!(ctx, "{}\t{}\t{}", algorithm, slot - 1, name)?; + } +} + +/// Print the status of the OTP slots. +pub fn otp_status(ctx: &mut ExecCtx<'_>, all: bool) -> Result<()> { + with_device(ctx, |ctx, device| { + println!(ctx, "alg\tslot\tname")?; + print_otp_status(ctx, args::OtpAlgorithm::Hotp, &device, all)?; + print_otp_status(ctx, args::OtpAlgorithm::Totp, &device, all)?; + Ok(()) + }) +} + +/// Clear the PIN stored by various operations. +pub fn pin_clear(ctx: &mut ExecCtx<'_>) -> Result<()> { + with_device(ctx, |_ctx, device| { + pinentry::clear(&pinentry::PinEntry::from(args::PinType::Admin, &device)?)?; + pinentry::clear(&pinentry::PinEntry::from(args::PinType::User, &device)?)?; + Ok(()) + }) +} + +/// Choose a PIN of the given type. +/// +/// If the user has set the respective environment variable for the +/// given PIN type, it will be used. +fn choose_pin(ctx: &mut ExecCtx<'_>, pin_entry: &pinentry::PinEntry, new: bool) -> Result<String> { + let new_pin = match pin_entry.pin_type() { + args::PinType::Admin => { + if new { + &ctx.new_admin_pin + } else { + &ctx.admin_pin + } + } + args::PinType::User => { + if new { + &ctx.new_user_pin + } else { + &ctx.user_pin + } + } + }; + + if let Some(new_pin) = new_pin { + new_pin + .to_str() + .ok_or_else(|| Error::from("Failed to read PIN: invalid Unicode data found")) + .map(ToOwned::to_owned) + } else { + pinentry::choose(ctx, pin_entry) + } +} + +/// Change a PIN. +pub fn pin_set(ctx: &mut ExecCtx<'_>, pin_type: args::PinType) -> Result<()> { + with_device(ctx, |ctx, mut device| { + let pin_entry = pinentry::PinEntry::from(pin_type, &device)?; + let new_pin = choose_pin(ctx, &pin_entry, true)?; + + try_with_pin( + ctx, + &pin_entry, + "Could not change the PIN", + |current_pin| match pin_type { + args::PinType::Admin => device.change_admin_pin(¤t_pin, &new_pin), + args::PinType::User => device.change_user_pin(¤t_pin, &new_pin), + }, + )?; + + // We just changed the PIN but confirmed the action with the old PIN, + // which may have caused it to be cached. Since it no longer applies, + // make sure to evict the corresponding entry from the cache. + pinentry::clear(&pin_entry) + }) +} + +/// Unblock and reset the user PIN. +pub fn pin_unblock(ctx: &mut ExecCtx<'_>) -> Result<()> { + with_device(ctx, |ctx, mut device| { + let pin_entry = pinentry::PinEntry::from(args::PinType::User, &device)?; + let user_pin = choose_pin(ctx, &pin_entry, false)?; + let pin_entry = pinentry::PinEntry::from(args::PinType::Admin, &device)?; + + try_with_pin( + ctx, + &pin_entry, + "Could not unblock the user PIN", + |admin_pin| device.unlock_user_pin(&admin_pin, &user_pin), + ) + }) +} + +fn print_pws_data( + ctx: &mut ExecCtx<'_>, + description: &'static str, + result: result::Result<String, nitrokey::Error>, + quiet: bool, +) -> Result<()> { + let value = result.map_err(|err| get_error("Could not access PWS slot", err))?; + if quiet { + println!(ctx, "{}", value)?; + } else { + println!(ctx, "{} {}", description, value)?; + } + Ok(()) +} + +fn check_slot(pws: &nitrokey::PasswordSafe<'_, '_>, slot: u8) -> Result<()> { + if slot >= nitrokey::SLOT_COUNT { + return Err(nitrokey::Error::from(nitrokey::LibraryError::InvalidSlot).into()); + } + let status = pws + .get_slot_status() + .map_err(|err| get_error("Could not read PWS slot status", err))?; + if status[slot as usize] { + Ok(()) + } else { + Err(get_error( + "Could not access PWS slot", + nitrokey::CommandError::SlotNotProgrammed.into(), + )) + } +} + +/// Read a PWS slot. +pub fn pws_get( + ctx: &mut ExecCtx<'_>, + slot: u8, + show_name: bool, + show_login: bool, + show_password: bool, + quiet: bool, +) -> Result<()> { + with_password_safe(ctx, |ctx, pws| { + check_slot(&pws, slot)?; + + let show_all = !show_name && !show_login && !show_password; + if show_all || show_name { + print_pws_data(ctx, "name: ", pws.get_slot_name(slot), quiet)?; + } + if show_all || show_login { + print_pws_data(ctx, "login: ", pws.get_slot_login(slot), quiet)?; + } + if show_all || show_password { + print_pws_data(ctx, "password:", pws.get_slot_password(slot), quiet)?; + } + Ok(()) + }) +} + +/// Write a PWS slot. +pub fn pws_set( + ctx: &mut ExecCtx<'_>, + slot: u8, + name: &str, + login: &str, + password: &str, +) -> Result<()> { + with_password_safe(ctx, |_ctx, mut pws| { + pws + .write_slot(slot, name, login, password) + .map_err(|err| get_error("Could not write PWS slot", err)) + }) +} + +/// Clear a PWS slot. +pub fn pws_clear(ctx: &mut ExecCtx<'_>, slot: u8) -> Result<()> { + with_password_safe(ctx, |_ctx, mut pws| { + pws + .erase_slot(slot) + .map_err(|err| get_error("Could not clear PWS slot", err)) + }) +} + +fn print_pws_slot( + ctx: &mut ExecCtx<'_>, + pws: &nitrokey::PasswordSafe<'_, '_>, + slot: usize, + programmed: bool, +) -> Result<()> { + if slot > u8::MAX as usize { + return Err(Error::from("Invalid PWS slot number")); + } + let slot = slot as u8; + let name = if programmed { + pws + .get_slot_name(slot) + .map_err(|err| get_error("Could not read PWS slot", err))? + } else { + "[not programmed]".to_string() + }; + println!(ctx, "{}\t{}", slot, name)?; + Ok(()) +} + +/// Print the status of all PWS slots. +pub fn pws_status(ctx: &mut ExecCtx<'_>, all: bool) -> Result<()> { + with_password_safe(ctx, |ctx, pws| { + let slots = pws + .get_slot_status() + .map_err(|err| get_error("Could not read PWS slot status", err))?; + println!(ctx, "slot\tname")?; + for (i, &value) in slots.iter().enumerate().filter(|(_, &value)| all || value) { + print_pws_slot(ctx, &pws, i, value)?; + } + Ok(()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn prepare_secret_ascii() { + let result = prepare_ascii_secret("12345678901234567890"); + assert_eq!( + "3132333435363738393031323334353637383930".to_string(), + result.unwrap() + ); + } + + #[test] + fn prepare_secret_non_ascii() { + let result = prepare_ascii_secret("Österreich"); + assert!(result.is_err()); + } + + #[test] + fn hex_string() { + assert_eq!(format_bytes(&[b' ']), "20"); + assert_eq!(format_bytes(&[b' ', b' ']), "2020"); + assert_eq!(format_bytes(&[b'\n', b'\n']), "0a0a"); + } +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..e891da2 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,118 @@ +// error.rs + +// ************************************************************************* +// * Copyright (C) 2017-2020 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +use std::fmt; +use std::io; +use std::str; +use std::string; + +use structopt::clap; + +/// A trait used to simplify error handling in conjunction with the +/// try_with_* functions we use for repeatedly asking the user for a +/// secret. +pub trait TryInto<T> { + fn try_into(self) -> Result<T, Error>; +} + +impl<T, U> TryInto<U> for T +where + T: Into<U>, +{ + fn try_into(self) -> Result<U, Error> { + Ok(self.into()) + } +} + +#[derive(Debug)] +pub enum Error { + ClapError(clap::Error), + IoError(io::Error), + NitrokeyError(Option<&'static str>, nitrokey::Error), + Utf8Error(str::Utf8Error), + Error(String), +} + +impl TryInto<nitrokey::Error> for Error { + fn try_into(self) -> Result<nitrokey::Error, Error> { + match self { + Error::NitrokeyError(_, err) => Ok(err), + err => Err(err), + } + } +} + +impl From<&str> for Error { + fn from(s: &str) -> Error { + Error::Error(s.to_string()) + } +} + +impl From<String> for Error { + fn from(s: String) -> Error { + Error::Error(s) + } +} + +impl From<clap::Error> for Error { + fn from(e: clap::Error) -> Error { + Error::ClapError(e) + } +} + +impl From<nitrokey::Error> for Error { + fn from(e: nitrokey::Error) -> Error { + Error::NitrokeyError(None, e) + } +} + +impl From<io::Error> for Error { + fn from(e: io::Error) -> Error { + Error::IoError(e) + } +} + +impl From<str::Utf8Error> for Error { + fn from(e: str::Utf8Error) -> Error { + Error::Utf8Error(e) + } +} + +impl From<string::FromUtf8Error> for Error { + fn from(e: string::FromUtf8Error) -> Error { + Error::Utf8Error(e.utf8_error()) + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Error::ClapError(ref e) => write!(f, "{}", e), + Error::NitrokeyError(ref ctx, ref e) => { + if let Some(ctx) = ctx { + write!(f, "{}: ", ctx)?; + } + write!(f, "{}", e) + } + Error::Utf8Error(_) => write!(f, "Encountered UTF-8 conversion error"), + Error::IoError(ref e) => write!(f, "IO error: {}", e), + Error::Error(ref e) => write!(f, "{}", e), + } + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..27097c9 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,239 @@ +// main.rs + +// ************************************************************************* +// * Copyright (C) 2017-2020 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +#![warn( + bad_style, + dead_code, + future_incompatible, + illegal_floating_point_literal_pattern, + improper_ctypes, + intra_doc_link_resolution_failure, + late_bound_lifetime_arguments, + missing_copy_implementations, + missing_debug_implementations, + missing_docs, + no_mangle_generic_items, + non_shorthand_field_patterns, + nonstandard_style, + overflowing_literals, + path_statements, + patterns_in_fns_without_body, + private_in_public, + proc_macro_derive_resolution_fallback, + renamed_and_removed_lints, + rust_2018_compatibility, + rust_2018_idioms, + safe_packed_borrows, + stable_features, + trivial_bounds, + trivial_numeric_casts, + type_alias_bounds, + tyvar_behind_raw_pointer, + unconditional_recursion, + unreachable_code, + unreachable_patterns, + unstable_features, + unstable_name_collisions, + unused, + unused_comparisons, + unused_import_braces, + unused_lifetimes, + unused_qualifications, + unused_results, + where_clauses_object_safety, + while_true +)] + +//! Nitrocli is a program providing a command line interface to certain +//! commands of Nitrokey Pro and Storage devices. + +#[macro_use] +mod redefine; +#[macro_use] +mod arg_util; + +mod args; +mod commands; +mod error; +mod pinentry; +#[cfg(test)] +mod tests; + +use std::env; +use std::ffi; +use std::io; +use std::process; +use std::result; + +use crate::error::Error; + +type Result<T> = result::Result<T, Error>; + +const NITROCLI_ADMIN_PIN: &str = "NITROCLI_ADMIN_PIN"; +const NITROCLI_USER_PIN: &str = "NITROCLI_USER_PIN"; +const NITROCLI_NEW_ADMIN_PIN: &str = "NITROCLI_NEW_ADMIN_PIN"; +const NITROCLI_NEW_USER_PIN: &str = "NITROCLI_NEW_USER_PIN"; +const NITROCLI_PASSWORD: &str = "NITROCLI_PASSWORD"; +const NITROCLI_NO_CACHE: &str = "NITROCLI_NO_CACHE"; + +trait Stdio { + fn stdio(&mut self) -> (&mut dyn io::Write, &mut dyn io::Write); +} + +impl<'io> Stdio for RunCtx<'io> { + fn stdio(&mut self) -> (&mut dyn io::Write, &mut dyn io::Write) { + (self.stdout, self.stderr) + } +} + +impl<W> Stdio for (&mut W, &mut W) +where + W: io::Write, +{ + fn stdio(&mut self) -> (&mut dyn io::Write, &mut dyn io::Write) { + (self.0, self.1) + } +} + +/// A command execution context that captures additional data pertaining +/// the command execution. +#[allow(missing_debug_implementations)] +pub struct ExecCtx<'io> { + /// The Nitrokey model to use. + pub model: Option<args::DeviceModel>, + /// See `RunCtx::stdout`. + pub stdout: &'io mut dyn io::Write, + /// See `RunCtx::stderr`. + pub stderr: &'io mut dyn io::Write, + /// See `RunCtx::admin_pin`. + pub admin_pin: Option<ffi::OsString>, + /// See `RunCtx::user_pin`. + pub user_pin: Option<ffi::OsString>, + /// See `RunCtx::new_admin_pin`. + pub new_admin_pin: Option<ffi::OsString>, + /// See `RunCtx::new_user_pin`. + pub new_user_pin: Option<ffi::OsString>, + /// See `RunCtx::password`. + pub password: Option<ffi::OsString>, + /// See `RunCtx::no_cache`. + pub no_cache: bool, + /// The verbosity level to use for logging. + pub verbosity: u64, +} + +impl<'io> Stdio for ExecCtx<'io> { + fn stdio(&mut self) -> (&mut dyn io::Write, &mut dyn io::Write) { + (self.stdout, self.stderr) + } +} + +/// Parse the command-line arguments and execute the selected command. +fn handle_arguments(ctx: &mut RunCtx<'_>, args: Vec<String>) -> Result<()> { + use structopt::StructOpt; + + match args::Args::from_iter_safe(args.iter()) { + Ok(args) => { + let mut ctx = ExecCtx { + model: args.model, + stdout: ctx.stdout, + stderr: ctx.stderr, + admin_pin: ctx.admin_pin.take(), + user_pin: ctx.user_pin.take(), + new_admin_pin: ctx.new_admin_pin.take(), + new_user_pin: ctx.new_user_pin.take(), + password: ctx.password.take(), + no_cache: ctx.no_cache, + verbosity: args.verbose.into(), + }; + args.cmd.execute(&mut ctx) + } + Err(err) => { + if err.use_stderr() { + Err(err.into()) + } else { + println!(ctx, "{}", err.message)?; + Ok(()) + } + } + } +} + +/// The context used when running the program. +pub(crate) struct RunCtx<'io> { + /// The `Write` object used as standard output throughout the program. + pub stdout: &'io mut dyn io::Write, + /// The `Write` object used as standard error throughout the program. + pub stderr: &'io mut dyn io::Write, + /// The admin PIN, if provided through an environment variable. + pub admin_pin: Option<ffi::OsString>, + /// The user PIN, if provided through an environment variable. + pub user_pin: Option<ffi::OsString>, + /// The new admin PIN to set, if provided through an environment variable. + /// + /// This variable is only used by commands that change the admin PIN. + pub new_admin_pin: Option<ffi::OsString>, + /// The new user PIN, if provided through an environment variable. + /// + /// This variable is only used by commands that change the user PIN. + pub new_user_pin: Option<ffi::OsString>, + /// A password used by some commands, if provided through an environment variable. + pub password: Option<ffi::OsString>, + /// Whether to bypass the cache for all secrets or not. + pub no_cache: bool, +} + +fn run<'ctx, 'io: 'ctx>(ctx: &'ctx mut RunCtx<'io>, args: Vec<String>) -> i32 { + match handle_arguments(ctx, args) { + Ok(()) => 0, + Err(err) => { + let _ = eprintln!(ctx, "{}", err); + 1 + } + } +} + +fn main() { + use std::io::Write; + + let mut stdout = io::stdout(); + let mut stderr = io::stderr(); + let args = env::args().collect::<Vec<_>>(); + let ctx = &mut RunCtx { + stdout: &mut stdout, + stderr: &mut stderr, + admin_pin: env::var_os(NITROCLI_ADMIN_PIN), + user_pin: env::var_os(NITROCLI_USER_PIN), + new_admin_pin: env::var_os(NITROCLI_NEW_ADMIN_PIN), + new_user_pin: env::var_os(NITROCLI_NEW_USER_PIN), + password: env::var_os(NITROCLI_PASSWORD), + no_cache: env::var_os(NITROCLI_NO_CACHE).is_some(), + }; + + let rc = run(ctx, args); + // We exit the process the hard way below. The problem is that because + // of this, buffered IO may not be flushed. So make sure to explicitly + // flush before exiting. Note that stderr is unbuffered, alleviating + // the need for any flushing there. + // Ideally we would just make `main` return an i32 and let Rust deal + // with all of this, but the `process::Termination` functionality is + // still unstable and we have no way to convince the caller to "just + // exit" without printing additional information. + let _ = stdout.flush(); + process::exit(rc); +} diff --git a/src/pinentry.rs b/src/pinentry.rs new file mode 100644 index 0000000..d1387f4 --- /dev/null +++ b/src/pinentry.rs @@ -0,0 +1,395 @@ +// pinentry.rs + +// ************************************************************************* +// * Copyright (C) 2017-2020 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +use std::borrow; +use std::fmt; +use std::io; +use std::process; +use std::str; + +use crate::args; +use crate::error::Error; +use crate::ExecCtx; + +type CowStr = borrow::Cow<'static, str>; + +/// A trait representing a secret to be entered by the user. +pub trait SecretEntry: fmt::Debug { + /// The cache ID to use for this secret. + fn cache_id(&self) -> Option<CowStr>; + /// The prompt to display when asking for the secret. + fn prompt(&self) -> CowStr; + /// The description to display when asking for the secret. + fn description(&self, mode: Mode) -> CowStr; + /// The minimum number of characters the secret needs to have. + fn min_len(&self) -> u8; +} + +#[derive(Debug)] +pub struct PinEntry { + pin_type: args::PinType, + model: nitrokey::Model, + serial: nitrokey::SerialNumber, +} + +impl PinEntry { + pub fn from<'mgr, D>(pin_type: args::PinType, device: &D) -> crate::Result<Self> + where + D: nitrokey::Device<'mgr>, + { + let model = device.get_model(); + let serial = device.get_serial_number()?; + Ok(Self { + pin_type, + model, + serial, + }) + } + + pub fn pin_type(&self) -> args::PinType { + self.pin_type + } +} + +impl SecretEntry for PinEntry { + fn cache_id(&self) -> Option<CowStr> { + let model = self.model.to_string().to_lowercase(); + let suffix = format!("{}:{}", model, self.serial); + let cache_id = match self.pin_type { + args::PinType::Admin => format!("nitrocli:admin:{}", suffix), + args::PinType::User => format!("nitrocli:user:{}", suffix), + }; + Some(cache_id.into()) + } + + fn prompt(&self) -> CowStr { + match self.pin_type { + args::PinType::Admin => "Admin PIN", + args::PinType::User => "User PIN", + } + .into() + } + + fn description(&self, mode: Mode) -> CowStr { + format!( + "{} for\rNitrokey {} {}", + match self.pin_type { + args::PinType::Admin => match mode { + Mode::Choose => "Please enter a new admin PIN", + Mode::Confirm => "Please confirm the new admin PIN", + Mode::Query => "Please enter the admin PIN", + }, + args::PinType::User => match mode { + Mode::Choose => "Please enter a new user PIN", + Mode::Confirm => "Please confirm the new user PIN", + Mode::Query => "Please enter the user PIN", + }, + }, + self.model, + self.serial, + ) + .into() + } + + fn min_len(&self) -> u8 { + match self.pin_type { + args::PinType::Admin => 8, + args::PinType::User => 6, + } + } +} + +#[derive(Debug)] +pub struct PwdEntry { + model: nitrokey::Model, + serial: nitrokey::SerialNumber, +} + +impl PwdEntry { + pub fn from<'mgr, D>(device: &D) -> crate::Result<Self> + where + D: nitrokey::Device<'mgr>, + { + let model = device.get_model(); + let serial = device.get_serial_number()?; + Ok(Self { model, serial }) + } +} + +impl SecretEntry for PwdEntry { + fn cache_id(&self) -> Option<CowStr> { + None + } + + fn prompt(&self) -> CowStr { + "Password".into() + } + + fn description(&self, mode: Mode) -> CowStr { + format!( + "{} for\rNitrokey {} {}", + match mode { + Mode::Choose => "Please enter a new hidden volume password", + Mode::Confirm => "Please confirm the new hidden volume password", + Mode::Query => "Please enter a hidden volume password", + }, + self.model, + self.serial, + ) + .into() + } + + fn min_len(&self) -> u8 { + // More or less arbitrary minimum length based on the fact that the + // manual mentions six letter passwords in examples. Users + // *probably* should go longer than that, but we don't want to be + // too opinionated. + 6 + } +} + +/// Secret entry mode for pinentry. +/// +/// This enum describes the context of the pinentry query, for example +/// prompting for the current secret or requesting a new one. The mode +/// may affect the pinentry description and whether a quality bar is +/// shown. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Mode { + /// Let the user choose a new secret. + Choose, + /// Let the user confirm the previously chosen secret. + Confirm, + /// Query an existing secret. + Query, +} + +impl Mode { + fn show_quality_bar(self) -> bool { + self == Mode::Choose + } +} + +fn parse_pinentry_pin<R>(response: R) -> crate::Result<String> +where + R: AsRef<str>, +{ + let string = response.as_ref(); + let lines: Vec<&str> = string.lines().collect(); + + // We expect the response to be of the form: + // > D passphrase + // > OK + // or potentially: + // > ERR 83886179 Operation cancelled <Pinentry> + if lines.len() == 2 && lines[1] == "OK" && lines[0].starts_with("D ") { + // We got the only valid answer we accept. + let (_, pass) = lines[0].split_at(2); + return Ok(pass.to_string()); + } + + // Check if we are dealing with a special "ERR " line and report that + // specially. + if !lines.is_empty() && lines[0].starts_with("ERR ") { + let (_, error) = lines[0].split_at(4); + return Err(Error::from(error)); + } + Err(Error::Error(format!("Unexpected response: {}", string))) +} + +/// Inquire a secret from the user. +/// +/// This function inquires a secret from the user or returns a cached +/// entry, if available (and if caching is not disabled for the given +/// execution context). If an error message is set, it is displayed in +/// the entry dialog. The mode describes the context of the pinentry +/// dialog. It is used to choose an appropriate description and to +/// decide whether a quality bar is shown in the dialog. +pub fn inquire<E>( + ctx: &mut ExecCtx<'_>, + entry: &E, + mode: Mode, + error_msg: Option<&str>, +) -> crate::Result<String> +where + E: SecretEntry, +{ + let cache_id = entry + .cache_id() + .and_then(|id| if ctx.no_cache { None } else { Some(id) }) + // "X" is a sentinel value indicating that no caching is desired. + .unwrap_or_else(|| "X".into()) + .into(); + + let error_msg = error_msg + .map(|msg| msg.replace(" ", "+")) + .unwrap_or_else(|| String::from("+")); + let prompt = entry.prompt().replace(" ", "+"); + let description = entry.description(mode).replace(" ", "+"); + + let args = vec![cache_id, error_msg, prompt, description].join(" "); + let mut command = "GET_PASSPHRASE --data ".to_string(); + if mode.show_quality_bar() { + command += "--qualitybar "; + } + command += &args; + // An error reported for the GET_PASSPHRASE command does not actually + // cause gpg-connect-agent to exit with a non-zero error code, we have + // to evaluate the output to determine success/failure. + let output = process::Command::new("gpg-connect-agent") + .arg(command) + .arg("/bye") + .output() + .map_err(|err| match err.kind() { + io::ErrorKind::NotFound => { + io::Error::new(io::ErrorKind::NotFound, "gpg-connect-agent not found") + } + _ => err, + })?; + parse_pinentry_pin(str::from_utf8(&output.stdout)?) +} + +fn check<E>(entry: &E, secret: &str) -> crate::Result<()> +where + E: SecretEntry, +{ + if secret.len() < usize::from(entry.min_len()) { + Err(Error::Error(format!( + "The secret must be at least {} characters long", + entry.min_len() + ))) + } else { + Ok(()) + } +} + +pub fn choose<E>(ctx: &mut ExecCtx<'_>, entry: &E) -> crate::Result<String> +where + E: SecretEntry, +{ + clear(entry)?; + let chosen = inquire(ctx, entry, Mode::Choose, None)?; + clear(entry)?; + check(entry, &chosen)?; + + let confirmed = inquire(ctx, entry, Mode::Confirm, None)?; + clear(entry)?; + + if chosen != confirmed { + Err(Error::from("Entered secrets do not match")) + } else { + Ok(chosen) + } +} + +fn parse_pinentry_response<R>(response: R) -> crate::Result<()> +where + R: AsRef<str>, +{ + let string = response.as_ref(); + let lines = string.lines().collect::<Vec<_>>(); + + if lines.len() == 1 && lines[0] == "OK" { + // We got the only valid answer we accept. + return Ok(()); + } + Err(Error::Error(format!("Unexpected response: {}", string))) +} + +/// Clear the cached secret represented by the given entry. +pub fn clear<E>(entry: &E) -> crate::Result<()> +where + E: SecretEntry, +{ + if let Some(cache_id) = entry.cache_id() { + let command = format!("CLEAR_PASSPHRASE {}", cache_id); + let output = process::Command::new("gpg-connect-agent") + .arg(command) + .arg("/bye") + .output()?; + + parse_pinentry_response(str::from_utf8(&output.stdout)?) + } else { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_pinentry_pin_good() { + let response = "D passphrase\nOK\n"; + let expected = "passphrase"; + + assert_eq!(parse_pinentry_pin(response).unwrap(), expected) + } + + #[test] + fn parse_pinentry_pin_error() { + let error = "83886179 Operation cancelled"; + let response = "ERR ".to_string() + error + "\n"; + let expected = error; + + let error = parse_pinentry_pin(response); + + if let Error::Error(ref e) = error.err().unwrap() { + assert_eq!(e, &expected); + } else { + panic!("Unexpected result"); + } + } + + #[test] + fn parse_pinentry_pin_unexpected() { + let response = "foobar\n"; + let expected = format!("Unexpected response: {}", response); + let error = parse_pinentry_pin(response); + + if let Error::Error(ref e) = error.err().unwrap() { + assert_eq!(e, &expected); + } else { + panic!("Unexpected result"); + } + } + + #[test] + fn parse_pinentry_response_ok() { + assert!(parse_pinentry_response("OK\n").is_ok()) + } + + #[test] + fn parse_pinentry_response_ok_no_newline() { + assert!(parse_pinentry_response("OK").is_ok()) + } + + #[test] + fn parse_pinentry_response_unexpected() { + let response = "ERR 42"; + let expected = format!("Unexpected response: {}", response); + let error = parse_pinentry_response(response); + + if let Error::Error(ref e) = error.err().unwrap() { + assert_eq!(e, &expected); + } else { + panic!("Unexpected result"); + } + } +} diff --git a/src/redefine.rs b/src/redefine.rs new file mode 100644 index 0000000..a79cb4b --- /dev/null +++ b/src/redefine.rs @@ -0,0 +1,38 @@ +// redefine.rs + +// ************************************************************************* +// * Copyright (C) 2019 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +// A replacement of the standard println!() macro that requires an +// execution context as the first argument and prints to its stdout. +macro_rules! println { + ($ctx:expr) => { + writeln!($ctx.stdout, "") + }; + ($ctx:expr, $($arg:tt)*) => { + writeln!($ctx.stdout, $($arg)*) + }; +} + +macro_rules! eprintln { + ($ctx:expr) => { + writeln!($ctx.stderr, "") + }; + ($ctx:expr, $($arg:tt)*) => { + writeln!($ctx.stderr, $($arg)*) + }; +} diff --git a/src/tests/config.rs b/src/tests/config.rs new file mode 100644 index 0000000..fa311d5 --- /dev/null +++ b/src/tests/config.rs @@ -0,0 +1,84 @@ +// config.rs + +// ************************************************************************* +// * Copyright (C) 2019-2020 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +use super::*; + +#[test] +fn mutually_exclusive_set_options() { + fn test(option1: &str, option2: &str) { + let (rc, out, err) = Nitrocli::new().run(&["config", "set", option1, option2]); + + assert_ne!(rc, 0); + assert_eq!(out, b""); + + let err = String::from_utf8(err).unwrap(); + assert!(err.contains("cannot be used with"), err); + } + + test("-c", "-C"); + test("-o", "-O"); + test("-s", "-S"); +} + +#[test_device] +fn get(model: nitrokey::Model) -> crate::Result<()> { + let re = regex::Regex::new( + r#"^Config: + numlock binding: (not set|\d+) + capslock binding: (not set|\d+) + scrollock binding: (not set|\d+) + require user PIN for OTP: (true|false) +$"#, + ) + .unwrap(); + + let out = Nitrocli::with_model(model).handle(&["config", "get"])?; + assert!(re.is_match(&out), out); + Ok(()) +} + +#[test_device] +fn set_wrong_usage(model: nitrokey::Model) { + let res = Nitrocli::with_model(model).handle(&["config", "set", "--numlock", "2", "-N"]); + let err = res.unwrap_str_err(); + assert!( + err.contains("The argument '--numlock <numlock>' cannot be used with '--no-numlock'"), + err, + ); +} + +#[test_device] +fn set_get(model: nitrokey::Model) -> crate::Result<()> { + let mut ncli = Nitrocli::with_model(model); + let _ = ncli.handle(&["config", "set", "-s", "1", "-c", "0", "-N"])?; + + let re = regex::Regex::new( + r#"^Config: + numlock binding: not set + capslock binding: 0 + scrollock binding: 1 + require user PIN for OTP: (true|false) +$"#, + ) + .unwrap(); + + let out = ncli.handle(&["config", "get"])?; + assert!(re.is_match(&out), out); + Ok(()) +} diff --git a/src/tests/encrypted.rs b/src/tests/encrypted.rs new file mode 100644 index 0000000..aed2662 --- /dev/null +++ b/src/tests/encrypted.rs @@ -0,0 +1,95 @@ +// encrypted.rs + +// ************************************************************************* +// * Copyright (C) 2019 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +use super::*; + +#[test_device(storage)] +fn status_open_close(model: nitrokey::Model) -> crate::Result<()> { + fn make_re(open: Option<bool>) -> regex::Regex { + let encrypted = match open { + Some(open) => { + if open { + "active" + } else { + "(read-only|inactive)" + } + } + None => "(read-only|active|inactive)", + }; + let re = format!( + r#" + volumes: + unencrypted: (read-only|active|inactive) + encrypted: {} + hidden: (read-only|active|inactive) +$"#, + encrypted + ); + regex::Regex::new(&re).unwrap() + } + + let mut ncli = Nitrocli::with_model(model); + let out = ncli.handle(&["status"])?; + assert!(make_re(None).is_match(&out), out); + + let _ = ncli.handle(&["encrypted", "open"])?; + let out = ncli.handle(&["status"])?; + assert!(make_re(Some(true)).is_match(&out), out); + + let _ = ncli.handle(&["encrypted", "close"])?; + let out = ncli.handle(&["status"])?; + assert!(make_re(Some(false)).is_match(&out), out); + + Ok(()) +} + +#[test_device(pro)] +fn encrypted_open_on_pro(model: nitrokey::Model) { + let res = Nitrocli::with_model(model).handle(&["encrypted", "open"]); + assert_eq!( + res.unwrap_str_err(), + "This command is only available on the Nitrokey Storage", + ); +} + +#[test_device(storage)] +fn encrypted_open_close(model: nitrokey::Model) -> crate::Result<()> { + let mut ncli = Nitrocli::with_model(model); + let out = ncli.handle(&["encrypted", "open"])?; + assert!(out.is_empty()); + + { + let mut manager = nitrokey::force_take()?; + let device = manager.connect_storage()?; + assert!(device.get_storage_status()?.encrypted_volume.active); + assert!(!device.get_storage_status()?.hidden_volume.active); + } + + let out = ncli.handle(&["encrypted", "close"])?; + assert!(out.is_empty()); + + { + let mut manager = nitrokey::force_take()?; + let device = manager.connect_storage()?; + assert!(!device.get_storage_status()?.encrypted_volume.active); + assert!(!device.get_storage_status()?.hidden_volume.active); + } + + Ok(()) +} diff --git a/src/tests/hidden.rs b/src/tests/hidden.rs new file mode 100644 index 0000000..eabcfd4 --- /dev/null +++ b/src/tests/hidden.rs @@ -0,0 +1,49 @@ +// hidden.rs + +// ************************************************************************* +// * Copyright (C) 2019 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +use super::*; + +#[test_device(storage)] +fn hidden_create_open_close(model: nitrokey::Model) -> crate::Result<()> { + let mut ncli = Nitrocli::with_model(model); + let out = ncli.handle(&["hidden", "create", "0", "50", "100"])?; + assert!(out.is_empty()); + + let out = ncli.handle(&["hidden", "open"])?; + assert!(out.is_empty()); + + { + let mut manager = nitrokey::force_take()?; + let device = manager.connect_storage()?; + assert!(!device.get_storage_status()?.encrypted_volume.active); + assert!(device.get_storage_status()?.hidden_volume.active); + } + + let out = ncli.handle(&["hidden", "close"])?; + assert!(out.is_empty()); + + { + let mut manager = nitrokey::force_take()?; + let device = manager.connect_storage()?; + assert!(!device.get_storage_status()?.encrypted_volume.active); + assert!(!device.get_storage_status()?.hidden_volume.active); + } + + Ok(()) +} diff --git a/src/tests/list.rs b/src/tests/list.rs new file mode 100644 index 0000000..4f80afe --- /dev/null +++ b/src/tests/list.rs @@ -0,0 +1,42 @@ +// list.rs + +// ************************************************************************* +// * Copyright (C) 2020 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +use super::*; + +#[test_device] +fn not_connected() -> crate::Result<()> { + let res = Nitrocli::new().handle(&["list"])?; + assert_eq!(res, "No Nitrokey device connected\n"); + + Ok(()) +} + +#[test_device] +fn connected(model: nitrokey::Model) -> crate::Result<()> { + let re = regex::Regex::new( + r#"^device path\tmodel\tserial number +([[:^space:]]+\t(Pro|Storage|unknown)\t0x[[:xdigit:]]+ +)+$"#, + ) + .unwrap(); + + let out = Nitrocli::with_model(model).handle(&["list"])?; + assert!(re.is_match(&out), out); + Ok(()) +} diff --git a/src/tests/lock.rs b/src/tests/lock.rs new file mode 100644 index 0000000..b29f394 --- /dev/null +++ b/src/tests/lock.rs @@ -0,0 +1,44 @@ +// lock.rs + +// ************************************************************************* +// * Copyright (C) 2019 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +use super::*; + +#[test_device(pro)] +fn lock_pro(model: nitrokey::Model) -> crate::Result<()> { + // We can't really test much more here than just success of the command. + let out = Nitrocli::with_model(model).handle(&["lock"])?; + assert!(out.is_empty()); + + Ok(()) +} + +#[test_device(storage)] +fn lock_storage(model: nitrokey::Model) -> crate::Result<()> { + let mut ncli = Nitrocli::with_model(model); + let _ = ncli.handle(&["encrypted", "open"])?; + + let out = ncli.handle(&["lock"])?; + assert!(out.is_empty()); + + let mut manager = nitrokey::force_take()?; + let device = manager.connect_storage()?; + assert!(!device.get_storage_status()?.encrypted_volume.active); + + Ok(()) +} diff --git a/src/tests/mod.rs b/src/tests/mod.rs new file mode 100644 index 0000000..abf63e3 --- /dev/null +++ b/src/tests/mod.rs @@ -0,0 +1,188 @@ +// mod.rs + +// ************************************************************************* +// * Copyright (C) 2019-2020 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +use std::ffi; +use std::fmt; + +use nitrokey_test::test as test_device; + +mod config; +mod encrypted; +mod hidden; +mod list; +mod lock; +mod otp; +mod pin; +mod pws; +mod reset; +mod run; +mod status; +mod unencrypted; + +/// A trait simplifying checking for expected errors. +pub trait UnwrapError { + /// Unwrap an Error::Error variant. + fn unwrap_str_err(self) -> String; + /// Unwrap a Error::CommandError variant. + fn unwrap_cmd_err(self) -> (Option<&'static str>, nitrokey::CommandError); + /// Unwrap a Error::LibraryError variant. + fn unwrap_lib_err(self) -> (Option<&'static str>, nitrokey::LibraryError); +} + +impl<T> UnwrapError for crate::Result<T> +where + T: fmt::Debug, +{ + fn unwrap_str_err(self) -> String { + match self.unwrap_err() { + crate::Error::ClapError(err) => { + if err.use_stderr() { + err.message + } else { + String::new() + } + } + crate::Error::Error(err) => err, + err => panic!("Unexpected error variant found: {:?}", err), + } + } + + fn unwrap_cmd_err(self) -> (Option<&'static str>, nitrokey::CommandError) { + match self.unwrap_err() { + crate::Error::NitrokeyError(ctx, err) => match err { + nitrokey::Error::CommandError(err) => (ctx, err), + err => panic!("Unexpected error variant found: {:?}", err), + }, + err => panic!("Unexpected error variant found: {:?}", err), + } + } + + fn unwrap_lib_err(self) -> (Option<&'static str>, nitrokey::LibraryError) { + match self.unwrap_err() { + crate::Error::NitrokeyError(ctx, err) => match err { + nitrokey::Error::LibraryError(err) => (ctx, err), + err => panic!("Unexpected error variant found: {:?}", err), + }, + err => panic!("Unexpected error variant found: {:?}", err), + } + } +} + +struct Nitrocli { + model: Option<nitrokey::Model>, + admin_pin: Option<ffi::OsString>, + user_pin: Option<ffi::OsString>, + new_admin_pin: Option<ffi::OsString>, + new_user_pin: Option<ffi::OsString>, + password: Option<ffi::OsString>, +} + +impl Nitrocli { + pub fn new() -> Self { + Self { + model: None, + admin_pin: Some(nitrokey::DEFAULT_ADMIN_PIN.into()), + user_pin: Some(nitrokey::DEFAULT_USER_PIN.into()), + new_admin_pin: None, + new_user_pin: None, + password: None, + } + } + + pub fn with_model<M>(model: M) -> Self + where + M: Into<nitrokey::Model>, + { + Self { + model: Some(model.into()), + admin_pin: Some(nitrokey::DEFAULT_ADMIN_PIN.into()), + user_pin: Some(nitrokey::DEFAULT_USER_PIN.into()), + new_admin_pin: None, + new_user_pin: None, + password: Some("1234567".into()), + } + } + + pub fn admin_pin(&mut self, pin: impl Into<ffi::OsString>) { + self.admin_pin = Some(pin.into()) + } + + pub fn new_admin_pin(&mut self, pin: impl Into<ffi::OsString>) { + self.new_admin_pin = Some(pin.into()) + } + + pub fn user_pin(&mut self, pin: impl Into<ffi::OsString>) { + self.user_pin = Some(pin.into()) + } + + pub fn new_user_pin(&mut self, pin: impl Into<ffi::OsString>) { + self.new_user_pin = Some(pin.into()) + } + + fn model_to_arg(model: nitrokey::Model) -> &'static str { + match model { + nitrokey::Model::Pro => "--model=pro", + nitrokey::Model::Storage => "--model=storage", + } + } + + fn do_run<F, R>(&mut self, args: &[&str], f: F) -> (R, Vec<u8>, Vec<u8>) + where + F: FnOnce(&mut crate::RunCtx<'_>, Vec<String>) -> R, + { + let args = ["nitrocli"] + .iter() + .cloned() + .chain(self.model.map(Self::model_to_arg)) + .chain(args.iter().cloned()) + .map(ToOwned::to_owned) + .collect(); + + let mut stdout = Vec::new(); + let mut stderr = Vec::new(); + + let ctx = &mut crate::RunCtx { + stdout: &mut stdout, + stderr: &mut stderr, + admin_pin: self.admin_pin.clone(), + user_pin: self.user_pin.clone(), + new_admin_pin: self.new_admin_pin.clone(), + new_user_pin: self.new_user_pin.clone(), + password: self.password.clone(), + no_cache: true, + }; + + (f(ctx, args), stdout, stderr) + } + + /// Run `nitrocli`'s `run` function. + pub fn run(&mut self, args: &[&str]) -> (i32, Vec<u8>, Vec<u8>) { + self.do_run(args, |c, a| crate::run(c, a)) + } + + /// Run `nitrocli`'s `handle_arguments` function. + pub fn handle(&mut self, args: &[&str]) -> crate::Result<String> { + let (res, out, _) = self.do_run(args, |c, a| crate::handle_arguments(c, a)); + res.map(|_| String::from_utf8_lossy(&out).into_owned()) + } + + pub fn model(&self) -> Option<nitrokey::Model> { + self.model + } +} diff --git a/src/tests/otp.rs b/src/tests/otp.rs new file mode 100644 index 0000000..f923170 --- /dev/null +++ b/src/tests/otp.rs @@ -0,0 +1,130 @@ +// otp.rs + +// ************************************************************************* +// * Copyright (C) 2019-2020 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +use super::*; + +use crate::args; + +#[test_device] +fn set_invalid_slot_raw(model: nitrokey::Model) { + let (rc, out, err) = Nitrocli::with_model(model).run(&["otp", "set", "100", "name", "1234"]); + + assert_ne!(rc, 0); + assert_eq!(out, b""); + assert_eq!(&err[..24], b"Could not write OTP slot"); +} + +#[test_device] +fn set_invalid_slot(model: nitrokey::Model) { + let res = Nitrocli::with_model(model).handle(&["otp", "set", "100", "name", "1234"]); + + assert_eq!( + res.unwrap_lib_err(), + ( + Some("Could not write OTP slot"), + nitrokey::LibraryError::InvalidSlot + ) + ); +} + +#[test_device] +fn status(model: nitrokey::Model) -> crate::Result<()> { + let re = regex::Regex::new( + r#"^alg\tslot\tname +((totp|hotp)\t\d+\t.+\n)+$"#, + ) + .unwrap(); + + let mut ncli = Nitrocli::with_model(model); + // Make sure that we have at least something to display by ensuring + // that there is one slot programmed. + let _ = ncli.handle(&["otp", "set", "0", "the-name", "123456"])?; + + let out = ncli.handle(&["otp", "status"])?; + assert!(re.is_match(&out), out); + Ok(()) +} + +#[test_device] +fn set_get_hotp(model: nitrokey::Model) -> crate::Result<()> { + // Secret and expected HOTP values as per RFC 4226: Appendix D -- HOTP + // Algorithm: Test Values. + const SECRET: &str = "12345678901234567890"; + const OTP1: &str = concat!(755224, "\n"); + const OTP2: &str = concat!(287082, "\n"); + + let mut ncli = Nitrocli::with_model(model); + let _ = ncli.handle(&[ + "otp", "set", "-a", "hotp", "-f", "ascii", "1", "name", &SECRET, + ])?; + + let out = ncli.handle(&["otp", "get", "-a", "hotp", "1"])?; + assert_eq!(out, OTP1); + + let out = ncli.handle(&["otp", "get", "-a", "hotp", "1"])?; + assert_eq!(out, OTP2); + Ok(()) +} + +#[test_device] +fn set_get_totp(model: nitrokey::Model) -> crate::Result<()> { + // Secret and expected TOTP values as per RFC 6238: Appendix B -- + // Test Vectors. + const SECRET: &str = "12345678901234567890"; + const TIME: &str = stringify!(1111111111); + const OTP: &str = concat!(14050471, "\n"); + + let mut ncli = Nitrocli::with_model(model); + let _ = ncli.handle(&["otp", "set", "-d", "8", "-f", "ascii", "2", "name", &SECRET])?; + + let out = ncli.handle(&["otp", "get", "-t", TIME, "2"])?; + assert_eq!(out, OTP); + Ok(()) +} + +#[test_device] +fn set_totp_uneven_chars(model: nitrokey::Model) -> crate::Result<()> { + let secrets = [ + (args::OtpSecretFormat::Hex, "123"), + (args::OtpSecretFormat::Base32, "FBILDWWGA2"), + ]; + + for (format, secret) in &secrets { + let mut ncli = Nitrocli::with_model(model); + let _ = ncli.handle(&["otp", "set", "-f", format.as_ref(), "3", "foobar", &secret])?; + } + Ok(()) +} + +#[test_device] +fn clear(model: nitrokey::Model) -> crate::Result<()> { + let mut ncli = Nitrocli::with_model(model); + let _ = ncli.handle(&["otp", "set", "3", "hotp-test", "abcdef"])?; + let _ = ncli.handle(&["otp", "clear", "3"])?; + let res = ncli.handle(&["otp", "get", "3"]); + + assert_eq!( + res.unwrap_cmd_err(), + ( + Some("Could not generate OTP"), + nitrokey::CommandError::SlotNotProgrammed + ) + ); + Ok(()) +} diff --git a/src/tests/pin.rs b/src/tests/pin.rs new file mode 100644 index 0000000..958a36d --- /dev/null +++ b/src/tests/pin.rs @@ -0,0 +1,84 @@ +// pin.rs + +// ************************************************************************* +// * Copyright (C) 2019 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +use nitrokey::Authenticate; +use nitrokey::Device; + +use super::*; + +#[test_device] +fn unblock(model: nitrokey::Model) -> crate::Result<()> { + { + let mut manager = nitrokey::force_take()?; + let device = manager.connect_model(model)?; + let (device, err) = device.authenticate_user("wrong-pin").unwrap_err(); + match err { + nitrokey::Error::CommandError(err) if err == nitrokey::CommandError::WrongPassword => (), + _ => panic!("Unexpected error variant found: {:?}", err), + } + assert!(device.get_user_retry_count()? < 3); + } + + let _ = Nitrocli::with_model(model).handle(&["pin", "unblock"])?; + + { + let mut manager = nitrokey::force_take()?; + let device = manager.connect_model(model)?; + assert_eq!(device.get_user_retry_count()?, 3); + } + Ok(()) +} + +#[test_device] +fn set_user(model: nitrokey::Model) -> crate::Result<()> { + let mut ncli = Nitrocli::with_model(model); + // Set a new user PIN. + ncli.new_user_pin("new-pin"); + let out = ncli.handle(&["pin", "set", "user"])?; + assert!(out.is_empty()); + + { + let mut manager = nitrokey::force_take()?; + let device = manager.connect_model(model)?; + let (_, err) = device + .authenticate_user(nitrokey::DEFAULT_USER_PIN) + .unwrap_err(); + + match err { + nitrokey::Error::CommandError(err) if err == nitrokey::CommandError::WrongPassword => (), + _ => panic!("Unexpected error variant found: {:?}", err), + } + } + + // Revert to the default user PIN. + ncli.user_pin("new-pin"); + ncli.new_user_pin(nitrokey::DEFAULT_USER_PIN); + + let out = ncli.handle(&["pin", "set", "user"])?; + assert!(out.is_empty()); + + { + let mut manager = nitrokey::force_take()?; + let device = manager.connect_model(ncli.model().unwrap())?; + let _ = device + .authenticate_user(nitrokey::DEFAULT_USER_PIN) + .unwrap(); + } + Ok(()) +} diff --git a/src/tests/pws.rs b/src/tests/pws.rs new file mode 100644 index 0000000..651b2d5 --- /dev/null +++ b/src/tests/pws.rs @@ -0,0 +1,123 @@ +// pws.rs + +// ************************************************************************* +// * Copyright (C) 2019 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +use super::*; + +#[test_device] +fn set_invalid_slot(model: nitrokey::Model) { + let res = Nitrocli::with_model(model).handle(&["pws", "set", "100", "name", "login", "1234"]); + + assert_eq!( + res.unwrap_lib_err(), + ( + Some("Could not write PWS slot"), + nitrokey::LibraryError::InvalidSlot + ) + ); +} + +#[test_device] +fn status(model: nitrokey::Model) -> crate::Result<()> { + let re = regex::Regex::new( + r#"^slot\tname +(\d+\t.+\n)+$"#, + ) + .unwrap(); + + let mut ncli = Nitrocli::with_model(model); + // Make sure that we have at least something to display by ensuring + // that there are there is one slot programmed. + let _ = ncli.handle(&["pws", "set", "0", "the-name", "the-login", "123456"])?; + + let out = ncli.handle(&["pws", "status"])?; + assert!(re.is_match(&out), out); + Ok(()) +} + +#[test_device] +fn set_get(model: nitrokey::Model) -> crate::Result<()> { + const NAME: &str = "dropbox"; + const LOGIN: &str = "d-e-s-o"; + const PASSWORD: &str = "my-secret-password"; + + let mut ncli = Nitrocli::with_model(model); + let _ = ncli.handle(&["pws", "set", "1", &NAME, &LOGIN, &PASSWORD])?; + + let out = ncli.handle(&["pws", "get", "1", "--quiet", "--name"])?; + assert_eq!(out, format!("{}\n", NAME)); + + let out = ncli.handle(&["pws", "get", "1", "--quiet", "--login"])?; + assert_eq!(out, format!("{}\n", LOGIN)); + + let out = ncli.handle(&["pws", "get", "1", "--quiet", "--password"])?; + assert_eq!(out, format!("{}\n", PASSWORD)); + + let out = ncli.handle(&["pws", "get", "1", "--quiet"])?; + assert_eq!(out, format!("{}\n{}\n{}\n", NAME, LOGIN, PASSWORD)); + + let out = ncli.handle(&["pws", "get", "1"])?; + assert_eq!( + out, + format!( + "name: {}\nlogin: {}\npassword: {}\n", + NAME, LOGIN, PASSWORD + ), + ); + Ok(()) +} + +#[test_device] +fn set_reset_get(model: nitrokey::Model) -> crate::Result<()> { + const NAME: &str = "some/svc"; + const LOGIN: &str = "a\\user"; + const PASSWORD: &str = "!@&-)*(&+%^@"; + + let mut ncli = Nitrocli::with_model(model); + let _ = ncli.handle(&["pws", "set", "2", &NAME, &LOGIN, &PASSWORD])?; + + let out = ncli.handle(&["reset"])?; + assert_eq!(out, ""); + + let res = ncli.handle(&["pws", "get", "2"]); + assert_eq!( + res.unwrap_cmd_err(), + ( + Some("Could not access PWS slot"), + nitrokey::CommandError::SlotNotProgrammed + ) + ); + Ok(()) +} + +#[test_device] +fn clear(model: nitrokey::Model) -> crate::Result<()> { + let mut ncli = Nitrocli::with_model(model); + let _ = ncli.handle(&["pws", "set", "10", "clear-test", "some-login", "abcdef"])?; + let _ = ncli.handle(&["pws", "clear", "10"])?; + let res = ncli.handle(&["pws", "get", "10"]); + + assert_eq!( + res.unwrap_cmd_err(), + ( + Some("Could not access PWS slot"), + nitrokey::CommandError::SlotNotProgrammed + ) + ); + Ok(()) +} diff --git a/src/tests/reset.rs b/src/tests/reset.rs new file mode 100644 index 0000000..e197970 --- /dev/null +++ b/src/tests/reset.rs @@ -0,0 +1,60 @@ +// reset.rs + +// ************************************************************************* +// * Copyright (C) 2019 Robin Krahl (robin.krahl@ireas.org) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +use nitrokey::Authenticate; +use nitrokey::GetPasswordSafe; + +use super::*; + +#[test_device] +fn reset(model: nitrokey::Model) -> crate::Result<()> { + let new_admin_pin = "87654321"; + let mut ncli = Nitrocli::with_model(model); + + // Change the admin PIN. + ncli.new_admin_pin(new_admin_pin); + let _ = ncli.handle(&["pin", "set", "admin"])?; + + { + let mut manager = nitrokey::force_take()?; + // Check that the admin PIN has been changed. + let device = manager.connect_model(ncli.model().unwrap())?; + let _ = device.authenticate_admin(new_admin_pin).unwrap(); + } + + // Perform factory reset + ncli.admin_pin(new_admin_pin); + let out = ncli.handle(&["reset"])?; + assert!(out.is_empty()); + + { + let mut manager = nitrokey::force_take()?; + // Check that the admin PIN has been reset. + let device = manager.connect_model(ncli.model().unwrap())?; + let mut device = device + .authenticate_admin(nitrokey::DEFAULT_ADMIN_PIN) + .unwrap(); + + // Check that the password store works, i.e., the AES key has been + // built. + let _ = device.get_password_safe(nitrokey::DEFAULT_USER_PIN)?; + } + + Ok(()) +} diff --git a/src/tests/run.rs b/src/tests/run.rs new file mode 100644 index 0000000..22e7004 --- /dev/null +++ b/src/tests/run.rs @@ -0,0 +1,110 @@ +// run.rs + +// ************************************************************************* +// * Copyright (C) 2019-2020 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +use super::*; + +#[test] +fn no_command_or_option() { + let (rc, out, err) = Nitrocli::new().run(&[]); + + assert_ne!(rc, 0); + assert_eq!(out, b""); + + let s = String::from_utf8_lossy(&err).into_owned(); + assert!(s.starts_with("nitrocli"), s); + assert!(s.contains("USAGE:\n"), s); +} + +#[test] +fn help_options() { + fn test_run(args: &[&str], help: &str) { + let mut all = args.to_vec(); + all.push(help); + + let (rc, out, err) = Nitrocli::new().run(&all); + + assert_eq!(rc, 0); + assert_eq!(err, b""); + + let s = String::from_utf8_lossy(&out).into_owned(); + let mut args = args.to_vec(); + args.insert(0, "nitrocli"); + assert!(s.starts_with(&args.join("-")), s); + assert!(s.contains("USAGE:\n"), s); + } + + fn test(args: &[&str]) { + test_run(args, "--help"); + test_run(args, "-h"); + } + + test(&[]); + test(&["config"]); + test(&["config", "get"]); + test(&["config", "set"]); + test(&["encrypted"]); + test(&["encrypted", "open"]); + test(&["encrypted", "close"]); + test(&["hidden"]); + test(&["hidden", "close"]); + test(&["hidden", "create"]); + test(&["hidden", "open"]); + test(&["lock"]); + test(&["otp"]); + test(&["otp", "clear"]); + test(&["otp", "get"]); + test(&["otp", "set"]); + test(&["otp", "status"]); + test(&["pin"]); + test(&["pin", "clear"]); + test(&["pin", "set"]); + test(&["pin", "unblock"]); + test(&["pws"]); + test(&["pws", "clear"]); + test(&["pws", "get"]); + test(&["pws", "set"]); + test(&["pws", "status"]); + test(&["reset"]); + test(&["status"]); + test(&["unencrypted"]); + test(&["unencrypted", "set"]); +} + +#[test] +#[ignore] +fn version_option() { + // clap sends the version output directly to stdout: https://github.com/clap-rs/clap/issues/1390 + // Therefore we ignore this test for the time being. + + fn test(re: ®ex::Regex, opt: &'static str) { + let (rc, out, err) = Nitrocli::new().run(&[opt]); + + assert_eq!(rc, 0); + assert_eq!(err, b""); + + let s = String::from_utf8_lossy(&out).into_owned(); + let _ = re; + assert!(re.is_match(&s), out); + } + + let re = regex::Regex::new(r"^nitrocli \d+.\d+.\d+(-[^-]+)*\n$").unwrap(); + + test(&re, "--version"); + test(&re, "-V"); +} diff --git a/src/tests/status.rs b/src/tests/status.rs new file mode 100644 index 0000000..c9f4976 --- /dev/null +++ b/src/tests/status.rs @@ -0,0 +1,81 @@ +// status.rs + +// ************************************************************************* +// * Copyright (C) 2019 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +use super::*; + +// This test acts as verification that conversion of Error::Error +// variants into the proper exit code works properly. +#[test_device] +fn not_found_raw() { + let (rc, out, err) = Nitrocli::new().run(&["status"]); + + assert_ne!(rc, 0); + assert_eq!(out, b""); + assert_eq!(err, b"Nitrokey device not found\n"); +} + +#[test_device] +fn not_found() { + let res = Nitrocli::new().handle(&["status"]); + assert_eq!(res.unwrap_str_err(), "Nitrokey device not found"); +} + +#[test_device(pro)] +fn output_pro(model: nitrokey::Model) -> crate::Result<()> { + let re = regex::Regex::new( + r#"^Status: + model: Pro + serial number: 0x[[:xdigit:]]{8} + firmware version: v\d+\.\d+ + user retry count: [0-3] + admin retry count: [0-3] +$"#, + ) + .unwrap(); + + let out = Nitrocli::with_model(model).handle(&["status"])?; + assert!(re.is_match(&out), out); + Ok(()) +} + +#[test_device(storage)] +fn output_storage(model: nitrokey::Model) -> crate::Result<()> { + let re = regex::Regex::new( + r#"^Status: + model: Storage + serial number: 0x[[:xdigit:]]{8} + firmware version: v\d+\.\d+ + user retry count: [0-3] + admin retry count: [0-3] + Storage: + SD card ID: 0x[[:xdigit:]]{8} + firmware: (un)?locked + storage keys: (not )?created + volumes: + unencrypted: (read-only|active|inactive) + encrypted: (read-only|active|inactive) + hidden: (read-only|active|inactive) +$"#, + ) + .unwrap(); + + let out = Nitrocli::with_model(model).handle(&["status"])?; + assert!(re.is_match(&out), out); + Ok(()) +} diff --git a/src/tests/unencrypted.rs b/src/tests/unencrypted.rs new file mode 100644 index 0000000..ceeb17c --- /dev/null +++ b/src/tests/unencrypted.rs @@ -0,0 +1,46 @@ +// unencrypted.rs + +// ************************************************************************* +// * Copyright (C) 2019 Daniel Mueller (deso@posteo.net) * +// * * +// * This program is free software: you can redistribute it and/or modify * +// * it under the terms of the GNU General Public License as published by * +// * the Free Software Foundation, either version 3 of the License, or * +// * (at your option) any later version. * +// * * +// * This program is distributed in the hope that it will be useful, * +// * but WITHOUT ANY WARRANTY; without even the implied warranty of * +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +// * GNU General Public License for more details. * +// * * +// * You should have received a copy of the GNU General Public License * +// * along with this program. If not, see <http://www.gnu.org/licenses/>. * +// ************************************************************************* + +use super::*; + +#[test_device(storage)] +fn unencrypted_set_read_write(model: nitrokey::Model) -> crate::Result<()> { + let mut ncli = Nitrocli::with_model(model); + let out = ncli.handle(&["unencrypted", "set", "read-write"])?; + assert!(out.is_empty()); + + { + let mut manager = nitrokey::force_take()?; + let device = manager.connect_storage()?; + assert!(device.get_storage_status()?.unencrypted_volume.active); + assert!(!device.get_storage_status()?.unencrypted_volume.read_only); + } + + let out = ncli.handle(&["unencrypted", "set", "read-only"])?; + assert!(out.is_empty()); + + { + let mut manager = nitrokey::force_take()?; + let device = manager.connect_storage()?; + assert!(device.get_storage_status()?.unencrypted_volume.active); + assert!(device.get_storage_status()?.unencrypted_volume.read_only); + } + + Ok(()) +} |