enable fido requests to be sent to multiple devices at once

This commit is contained in:
shimun 2020-04-06 21:00:11 +02:00
commit 49e2835f60
Signed by: shimun
GPG Key ID: E81D8382DC2F971B
5 changed files with 653 additions and 438 deletions

801
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
[package] [package]
name = "fido2luks" name = "fido2luks"
version = "0.2.5" version = "0.2.6"
authors = ["shimunn <shimun@shimun.net>"] authors = ["shimunn <shimun@shimun.net>"]
edition = "2018" edition = "2018"
@ -14,9 +14,7 @@ categories = ["command-line-utilities"]
license-file = "LICENSE" license-file = "LICENSE"
[dependencies] [dependencies]
ctap_hmac = "0.2.2" ctap_hmac = { version="0.4.1", features = ["request_multiple"] }
hex = "0.3.2" hex = "0.3.2"
ring = "0.13.5" ring = "0.13.5"
failure = "0.1.5" failure = "0.1.5"

View File

@ -4,11 +4,11 @@ use crate::*;
use structopt::StructOpt; use structopt::StructOpt;
use failure::_core::fmt::{Error, Formatter}; use ctap::{FidoCredential, FidoErrorKind};
use failure::_core::fmt::{Display, Error, Formatter};
use failure::_core::str::FromStr; use failure::_core::str::FromStr;
use failure::_core::time::Duration; use failure::_core::time::Duration;
use std::io::Write; use std::io::Write;
use std::process::exit; use std::process::exit;
use std::thread; use std::thread;
@ -16,9 +16,9 @@ use crate::util::read_password;
use std::time::SystemTime; use std::time::SystemTime;
#[derive(Debug, Eq, PartialEq, Clone)] #[derive(Debug, Eq, PartialEq, Clone)]
pub struct HexEncoded(Vec<u8>); pub struct HexEncoded(pub Vec<u8>);
impl std::fmt::Display for HexEncoded { impl Display for HexEncoded {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
f.write_str(&hex::encode(&self.0)) f.write_str(&hex::encode(&self.0))
} }
@ -32,6 +32,30 @@ impl FromStr for HexEncoded {
} }
} }
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct CommaSeparated<T: FromStr + Display>(pub Vec<T>);
impl<T: Display + FromStr> Display for CommaSeparated<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
for i in &self.0 {
f.write_str(&i.to_string())?;
f.write_str(",")?;
}
Ok(())
}
}
impl<T: Display + FromStr> FromStr for CommaSeparated<T> {
type Err = <T as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(CommaSeparated(
s.split(',')
.map(|part| <T as FromStr>::from_str(part))
.collect::<Result<Vec<_>, _>>()?,
))
}
}
#[derive(Debug, StructOpt)] #[derive(Debug, StructOpt)]
pub struct Args { pub struct Args {
/// Request passwords via Stdin instead of using the password helper /// Request passwords via Stdin instead of using the password helper
@ -43,9 +67,9 @@ pub struct Args {
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, StructOpt, Clone)]
pub struct SecretGeneration { pub struct SecretGeneration {
/// FIDO credential id, generate using fido2luks credential /// FIDO credential ids, seperated by ',' generate using fido2luks credential
#[structopt(name = "credential-id", env = "FIDO2LUKS_CREDENTIAL_ID")] #[structopt(name = "credential-id", env = "FIDO2LUKS_CREDENTIAL_ID")]
pub credential_id: HexEncoded, pub credential_ids: CommaSeparated<HexEncoded>,
/// Salt for secret generation, defaults to 'ask' /// Salt for secret generation, defaults to 'ask'
/// ///
/// Options:{n} /// Options:{n}
@ -99,9 +123,11 @@ impl SecretGeneration {
let mut salt = [0u8; 32]; let mut salt = [0u8; 32];
match self.password_helper { match self.password_helper {
PasswordHelper::Stdin if !self.verify_password.unwrap_or(true) => { PasswordHelper::Stdin if !self.verify_password.unwrap_or(true) => {
salt.copy_from_slice( salt.copy_from_slice(&util::sha256(&[&read_password(
read_password(password_query, self.verify_password.unwrap_or(true))?.as_bytes(), password_query,
); self.verify_password.unwrap_or(true),
)?
.as_bytes()[..]]));
} }
_ => { _ => {
salt = self.salt.obtain(&self.password_helper)?; salt = self.salt.obtain(&self.password_helper)?;
@ -122,13 +148,60 @@ impl SecretGeneration {
} }
thread::sleep(Duration::from_millis(500)); thread::sleep(Duration::from_millis(500));
} }
let credentials = &self
.credential_ids
.0
.iter()
.map(|HexEncoded(id)| FidoCredential {
id: id.to_vec(),
public_key: None,
})
.collect::<Vec<_>>();
let credentials = credentials.iter().collect::<Vec<_>>();
Ok(assemble_secret( Ok(assemble_secret(
&perform_challenge(&self.credential_id.0, &salt)?, &perform_challenge(&credentials[..], &salt, timeout - start.elapsed().unwrap())?,
&salt, &salt,
)) ))
} }
} }
#[derive(Debug, StructOpt, Clone)]
pub struct LuksSettings {
/// Number of milliseconds required to derive the volume decryption key
/// Defaults to 10ms when using an authenticator or the default by cryptsetup when using a password
#[structopt(long = "kdf-time", name = "kdf-time")]
kdf_time: Option<u64>,
}
#[derive(Debug, StructOpt, Clone)]
pub struct OtherSecret {
/// Use a keyfile instead of a password
#[structopt(short = "d", long = "keyfile", conflicts_with = "fido_device")]
keyfile: Option<PathBuf>,
/// Use another fido device instead of a password
/// Note: this requires for the credential fot the other device to be passed as argument as well
#[structopt(short = "f", long = "fido-device", conflicts_with = "keyfile")]
fido_device: bool,
}
impl OtherSecret {
pub fn obtain(
&self,
secret_gen: &SecretGeneration,
verify_password: bool,
password_question: &str,
) -> Fido2LuksResult<Vec<u8>> {
match &self.keyfile {
Some(keyfile) => util::read_keyfile(keyfile.clone()),
None if self.fido_device => {
Ok(Vec::from(&secret_gen.obtain_secret(password_question)?[..]))
}
None => util::read_password(password_question, verify_password)
.map(|p| p.as_bytes().to_vec()),
}
}
}
#[derive(Debug, StructOpt)] #[derive(Debug, StructOpt)]
pub enum Command { pub enum Command {
#[structopt(name = "print-secret")] #[structopt(name = "print-secret")]
@ -147,11 +220,12 @@ pub enum Command {
/// Will wipe all other keys /// Will wipe all other keys
#[structopt(short = "e", long = "exclusive")] #[structopt(short = "e", long = "exclusive")]
exclusive: bool, exclusive: bool,
/// Use a keyfile instead of typing a previous password #[structopt(flatten)]
#[structopt(short = "d", long = "keyfile")] existing_secret: OtherSecret,
keyfile: Option<PathBuf>,
#[structopt(flatten)] #[structopt(flatten)]
secret_gen: SecretGeneration, secret_gen: SecretGeneration,
#[structopt(flatten)]
luks_settings: LuksSettings,
}, },
/// Replace a previously added key with a password /// Replace a previously added key with a password
#[structopt(name = "replace-key")] #[structopt(name = "replace-key")]
@ -161,11 +235,12 @@ pub enum Command {
/// Add the password and keep the key /// Add the password and keep the key
#[structopt(short = "a", long = "add-password")] #[structopt(short = "a", long = "add-password")]
add_password: bool, add_password: bool,
/// Use a keyfile instead of typing a previous password #[structopt(flatten)]
#[structopt(short = "d", long = "keyfile")] replacement: OtherSecret,
keyfile: Option<PathBuf>,
#[structopt(flatten)] #[structopt(flatten)]
secret_gen: SecretGeneration, secret_gen: SecretGeneration,
#[structopt(flatten)]
luks_settings: LuksSettings,
}, },
/// Open the LUKS device /// Open the LUKS device
#[structopt(name = "open")] #[structopt(name = "open")]
@ -221,16 +296,19 @@ pub fn run_cli() -> Fido2LuksResult<()> {
Command::AddKey { Command::AddKey {
device, device,
exclusive, exclusive,
keyfile, existing_secret,
ref secret_gen, ref secret_gen,
luks_settings,
} => { } => {
let old_secret = if let Some(keyfile) = keyfile.clone() { let old_secret = existing_secret.obtain(&secret_gen, false, "Existing password")?;
util::read_keyfile(keyfile.clone()) let secret_gen = secret_gen.patch(&args, None);
} else { let secret = secret_gen.obtain_secret("Password")?;
util::read_password("Old password", false).map(|p| p.as_bytes().to_vec()) let added_slot = luks::add_key(
}?; device.clone(),
let secret = secret_gen.patch(&args, None).obtain_secret("Password")?; &secret,
let added_slot = luks::add_key(device.clone(), &secret, &old_secret[..], Some(10))?; &old_secret[..],
luks_settings.kdf_time.or(Some(10)),
)?;
if *exclusive { if *exclusive {
let destroyed = luks::remove_keyslots(&device, &[added_slot])?; let destroyed = luks::remove_keyslots(&device, &[added_slot])?;
println!( println!(
@ -251,21 +329,17 @@ pub fn run_cli() -> Fido2LuksResult<()> {
Command::ReplaceKey { Command::ReplaceKey {
device, device,
add_password, add_password,
keyfile, replacement,
ref secret_gen, ref secret_gen,
luks_settings,
} => { } => {
let new_secret = if let Some(keyfile) = keyfile.clone() { let secret_gen = secret_gen.patch(&args, Some(false));
util::read_keyfile(keyfile.clone()) let secret = secret_gen.obtain_secret("Password")?;
} else { let new_secret = replacement.obtain(&secret_gen, true, "Replacement password")?;
util::read_password("Password to add", *add_password).map(|p| p.as_bytes().to_vec())
}?;
let secret = secret_gen
.patch(&args, Some(false))
.obtain_secret("Password")?;
let slot = if *add_password { let slot = if *add_password {
luks::add_key(device, &new_secret[..], &secret, None) luks::add_key(device, &new_secret[..], &secret, luks_settings.kdf_time)
} else { } else {
luks::replace_key(device, &new_secret[..], &secret, Some(5)) luks::replace_key(device, &new_secret[..], &secret, luks_settings.kdf_time)
}?; }?;
println!( println!(
"Added to password to device {}, slot: {}", "Added to password to device {}, slot: {}",
@ -282,18 +356,25 @@ pub fn run_cli() -> Fido2LuksResult<()> {
} => { } => {
let mut retries = *retries; let mut retries = *retries;
loop { loop {
let secret = secret_gen match secret_gen
.patch(&args, Some(false)) .patch(&args, Some(false))
.obtain_secret("Password")?; .obtain_secret("Password")
match luks::open_container(&device, &name, &secret) { .and_then(|secret| luks::open_container(&device, &name, &secret))
Err(e) => match e { {
Fido2LuksError::WrongSecret if retries > 0 => { Err(e) => {
match e {
Fido2LuksError::WrongSecret if retries > 0 => (),
Fido2LuksError::AuthenticatorError { ref cause }
if cause.kind() == FidoErrorKind::Timeout && retries > 0 =>
{
()
}
e => break Err(e)?,
}
retries -= 1; retries -= 1;
eprintln!("{}", e); eprintln!("{}", e);
continue;
} }
e => Err(e)?,
},
res => break res, res => break res,
} }
} }

View File

@ -1,91 +1,49 @@
use crate::error::*; use crate::error::*;
use crate::util::sha256;
use crate::util;
use ctap::{ use ctap::{
self, self, extensions::hmac::HmacExtension, request_multiple_devices, FidoAssertionRequestBuilder,
extensions::hmac::{FidoHmacCredential, HmacExtension}, FidoCredential, FidoCredentialRequestBuilder, FidoDevice, FidoError, FidoErrorKind,
AuthenticatorOptions, FidoDevice, FidoError, FidoErrorKind, PublicKeyCredentialRpEntity,
PublicKeyCredentialUserEntity,
}; };
use std::time::Duration;
const RP_ID: &'static str = "fido2luks"; const RP_ID: &'static str = "fido2luks";
fn authenticator_options() -> Option<AuthenticatorOptions> { pub fn make_credential_id(name: Option<&str>) -> Fido2LuksResult<FidoCredential> {
Some(AuthenticatorOptions { let mut request = FidoCredentialRequestBuilder::default().rp_id(RP_ID);
uv: false, //TODO: should get this from config if let Some(user_name) = name {
rk: true, request = request.user_name(user_name);
}) }
let request = request.build().unwrap();
let make_credential = |device: &mut FidoDevice| device.make_hmac_credential(&request);
Ok(request_multiple_devices(
get_devices()?
.iter_mut()
.map(|device| (device, &make_credential)),
None,
)?)
} }
fn authenticator_rp() -> PublicKeyCredentialRpEntity<'static> { pub fn perform_challenge(
PublicKeyCredentialRpEntity { credentials: &[&FidoCredential],
id: RP_ID, salt: &[u8; 32],
name: None, timeout: Duration,
icon: None, ) -> Fido2LuksResult<[u8; 32]> {
} let request = FidoAssertionRequestBuilder::default()
} .rp_id(RP_ID)
.credentials(credentials)
fn authenticator_user(name: Option<&str>) -> PublicKeyCredentialUserEntity { .build()
PublicKeyCredentialUserEntity { .unwrap();
id: &[0u8], let get_assertion = |device: &mut FidoDevice| {
name: name.unwrap_or(""), device.get_hmac_assertion(&request, &util::sha256(&[&salt[..]]), None)
icon: None,
display_name: name,
}
}
pub fn make_credential_id(name: Option<&str>) -> Fido2LuksResult<FidoHmacCredential> {
let mut errs = Vec::new();
match get_devices()? {
ref devs if devs.is_empty() => Err(Fido2LuksError::NoAuthenticatorError)?,
devs => {
for mut dev in devs.into_iter() {
match dev
.make_hmac_credential_full(
authenticator_rp(),
authenticator_user(name),
&[0u8; 32],
&[],
authenticator_options(),
)
.map(|cred| cred.into())
{
//TODO: make credentials device specific
Ok(cred) => {
return Ok(cred);
}
Err(e) => {
errs.push(e);
}
}
}
}
}
Err(errs.pop().ok_or(Fido2LuksError::NoAuthenticatorError)?)?
}
pub fn perform_challenge(credential_id: &[u8], salt: &[u8; 32]) -> Fido2LuksResult<[u8; 32]> {
let cred = FidoHmacCredential {
id: credential_id.to_vec(),
rp_id: RP_ID.to_string(),
}; };
let mut errs = Vec::new(); let (_, (secret, _)) = request_multiple_devices(
match get_devices()? { get_devices()?
ref devs if devs.is_empty() => Err(Fido2LuksError::NoAuthenticatorError)?, .iter_mut()
devs => { .map(|device| (device, &get_assertion)),
for mut dev in devs.into_iter() { Some(timeout),
match dev.get_hmac_assertion(&cred, &sha256(&[&salt[..]]), None, None) { )?;
Ok(secret) => { Ok(secret)
return Ok(secret.0);
}
Err(e) => {
errs.push(e);
}
}
}
}
}
Err(errs.pop().ok_or(Fido2LuksError::NoAuthenticatorError)?)?
} }
pub fn get_devices() -> Fido2LuksResult<Vec<FidoDevice>> { pub fn get_devices() -> Fido2LuksResult<Vec<FidoDevice>> {

View File

@ -34,7 +34,6 @@ pub fn add_key<P: AsRef<Path>>(
iteration_time: Option<u64>, iteration_time: Option<u64>,
) -> Fido2LuksResult<u32> { ) -> Fido2LuksResult<u32> {
let mut device = load_device_handle(path)?; let mut device = load_device_handle(path)?;
// Set iteration time not sure wether this applies to luks2 as well
if let Some(millis) = iteration_time { if let Some(millis) = iteration_time {
device.settings_handle().set_iteration_time(millis) device.settings_handle().set_iteration_time(millis)
} }