aboutsummaryrefslogtreecommitdiff
path: root/nitrocli/src
diff options
context:
space:
mode:
Diffstat (limited to 'nitrocli/src')
-rw-r--r--nitrocli/src/arg_util.rs158
-rw-r--r--nitrocli/src/args.rs951
-rw-r--r--nitrocli/src/commands.rs909
-rw-r--r--nitrocli/src/error.rs79
-rw-r--r--nitrocli/src/main.rs177
-rw-r--r--nitrocli/src/pinentry.rs404
-rw-r--r--nitrocli/src/redefine.rs38
-rw-r--r--nitrocli/src/tests/config.rs66
-rw-r--r--nitrocli/src/tests/encrypted.rs90
-rw-r--r--nitrocli/src/tests/hidden.rs44
-rw-r--r--nitrocli/src/tests/lock.rs43
-rw-r--r--nitrocli/src/tests/mod.rs182
-rw-r--r--nitrocli/src/tests/otp.rs114
-rw-r--r--nitrocli/src/tests/pin.rs64
-rw-r--r--nitrocli/src/tests/pws.rs123
-rw-r--r--nitrocli/src/tests/reset.rs54
-rw-r--r--nitrocli/src/tests/run.rs66
-rw-r--r--nitrocli/src/tests/status.rs81
-rw-r--r--nitrocli/src/tests/unencrypted.rs41
19 files changed, 0 insertions, 3684 deletions
diff --git a/nitrocli/src/arg_util.rs b/nitrocli/src/arg_util.rs
deleted file mode 100644
index e2e7b1d..0000000
--- a/nitrocli/src/arg_util.rs
+++ /dev/null
@@ -1,158 +0,0 @@
-// 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 <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-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<str> for $name {
- fn as_ref(&self) -> &'static str {
- match *self {
- $(
- $name::$var => $str,
- )*
- }
- }
- }
-
- impl ::std::fmt::Display for $name {
- fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
- write!(f, "{}", self.as_ref())
- }
- }
-
- impl ::std::str::FromStr for $name {
- type Err = ();
-
- fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
- 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/nitrocli/src/args.rs b/nitrocli/src/args.rs
deleted file mode 100644
index ae09c07..0000000
--- a/nitrocli/src/args.rs
+++ /dev/null
@@ -1,951 +0,0 @@
-// 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 <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-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<T> = result::Result<T, Error>;
-
-/// 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<u8>,
- 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<usize> {
- 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<W> Stdio for (&mut W, &mut W)
-where
- W: io::Write,
-{
- fn stdio(&mut self) -> (&mut dyn io::Write, &mut dyn io::Write) {
- (self.0, self.1)
- }
-}
-
-/// A command execution context that captures additional data pertaining
-/// the command execution.
-pub struct ExecCtx<'io> {
- pub model: Option<DeviceModel>,
- pub stdout: &'io mut dyn io::Write,
- pub stderr: &'io mut dyn io::Write,
- pub admin_pin: Option<ffi::OsString>,
- pub user_pin: Option<ffi::OsString>,
- pub new_admin_pin: Option<ffi::OsString>,
- pub new_user_pin: Option<ffi::OsString>,
- pub password: Option<ffi::OsString>,
- 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 From<DeviceModel> 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<T> {
- Enable(T),
- Disable,
- Ignore,
-}
-
-impl<T> ConfigOption<T> {
- fn try_from(disable: bool, value: Option<T>, name: &'static str) -> Result<Self> {
- 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<T>) -> Option<T> {
- 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<OtpMode> for nitrokey::OtpMode {
- fn from(mode: OtpMode) -> Self {
- match mode {
- OtpMode::SixDigits => nitrokey::OtpMode::SixDigits,
- OtpMode::EightDigits => nitrokey::OtpMode::EightDigits,
- }
- }
-}
-
-Enum! {OtpSecretFormat, [
- Ascii => "ascii",
- Base32 => "base32",
- Hex => "hex",
-]}
-
-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<String>,
-) -> 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<String>) -> 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<String>) -> 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<String>) -> 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!("nitrocli {}", subcommand));
- subcommand.execute(ctx, subargs)
-}
-
-/// Change the configuration of the unencrypted volume.
-fn unencrypted_set(ctx: &mut ExecCtx<'_>, args: Vec<String>) -> 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<String>) -> 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!("nitrocli {}", subcommand));
- subcommand.execute(ctx, subargs)
-}
-
-/// Open the encrypted volume on the Nitrokey.
-fn encrypted_open(ctx: &mut ExecCtx<'_>, args: Vec<String>) -> 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<String>) -> 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<String>) -> 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!("nitrocli {} {}", Command::Hidden, subcommand));
- subcommand.execute(ctx, subargs)
-}
-
-fn hidden_create(ctx: &mut ExecCtx<'_>, args: Vec<String>) -> 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<String>) -> 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<String>) -> 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<String>) -> 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!("nitrocli {} {}", Command::Config, subcommand));
- subcommand.execute(ctx, subargs)
-}
-
-/// Read the Nitrokey configuration.
-fn config_get(ctx: &mut ExecCtx<'_>, args: Vec<String>) -> 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<String>) -> 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<String>) -> 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<String>) -> 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!("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<String>) -> 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<u64> = 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<String>) -> 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: Option<OtpSecretFormat> = None;
- let fmt_help = format!(
- "The format of the secret ({})",
- fmt_enum!(OtpSecretFormat::all_variants())
- );
- 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::StoreOption,
- &fmt_help,
- );
- parse(ctx, parser, args)?;
-
- let secret_format = secret_format.unwrap_or(OtpSecretFormat::Hex);
-
- 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<String>) -> 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<String>) -> 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<String>) -> 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!("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<String>) -> 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<String>) -> 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<String>) -> 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<String>) -> 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!("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<String>) -> 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<String>) -> 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<String>) -> 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<String>) -> 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<String>) -> Result<()> {
- use std::io::Write;
-
- let mut version = false;
- let mut model: Option<DeviceModel> = 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::<u64>(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, "nitrocli {}", env!("CARGO_PKG_VERSION"))?;
- Ok(())
- } else {
- stdout_buf.flush()?;
- stderr_buf.flush()?;
-
- result?;
- subargs.insert(0, format!("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/nitrocli/src/commands.rs b/nitrocli/src/commands.rs
deleted file mode 100644
index 8db5cd8..0000000
--- a/nitrocli/src/commands.rs
+++ /dev/null
@@ -1,909 +0,0 @@
-// commands.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 <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-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 crate::args;
-use crate::error::Error;
-use crate::pinentry;
-use crate::Result;
-
-const NITROKEY_DEFAULT_ADMIN_PIN: &str = "12345678";
-
-/// Create an `error::Error` with an error message of the format `msg: err`.
-fn get_error(msg: &'static str, err: nitrokey::CommandError) -> Error {
- Error::CommandError(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 return it.
-fn get_device(ctx: &mut args::ExecCtx<'_>) -> Result<nitrokey::DeviceWrapper> {
- set_log_level(ctx);
-
- match ctx.model {
- Some(model) => nitrokey::connect_model(model.into()),
- None => nitrokey::connect(),
- }
- .map_err(|_| Error::from("Nitrokey device not found"))
-}
-
-/// Connect to a Nitrokey Storage device and return it.
-fn get_storage_device(ctx: &mut args::ExecCtx<'_>) -> Result<nitrokey::Storage> {
- 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",
- ));
- }
- }
-
- nitrokey::Storage::connect().or_else(|_| Err(Error::from("Nitrokey Storage device not found")))
-}
-
-/// Open the password safe on the given device.
-fn get_password_safe<'dev, D>(
- ctx: &mut args::ExecCtx<'_>,
- device: &'dev D,
-) -> Result<nitrokey::PasswordSafe<'dev>>
-where
- D: 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",
- (),
- |_, pin| device.get_password_safe(pin).map_err(|err| ((), err)),
- )
-}
-
-/// Authenticate the given device using the given PIN type and operation.
-///
-/// If an error occurs, the error message `msg` is used.
-fn authenticate<D, A, F>(
- ctx: &mut args::ExecCtx<'_>,
- device: D,
- pin_type: pinentry::PinType,
- msg: &'static str,
- op: F,
-) -> Result<A>
-where
- D: Device,
- F: Fn(D, &str) -> result::Result<A, (D, nitrokey::CommandError)>,
-{
- 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<T>(ctx: &mut args::ExecCtx<'_>, device: T) -> Result<nitrokey::User<T>>
-where
- T: Device,
-{
- authenticate(
- ctx,
- device,
- pinentry::PinType::User,
- "Could not authenticate as user",
- |device, pin| device.authenticate_user(pin),
- )
-}
-
-/// Authenticate the given device with the admin PIN.
-fn authenticate_admin<T>(ctx: &mut args::ExecCtx<'_>, device: T) -> Result<nitrokey::Admin<T>>
-where
- T: Device,
-{
- authenticate(
- ctx,
- device,
- pinentry::PinType::Admin,
- "Could not authenticate as admin",
- |device, pin| device.authenticate_admin(pin),
- )
-}
-
-/// Return a string representation of the given volume status.
-fn get_volume_status(status: &nitrokey::VolumeStatus) -> &'static str {
- if status.active {
- if status.read_only {
- "read-only"
- } else {
- "active"
- }
- } else {
- "inactive"
- }
-}
-
-/// Try to execute the given function with a pin queried using pinentry.
-///
-/// This function will query the pin of the given type from the user
-/// using pinentry. It will then execute the given function. If this
-/// function returns a result, the result will be passed on. If it
-/// returns a `CommandError::WrongPassword`, the user will be asked
-/// again to enter the pin. Otherwise, this function returns an error
-/// containing the given error message. The user will have at most
-/// three tries to get the pin right.
-///
-/// The data argument can be used to pass on data between the tries. At
-/// the first try, this function will call `op` with `data`. At the
-/// second or third try, it will call `op` with the data returned by the
-/// previous call to `op`.
-fn try_with_pin_and_data_with_pinentry<D, F, R>(
- ctx: &mut args::ExecCtx<'_>,
- pin_entry: &pinentry::PinEntry,
- msg: &'static str,
- data: D,
- op: F,
-) -> Result<R>
-where
- F: Fn(D, &str) -> result::Result<R, (D, nitrokey::CommandError)>,
-{
- 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(data, &pin) {
- Ok(result) => return Ok(result),
- Err((new_data, err)) => match err {
- 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)),
- },
- };
- }
-}
-
-/// Try to execute the given function with a PIN.
-fn try_with_pin_and_data<D, F, R>(
- ctx: &mut args::ExecCtx<'_>,
- pin_entry: &pinentry::PinEntry,
- msg: &'static str,
- data: D,
- op: F,
-) -> Result<R>
-where
- F: Fn(D, &str) -> result::Result<R, (D, nitrokey::CommandError)>,
-{
- let pin = match pin_entry.pin_type() {
- pinentry::PinType::Admin => &ctx.admin_pin,
- pinentry::PinType::User => &ctx.user_pin,
- };
-
- 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(data, &pin).map_err(|(_, err)| get_error(msg, err))
- } else {
- try_with_pin_and_data_with_pinentry(ctx, pin_entry, msg, data, op)
- }
-}
-
-/// Try to execute the given function with a pin queried using pinentry.
-///
-/// This function behaves exactly as `try_with_pin_and_data`, but
-/// it refrains from passing any data to it.
-fn try_with_pin<F>(
- ctx: &mut args::ExecCtx<'_>,
- pin_entry: &pinentry::PinEntry,
- msg: &'static str,
- op: F,
-) -> Result<()>
-where
- F: Fn(&str) -> result::Result<(), nitrokey::CommandError>,
-{
- try_with_pin_and_data(ctx, pin_entry, msg, (), |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: {fwv0}.{fwv1}
- user retry count: {urc}
- admin retry count: {arc}"#,
- model = model,
- id = serial_number,
- fwv0 = device.get_major_firmware_version(),
- fwv1 = device.get_minor_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<()> {
- let device = get_device(ctx)?;
- 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<()> {
- let device = get_device(ctx)?;
- 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<()> {
- let device = get_storage_device(ctx)?;
- 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<()> {
- let device = get_storage_device(ctx)?;
- 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<()> {
- // 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() };
-
- get_storage_device(ctx)?
- .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<()> {
- let device = get_storage_device(ctx)?;
- 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<()> {
- let device = get_storage_device(ctx)?;
- 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<()> {
- unsafe { sync() };
-
- get_storage_device(ctx)?
- .disable_hidden_volume()
- .map_err(|err| get_error("Closing hidden volume failed", err))
-}
-
-/// Return a String representation of the given Option.
-fn format_option<T: fmt::Display>(option: Option<T>) -> String {
- match option {
- Some(value) => format!("{}", value),
- None => "not set".to_string(),
- }
-}
-
-/// Read the Nitrokey configuration.
-pub fn config_get(ctx: &mut args::ExecCtx<'_>) -> Result<()> {
- let config = get_device(ctx)?
- .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<u8>,
- capslock: args::ConfigOption<u8>,
- scrollock: args::ConfigOption<u8>,
- user_password: Option<bool>,
-) -> Result<()> {
- let device = get_device(ctx)?;
- let 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<()> {
- get_device(ctx)?
- .lock()
- .map_err(|err| get_error("Could not lock the device", err))
-}
-
-fn get_otp<T: GenerateOtp>(slot: u8, algorithm: args::OtpAlgorithm, device: &T) -> Result<String> {
- match algorithm {
- args::OtpAlgorithm::Hotp => device.get_hotp_code(slot),
- args::OtpAlgorithm::Totp => device.get_totp_code(slot),
- }
- .map_err(|err| get_error("Could not generate OTP", err))
-}
-
-fn get_unix_timestamp() -> Result<u64> {
- time::SystemTime::now()
- .duration_since(time::UNIX_EPOCH)
- .or_else(|_| 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<u64>,
-) -> Result<()> {
- let device = get_device(ctx)?;
- 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 user = authenticate_user(ctx, device)?;
- get_otp(slot, algorithm, &user)
- } else {
- get_otp(slot, algorithm, &device)
- }?;
- println!(ctx, "{}", otp)?;
- Ok(())
-}
-
-/// Format a byte vector as a hex string.
-fn format_bytes(bytes: &[u8]) -> String {
- bytes
- .iter()
- .map(|c| format!("{:x}", c))
- .collect::<Vec<_>>()
- .join("")
-}
-
-/// Prepare an ASCII secret string for libnitrokey.
-///
-/// libnitrokey expects secrets as hexadecimal strings. This function transforms an ASCII string
-/// into a hexadecimal string or returns an error if the given string contains non-ASCII
-/// characters.
-fn prepare_ascii_secret(secret: &str) -> Result<String> {
- if secret.is_ascii() {
- Ok(format_bytes(&secret.as_bytes()))
- } else {
- Err(Error::from(
- "The given secret is not an ASCII string despite --format ascii being set",
- ))
- }
-}
-
-/// Prepare a base32 secret string for libnitrokey.
-fn prepare_base32_secret(secret: &str) -> Result<String> {
- base32::decode(base32::Alphabet::RFC4648 { padding: false }, secret)
- .map(|vec| format_bytes(&vec))
- .ok_or_else(|| Error::from("Could not parse base32 secret"))
-}
-
-/// Configure a one-time password slot on the Nitrokey device.
-pub fn otp_set(
- ctx: &mut args::ExecCtx<'_>,
- data: nitrokey::OtpSlotData,
- algorithm: args::OtpAlgorithm,
- counter: u64,
- time_window: u16,
- secret_format: args::OtpSecretFormat,
-) -> Result<()> {
- let secret = match secret_format {
- args::OtpSecretFormat::Ascii => prepare_ascii_secret(&data.secret)?,
- args::OtpSecretFormat::Base32 => prepare_base32_secret(&data.secret)?,
- args::OtpSecretFormat::Hex => data.secret,
- };
- let data = nitrokey::OtpSlotData { secret, ..data };
- let device = get_device(ctx)?;
- let 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<()> {
- let device = get_device(ctx)?;
- let 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::CommandError::InvalidSlot) => return Ok(()),
- Err(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<()> {
- let device = get_device(ctx)?;
- 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<()> {
- let device = get_device(ctx)?;
-
- 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<String> {
- 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<()> {
- let device = get_device(ctx)?;
- 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(&current_pin, &new_pin),
- pinentry::PinType::User => device.change_user_pin(&current_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<()> {
- let device = get_device(ctx)?;
- 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<String, nitrokey::CommandError>,
- 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::CommandError::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,
- ))
- }
-}
-
-/// 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<()> {
- let device = get_device(ctx)?;
- let pws = get_password_safe(ctx, &device)?;
- 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<()> {
- let device = get_device(ctx)?;
- let pws = get_password_safe(ctx, &device)?;
- 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<()> {
- let device = get_device(ctx)?;
- let pws = get_password_safe(ctx, &device)?;
- 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<()> {
- let device = get_device(ctx)?;
- let pws = get_password_safe(ctx, &device)?;
- 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
- .into_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());
- }
-}
diff --git a/nitrocli/src/error.rs b/nitrocli/src/error.rs
deleted file mode 100644
index 1346526..0000000
--- a/nitrocli/src/error.rs
+++ /dev/null
@@ -1,79 +0,0 @@
-// 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 <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-use std::fmt;
-use std::io;
-use std::str;
-use std::string;
-
-#[derive(Debug)]
-pub enum Error {
- ArgparseError(i32),
- CommandError(Option<&'static str>, nitrokey::CommandError),
- IoError(io::Error),
- Utf8Error(str::Utf8Error),
- Error(String),
-}
-
-impl From<&str> for Error {
- fn from(s: &str) -> Error {
- Error::Error(s.to_string())
- }
-}
-
-impl From<nitrokey::CommandError> for Error {
- fn from(e: nitrokey::CommandError) -> Error {
- Error::CommandError(None, e)
- }
-}
-
-impl From<io::Error> for Error {
- fn from(e: io::Error) -> Error {
- Error::IoError(e)
- }
-}
-
-impl From<str::Utf8Error> for Error {
- fn from(e: str::Utf8Error) -> Error {
- Error::Utf8Error(e)
- }
-}
-
-impl From<string::FromUtf8Error> for Error {
- fn from(e: string::FromUtf8Error) -> Error {
- Error::Utf8Error(e.utf8_error())
- }
-}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match *self {
- Error::ArgparseError(_) => write!(f, "Could not parse arguments"),
- Error::CommandError(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/nitrocli/src/main.rs b/nitrocli/src/main.rs
deleted file mode 100644
index 5cb3faf..0000000
--- a/nitrocli/src/main.rs
+++ /dev/null
@@ -1,177 +0,0 @@
-// main.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 <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-#![deny(
- dead_code,
- 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,
- overflowing_literals,
- path_statements,
- patterns_in_fns_without_body,
- plugin_as_library,
- private_in_public,
- proc_macro_derive_resolution_fallback,
- safe_packed_borrows,
- stable_features,
- trivial_bounds,
- trivial_numeric_casts,
- type_alias_bounds,
- tyvar_behind_raw_pointer,
- unconditional_recursion,
- unions_with_drop_fields,
- 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
-)]
-#![warn(
- bad_style,
- future_incompatible,
- nonstandard_style,
- renamed_and_removed_lints,
- rust_2018_compatibility,
- rust_2018_idioms
-)]
-
-//! 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::alloc;
-use std::env;
-use std::ffi;
-use std::io;
-use std::process;
-use std::result;
-
-use crate::error::Error;
-
-// Switch from the default allocator (typically jemalloc) to the system
-// allocator (malloc based on Unix systems). Our application is by no
-// means allocation intensive and the default allocator is typically
-// much larger in size, causing binary bloat.
-#[global_allocator]
-static A: alloc::System = alloc::System;
-
-type Result<T> = result::Result<T, Error>;
-
-const NITROCLI_ADMIN_PIN: &str = "NITROCLI_ADMIN_PIN";
-const NITROCLI_USER_PIN: &str = "NITROCLI_USER_PIN";
-const NITROCLI_NEW_ADMIN_PIN: &str = "NITROCLI_NEW_ADMIN_PIN";
-const NITROCLI_NEW_USER_PIN: &str = "NITROCLI_NEW_USER_PIN";
-const NITROCLI_PASSWORD: &str = "NITROCLI_PASSWORD";
-const NITROCLI_NO_CACHE: &str = "NITROCLI_NO_CACHE";
-
-/// The context used when running the program.
-pub(crate) struct RunCtx<'io> {
- /// The `Write` object used as standard output throughout the program.
- pub stdout: &'io mut dyn io::Write,
- /// The `Write` object used as standard error throughout the program.
- pub stderr: &'io mut dyn io::Write,
- /// The admin PIN, if provided through an environment variable.
- pub admin_pin: Option<ffi::OsString>,
- /// The user PIN, if provided through an environment variable.
- pub user_pin: Option<ffi::OsString>,
- /// The new admin PIN to set, if provided through an environment variable.
- ///
- /// This variable is only used by commands that change the admin PIN.
- pub new_admin_pin: Option<ffi::OsString>,
- /// The new user PIN, if provided through an environment variable.
- ///
- /// This variable is only used by commands that change the user PIN.
- pub new_user_pin: Option<ffi::OsString>,
- /// A password used by some commands, if provided through an environment variable.
- pub password: Option<ffi::OsString>,
- /// Whether to bypass the cache for all secrets or not.
- pub no_cache: bool,
-}
-
-fn run<'ctx, 'io: 'ctx>(ctx: &'ctx mut RunCtx<'io>, args: Vec<String>) -> i32 {
- match 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::<Vec<_>>();
- let ctx = &mut RunCtx {
- stdout: &mut stdout,
- stderr: &mut stderr,
- admin_pin: env::var_os(NITROCLI_ADMIN_PIN),
- user_pin: env::var_os(NITROCLI_USER_PIN),
- new_admin_pin: env::var_os(NITROCLI_NEW_ADMIN_PIN),
- new_user_pin: env::var_os(NITROCLI_NEW_USER_PIN),
- password: env::var_os(NITROCLI_PASSWORD),
- no_cache: env::var_os(NITROCLI_NO_CACHE).is_some(),
- };
-
- let rc = run(ctx, args);
- // We exit the process the hard way below. The problem is that because
- // of this, buffered IO may not be flushed. So make sure to explicitly
- // flush before exiting. Note that stderr is unbuffered, alleviating
- // the need for any flushing there.
- // Ideally we would just make `main` return an i32 and let Rust deal
- // with all of this, but the `process::Termination` functionality is
- // still unstable and we have no way to convince the caller to "just
- // exit" without printing additional information.
- let _ = stdout.flush();
- process::exit(rc);
-}
diff --git a/nitrocli/src/pinentry.rs b/nitrocli/src/pinentry.rs
deleted file mode 100644
index 0733cd1..0000000
--- a/nitrocli/src/pinentry.rs
+++ /dev/null
@@ -1,404 +0,0 @@
-// pinentry.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 <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-use std::borrow;
-use std::fmt;
-use std::io;
-use std::process;
-use std::str;
-
-use crate::args;
-use crate::error::Error;
-
-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<CowStr>;
- /// The prompt to display when asking for the secret.
- fn prompt(&self) -> CowStr;
- /// The description to display when asking for the secret.
- fn description(&self, mode: Mode) -> CowStr;
- /// The minimum number of characters the secret needs to have.
- fn min_len(&self) -> u8;
-}
-
-#[derive(Debug)]
-pub struct PinEntry {
- pin_type: PinType,
- model: nitrokey::Model,
- serial: String,
-}
-
-impl PinEntry {
- pub fn from<D>(pin_type: PinType, device: &D) -> crate::Result<Self>
- where
- D: nitrokey::Device,
- {
- 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<CowStr> {
- 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<D>(device: &D) -> crate::Result<Self>
- where
- D: nitrokey::Device,
- {
- let model = device.get_model();
- let serial = device.get_serial_number()?;
- Ok(Self { model, serial })
- }
-}
-
-impl SecretEntry for PwdEntry {
- fn cache_id(&self) -> Option<CowStr> {
- None
- }
-
- fn prompt(&self) -> CowStr {
- "Password".into()
- }
-
- fn description(&self, mode: Mode) -> CowStr {
- format!(
- "{} for\rNitrokey {} {}",
- match mode {
- Mode::Choose => "Please enter a new hidden volume password",
- Mode::Confirm => "Please confirm the new hidden volume password",
- Mode::Query => "Please enter a hidden volume password",
- },
- self.model,
- self.serial,
- )
- .into()
- }
-
- fn min_len(&self) -> u8 {
- // More or less arbitrary minimum length based on the fact that the
- // manual mentions six letter passwords in examples. Users
- // *probably* should go longer than that, but we don't want to be
- // too opinionated.
- 6
- }
-}
-
-/// Secret entry mode for pinentry.
-///
-/// This enum describes the context of the pinentry query, for example
-/// prompting for the current secret or requesting a new one. The mode
-/// may affect the pinentry description and whether a quality bar is
-/// shown.
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub enum Mode {
- /// Let the user choose a new secret.
- Choose,
- /// Let the user confirm the previously chosen secret.
- Confirm,
- /// Query an existing secret.
- Query,
-}
-
-impl Mode {
- fn show_quality_bar(self) -> bool {
- self == Mode::Choose
- }
-}
-
-fn parse_pinentry_pin<R>(response: R) -> crate::Result<String>
-where
- R: AsRef<str>,
-{
- let string = response.as_ref();
- let lines: Vec<&str> = string.lines().collect();
-
- // We expect the response to be of the form:
- // > D passphrase
- // > OK
- // or potentially:
- // > ERR 83886179 Operation cancelled <Pinentry>
- if lines.len() == 2 && lines[1] == "OK" && lines[0].starts_with("D ") {
- // We got the only valid answer we accept.
- let (_, pass) = lines[0].split_at(2);
- return Ok(pass.to_string());
- }
-
- // Check if we are dealing with a special "ERR " line and report that
- // specially.
- if !lines.is_empty() && lines[0].starts_with("ERR ") {
- let (_, error) = lines[0].split_at(4);
- return Err(Error::from(error));
- }
- Err(Error::Error(format!("Unexpected response: {}", string)))
-}
-
-/// Inquire a secret from the user.
-///
-/// This function inquires a secret from the user or returns a cached
-/// entry, if available (and if caching is not disabled for the given
-/// execution context). If an error message is set, it is displayed in
-/// the entry dialog. The mode describes the context of the pinentry
-/// dialog. It is used to choose an appropriate description and to
-/// decide whether a quality bar is shown in the dialog.
-pub fn inquire<E>(
- ctx: &mut args::ExecCtx<'_>,
- entry: &E,
- mode: Mode,
- error_msg: Option<&str>,
-) -> crate::Result<String>
-where
- E: SecretEntry,
-{
- let cache_id = entry
- .cache_id()
- .and_then(|id| if ctx.no_cache { None } else { Some(id) })
- // "X" is a sentinel value indicating that no caching is desired.
- .unwrap_or_else(|| "X".into())
- .into();
-
- let error_msg = error_msg
- .map(|msg| msg.replace(" ", "+"))
- .unwrap_or_else(|| String::from("+"));
- let prompt = entry.prompt().replace(" ", "+");
- let description = entry.description(mode).replace(" ", "+");
-
- let args = vec![cache_id, error_msg, prompt, description].join(" ");
- let mut command = "GET_PASSPHRASE --data ".to_string();
- if mode.show_quality_bar() {
- command += "--qualitybar ";
- }
- command += &args;
- // An error reported for the GET_PASSPHRASE command does not actually
- // cause gpg-connect-agent to exit with a non-zero error code, we have
- // to evaluate the output to determine success/failure.
- let output = process::Command::new("gpg-connect-agent")
- .arg(command)
- .arg("/bye")
- .output()
- .map_err(|err| match err.kind() {
- io::ErrorKind::NotFound => {
- io::Error::new(io::ErrorKind::NotFound, "gpg-connect-agent not found")
- }
- _ => err,
- })?;
- parse_pinentry_pin(str::from_utf8(&output.stdout)?)
-}
-
-fn check<E>(entry: &E, secret: &str) -> crate::Result<()>
-where
- E: SecretEntry,
-{
- if secret.len() < usize::from(entry.min_len()) {
- Err(Error::Error(format!(
- "The secret must be at least {} characters long",
- entry.min_len()
- )))
- } else {
- Ok(())
- }
-}
-
-pub fn choose<E>(ctx: &mut args::ExecCtx<'_>, entry: &E) -> crate::Result<String>
-where
- E: SecretEntry,
-{
- clear(entry)?;
- let chosen = inquire(ctx, entry, Mode::Choose, None)?;
- clear(entry)?;
- check(entry, &chosen)?;
-
- let confirmed = inquire(ctx, entry, Mode::Confirm, None)?;
- clear(entry)?;
-
- if chosen != confirmed {
- Err(Error::from("Entered secrets do not match"))
- } else {
- Ok(chosen)
- }
-}
-
-fn parse_pinentry_response<R>(response: R) -> crate::Result<()>
-where
- R: AsRef<str>,
-{
- let string = response.as_ref();
- let lines = string.lines().collect::<Vec<_>>();
-
- if lines.len() == 1 && lines[0] == "OK" {
- // We got the only valid answer we accept.
- return Ok(());
- }
- Err(Error::Error(format!("Unexpected response: {}", string)))
-}
-
-/// Clear the cached secret represented by the given entry.
-pub fn clear<E>(entry: &E) -> crate::Result<()>
-where
- E: SecretEntry,
-{
- if let Some(cache_id) = entry.cache_id() {
- let command = format!("CLEAR_PASSPHRASE {}", cache_id);
- let output = process::Command::new("gpg-connect-agent")
- .arg(command)
- .arg("/bye")
- .output()?;
-
- parse_pinentry_response(str::from_utf8(&output.stdout)?)
- } else {
- Ok(())
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn parse_pinentry_pin_good() {
- let response = "D passphrase\nOK\n";
- let expected = "passphrase";
-
- assert_eq!(parse_pinentry_pin(response).unwrap(), expected)
- }
-
- #[test]
- fn parse_pinentry_pin_error() {
- let error = "83886179 Operation cancelled";
- let response = "ERR ".to_string() + error + "\n";
- let expected = error;
-
- let error = parse_pinentry_pin(response.to_string());
-
- 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/nitrocli/src/redefine.rs b/nitrocli/src/redefine.rs
deleted file mode 100644
index a79cb4b..0000000
--- a/nitrocli/src/redefine.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-// redefine.rs
-
-// *************************************************************************
-// * Copyright (C) 2019 Daniel Mueller (deso@posteo.net) *
-// * *
-// * This program is free software: you can redistribute it and/or modify *
-// * it under the terms of the GNU General Public License as published by *
-// * the Free Software Foundation, either version 3 of the License, or *
-// * (at your option) any later version. *
-// * *
-// * This program is distributed in the hope that it will be useful, *
-// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
-// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
-// * GNU General Public License for more details. *
-// * *
-// * You should have received a copy of the GNU General Public License *
-// * along with this program. If not, see <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-// A replacement of the standard println!() macro that requires an
-// execution context as the first argument and prints to its stdout.
-macro_rules! println {
- ($ctx:expr) => {
- writeln!($ctx.stdout, "")
- };
- ($ctx:expr, $($arg:tt)*) => {
- writeln!($ctx.stdout, $($arg)*)
- };
-}
-
-macro_rules! eprintln {
- ($ctx:expr) => {
- writeln!($ctx.stderr, "")
- };
- ($ctx:expr, $($arg:tt)*) => {
- writeln!($ctx.stderr, $($arg)*)
- };
-}
diff --git a/nitrocli/src/tests/config.rs b/nitrocli/src/tests/config.rs
deleted file mode 100644
index 8983cb8..0000000
--- a/nitrocli/src/tests/config.rs
+++ /dev/null
@@ -1,66 +0,0 @@
-// 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 <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-use super::*;
-
-#[test_device]
-fn get(device: nitrokey::DeviceWrapper) -> 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_dev(device).handle(&["config", "get"])?;
- assert!(re.is_match(&out), out);
- Ok(())
-}
-
-#[test_device]
-fn set_wrong_usage(device: nitrokey::DeviceWrapper) {
- let res = Nitrocli::with_dev(device).handle(&["config", "set", "--numlock", "2", "-N"]);
- assert_eq!(
- res.unwrap_str_err(),
- "--numlock and --no-numlock are mutually exclusive"
- );
-}
-
-#[test_device]
-fn set_get(device: nitrokey::DeviceWrapper) -> crate::Result<()> {
- let mut ncli = Nitrocli::with_dev(device);
- 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/nitrocli/src/tests/encrypted.rs b/nitrocli/src/tests/encrypted.rs
deleted file mode 100644
index 8aef864..0000000
--- a/nitrocli/src/tests/encrypted.rs
+++ /dev/null
@@ -1,90 +0,0 @@
-// encrypted.rs
-
-// *************************************************************************
-// * Copyright (C) 2019 Daniel Mueller (deso@posteo.net) *
-// * *
-// * This program is free software: you can redistribute it and/or modify *
-// * it under the terms of the GNU General Public License as published by *
-// * the Free Software Foundation, either version 3 of the License, or *
-// * (at your option) any later version. *
-// * *
-// * This program is distributed in the hope that it will be useful, *
-// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
-// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
-// * GNU General Public License for more details. *
-// * *
-// * You should have received a copy of the GNU General Public License *
-// * along with this program. If not, see <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-use super::*;
-
-#[test_device]
-fn status_open_close(device: nitrokey::Storage) -> crate::Result<()> {
- fn make_re(open: Option<bool>) -> regex::Regex {
- let encrypted = match open {
- Some(open) => {
- if open {
- "active"
- } else {
- "(read-only|inactive)"
- }
- }
- None => "(read-only|active|inactive)",
- };
- let re = format!(
- r#"
- volumes:
- unencrypted: (read-only|active|inactive)
- encrypted: {}
- hidden: (read-only|active|inactive)
-$"#,
- encrypted
- );
- regex::Regex::new(&re).unwrap()
- }
-
- let mut ncli = Nitrocli::with_dev(device);
- 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]
-fn encrypted_open_on_pro(device: nitrokey::Pro) {
- let res = Nitrocli::with_dev(device).handle(&["encrypted", "open"]);
- assert_eq!(
- res.unwrap_str_err(),
- "This command is only available on the Nitrokey Storage",
- );
-}
-
-#[test_device]
-fn encrypted_open_close(device: nitrokey::Storage) -> crate::Result<()> {
- let mut ncli = Nitrocli::with_dev(device);
- let out = ncli.handle(&["encrypted", "open"])?;
- assert!(out.is_empty());
-
- let device = nitrokey::Storage::connect()?;
- assert!(device.get_status()?.encrypted_volume.active);
- assert!(!device.get_status()?.hidden_volume.active);
- drop(device);
-
- let out = ncli.handle(&["encrypted", "close"])?;
- assert!(out.is_empty());
-
- let device = nitrokey::Storage::connect()?;
- assert!(!device.get_status()?.encrypted_volume.active);
- assert!(!device.get_status()?.hidden_volume.active);
-
- Ok(())
-}
diff --git a/nitrocli/src/tests/hidden.rs b/nitrocli/src/tests/hidden.rs
deleted file mode 100644
index 483a801..0000000
--- a/nitrocli/src/tests/hidden.rs
+++ /dev/null
@@ -1,44 +0,0 @@
-// hidden.rs
-
-// *************************************************************************
-// * Copyright (C) 2019 Daniel Mueller (deso@posteo.net) *
-// * *
-// * This program is free software: you can redistribute it and/or modify *
-// * it under the terms of the GNU General Public License as published by *
-// * the Free Software Foundation, either version 3 of the License, or *
-// * (at your option) any later version. *
-// * *
-// * This program is distributed in the hope that it will be useful, *
-// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
-// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
-// * GNU General Public License for more details. *
-// * *
-// * You should have received a copy of the GNU General Public License *
-// * along with this program. If not, see <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-use super::*;
-
-#[test_device]
-fn hidden_create_open_close(device: nitrokey::Storage) -> crate::Result<()> {
- let mut ncli = Nitrocli::with_dev(device);
- let out = ncli.handle(&["hidden", "create", "0", "50", "100"])?;
- assert!(out.is_empty());
-
- let out = ncli.handle(&["hidden", "open"])?;
- assert!(out.is_empty());
-
- let device = nitrokey::Storage::connect()?;
- assert!(!device.get_status()?.encrypted_volume.active);
- assert!(device.get_status()?.hidden_volume.active);
- drop(device);
-
- let out = ncli.handle(&["hidden", "close"])?;
- assert!(out.is_empty());
-
- let device = nitrokey::Storage::connect()?;
- assert!(!device.get_status()?.encrypted_volume.active);
- assert!(!device.get_status()?.hidden_volume.active);
-
- Ok(())
-}
diff --git a/nitrocli/src/tests/lock.rs b/nitrocli/src/tests/lock.rs
deleted file mode 100644
index d23d2ae..0000000
--- a/nitrocli/src/tests/lock.rs
+++ /dev/null
@@ -1,43 +0,0 @@
-// lock.rs
-
-// *************************************************************************
-// * Copyright (C) 2019 Daniel Mueller (deso@posteo.net) *
-// * *
-// * This program is free software: you can redistribute it and/or modify *
-// * it under the terms of the GNU General Public License as published by *
-// * the Free Software Foundation, either version 3 of the License, or *
-// * (at your option) any later version. *
-// * *
-// * This program is distributed in the hope that it will be useful, *
-// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
-// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
-// * GNU General Public License for more details. *
-// * *
-// * You should have received a copy of the GNU General Public License *
-// * along with this program. If not, see <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-use super::*;
-
-#[test_device]
-fn lock_pro(device: nitrokey::Pro) -> crate::Result<()> {
- // We can't really test much more here than just success of the command.
- let out = Nitrocli::with_dev(device).handle(&["lock"])?;
- assert!(out.is_empty());
-
- Ok(())
-}
-
-#[test_device]
-fn lock_storage(device: nitrokey::Storage) -> crate::Result<()> {
- let mut ncli = Nitrocli::with_dev(device);
- let _ = ncli.handle(&["encrypted", "open"])?;
-
- let out = ncli.handle(&["lock"])?;
- assert!(out.is_empty());
-
- let device = nitrokey::Storage::connect()?;
- assert!(!device.get_status()?.encrypted_volume.active);
-
- Ok(())
-}
diff --git a/nitrocli/src/tests/mod.rs b/nitrocli/src/tests/mod.rs
deleted file mode 100644
index 2f2926f..0000000
--- a/nitrocli/src/tests/mod.rs
+++ /dev/null
@@ -1,182 +0,0 @@
-// mod.rs
-
-// *************************************************************************
-// * Copyright (C) 2019 Daniel Mueller (deso@posteo.net) *
-// * *
-// * This program is free software: you can redistribute it and/or modify *
-// * it under the terms of the GNU General Public License as published by *
-// * the Free Software Foundation, either version 3 of the License, or *
-// * (at your option) any later version. *
-// * *
-// * This program is distributed in the hope that it will be useful, *
-// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
-// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
-// * GNU General Public License for more details. *
-// * *
-// * You should have received a copy of the GNU General Public License *
-// * along with this program. If not, see <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-use std::ffi;
-use std::fmt;
-
-use nitrokey_test::test as test_device;
-
-// TODO: Those defines should potentially be taken from the `nitrokey`
-// crate, once exported.
-const NITROKEY_DEFAULT_ADMIN_PIN: &str = "12345678";
-const NITROKEY_DEFAULT_USER_PIN: &str = "123456";
-
-// TODO: This is a hack to make the nitrokey-test crate work across
-// module boundaries. Upon first use of the nitrokey_test::test
-// macro a new function, __nitrokey_mutex, will be emitted, but it
-// is not visible in a different module. To work around that we
-// trigger the macro here first and then `use super::*` from all
-// of the submodules.
-#[test_device]
-fn dummy() {}
-
-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);
-}
-
-impl<T> UnwrapError for crate::Result<T>
-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::CommandError(ctx, err) => (ctx, err),
- err => panic!("Unexpected error variant found: {:?}", err),
- }
- }
-}
-
-struct Nitrocli {
- model: Option<nitrokey::Model>,
- admin_pin: Option<ffi::OsString>,
- user_pin: Option<ffi::OsString>,
- new_admin_pin: Option<ffi::OsString>,
- new_user_pin: Option<ffi::OsString>,
- password: Option<ffi::OsString>,
-}
-
-impl Nitrocli {
- pub fn new() -> Self {
- Self {
- model: None,
- admin_pin: Some(NITROKEY_DEFAULT_ADMIN_PIN.into()),
- user_pin: Some(NITROKEY_DEFAULT_USER_PIN.into()),
- new_admin_pin: None,
- new_user_pin: None,
- password: None,
- }
- }
-
- pub fn with_dev<D>(device: D) -> Self
- where
- D: nitrokey::Device,
- {
- let result = Self {
- model: Some(device.get_model()),
- 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()),
- };
-
- drop(device);
- result
- }
-
- pub fn admin_pin(&mut self, pin: impl Into<ffi::OsString>) {
- self.admin_pin = Some(pin.into())
- }
-
- pub fn new_admin_pin(&mut self, pin: impl Into<ffi::OsString>) {
- self.new_admin_pin = Some(pin.into())
- }
-
- pub fn user_pin(&mut self, pin: impl Into<ffi::OsString>) {
- self.user_pin = Some(pin.into())
- }
-
- pub fn new_user_pin(&mut self, pin: impl Into<ffi::OsString>) {
- self.new_user_pin = Some(pin.into())
- }
-
- fn model_to_arg(model: nitrokey::Model) -> &'static str {
- match model {
- nitrokey::Model::Pro => "--model=pro",
- nitrokey::Model::Storage => "--model=storage",
- }
- }
-
- fn do_run<F, R>(&mut self, args: &[&'static str], f: F) -> (R, Vec<u8>, Vec<u8>)
- where
- F: FnOnce(&mut crate::RunCtx<'_>, Vec<String>) -> R,
- {
- let args = ["nitrocli"]
- .into_iter()
- .cloned()
- .chain(self.model.map(Self::model_to_arg))
- .chain(args.into_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: &[&'static str]) -> (i32, Vec<u8>, Vec<u8>) {
- self.do_run(args, |c, a| crate::run(c, a))
- }
-
- /// Run `nitrocli`'s `handle_arguments` function.
- pub fn handle(&mut self, args: &[&'static str]) -> crate::Result<String> {
- 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<nitrokey::Model> {
- self.model
- }
-}
diff --git a/nitrocli/src/tests/otp.rs b/nitrocli/src/tests/otp.rs
deleted file mode 100644
index 39ddf29..0000000
--- a/nitrocli/src/tests/otp.rs
+++ /dev/null
@@ -1,114 +0,0 @@
-// 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 <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-use super::*;
-
-#[test_device]
-fn set_invalid_slot_raw(device: nitrokey::DeviceWrapper) {
- let (rc, out, err) = Nitrocli::with_dev(device).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(device: nitrokey::DeviceWrapper) {
- let res = Nitrocli::with_dev(device).handle(&["otp", "set", "100", "name", "1234"]);
-
- assert_eq!(
- res.unwrap_cmd_err(),
- (
- Some("Could not write OTP slot"),
- nitrokey::CommandError::InvalidSlot
- )
- );
-}
-
-#[test_device]
-fn status(device: nitrokey::DeviceWrapper) -> crate::Result<()> {
- let re = regex::Regex::new(
- r#"^alg\tslot\tname
-((totp|hotp)\t\d+\t.+\n)+$"#,
- )
- .unwrap();
-
- let mut ncli = Nitrocli::with_dev(device);
- // 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(device: nitrokey::DeviceWrapper) -> 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_dev(device);
- 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(device: nitrokey::DeviceWrapper) -> 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_dev(device);
- 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 clear(device: nitrokey::DeviceWrapper) -> crate::Result<()> {
- let mut ncli = Nitrocli::with_dev(device);
- 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/nitrocli/src/tests/pin.rs b/nitrocli/src/tests/pin.rs
deleted file mode 100644
index fe61b2d..0000000
--- a/nitrocli/src/tests/pin.rs
+++ /dev/null
@@ -1,64 +0,0 @@
-// pin.rs
-
-// *************************************************************************
-// * Copyright (C) 2019 Daniel Mueller (deso@posteo.net) *
-// * *
-// * This program is free software: you can redistribute it and/or modify *
-// * it under the terms of the GNU General Public License as published by *
-// * the Free Software Foundation, either version 3 of the License, or *
-// * (at your option) any later version. *
-// * *
-// * This program is distributed in the hope that it will be useful, *
-// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
-// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
-// * GNU General Public License for more details. *
-// * *
-// * You should have received a copy of the GNU General Public License *
-// * along with this program. If not, see <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-use nitrokey::Authenticate;
-use nitrokey::Device;
-
-use super::*;
-
-#[test_device]
-fn unblock(device: nitrokey::DeviceWrapper) -> crate::Result<()> {
- let (device, err) = device.authenticate_user("wrong-pin").unwrap_err();
- assert_eq!(err, nitrokey::CommandError::WrongPassword);
- assert!(device.get_user_retry_count() < 3);
-
- let model = device.get_model();
- let _ = Nitrocli::with_dev(device).handle(&["pin", "unblock"])?;
- let device = nitrokey::connect_model(model)?;
- assert_eq!(device.get_user_retry_count(), 3);
- Ok(())
-}
-
-#[test_device]
-fn set_user(device: nitrokey::DeviceWrapper) -> crate::Result<()> {
- let mut ncli = Nitrocli::with_dev(device);
-
- // Set a new user PIN.
- ncli.new_user_pin("new-pin");
- let out = ncli.handle(&["pin", "set", "user"])?;
- assert!(out.is_empty());
-
- let device = nitrokey::connect_model(ncli.model().unwrap())?;
- let (device, err) = device
- .authenticate_user(NITROKEY_DEFAULT_USER_PIN)
- .unwrap_err();
- assert_eq!(err, nitrokey::CommandError::WrongPassword);
- drop(device);
-
- // 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 device = nitrokey::connect_model(ncli.model().unwrap())?;
- let _ = device.authenticate_user(NITROKEY_DEFAULT_USER_PIN).unwrap();
- Ok(())
-}
diff --git a/nitrocli/src/tests/pws.rs b/nitrocli/src/tests/pws.rs
deleted file mode 100644
index 5d0f245..0000000
--- a/nitrocli/src/tests/pws.rs
+++ /dev/null
@@ -1,123 +0,0 @@
-// pws.rs
-
-// *************************************************************************
-// * Copyright (C) 2019 Daniel Mueller (deso@posteo.net) *
-// * *
-// * This program is free software: you can redistribute it and/or modify *
-// * it under the terms of the GNU General Public License as published by *
-// * the Free Software Foundation, either version 3 of the License, or *
-// * (at your option) any later version. *
-// * *
-// * This program is distributed in the hope that it will be useful, *
-// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
-// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
-// * GNU General Public License for more details. *
-// * *
-// * You should have received a copy of the GNU General Public License *
-// * along with this program. If not, see <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-use super::*;
-
-#[test_device]
-fn set_invalid_slot(device: nitrokey::DeviceWrapper) {
- let res = Nitrocli::with_dev(device).handle(&["pws", "set", "100", "name", "login", "1234"]);
-
- assert_eq!(
- res.unwrap_cmd_err(),
- (
- Some("Could not write PWS slot"),
- nitrokey::CommandError::InvalidSlot
- )
- );
-}
-
-#[test_device]
-fn status(device: nitrokey::DeviceWrapper) -> crate::Result<()> {
- let re = regex::Regex::new(
- r#"^slot\tname
-(\d+\t.+\n)+$"#,
- )
- .unwrap();
-
- let mut ncli = Nitrocli::with_dev(device);
- // 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(device: nitrokey::DeviceWrapper) -> crate::Result<()> {
- const NAME: &str = "dropbox";
- const LOGIN: &str = "d-e-s-o";
- const PASSWORD: &str = "my-secret-password";
-
- let mut ncli = Nitrocli::with_dev(device);
- 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(device: nitrokey::DeviceWrapper) -> crate::Result<()> {
- const NAME: &str = "some/svc";
- const LOGIN: &str = "a\\user";
- const PASSWORD: &str = "!@&-)*(&+%^@";
-
- let mut ncli = Nitrocli::with_dev(device);
- 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(device: nitrokey::DeviceWrapper) -> crate::Result<()> {
- let mut ncli = Nitrocli::with_dev(device);
- 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/nitrocli/src/tests/reset.rs b/nitrocli/src/tests/reset.rs
deleted file mode 100644
index 2e567fa..0000000
--- a/nitrocli/src/tests/reset.rs
+++ /dev/null
@@ -1,54 +0,0 @@
-// reset.rs
-
-// *************************************************************************
-// * Copyright (C) 2019 Robin Krahl (robin.krahl@ireas.org) *
-// * *
-// * This program is free software: you can redistribute it and/or modify *
-// * it under the terms of the GNU General Public License as published by *
-// * the Free Software Foundation, either version 3 of the License, or *
-// * (at your option) any later version. *
-// * *
-// * This program is distributed in the hope that it will be useful, *
-// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
-// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
-// * GNU General Public License for more details. *
-// * *
-// * You should have received a copy of the GNU General Public License *
-// * along with this program. If not, see <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-use nitrokey::Authenticate;
-use nitrokey::GetPasswordSafe;
-
-use super::*;
-
-#[test_device]
-fn reset(device: nitrokey::DeviceWrapper) -> crate::Result<()> {
- let new_admin_pin = "87654321";
- let mut ncli = Nitrocli::with_dev(device);
-
- // Change the admin PIN.
- ncli.new_admin_pin(new_admin_pin);
- let _ = ncli.handle(&["pin", "set", "admin"])?;
-
- // Check that the admin PIN has been changed.
- let device = nitrokey::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());
-
- // Check that the admin PIN has been reset.
- let device = nitrokey::connect_model(ncli.model().unwrap())?;
- let 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/nitrocli/src/tests/run.rs b/nitrocli/src/tests/run.rs
deleted file mode 100644
index dda7473..0000000
--- a/nitrocli/src/tests/run.rs
+++ /dev/null
@@ -1,66 +0,0 @@
-// 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 <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-use super::*;
-
-#[test]
-fn no_command_or_option() {
- let (rc, out, err) = Nitrocli::new().run(&[]);
-
- assert_ne!(rc, 0);
- assert_eq!(out, b"");
-
- let s = String::from_utf8_lossy(&err).into_owned();
- assert!(s.starts_with("Usage:\n"), s);
-}
-
-#[test]
-fn help_option() {
- fn test(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();
- assert!(s.starts_with("Usage:\n"), s);
- }
-
- test("--help");
- test("-h")
-}
-
-#[test]
-fn version_option() {
- fn test(re: &regex::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/nitrocli/src/tests/status.rs b/nitrocli/src/tests/status.rs
deleted file mode 100644
index 7aac5ad..0000000
--- a/nitrocli/src/tests/status.rs
+++ /dev/null
@@ -1,81 +0,0 @@
-// status.rs
-
-// *************************************************************************
-// * Copyright (C) 2019 Daniel Mueller (deso@posteo.net) *
-// * *
-// * This program is free software: you can redistribute it and/or modify *
-// * it under the terms of the GNU General Public License as published by *
-// * the Free Software Foundation, either version 3 of the License, or *
-// * (at your option) any later version. *
-// * *
-// * This program is distributed in the hope that it will be useful, *
-// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
-// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
-// * GNU General Public License for more details. *
-// * *
-// * You should have received a copy of the GNU General Public License *
-// * along with this program. If not, see <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-use super::*;
-
-// This test acts as verification that conversion of Error::Error
-// variants into the proper exit code works properly.
-#[test_device]
-fn not_found_raw() {
- let (rc, out, err) = Nitrocli::new().run(&["status"]);
-
- assert_ne!(rc, 0);
- assert_eq!(out, b"");
- assert_eq!(err, b"Nitrokey device not found\n");
-}
-
-#[test_device]
-fn not_found() {
- let res = Nitrocli::new().handle(&["status"]);
- assert_eq!(res.unwrap_str_err(), "Nitrokey device not found");
-}
-
-#[test_device]
-fn output_pro(device: nitrokey::Pro) -> crate::Result<()> {
- let re = regex::Regex::new(
- r#"^Status:
- model: Pro
- serial number: 0x[[:xdigit:]]{8}
- firmware version: \d+\.\d+
- user retry count: [0-3]
- admin retry count: [0-3]
-$"#,
- )
- .unwrap();
-
- let out = Nitrocli::with_dev(device).handle(&["status"])?;
- assert!(re.is_match(&out), out);
- Ok(())
-}
-
-#[test_device]
-fn output_storage(device: nitrokey::Storage) -> crate::Result<()> {
- let re = regex::Regex::new(
- r#"^Status:
- model: Storage
- serial number: 0x[[:xdigit:]]{8}
- firmware version: \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_dev(device).handle(&["status"])?;
- assert!(re.is_match(&out), out);
- Ok(())
-}
diff --git a/nitrocli/src/tests/unencrypted.rs b/nitrocli/src/tests/unencrypted.rs
deleted file mode 100644
index c976f50..0000000
--- a/nitrocli/src/tests/unencrypted.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-// unencrypted.rs
-
-// *************************************************************************
-// * Copyright (C) 2019 Daniel Mueller (deso@posteo.net) *
-// * *
-// * This program is free software: you can redistribute it and/or modify *
-// * it under the terms of the GNU General Public License as published by *
-// * the Free Software Foundation, either version 3 of the License, or *
-// * (at your option) any later version. *
-// * *
-// * This program is distributed in the hope that it will be useful, *
-// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
-// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
-// * GNU General Public License for more details. *
-// * *
-// * You should have received a copy of the GNU General Public License *
-// * along with this program. If not, see <http://www.gnu.org/licenses/>. *
-// *************************************************************************
-
-use super::*;
-
-#[test_device]
-fn unencrypted_set_read_write(device: nitrokey::Storage) -> crate::Result<()> {
- let mut ncli = Nitrocli::with_dev(device);
- let out = ncli.handle(&["unencrypted", "set", "read-write"])?;
- assert!(out.is_empty());
-
- let device = nitrokey::Storage::connect()?;
- assert!(device.get_status()?.unencrypted_volume.active);
- assert!(!device.get_status()?.unencrypted_volume.read_only);
- drop(device);
-
- let out = ncli.handle(&["unencrypted", "set", "read-only"])?;
- assert!(out.is_empty());
-
- let device = nitrokey::Storage::connect()?;
- assert!(device.get_status()?.unencrypted_volume.active);
- assert!(device.get_status()?.unencrypted_volume.read_only);
-
- Ok(())
-}