From 681cc8882f7995407c33eb48730daaa901074460 Mon Sep 17 00:00:00 2001 From: Daniel Mueller Date: Sat, 4 Apr 2020 15:32:14 -0700 Subject: Move nitrocli source code into repository root Now that all vendored dependencies have been removed, this change moves the program's source code from the nitrocli/ directory into the root of the repository. --- src/arg_util.rs | 158 ++++++++ src/args.rs | 984 +++++++++++++++++++++++++++++++++++++++++++++++ src/commands.rs | 984 +++++++++++++++++++++++++++++++++++++++++++++++ src/error.rs | 104 +++++ src/main.rs | 167 ++++++++ src/pinentry.rs | 404 +++++++++++++++++++ src/redefine.rs | 38 ++ src/tests/config.rs | 66 ++++ src/tests/encrypted.rs | 95 +++++ src/tests/hidden.rs | 49 +++ src/tests/lock.rs | 44 +++ src/tests/mod.rs | 180 +++++++++ src/tests/otp.rs | 130 +++++++ src/tests/pin.rs | 84 ++++ src/tests/pws.rs | 123 ++++++ src/tests/reset.rs | 60 +++ src/tests/run.rs | 103 +++++ src/tests/status.rs | 81 ++++ src/tests/unencrypted.rs | 46 +++ 19 files changed, 3900 insertions(+) create mode 100644 src/arg_util.rs create mode 100644 src/args.rs create mode 100644 src/commands.rs create mode 100644 src/error.rs create mode 100644 src/main.rs create mode 100644 src/pinentry.rs create mode 100644 src/redefine.rs create mode 100644 src/tests/config.rs create mode 100644 src/tests/encrypted.rs create mode 100644 src/tests/hidden.rs create mode 100644 src/tests/lock.rs create mode 100644 src/tests/mod.rs create mode 100644 src/tests/otp.rs create mode 100644 src/tests/pin.rs create mode 100644 src/tests/pws.rs create mode 100644 src/tests/reset.rs create mode 100644 src/tests/run.rs create mode 100644 src/tests/status.rs create mode 100644 src/tests/unencrypted.rs (limited to 'src') diff --git a/src/arg_util.rs b/src/arg_util.rs new file mode 100644 index 0000000..e2e7b1d --- /dev/null +++ b/src/arg_util.rs @@ -0,0 +1,158 @@ +// arg_util.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 . * +// ************************************************************************* + +macro_rules! count { + ($head:ident) => { 1 }; + ($head:ident, $($tail:ident),*) => { + 1 + count!($($tail),*) + } +} + +/// 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 { + ( $name:ident, [ $( $var:ident => ($str:expr, $exec:expr), ) *] ) => { + Enum! {$name, [ + $( $var => $str, )* + ]} + + #[allow(unused_qualifications)] + impl $name { + fn execute( + self, + ctx: &mut crate::args::ExecCtx<'_>, + args: ::std::vec::Vec<::std::string::String>, + ) -> crate::Result<()> { + match self { + $( + $name::$var => $exec(ctx, args), + )* + } + } + } + }; + ( $name:ident, [ $( $var:ident => $str:expr, ) *] ) => { + #[derive(Clone, Copy, Debug, PartialEq)] + pub enum $name { + $( + $var, + )* + } + + impl $name { + #[allow(unused)] + pub fn all(&self) -> [$name; count!($($var),*) ] { + $name::all_variants() + } + + pub fn all_variants() -> [$name; count!($($var),*) ] { + [ + $( + $name::$var, + )* + ] + } + } + + impl ::std::convert::AsRef 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 = (); + + fn from_str(s: &str) -> ::std::result::Result { + match s { + $( + $str => Ok($name::$var), + )* + _ => Err(()), + } + } + } + }; +} + +/// A macro for formatting the variants of an enum (as created by the +/// Enum!{} macro) ready to be used in a help text. The supplied `fmt` +/// needs to contain the named parameter `{variants}`, which will be +/// replaced with a generated version of the enum's variants. +macro_rules! fmt_enum { + ( $enm:ident ) => {{ + fmt_enum!($enm.all()) + }}; + ( $all:expr ) => {{ + $all + .iter() + .map(::std::convert::AsRef::as_ref) + .collect::<::std::vec::Vec<_>>() + .join("|") + }}; +} + +/// A macro for generating the help text for a command/subcommand. The +/// argument is the variable representing the command (which in turn is +/// an enum). +/// Note that the name of this variable is embedded into the help text! +macro_rules! cmd_help { + ( $cmd:ident ) => { + format!( + concat!("The ", stringify!($cmd), " to execute ({})"), + fmt_enum!($cmd) + ) + }; +} + +#[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..9f4cae2 --- /dev/null +++ b/src/args.rs @@ -0,0 +1,984 @@ +// args.rs + +// ************************************************************************* +// * Copyright (C) 2018-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 . * +// ************************************************************************* + +use std::ffi; +use std::io; +use std::result; +use std::str; + +use crate::commands; +use crate::error::Error; +use crate::pinentry; +use crate::RunCtx; + +type Result = result::Result; + +/// Wraps a writer and buffers its output. +/// +/// This implementation is similar to `io::BufWriter`, but: +/// - The inner writer is only written to if `flush` is called. +/// - The buffer may grow infinitely large. +struct BufWriter<'w, W: io::Write + ?Sized> { + buf: Vec, + inner: &'w mut W, +} + +impl<'w, W: io::Write + ?Sized> BufWriter<'w, W> { + pub fn new(inner: &'w mut W) -> Self { + BufWriter { + buf: Vec::with_capacity(128), + inner, + } + } +} + +impl<'w, W: io::Write + ?Sized> io::Write for BufWriter<'w, W> { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.buf.extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + self.inner.write_all(&self.buf)?; + self.buf.clear(); + self.inner.flush() + } +} + +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 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. +pub struct ExecCtx<'io> { + pub model: Option, + pub stdout: &'io mut dyn io::Write, + pub stderr: &'io mut dyn io::Write, + pub admin_pin: Option, + pub user_pin: Option, + pub new_admin_pin: Option, + pub new_user_pin: Option, + pub password: Option, + pub no_cache: bool, + 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) + } +} + +/// The available Nitrokey models. +#[allow(unused_doc_comments)] +Enum! {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 for nitrokey::Model { + fn from(model: DeviceModel) -> nitrokey::Model { + match model { + DeviceModel::Pro => nitrokey::Model::Pro, + DeviceModel::Storage => nitrokey::Model::Storage, + } + } +} + +/// A top-level command for nitrocli. +#[allow(unused_doc_comments)] +Enum! {Command, [ + Config => ("config", config), + Encrypted => ("encrypted", encrypted), + Hidden => ("hidden", hidden), + Lock => ("lock", lock), + Otp => ("otp", otp), + Pin => ("pin", pin), + Pws => ("pws", pws), + Reset => ("reset", reset), + Status => ("status", status), + Unencrypted => ("unencrypted", unencrypted), +]} + +Enum! {ConfigCommand, [ + Get => ("get", config_get), + Set => ("set", config_set), +]} + +#[derive(Clone, Copy, Debug)] +pub enum ConfigOption { + Enable(T), + Disable, + Ignore, +} + +impl ConfigOption { + fn try_from(disable: bool, value: Option, name: &'static str) -> Result { + if disable { + if value.is_some() { + Err(Error::Error(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) -> Option { + match self { + ConfigOption::Enable(value) => Some(value), + ConfigOption::Disable => None, + ConfigOption::Ignore => default, + } + } +} + +Enum! {OtpCommand, [ + Clear => ("clear", otp_clear), + Get => ("get", otp_get), + Set => ("set", otp_set), + Status => ("status", otp_status), +]} + +Enum! {OtpAlgorithm, [ + Hotp => "hotp", + Totp => "totp", +]} + +Enum! {OtpMode, [ + SixDigits => "6", + EightDigits => "8", +]} + +impl From 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", +]} + +Enum! {PinCommand, [ + Clear => ("clear", pin_clear), + Set => ("set", pin_set), + Unblock => ("unblock", pin_unblock), +]} + +Enum! {PwsCommand, [ + Clear => ("clear", pws_clear), + Get => ("get", pws_get), + Set => ("set", pws_set), + Status => ("status", pws_status), +]} + +fn parse( + ctx: &mut impl Stdio, + parser: argparse::ArgumentParser<'_>, + args: Vec, +) -> Result<()> { + let (stdout, stderr) = ctx.stdio(); + let result = parser + .parse(args, stdout, stderr) + .map_err(Error::ArgparseError); + drop(parser); + result +} + +/// Inquire the status of the Nitrokey. +fn status(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Prints the status of the connected Nitrokey device"); + parse(ctx, parser, args)?; + + commands::status(ctx) +} + +/// Perform a factory reset. +fn reset(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Performs a factory reset"); + parse(ctx, parser, args)?; + + commands::reset(ctx) +} + +Enum! {UnencryptedCommand, [ + Set => ("set", unencrypted_set), +]} + +Enum! {UnencryptedVolumeMode, [ + ReadWrite => "read-write", + ReadOnly => "read-only", +]} + +/// Execute an unencrypted subcommand. +fn unencrypted(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut subcommand = UnencryptedCommand::Set; + let help = cmd_help!(subcommand); + let mut subargs = vec![]; + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Interacts with the device's unencrypted volume"); + let _ = + parser + .refer(&mut subcommand) + .required() + .add_argument("subcommand", argparse::Store, &help); + let _ = parser.refer(&mut subargs).add_argument( + "arguments", + argparse::List, + "The arguments for the subcommand", + ); + parser.stop_on_first_argument(true); + parse(ctx, parser, args)?; + + subargs.insert( + 0, + format!( + "{} {} {}", + crate::NITROCLI, + Command::Unencrypted, + subcommand, + ), + ); + subcommand.execute(ctx, subargs) +} + +/// Change the configuration of the unencrypted volume. +fn unencrypted_set(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut mode = UnencryptedVolumeMode::ReadWrite; + let help = format!("The mode to change to ({})", fmt_enum!(mode)); + let mut parser = argparse::ArgumentParser::new(); + parser + .set_description("Changes the configuration of the unencrypted volume on a Nitrokey Storage"); + let _ = parser + .refer(&mut mode) + .required() + .add_argument("type", argparse::Store, &help); + parse(ctx, parser, args)?; + + commands::unencrypted_set(ctx, mode) +} + +Enum! {EncryptedCommand, [ + Close => ("close", encrypted_close), + Open => ("open", encrypted_open), +]} + +/// Execute an encrypted subcommand. +fn encrypted(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut subcommand = EncryptedCommand::Open; + let help = cmd_help!(subcommand); + let mut subargs = vec![]; + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Interacts with the device's encrypted volume"); + let _ = + parser + .refer(&mut subcommand) + .required() + .add_argument("subcommand", argparse::Store, &help); + let _ = parser.refer(&mut subargs).add_argument( + "arguments", + argparse::List, + "The arguments for the subcommand", + ); + parser.stop_on_first_argument(true); + parse(ctx, parser, args)?; + + subargs.insert( + 0, + format!("{} {} {}", crate::NITROCLI, Command::Encrypted, subcommand), + ); + subcommand.execute(ctx, subargs) +} + +/// Open the encrypted volume on the Nitrokey. +fn encrypted_open(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Opens the encrypted volume on a Nitrokey Storage"); + parse(ctx, parser, args)?; + + commands::encrypted_open(ctx) +} + +/// Close the previously opened encrypted volume. +fn encrypted_close(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Closes the encrypted volume on a Nitrokey Storage"); + parse(ctx, parser, args)?; + + commands::encrypted_close(ctx) +} + +Enum! {HiddenCommand, [ + Close => ("close", hidden_close), + Create => ("create", hidden_create), + Open => ("open", hidden_open), +]} + +/// Execute a hidden subcommand. +fn hidden(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut subcommand = HiddenCommand::Open; + let help = cmd_help!(subcommand); + let mut subargs = vec![]; + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Interacts with the device's hidden volume"); + let _ = + parser + .refer(&mut subcommand) + .required() + .add_argument("subcommand", argparse::Store, &help); + let _ = parser.refer(&mut subargs).add_argument( + "arguments", + argparse::List, + "The arguments for the subcommand", + ); + parser.stop_on_first_argument(true); + parse(ctx, parser, args)?; + + subargs.insert( + 0, + format!("{} {} {}", crate::NITROCLI, Command::Hidden, subcommand), + ); + subcommand.execute(ctx, subargs) +} + +fn hidden_create(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut slot: u8 = 0; + let mut start: u8 = 0; + let mut end: u8 = 0; + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Creates a hidden volume on a Nitrokey Storage"); + let _ = parser.refer(&mut slot).required().add_argument( + "slot", + argparse::Store, + "The hidden volume slot to use", + ); + let _ = parser.refer(&mut start).required().add_argument( + "start", + argparse::Store, + "The start location of the hidden volume as percentage of the \ + encrypted volume's size (0-99)", + ); + let _ = parser.refer(&mut end).required().add_argument( + "end", + argparse::Store, + "The end location of the hidden volume as percentage of the \ + encrypted volume's size (1-100)", + ); + parse(ctx, parser, args)?; + + commands::hidden_create(ctx, slot, start, end) +} + +fn hidden_open(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Opens a hidden volume on a Nitrokey Storage"); + parse(ctx, parser, args)?; + + commands::hidden_open(ctx) +} + +fn hidden_close(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Closes the hidden volume on a Nitrokey Storage"); + parse(ctx, parser, args)?; + + commands::hidden_close(ctx) +} + +/// Execute a config subcommand. +fn config(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut subcommand = ConfigCommand::Get; + let help = cmd_help!(subcommand); + let mut subargs = vec![]; + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Reads or writes the device configuration"); + let _ = + parser + .refer(&mut subcommand) + .required() + .add_argument("subcommand", argparse::Store, &help); + let _ = parser.refer(&mut subargs).add_argument( + "arguments", + argparse::List, + "The arguments for the subcommand", + ); + parser.stop_on_first_argument(true); + parse(ctx, parser, args)?; + + subargs.insert( + 0, + format!("{} {} {}", crate::NITROCLI, Command::Config, subcommand), + ); + subcommand.execute(ctx, subargs) +} + +/// Read the Nitrokey configuration. +fn config_get(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Prints the Nitrokey configuration"); + parse(ctx, parser, args)?; + + commands::config_get(ctx) +} + +/// Write the Nitrokey configuration. +fn config_set(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut numlock = None; + let mut no_numlock = false; + let mut capslock = None; + let mut no_capslock = false; + let mut scrollock = None; + let mut no_scrollock = false; + let mut otp_pin = false; + let mut no_otp_pin = false; + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Changes the Nitrokey configuration"); + let _ = parser.refer(&mut numlock).add_option( + &["-n", "--numlock"], + argparse::StoreOption, + "Set the numlock option to the given HOTP slot", + ); + let _ = parser.refer(&mut no_numlock).add_option( + &["-N", "--no-numlock"], + argparse::StoreTrue, + "Unset the numlock option", + ); + let _ = parser.refer(&mut capslock).add_option( + &["-c", "--capslock"], + argparse::StoreOption, + "Set the capslock option to the given HOTP slot", + ); + let _ = parser.refer(&mut no_capslock).add_option( + &["-C", "--no-capslock"], + argparse::StoreTrue, + "Unset the capslock option", + ); + let _ = parser.refer(&mut scrollock).add_option( + &["-s", "--scrollock"], + argparse::StoreOption, + "Set the scrollock option to the given HOTP slot", + ); + let _ = parser.refer(&mut no_scrollock).add_option( + &["-S", "--no-scrollock"], + argparse::StoreTrue, + "Unset the scrollock option", + ); + let _ = parser.refer(&mut otp_pin).add_option( + &["-o", "--otp-pin"], + argparse::StoreTrue, + "Require the user PIN to generate one-time passwords", + ); + let _ = parser.refer(&mut no_otp_pin).add_option( + &["-O", "--no-otp-pin"], + argparse::StoreTrue, + "Allow one-time password generation without PIN", + ); + parse(ctx, parser, args)?; + + let numlock = ConfigOption::try_from(no_numlock, numlock, "numlock")?; + let capslock = ConfigOption::try_from(no_capslock, capslock, "capslock")?; + let scrollock = ConfigOption::try_from(no_scrollock, scrollock, "scrollock")?; + let otp_pin = if otp_pin { + Some(true) + } else if no_otp_pin { + Some(false) + } else { + None + }; + commands::config_set(ctx, numlock, capslock, scrollock, otp_pin) +} + +/// Lock the Nitrokey. +fn lock(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Locks the connected Nitrokey device"); + parse(ctx, parser, args)?; + + commands::lock(ctx) +} + +/// Execute an OTP subcommand. +fn otp(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut subcommand = OtpCommand::Get; + let help = cmd_help!(subcommand); + let mut subargs = vec![]; + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Accesses one-time passwords"); + let _ = + parser + .refer(&mut subcommand) + .required() + .add_argument("subcommand", argparse::Store, &help); + let _ = parser.refer(&mut subargs).add_argument( + "arguments", + argparse::List, + "The arguments for the subcommand", + ); + parser.stop_on_first_argument(true); + parse(ctx, parser, args)?; + + subargs.insert( + 0, + format!("{} {} {}", crate::NITROCLI, Command::Otp, subcommand), + ); + subcommand.execute(ctx, subargs) +} + +/// Generate a one-time password on the Nitrokey device. +fn otp_get(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut slot: u8 = 0; + let mut algorithm = OtpAlgorithm::Totp; + let help = format!( + "The OTP algorithm to use ({}, default: {})", + fmt_enum!(algorithm), + algorithm + ); + let mut time: Option = None; + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Generates a one-time password"); + let _ = + parser + .refer(&mut slot) + .required() + .add_argument("slot", argparse::Store, "The OTP slot to use"); + let _ = parser + .refer(&mut algorithm) + .add_option(&["-a", "--algorithm"], argparse::Store, &help); + let _ = parser.refer(&mut time).add_option( + &["-t", "--time"], + argparse::StoreOption, + "The time to use for TOTP generation (Unix timestamp, default: system time)", + ); + parse(ctx, parser, args)?; + + commands::otp_get(ctx, slot, algorithm, time) +} + +/// Configure a one-time password slot on the Nitrokey device. +pub fn otp_set(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut slot: u8 = 0; + let mut algorithm = OtpAlgorithm::Totp; + let algo_help = format!( + "The OTP algorithm to use ({}, default: {})", + fmt_enum!(algorithm), + algorithm + ); + let mut name = "".to_owned(); + let mut secret = "".to_owned(); + let mut digits = OtpMode::SixDigits; + let mut counter: u64 = 0; + let mut time_window: u16 = 30; + let mut secret_format = OtpSecretFormat::Hex; + let fmt_help = format!( + "The format of the secret ({}, default: {})", + fmt_enum!(OtpSecretFormat::all_variants()), + secret_format, + ); + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Configures a one-time password slot"); + let _ = + parser + .refer(&mut slot) + .required() + .add_argument("slot", argparse::Store, "The OTP slot to use"); + let _ = + parser + .refer(&mut algorithm) + .add_option(&["-a", "--algorithm"], argparse::Store, &algo_help); + let _ = parser.refer(&mut name).required().add_argument( + "name", + argparse::Store, + "The name of the slot", + ); + let _ = parser.refer(&mut secret).required().add_argument( + "secret", + argparse::Store, + "The secret to store on the slot as a hexadecimal string (unless overwritten by --format)", + ); + let _ = parser.refer(&mut digits).add_option( + &["-d", "--digits"], + argparse::Store, + "The number of digits to use for the one-time password (6 or 8, default: 6)", + ); + let _ = parser.refer(&mut counter).add_option( + &["-c", "--counter"], + argparse::Store, + "The counter value for HOTP (default: 0)", + ); + let _ = parser.refer(&mut time_window).add_option( + &["-t", "--time-window"], + argparse::Store, + "The time window for TOTP (default: 30)", + ); + let _ = + parser + .refer(&mut secret_format) + .add_option(&["-f", "--format"], argparse::Store, &fmt_help); + parse(ctx, parser, args)?; + + let data = nitrokey::OtpSlotData { + number: slot, + name, + secret, + mode: nitrokey::OtpMode::from(digits), + use_enter: false, + token_id: None, + }; + commands::otp_set(ctx, data, algorithm, counter, time_window, secret_format) +} + +/// Clear an OTP slot. +fn otp_clear(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut slot: u8 = 0; + let mut algorithm = OtpAlgorithm::Totp; + let help = format!( + "The OTP algorithm to use ({}, default: {})", + fmt_enum!(algorithm), + algorithm + ); + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Clears a one-time password slot"); + let _ = parser.refer(&mut slot).required().add_argument( + "slot", + argparse::Store, + "The OTP slot to clear", + ); + let _ = parser + .refer(&mut algorithm) + .add_option(&["-a", "--algorithm"], argparse::Store, &help); + parse(ctx, parser, args)?; + + commands::otp_clear(ctx, slot, algorithm) +} + +/// Print the status of the OTP slots. +fn otp_status(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut all = false; + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Prints the status of the OTP slots"); + let _ = parser.refer(&mut all).add_option( + &["-a", "--all"], + argparse::StoreTrue, + "Show slots that are not programmed", + ); + parse(ctx, parser, args)?; + + commands::otp_status(ctx, all) +} + +/// Execute a PIN subcommand. +fn pin(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut subcommand = PinCommand::Clear; + let help = cmd_help!(subcommand); + let mut subargs = vec![]; + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Manages the Nitrokey PINs"); + let _ = + parser + .refer(&mut subcommand) + .required() + .add_argument("subcommand", argparse::Store, &help); + let _ = parser.refer(&mut subargs).add_argument( + "arguments", + argparse::List, + "The arguments for the subcommand", + ); + parser.stop_on_first_argument(true); + parse(ctx, parser, args)?; + + subargs.insert( + 0, + format!("{} {} {}", crate::NITROCLI, Command::Pin, subcommand), + ); + subcommand.execute(ctx, subargs) +} + +/// Clear the PIN as cached by various other commands. +fn pin_clear(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Clears the cached PINs"); + parse(ctx, parser, args)?; + + commands::pin_clear(ctx) +} + +/// Change a PIN. +fn pin_set(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut pintype = pinentry::PinType::User; + let help = format!("The PIN type to change ({})", fmt_enum!(pintype)); + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Changes a PIN"); + let _ = parser + .refer(&mut pintype) + .required() + .add_argument("type", argparse::Store, &help); + parse(ctx, parser, args)?; + + commands::pin_set(ctx, pintype) +} + +/// Unblock and reset the user PIN. +fn pin_unblock(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Unblocks and resets the user PIN"); + parse(ctx, parser, args)?; + + commands::pin_unblock(ctx) +} + +/// Execute a PWS subcommand. +fn pws(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut subcommand = PwsCommand::Get; + let mut subargs = vec![]; + let help = cmd_help!(subcommand); + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Accesses the password safe"); + let _ = + parser + .refer(&mut subcommand) + .required() + .add_argument("subcommand", argparse::Store, &help); + let _ = parser.refer(&mut subargs).add_argument( + "arguments", + argparse::List, + "The arguments for the subcommand", + ); + parser.stop_on_first_argument(true); + parse(ctx, parser, args)?; + + subargs.insert( + 0, + format!("{} {} {}", crate::NITROCLI, Command::Pws, subcommand), + ); + subcommand.execute(ctx, subargs) +} + +/// Access a slot of the password safe on the Nitrokey. +fn pws_get(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut slot: u8 = 0; + let mut name = false; + let mut login = false; + let mut password = false; + let mut quiet = false; + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Reads a password safe slot"); + let _ = parser.refer(&mut slot).required().add_argument( + "slot", + argparse::Store, + "The PWS slot to read", + ); + let _ = parser.refer(&mut name).add_option( + &["-n", "--name"], + argparse::StoreTrue, + "Show the name stored on the slot", + ); + let _ = parser.refer(&mut login).add_option( + &["-l", "--login"], + argparse::StoreTrue, + "Show the login stored on the slot", + ); + let _ = parser.refer(&mut password).add_option( + &["-p", "--password"], + argparse::StoreTrue, + "Show the password stored on the slot", + ); + let _ = parser.refer(&mut quiet).add_option( + &["-q", "--quiet"], + argparse::StoreTrue, + "Print the stored data without description", + ); + parse(ctx, parser, args)?; + + commands::pws_get(ctx, slot, name, login, password, quiet) +} + +/// Set a slot of the password safe on the Nitrokey. +fn pws_set(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut slot: u8 = 0; + let mut name = String::new(); + let mut login = String::new(); + let mut password = String::new(); + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Writes a password safe slot"); + let _ = parser.refer(&mut slot).required().add_argument( + "slot", + argparse::Store, + "The PWS slot to write", + ); + let _ = parser.refer(&mut name).required().add_argument( + "name", + argparse::Store, + "The name to store on the slot", + ); + let _ = parser.refer(&mut login).required().add_argument( + "login", + argparse::Store, + "The login to store on the slot", + ); + let _ = parser.refer(&mut password).required().add_argument( + "password", + argparse::Store, + "The password to store on the slot", + ); + parse(ctx, parser, args)?; + + commands::pws_set(ctx, slot, &name, &login, &password) +} + +/// Clear a PWS slot. +fn pws_clear(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut slot: u8 = 0; + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Clears a password safe slot"); + let _ = parser.refer(&mut slot).required().add_argument( + "slot", + argparse::Store, + "The PWS slot to clear", + ); + parse(ctx, parser, args)?; + + commands::pws_clear(ctx, slot) +} + +/// Print the status of the PWS slots. +fn pws_status(ctx: &mut ExecCtx<'_>, args: Vec) -> Result<()> { + let mut all = false; + let mut parser = argparse::ArgumentParser::new(); + parser.set_description("Prints the status of the PWS slots"); + let _ = parser.refer(&mut all).add_option( + &["-a", "--all"], + argparse::StoreTrue, + "Show slots that are not programmed", + ); + parse(ctx, parser, args)?; + + commands::pws_status(ctx, all) +} + +/// Parse the command-line arguments and execute the selected command. +pub(crate) fn handle_arguments(ctx: &mut RunCtx<'_>, args: Vec) -> Result<()> { + use std::io::Write; + + let mut version = false; + let mut model: Option = None; + let model_help = format!( + "Select the device model to connect to ({})", + fmt_enum!(DeviceModel::all_variants()) + ); + let mut verbosity = 0; + let mut command = Command::Status; + let cmd_help = cmd_help!(command); + let mut subargs = vec![]; + let mut parser = argparse::ArgumentParser::new(); + let _ = parser.refer(&mut version).add_option( + &["-V", "--version"], + argparse::StoreTrue, + "Print version information and exit", + ); + let _ = parser.refer(&mut verbosity).add_option( + &["-v", "--verbose"], + argparse::IncrBy::(1), + "Increase the log level (can be supplied multiple times)", + ); + let _ = + parser + .refer(&mut model) + .add_option(&["-m", "--model"], argparse::StoreOption, &model_help); + parser.set_description("Provides access to a Nitrokey device"); + let _ = parser + .refer(&mut command) + .required() + .add_argument("command", argparse::Store, &cmd_help); + let _ = parser.refer(&mut subargs).add_argument( + "arguments", + argparse::List, + "The arguments for the command", + ); + parser.stop_on_first_argument(true); + + let mut stdout_buf = BufWriter::new(ctx.stdout); + let mut stderr_buf = BufWriter::new(ctx.stderr); + let mut stdio_buf = (&mut stdout_buf, &mut stderr_buf); + let result = parse(&mut stdio_buf, parser, args); + + if version { + println!(ctx, "{} {}", crate::NITROCLI, env!("CARGO_PKG_VERSION"))?; + Ok(()) + } else { + stdout_buf.flush()?; + stderr_buf.flush()?; + + result?; + subargs.insert(0, format!("{} {}", crate::NITROCLI, command)); + + let mut ctx = ExecCtx { + 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, + }; + command.execute(&mut ctx, subargs) + } +} diff --git a/src/commands.rs b/src/commands.rs new file mode 100644 index 0000000..537a2cf --- /dev/null +++ b/src/commands.rs @@ -0,0 +1,984 @@ +// 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 . * +// ************************************************************************* + +use std::fmt; +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::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 args::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(ctx: &mut args::ExecCtx<'_>, op: F) -> Result<()> +where + F: FnOnce(&mut args::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(ctx: &mut args::ExecCtx<'_>, op: F) -> Result<()> +where + F: FnOnce(&mut args::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(ctx: &mut args::ExecCtx<'_>, mut op: F) -> Result<()> +where + F: FnMut(&mut args::ExecCtx<'_>, nitrokey::PasswordSafe<'_, '_>) -> Result<()>, +{ + with_device(ctx, |ctx, mut device| { + let pin_entry = pinentry::PinEntry::from(pinentry::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 args::ExecCtx<'_>, + device: D, + pin_type: pinentry::PinType, + msg: &'static str, + op: F, +) -> Result +where + D: Device<'mgr>, + F: FnMut(&mut args::ExecCtx<'_>, D, &str) -> result::Result, +{ + 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 args::ExecCtx<'_>, + device: T, +) -> Result> +where + T: Device<'mgr>, +{ + authenticate( + ctx, + device, + pinentry::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 args::ExecCtx<'_>, + device: T, +) -> Result> +where + T: Device<'mgr>, +{ + authenticate( + ctx, + device, + pinentry::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( + ctx: &mut args::ExecCtx<'_>, + pin_entry: &pinentry::PinEntry, + msg: &'static str, + data: D, + mut op: F, +) -> Result +where + F: FnMut(&mut args::ExecCtx<'_>, D, &str) -> result::Result, + E: error::TryInto, +{ + 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( + ctx: &mut args::ExecCtx<'_>, + pin_entry: &pinentry::PinEntry, + msg: &'static str, + data: D, + mut op: F, +) -> Result +where + F: FnMut(&mut args::ExecCtx<'_>, D, &str) -> result::Result, + E: Into + error::TryInto, +{ + 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. + pinentry::PinType::Admin => ctx.admin_pin.clone(), + pinentry::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( + ctx: &mut args::ExecCtx<'_>, + pin_entry: &pinentry::PinEntry, + msg: &'static str, + mut op: F, +) -> Result<()> +where + F: FnMut(&str) -> result::Result<(), E>, + E: Into + error::TryInto, +{ + 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 args::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 args::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: 0x{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_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 args::ExecCtx<'_>) -> Result<()> { + with_device(ctx, |ctx, device| { + let model = match device { + nitrokey::DeviceWrapper::Pro(_) => "Pro", + nitrokey::DeviceWrapper::Storage(_) => "Storage", + }; + print_status(ctx, model, &device) + }) +} + +/// Perform a factory reset. +pub fn reset(ctx: &mut args::ExecCtx<'_>) -> Result<()> { + with_device(ctx, |ctx, mut device| { + let pin_entry = pinentry::PinEntry::from(pinentry::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 args::ExecCtx<'_>, + mode: args::UnencryptedVolumeMode, +) -> Result<()> { + with_storage_device(ctx, |ctx, mut device| { + let pin_entry = pinentry::PinEntry::from(pinentry::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 args::ExecCtx<'_>) -> Result<()> { + with_storage_device(ctx, |ctx, mut device| { + let pin_entry = pinentry::PinEntry::from(pinentry::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 args::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 args::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 args::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 args::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(option: Option) -> String { + match option { + Some(value) => format!("{}", value), + None => "not set".to_string(), + } +} + +/// Read the Nitrokey configuration. +pub fn config_get(ctx: &mut args::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 args::ExecCtx<'_>, + numlock: args::ConfigOption, + capslock: args::ConfigOption, + scrollock: args::ConfigOption, + user_password: Option, +) -> Result<()> { + 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: user_password.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 args::ExecCtx<'_>) -> Result<()> { + with_device(ctx, |_ctx, mut device| { + device + .lock() + .map_err(|err| get_error("Could not lock the device", err)) + }) +} + +fn get_otp(slot: u8, algorithm: args::OtpAlgorithm, device: &mut T) -> Result +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 { + 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 args::ExecCtx<'_>, + slot: u8, + algorithm: args::OtpAlgorithm, + time: Option, +) -> 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::>() + .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 { + 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 { + 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 args::ExecCtx<'_>, + mut data: nitrokey::OtpSlotData, + algorithm: args::OtpAlgorithm, + counter: u64, + time_window: u16, + secret_format: args::OtpSecretFormat, +) -> Result<()> { + with_device(ctx, |ctx, device| { + let secret = match secret_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 algorithm { + args::OtpAlgorithm::Hotp => device.write_hotp_slot(data, counter), + args::OtpAlgorithm::Totp => device.write_totp_slot(data, time_window), + } + .map_err(|err| get_error("Could not write OTP slot", err))?; + Ok(()) + }) +} + +/// Clear an OTP slot. +pub fn otp_clear( + ctx: &mut args::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 args::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 args::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 args::ExecCtx<'_>) -> Result<()> { + with_device(ctx, |_ctx, device| { + pinentry::clear(&pinentry::PinEntry::from( + pinentry::PinType::Admin, + &device, + )?)?; + pinentry::clear(&pinentry::PinEntry::from(pinentry::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 args::ExecCtx<'_>, + pin_entry: &pinentry::PinEntry, + new: bool, +) -> Result { + let new_pin = match pin_entry.pin_type() { + pinentry::PinType::Admin => { + if new { + &ctx.new_admin_pin + } else { + &ctx.admin_pin + } + } + pinentry::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 args::ExecCtx<'_>, pin_type: pinentry::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 { + pinentry::PinType::Admin => device.change_admin_pin(¤t_pin, &new_pin), + pinentry::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 args::ExecCtx<'_>) -> Result<()> { + with_device(ctx, |ctx, mut device| { + let pin_entry = pinentry::PinEntry::from(pinentry::PinType::User, &device)?; + let user_pin = choose_pin(ctx, &pin_entry, false)?; + let pin_entry = pinentry::PinEntry::from(pinentry::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 args::ExecCtx<'_>, + description: &'static str, + result: result::Result, + 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 args::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 args::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 args::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 args::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 args::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..819bed8 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,104 @@ +// error.rs + +// ************************************************************************* +// * Copyright (C) 2017-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 . * +// ************************************************************************* + +use std::fmt; +use std::io; +use std::str; +use std::string; + +/// 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 { + fn try_into(self) -> Result; +} + +impl TryInto for T +where + T: Into, +{ + fn try_into(self) -> Result { + Ok(self.into()) + } +} + +#[derive(Debug)] +pub enum Error { + ArgparseError(i32), + IoError(io::Error), + NitrokeyError(Option<&'static str>, nitrokey::Error), + Utf8Error(str::Utf8Error), + Error(String), +} + +impl TryInto for Error { + fn try_into(self) -> Result { + 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 for Error { + fn from(e: nitrokey::Error) -> Error { + Error::NitrokeyError(None, e) + } +} + +impl From for Error { + fn from(e: io::Error) -> Error { + Error::IoError(e) + } +} + +impl From for Error { + fn from(e: str::Utf8Error) -> Error { + Error::Utf8Error(e) + } +} + +impl From 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::ArgparseError(_) => write!(f, "Could not parse arguments"), + 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..c639f14 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,167 @@ +// 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 . * +// ************************************************************************* + +#![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, + plugin_as_library, + 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 = result::Result; + +const NITROCLI: &str = "nitrocli"; +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"; + +/// 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, + /// The user PIN, if provided through an environment variable. + pub user_pin: Option, + /// 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, + /// 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, + /// A password used by some commands, if provided through an environment variable. + pub password: Option, + /// 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) -> i32 { + match args::handle_arguments(ctx, args) { + Ok(()) => 0, + Err(err) => match err { + Error::ArgparseError(err) => match err { + // argparse printed the help message + 0 => 0, + // argparse printed an error message + _ => 1, + }, + _ => { + 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::>(); + 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..fd47657 --- /dev/null +++ b/src/pinentry.rs @@ -0,0 +1,404 @@ +// 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 . * +// ************************************************************************* + +use std::borrow; +use std::fmt; +use std::io; +use std::process; +use std::str; + +use crate::args; +use crate::error::Error; + +type CowStr = borrow::Cow<'static, str>; + +/// PIN type requested from pinentry. +/// +/// The available PIN types correspond to the PIN types used by the Nitrokey devices: user and +/// admin. +#[allow(unused_doc_comments)] +Enum! {PinType, [ + Admin => "admin", + User => "user", +]} + +/// 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; + /// 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: PinType, + model: nitrokey::Model, + serial: String, +} + +impl PinEntry { + pub fn from<'mgr, D>(pin_type: PinType, device: &D) -> crate::Result + 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) -> PinType { + self.pin_type + } +} + +impl SecretEntry for PinEntry { + fn cache_id(&self) -> Option { + let model = self.model.to_string().to_lowercase(); + let suffix = format!("{}:{}", model, self.serial); + let cache_id = match self.pin_type { + PinType::Admin => format!("nitrocli:admin:{}", suffix), + PinType::User => format!("nitrocli:user:{}", suffix), + }; + Some(cache_id.into()) + } + + fn prompt(&self) -> CowStr { + match self.pin_type { + PinType::Admin => "Admin PIN", + PinType::User => "User PIN", + } + .into() + } + + fn description(&self, mode: Mode) -> CowStr { + format!( + "{} for\rNitrokey {} {}", + match self.pin_type { + 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", + }, + 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 { + PinType::Admin => 8, + PinType::User => 6, + } + } +} + +#[derive(Debug)] +pub struct PwdEntry { + model: nitrokey::Model, + serial: String, +} + +impl PwdEntry { + pub fn from<'mgr, D>(device: &D) -> crate::Result + 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 { + 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(response: R) -> crate::Result +where + R: AsRef, +{ + 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 + 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( + ctx: &mut args::ExecCtx<'_>, + entry: &E, + mode: Mode, + error_msg: Option<&str>, +) -> crate::Result +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(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(ctx: &mut args::ExecCtx<'_>, entry: &E) -> crate::Result +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(response: R) -> crate::Result<()> +where + R: AsRef, +{ + let string = response.as_ref(); + let lines = string.lines().collect::>(); + + 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(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 . * +// ************************************************************************* + +// 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..ea3a0e8 --- /dev/null +++ b/src/tests/config.rs @@ -0,0 +1,66 @@ +// config.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 . * +// ************************************************************************* + +use super::*; + +#[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"]); + assert_eq!( + res.unwrap_str_err(), + "--numlock and --no-numlock are mutually exclusive" + ); +} + +#[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..75b84c3 --- /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 . * +// ************************************************************************* + +use super::*; + +#[test_device(storage)] +fn status_open_close(model: nitrokey::Model) -> crate::Result<()> { + fn make_re(open: Option) -> 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_status()?.encrypted_volume.active); + assert!(!device.get_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_status()?.encrypted_volume.active); + assert!(!device.get_status()?.hidden_volume.active); + } + + Ok(()) +} diff --git a/src/tests/hidden.rs b/src/tests/hidden.rs new file mode 100644 index 0000000..28a5d23 --- /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 . * +// ************************************************************************* + +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_status()?.encrypted_volume.active); + assert!(device.get_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_status()?.encrypted_volume.active); + assert!(!device.get_status()?.hidden_volume.active); + } + + Ok(()) +} diff --git a/src/tests/lock.rs b/src/tests/lock.rs new file mode 100644 index 0000000..5140152 --- /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 . * +// ************************************************************************* + +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_status()?.encrypted_volume.active); + + Ok(()) +} diff --git a/src/tests/mod.rs b/src/tests/mod.rs new file mode 100644 index 0000000..5ebf285 --- /dev/null +++ b/src/tests/mod.rs @@ -0,0 +1,180 @@ +// 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 . * +// ************************************************************************* + +use std::ffi; +use std::fmt; + +use nitrokey_test::test as test_device; + +mod config; +mod encrypted; +mod hidden; +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 UnwrapError for crate::Result +where + T: fmt::Debug, +{ + fn unwrap_str_err(self) -> String { + match self.unwrap_err() { + 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, + admin_pin: Option, + user_pin: Option, + new_admin_pin: Option, + new_user_pin: Option, + password: Option, +} + +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(model: M) -> Self + where + M: Into, + { + 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) { + self.admin_pin = Some(pin.into()) + } + + pub fn new_admin_pin(&mut self, pin: impl Into) { + self.new_admin_pin = Some(pin.into()) + } + + pub fn user_pin(&mut self, pin: impl Into) { + self.user_pin = Some(pin.into()) + } + + pub fn new_user_pin(&mut self, pin: impl Into) { + 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(&mut self, args: &[&str], f: F) -> (R, Vec, Vec) + where + F: FnOnce(&mut crate::RunCtx<'_>, Vec) -> 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, Vec) { + 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 { + let (res, out, _) = self.do_run(args, |c, a| crate::args::handle_arguments(c, a)); + res.map(|_| String::from_utf8_lossy(&out).into_owned()) + } + + pub fn model(&self) -> Option { + self.model + } +} diff --git a/src/tests/otp.rs b/src/tests/otp.rs new file mode 100644 index 0000000..0ccecf9 --- /dev/null +++ b/src/tests/otp.rs @@ -0,0 +1,130 @@ +// otp.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 . * +// ************************************************************************* + +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 . * +// ************************************************************************* + +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 . * +// ************************************************************************* + +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 . * +// ************************************************************************* + +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..c59c660 --- /dev/null +++ b/src/tests/run.rs @@ -0,0 +1,103 @@ +// run.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 . * +// ************************************************************************* + +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("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 expected = format!("Usage:\n nitrocli {}", args.join(" ")); + assert!(s.starts_with(&expected), 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] +fn version_option() { + 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 . * +// ************************************************************************* + +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..547dcaf --- /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 . * +// ************************************************************************* + +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_status()?.unencrypted_volume.active); + assert!(!device.get_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_status()?.unencrypted_volume.active); + assert!(device.get_status()?.unencrypted_volume.read_only); + } + + Ok(()) +} -- cgit v1.2.1