structopt

This commit is contained in:
2019-09-20 15:54:47 +02:00
parent 84ffd1fb94
commit 78d5eafc9a
9 changed files with 301 additions and 410 deletions

View File

@@ -3,81 +3,14 @@ use crate::*;
use cryptsetup_rs as luks;
use cryptsetup_rs::api::{CryptDeviceHandle, CryptDeviceOpenBuilder, Luks1Params};
use cryptsetup_rs::{Luks1CryptDevice, CryptDevice};
use cryptsetup_rs::{CryptDevice, Luks1CryptDevice};
use libcryptsetup_sys::crypt_keyslot_info;
use ctap;
use ctap::extensions::hmac::{FidoHmacCredential, HmacExtension};
use ctap::FidoDevice;
use structopt::StructOpt;
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;
use std::thread;
use std::time::Duration;
pub fn setup() -> Fido2LuksResult<()> {
while !authenticator_connected()? {
eprintln!("Please connect your authenticator");
for _ in 0..3 {
thread::sleep(Duration::from_secs(1));
if authenticator_connected()? {
break;
}
}
}
let mut config = Config::default();
let save_config = |c: &Config| {
File::create("fido2luks.json")
.expect("Failed to save config")
.write_all(serde_json::to_string_pretty(c).unwrap().as_bytes())
.expect("Failed to save config");
};
fn ask_bool(q: &str) -> bool {
ask_str(&format!("{} (y/n)", q)).expect("Failed to read from stdin") == "y"
}
println!("1. Generating a credential");
let mut ccred: Option<FidoHmacCredential> = None;
for di in ctap::get_devices().expect("Failed to query USB for 2fa devices") {
let mut dev = FidoDevice::new(&di).expect("Failed to open 2fa device");
match dev.make_hmac_credential() {
Ok(cred) => {
ccred = Some(cred);
break;
}
Err(_e) => println!("Failed to to obtain credential trying next device(if applicable)"),
}
}
config.credential_id = hex::encode(ccred.expect("No credential could be obtained").id);
save_config(&config);
loop {
let device = ask_str("Path to your luks device: ").expect("Failed to read from stdin");;
if Path::new(&device).exists()
|| ask_bool(&format!("{} does not exist, save anyway?", device))
{
config.device = device.into();
break;
}
}
save_config(&config);
config.mapper_name = ask_str("Name for decrypted disk: ").expect("Failed to read from stdin");;
save_config(&config);
println!("Config saved to: fido2luks.json");
//let slot = add_key_to_luks(&config).expect("Failed to add key to device");
//println!("Added key to slot: {}", slot);
Ok(())
}
use std::process::exit;
pub fn add_key_to_luks(device: PathBuf, secret: &[u8; 32], exclusive: bool) -> Fido2LuksResult<u8> {
fn offer_format(
@@ -116,8 +49,12 @@ pub fn add_key_to_luks(device: PathBuf, secret: &[u8; 32], exclusive: bool) -> F
handle.set_iteration_time(50);
let slot = handle.add_keyslot(secret, prev_key.as_ref().map(|b| b.as_slice()), None)?;
if exclusive {
for old_slot in 0..8u8 {
if old_slot != slot && (handle.keyslot_status(old_slot.into()) == crypt_keyslot_info::CRYPT_SLOT_ACTIVE || handle.keyslot_status(old_slot.into()) == crypt_keyslot_info::CRYPT_SLOT_ACTIVE_LAST) {
for old_slot in 0..8u8 {
if old_slot != slot
&& (handle.keyslot_status(old_slot.into()) == crypt_keyslot_info::CRYPT_SLOT_ACTIVE
|| handle.keyslot_status(old_slot.into())
== crypt_keyslot_info::CRYPT_SLOT_ACTIVE_LAST)
{
handle.destroy_keyslot(old_slot)?;
}
}
@@ -128,3 +65,142 @@ pub fn add_key_to_luks(device: PathBuf, secret: &[u8; 32], exclusive: bool) -> F
pub fn authenticator_connected() -> Fido2LuksResult<bool> {
Ok(!device::get_devices()?.is_empty())
}
#[derive(Debug, StructOpt)]
pub struct Args {
/// Request passwords via Stdin instead of using the password helper
#[structopt(short = "i", long = "interactive")]
pub interactive: bool,
#[structopt(subcommand)]
pub command: Command,
}
#[derive(Debug, StructOpt, Clone)]
pub struct SecretGeneration {
/// FIDO credential id, generate using fido2luks credential
#[structopt(name = "credential-id", env = "FIDO2LUKS_CREDENTIAL_ID")]
pub credential_id: String,
/// Salt for secret generation, defaults to Password
#[structopt(name = "salt", env = "FIDO2LUKS_SALT", default_value = "Ask")]
pub salt: InputSalt,
/// Script used to obtain passwords, overridden by --interactive flag
#[structopt(
name = "password-helper",
env = "FIDO2LUKS_PASSWORD_HELPER",
default_value = "/usr/bin/systemd-ask-password 'Please enter second factor for LUKS disk encryption!'"
)]
pub password_helper: PasswordHelper,
}
impl SecretGeneration {
pub fn patch(&self, args: &Args) -> Self {
let mut me = self.clone();
if args.interactive {
me.password_helper = PasswordHelper::Stdin;
}
me
}
pub fn obtain_secret(&self) -> Fido2LuksResult<[u8; 32]> {
let salt = self.salt.obtain(&self.password_helper)?;
Ok(assemble_secret(
&perform_challenge(&self.credential_id, &salt)?,
&salt,
))
}
}
#[derive(Debug, StructOpt)]
pub enum Command {
#[structopt(name = "print-secret")]
PrintSecret {
/// Prints the secret as binary instead of hex encoded
#[structopt(short = "b", long = "bin")]
binary: bool,
#[structopt(flatten)]
secret_gen: SecretGeneration,
},
/// Adds a generated key to the specified LUKS device
#[structopt(name = "add-key")]
AddKey {
#[structopt(env = "FIDO2LUKS_DEVICE")]
device: PathBuf,
/// Will wipe all other keys
#[structopt(short = "e", long = "exclusive")]
exclusive: bool,
#[structopt(flatten)]
secret_gen: SecretGeneration,
},
/// Open the LUKS device
#[structopt(name = "open")]
Open {
#[structopt(env = "FIDO2LUKS_DEVICE")]
device: PathBuf,
#[structopt(env = "FIDO2LUKS_MAPPER_NAME")]
name: String,
#[structopt(flatten)]
secret_gen: SecretGeneration,
},
/// Generate a new FIDO credential
#[structopt(name = "credential")]
Credential,
/// Check if an authenticator is connected
#[structopt(name = "connected")]
Connected,
}
pub fn parse_cmdline() -> Args {
Args::from_args()
}
pub fn run_cli() -> Fido2LuksResult<()> {
let args = parse_cmdline();
match &args.command {
Command::Credential => {
let cred = make_credential_id()?;
println!("{}", hex::encode(&cred.id));
Ok(())
}
Command::PrintSecret {
binary,
ref secret_gen,
} => {
let secret = secret_gen.patch(&args).obtain_secret()?;
if *binary {
io::stdout().write(&secret[..])?;
} else {
io::stdout().write(hex::encode(&secret[..]).as_bytes())?;
}
Ok(io::stdout().flush()?)
}
Command::AddKey {
device,
exclusive,
ref secret_gen,
} => {
let secret = secret_gen.patch(&args).obtain_secret()?;
let slot = add_key_to_luks(device.clone(), &secret, *exclusive)?;
println!(
"Added to key to device {}, slot: {}",
device.display(),
slot
);
Ok(())
}
Command::Open {
device,
name,
ref secret_gen,
} => {
let secret = secret_gen.patch(&args).obtain_secret()?;
open_container(&device, &name, &secret)
}
Command::Connected => match get_devices() {
Ok(ref devs) if !devs.is_empty() => {
println!("Found {} devices", devs.len());
Ok(())
}
_ => exit(1),
},
}
}

View File

@@ -3,88 +3,14 @@ use crate::*;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap;
use std::convert::TryInto;
use std::env;
use std::fmt;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::path::PathBuf;
use std::process::Command;
use std::str::FromStr;
#[derive(Debug, Deserialize, Serialize)]
pub struct EnvConfig {
pub credential_id: String,
pub device: Option<String>,
pub salt: String,
pub mapper_name: Option<String>,
pub password_helper: String,
}
impl TryInto<Config> for EnvConfig {
type Error = Fido2LuksError;
fn try_into(self) -> Fido2LuksResult<Config> {
Ok(Config {
credential_id: self.credential_id,
device: self
.device
.ok_or(Fido2LuksError::ConfigurationError {
cause: ConfigurationError::MissingField("DEVICE".into()),
})?
.into(),
mapper_name: self.mapper_name.ok_or(Fido2LuksError::ConfigurationError {
cause: ConfigurationError::MissingField("DEVICE_MAPPER".into()),
})?,
password_helper: PasswordHelper::Script(self.password_helper),
input_salt: self.salt.as_str().into(),
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Config {
pub credential_id: String,
pub input_salt: InputSalt,
pub device: PathBuf,
pub mapper_name: String,
pub password_helper: PasswordHelper,
}
impl Config {
pub fn load_default_location() -> Fido2LuksResult<Config> {
Self::load_config(
&mut File::open(
env::vars()
.collect::<HashMap<_, _>>()
.get("FIDO2LUKS_CONFIG")
.unwrap_or(&"/etc/fido2luks.json".to_owned()),
)
.or(File::open("fido2luks.json"))?,
)
}
pub fn load_config(reader: &mut dyn Read) -> Fido2LuksResult<Config> {
let mut conf_str = String::new();
reader.read_to_string(&mut conf_str)?;
Ok(serde_json::from_str(&conf_str)?)
}
}
impl Default for Config {
fn default() -> Self {
Config {
credential_id: "<required>".into(),
input_salt: Default::default(),
device: "/dev/some-vg/<volume>".into(),
mapper_name: "2fa-secured-luks".into(),
password_helper: PasswordHelper::default(),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[derive(Debug, Clone)]
pub enum InputSalt {
AskPassword,
File { path: PathBuf },
@@ -107,6 +33,24 @@ impl From<&str> for InputSalt {
}
}
impl FromStr for InputSalt {
type Err = Fido2LuksError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self::from(s))
}
}
impl fmt::Display for InputSalt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.write_str(&match self {
InputSalt::AskPassword => "ask".to_string(),
InputSalt::File { path } => path.display().to_string(),
InputSalt::Both { path } => ["ask", path.display().to_string().as_str()].join(" + "),
})
}
}
impl InputSalt {
pub fn obtain(&self, password_helper: &PasswordHelper) -> Fido2LuksResult<[u8; 32]> {
let mut digest = Sha256::new();
@@ -140,7 +84,7 @@ impl InputSalt {
}
}
#[derive(Debug, Deserialize, Serialize)]
#[derive(Debug, Clone)]
pub enum PasswordHelper {
Script(String),
Systemd,
@@ -149,7 +93,10 @@ pub enum PasswordHelper {
impl Default for PasswordHelper {
fn default() -> Self {
PasswordHelper::Script("/usr/bin/systemd-ask-password --no-tty 'Please enter second factor for LUKS disk encryption!'".into())
PasswordHelper::Script(
"/usr/bin/systemd-ask-password 'Please enter second factor for LUKS disk encryption!'"
.into(),
)
}
}
@@ -162,6 +109,24 @@ impl From<&str> for PasswordHelper {
}
}
impl FromStr for PasswordHelper {
type Err = Fido2LuksError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self::from(s))
}
}
impl fmt::Display for PasswordHelper {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.write_str(&match self {
PasswordHelper::Stdin => "stdin".to_string(),
PasswordHelper::Systemd => "systemd".to_string(),
PasswordHelper::Script(path) => path.clone(),
})
}
}
impl PasswordHelper {
pub fn obtain(&self) -> Fido2LuksResult<String> {
use PasswordHelper::*;

View File

@@ -1,5 +1,5 @@
use ctap::FidoError;
use std::{fmt, io};
use std::io;
pub type Fido2LuksResult<T> = Result<T, Fido2LuksError>;
@@ -18,20 +18,11 @@ pub enum Fido2LuksError {
#[fail(display = "no authenticator found, please ensure you device is plugged in")]
IoError { cause: io::Error },
#[fail(display = "failed to parse config, please check formatting and contents")]
ConfigurationError { cause: ConfigurationError },
#[fail(display = "the submitted secret is not applicable to this luks device")]
WrongSecret,
#[fail(display = "not an utf8 string")]
StringEncodingError { cause: FromUtf8Error },
}
#[derive(Debug)]
pub enum ConfigurationError {
Json(serde_json::error::Error),
Env(envy::Error),
MissingField(String),
}
#[derive(Debug, Fail)]
pub enum AskPassError {
#[fail(display = "unable to retrieve password: {}", _0)]
@@ -40,22 +31,6 @@ pub enum AskPassError {
Mismatch,
}
impl From<serde_json::error::Error> for Fido2LuksError {
fn from(e: serde_json::error::Error) -> Self {
Fido2LuksError::ConfigurationError {
cause: ConfigurationError::Json(e),
}
}
}
impl From<envy::Error> for Fido2LuksError {
fn from(e: envy::Error) -> Self {
Fido2LuksError::ConfigurationError {
cause: ConfigurationError::Env(e),
}
}
}
use std::string::FromUtf8Error;
use Fido2LuksError::*;

View File

@@ -1,6 +1,5 @@
#[macro_use]
extern crate failure;
extern crate serde_derive;
use crate::cli::*;
use crate::config::*;
use crate::device::*;
@@ -12,15 +11,8 @@ use cryptsetup_rs as luks;
use cryptsetup_rs::Luks1CryptDevice;
use ctap;
use luks::device::Error::CryptsetupError;
use std::collections::HashMap;
use std::env;
use std::convert::TryInto;
use std::io::{self, stdout, Write};
use std::io::{self};
use std::path::PathBuf;
use std::process::exit;
mod cli;
mod config;
@@ -41,179 +33,7 @@ fn assemble_secret(hmac_result: &[u8], salt: &[u8]) -> [u8; 32] {
digest.result(&mut secret);
secret
}
fn ask_str(q: &str) -> Fido2LuksResult<String> {
let stdin = io::stdin();
let mut s = String::new();
print!("{}", q);
io::stdout().flush()?;
stdin.read_line(&mut s)?;
Ok(s.trim().to_owned())
}
fn open(conf: &Config, secret: &[u8; 32]) -> Fido2LuksResult<()> {
dbg!(hex::encode(&secret));
match open_container(&conf.device, &conf.mapper_name, &secret) {
Err(Fido2LuksError::LuksError {
cause: CryptsetupError(errno),
}) if errno.0 == 1 => Err(Fido2LuksError::WrongSecret)?,
e => e?,
};
Ok(())
}
/*fn package_self() -> Fido2LuksResult<()> {
let conf = Config::load_default_location()?;
let binary_path: PathBuf = env::args().next().unwrap().into();
let mut me = File::open(binary_path)?;
me.seek(io::SeekFrom::End(("config".as_bytes().len() * -1) as i64 - 4))?;
let conf_len = me.read_u32()?;
let mut buf = vec![0u8; 512];
me.read(&mut buf[0..6])?;
if String::from_utf8((&buf[0..6]).iter().collect()).map(|s| &s == "config").unwrap_or(false) {
}
Ok(())
}*/
fn main() -> Fido2LuksResult<()> {
let args: Vec<_> = env::args().skip(1).collect();
fn config_env() -> Fido2LuksResult<EnvConfig> {
Ok(envy::prefixed("FIDO2LUKS_").from_env::<EnvConfig>()?)
}
fn secret_from_env_config(conf: &EnvConfig) -> Fido2LuksResult<[u8; 32]> {
let conf = config_env()?;
let salt =
InputSalt::from(conf.salt.as_str()).obtain(&conf.password_helper.as_str().into())?;
Ok(assemble_secret(
&perform_challenge(&conf.credential_id, &salt)?,
&salt,
))
}
match &args.iter().map(|s| s.as_str()).collect::<Vec<_>>()[..] {
["print-secret"] => {
let conf = config_env()?;
io::stdout().write(hex::encode(&secret_from_env_config(&conf)?[..]).as_bytes())?;
Ok(io::stdout().flush()?)
}
["open"] => {
let mut conf = config_env()?;
open_container(
&conf
.device
.as_ref()
.expect("please specify FIDO2LUKS_DEVICE")
.into(),
&conf
.mapper_name
.as_ref()
.expect("please specify FIDO2LUKS_MAPPER_NAME"),
&secret_from_env_config(&conf)?,
)
}
["open", device, mapper_name] => {
let mut conf = config_env()?;
conf.mapper_name = Some(mapper_name.to_string());
conf.device = Some(device.to_string());
open_container(
&conf
.device
.as_ref()
.expect("please specify FIDO2LUKS_DEVICE")
.into(),
&conf
.mapper_name
.as_ref()
.expect("please specify FIDO2LUKS_MAPPER_NAME"),
&secret_from_env_config(&conf)?,
)
}
["credential"] => {
let cred = make_credential_id()?;
println!("{}", hex::encode(&cred.id));
Ok(())
}
["addkey", device] => {
let mut conf = config_env()?;
conf.device = conf.device.or(Some(device.to_string()));
let slot = add_key_to_luks(
conf.device.as_ref().unwrap().into(),
&secret_from_env_config(&conf)?, true
)?;
println!("Added to key to device {}, slot: {}", device, slot);
Ok(())
}
_ => {
println!(
"Usage:\n
fido2luks open <device> [name]\n
fido2luks addkey <device>\n\n
Environment variables:\n
<FIDO2LUKS_CREDENTIAL_ID>\n
<FIDO2LUKS_SALT>\n
"
);
Ok(())
}
}
}
fn main_old() -> Fido2LuksResult<()> {
let args: Vec<_> = env::args().skip(1).collect(); //Ignore program name -> Vec
let env = env::vars().collect::<HashMap<_, _>>();
let secret = |conf: &Config| -> Fido2LuksResult<[u8; 32]> {
let salt = conf.input_salt.obtain(&conf.password_helper)?;
Ok(assemble_secret(
&perform_challenge(&conf.credential_id, &salt)?,
&salt,
))
};
if args.is_empty() {
let conf = Config::load_default_location()?;
if env.contains_key("CRYPTTAB_NAME") {
//Indicates that this script is being run as keyscript
let mut out = stdout();
out.write(&secret(&conf)?)?;
Ok(out.flush()?)
} else {
io::stdout().write(&secret(&conf)?)?;
Ok(io::stdout().flush()?)
}
} else {
match args.first().map(|s| s.as_ref()).unwrap() {
//"addkey" => add_key_to_luks(&Config::load_default_location()?).map(|_| ()),
"setup" => setup(),
"open" if args.get(1).map(|a| &*a == "-e").unwrap_or(false) => {
let conf = envy::prefixed("FIDO2LUKS_")
.from_env::<EnvConfig>()
.expect("Missing env config values")
.try_into()?;
open(&conf, &secret(&conf)?)
}
"open" => open(
&Config::load_default_location()?,
&secret(&Config::load_default_location()?)?,
),
"connected" => match authenticator_connected()? {
false => {
println!("no");
exit(1)
}
_ => {
println!("yes");
exit(0)
}
},
_ => {
eprintln!("Usage: setup | addkey | connected");
Ok(())
} //"selfcontain" => package_self()
}
}
run_cli()
}