Compare commits
18 Commits
Author | SHA1 | Date | |
---|---|---|---|
a26b79bcd6
|
|||
69732a1ad6
|
|||
b8ae9d91f0
|
|||
fcdd2a2d3d
|
|||
c3d6425e2d
|
|||
5c0364587e
|
|||
9307503bdc
|
|||
b94f45d1ff
|
|||
c8fb636846
|
|||
49e2835f60
|
|||
d5c0d48f03
|
|||
ad2451f548
|
|||
bb7ee7c1ce
|
|||
0ba77963d2
|
|||
1658800553
|
|||
a394b7d1d1
|
|||
c99d7f562d
|
|||
c4f781e6e3
|
801
Cargo.lock
generated
801
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "fido2luks"
|
name = "fido2luks"
|
||||||
version = "0.2.4"
|
version = "0.2.7"
|
||||||
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.1"
|
ctap_hmac = { version="0.4.2", 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"
|
||||||
|
@@ -9,7 +9,7 @@ Note: This has only been tested under Fedora 31 using a Solo Key, Trezor Model T
|
|||||||
### Prerequisites
|
### Prerequisites
|
||||||
|
|
||||||
```
|
```
|
||||||
dnf install cargo cryptsetup-devel -y
|
dnf install clang cargo cryptsetup-devel -y
|
||||||
```
|
```
|
||||||
|
|
||||||
### Device
|
### Device
|
||||||
|
418
src/cli.rs
418
src/cli.rs
@@ -4,19 +4,21 @@ 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;
|
||||||
|
|
||||||
|
use crate::util::sha256;
|
||||||
use std::time::SystemTime;
|
use std::time::SystemTime;
|
||||||
#[derive(Debug, Eq, PartialEq, Clone)]
|
|
||||||
pub struct HexEncoded(Vec<u8>);
|
|
||||||
|
|
||||||
impl std::fmt::Display for HexEncoded {
|
#[derive(Debug, Eq, PartialEq, Clone)]
|
||||||
|
pub struct HexEncoded(pub Vec<u8>);
|
||||||
|
|
||||||
|
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))
|
||||||
}
|
}
|
||||||
@@ -30,20 +32,73 @@ 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 Credentials {
|
||||||
/// Request passwords via Stdin instead of using the password helper
|
/// FIDO credential ids, seperated by ',' generate using fido2luks credential
|
||||||
#[structopt(short = "i", long = "interactive")]
|
#[structopt(name = "credential-id", env = "FIDO2LUKS_CREDENTIAL_ID")]
|
||||||
pub interactive: bool,
|
pub ids: CommaSeparated<HexEncoded>,
|
||||||
#[structopt(subcommand)]
|
}
|
||||||
pub command: Command,
|
|
||||||
|
#[derive(Debug, StructOpt)]
|
||||||
|
pub struct AuthenticatorParameters {
|
||||||
|
/// Request a PIN to unlock the authenticator
|
||||||
|
#[structopt(short = "P", long = "pin")]
|
||||||
|
pub pin: bool,
|
||||||
|
|
||||||
|
/// Await for an authenticator to be connected, timeout after n seconds
|
||||||
|
#[structopt(
|
||||||
|
long = "await-dev",
|
||||||
|
name = "await-dev",
|
||||||
|
env = "FIDO2LUKS_DEVICE_AWAIT",
|
||||||
|
default_value = "15"
|
||||||
|
)]
|
||||||
|
pub await_time: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, StructOpt)]
|
||||||
|
pub struct LuksParameters {
|
||||||
|
#[structopt(env = "FIDO2LUKS_DEVICE")]
|
||||||
|
device: PathBuf,
|
||||||
|
|
||||||
|
/// Try to unlock the device using a specifc keyslot, ignore all other slots
|
||||||
|
#[structopt(long = "slot", env = "FIDO2LUKS_DEVICE_SLOT")]
|
||||||
|
slot: Option<u32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, StructOpt, Clone)]
|
#[derive(Debug, StructOpt, Clone)]
|
||||||
pub struct SecretGeneration {
|
pub struct LuksModParameters {
|
||||||
/// FIDO credential id, generate using fido2luks credential
|
/// Number of milliseconds required to derive the volume decryption key
|
||||||
#[structopt(name = "credential-id", env = "FIDO2LUKS_CREDENTIAL_ID")]
|
/// Defaults to 10ms when using an authenticator or the default by cryptsetup when using a password
|
||||||
pub credential_id: HexEncoded,
|
#[structopt(long = "kdf-time", name = "kdf-time")]
|
||||||
|
kdf_time: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, StructOpt)]
|
||||||
|
pub struct SecretParameters {
|
||||||
/// Salt for secret generation, defaults to 'ask'
|
/// Salt for secret generation, defaults to 'ask'
|
||||||
///
|
///
|
||||||
/// Options:{n}
|
/// Options:{n}
|
||||||
@@ -64,34 +119,20 @@ pub struct SecretGeneration {
|
|||||||
default_value = "/usr/bin/env systemd-ask-password 'Please enter second factor for LUKS disk encryption!'"
|
default_value = "/usr/bin/env systemd-ask-password 'Please enter second factor for LUKS disk encryption!'"
|
||||||
)]
|
)]
|
||||||
pub password_helper: PasswordHelper,
|
pub password_helper: PasswordHelper,
|
||||||
|
|
||||||
/// Await for an authenticator to be connected, timeout after n seconds
|
|
||||||
#[structopt(
|
|
||||||
long = "await-dev",
|
|
||||||
name = "await-dev",
|
|
||||||
env = "FIDO2LUKS_DEVICE_AWAIT",
|
|
||||||
default_value = "15"
|
|
||||||
)]
|
|
||||||
pub await_authenticator: u64,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SecretGeneration {
|
fn derive_secret(
|
||||||
pub fn patch(&self, args: &Args) -> Self {
|
credentials: &[HexEncoded],
|
||||||
let mut me = self.clone();
|
salt: &[u8; 32],
|
||||||
if args.interactive {
|
timeout: u64,
|
||||||
me.password_helper = PasswordHelper::Stdin;
|
pin: Option<&str>,
|
||||||
}
|
) -> Fido2LuksResult<[u8; 32]> {
|
||||||
me
|
let timeout = Duration::from_secs(timeout);
|
||||||
}
|
|
||||||
|
|
||||||
pub fn obtain_secret(&self) -> Fido2LuksResult<[u8; 32]> {
|
|
||||||
let salt = self.salt.obtain(&self.password_helper)?;
|
|
||||||
let timeout = Duration::from_secs(self.await_authenticator);
|
|
||||||
let start = SystemTime::now();
|
let start = SystemTime::now();
|
||||||
|
|
||||||
while let Ok(el) = start.elapsed() {
|
while let Ok(el) = start.elapsed() {
|
||||||
if el > timeout {
|
if el > timeout {
|
||||||
Err(error::Fido2LuksError::NoAuthenticatorError)?;
|
return Err(error::Fido2LuksError::NoAuthenticatorError);
|
||||||
}
|
}
|
||||||
if get_devices()
|
if get_devices()
|
||||||
.map(|devices| !devices.is_empty())
|
.map(|devices| !devices.is_empty())
|
||||||
@@ -101,11 +142,48 @@ impl SecretGeneration {
|
|||||||
}
|
}
|
||||||
thread::sleep(Duration::from_millis(500));
|
thread::sleep(Duration::from_millis(500));
|
||||||
}
|
}
|
||||||
Ok(assemble_secret(
|
|
||||||
&perform_challenge(&self.credential_id.0, &salt)?,
|
Ok(sha256(&[
|
||||||
&salt,
|
&perform_challenge(
|
||||||
))
|
&credentials
|
||||||
}
|
.iter()
|
||||||
|
.map(|hex| FidoCredential {
|
||||||
|
id: hex.0.clone(),
|
||||||
|
public_key: None,
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.iter()
|
||||||
|
.collect::<Vec<_>>()[..],
|
||||||
|
salt,
|
||||||
|
timeout - start.elapsed().unwrap(),
|
||||||
|
pin,
|
||||||
|
)?[..],
|
||||||
|
salt,
|
||||||
|
]))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_pin() -> Fido2LuksResult<String> {
|
||||||
|
util::read_password("Authenticator PIN", false)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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 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,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, StructOpt)]
|
#[derive(Debug, StructOpt)]
|
||||||
@@ -116,51 +194,72 @@ pub enum Command {
|
|||||||
#[structopt(short = "b", long = "bin")]
|
#[structopt(short = "b", long = "bin")]
|
||||||
binary: bool,
|
binary: bool,
|
||||||
#[structopt(flatten)]
|
#[structopt(flatten)]
|
||||||
secret_gen: SecretGeneration,
|
credentials: Credentials,
|
||||||
|
#[structopt(flatten)]
|
||||||
|
authenticator: AuthenticatorParameters,
|
||||||
|
#[structopt(flatten)]
|
||||||
|
secret: SecretParameters,
|
||||||
},
|
},
|
||||||
/// Adds a generated key to the specified LUKS device
|
/// Adds a generated key to the specified LUKS device
|
||||||
#[structopt(name = "add-key")]
|
#[structopt(name = "add-key")]
|
||||||
AddKey {
|
AddKey {
|
||||||
#[structopt(env = "FIDO2LUKS_DEVICE")]
|
#[structopt(flatten)]
|
||||||
device: PathBuf,
|
luks: LuksParameters,
|
||||||
|
#[structopt(flatten)]
|
||||||
|
credentials: Credentials,
|
||||||
|
#[structopt(flatten)]
|
||||||
|
authenticator: AuthenticatorParameters,
|
||||||
|
#[structopt(flatten)]
|
||||||
|
secret: SecretParameters,
|
||||||
/// 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(short = "d", long = "keyfile")]
|
|
||||||
keyfile: Option<PathBuf>,
|
|
||||||
#[structopt(flatten)]
|
#[structopt(flatten)]
|
||||||
secret_gen: SecretGeneration,
|
existing_secret: OtherSecret,
|
||||||
|
#[structopt(flatten)]
|
||||||
|
luks_mod: LuksModParameters,
|
||||||
},
|
},
|
||||||
/// Replace a previously added key with a password
|
/// Replace a previously added key with a password
|
||||||
#[structopt(name = "replace-key")]
|
#[structopt(name = "replace-key")]
|
||||||
ReplaceKey {
|
ReplaceKey {
|
||||||
#[structopt(env = "FIDO2LUKS_DEVICE")]
|
#[structopt(flatten)]
|
||||||
device: PathBuf,
|
luks: LuksParameters,
|
||||||
|
#[structopt(flatten)]
|
||||||
|
credentials: Credentials,
|
||||||
|
#[structopt(flatten)]
|
||||||
|
authenticator: AuthenticatorParameters,
|
||||||
|
#[structopt(flatten)]
|
||||||
|
secret: SecretParameters,
|
||||||
/// 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(short = "d", long = "keyfile")]
|
|
||||||
keyfile: Option<PathBuf>,
|
|
||||||
#[structopt(flatten)]
|
#[structopt(flatten)]
|
||||||
secret_gen: SecretGeneration,
|
replacement: OtherSecret,
|
||||||
|
#[structopt(flatten)]
|
||||||
|
luks_mod: LuksModParameters,
|
||||||
},
|
},
|
||||||
/// Open the LUKS device
|
/// Open the LUKS device
|
||||||
#[structopt(name = "open")]
|
#[structopt(name = "open")]
|
||||||
Open {
|
Open {
|
||||||
#[structopt(env = "FIDO2LUKS_DEVICE")]
|
#[structopt(flatten)]
|
||||||
device: PathBuf,
|
luks: LuksParameters,
|
||||||
#[structopt(env = "FIDO2LUKS_MAPPER_NAME")]
|
#[structopt(env = "FIDO2LUKS_MAPPER_NAME")]
|
||||||
name: String,
|
name: String,
|
||||||
|
#[structopt(flatten)]
|
||||||
|
credentials: Credentials,
|
||||||
|
#[structopt(flatten)]
|
||||||
|
authenticator: AuthenticatorParameters,
|
||||||
|
#[structopt(flatten)]
|
||||||
|
secret: SecretParameters,
|
||||||
|
|
||||||
#[structopt(short = "r", long = "max-retries", default_value = "0")]
|
#[structopt(short = "r", long = "max-retries", default_value = "0")]
|
||||||
retries: i32,
|
retries: i32,
|
||||||
#[structopt(flatten)]
|
|
||||||
secret_gen: SecretGeneration,
|
|
||||||
},
|
},
|
||||||
/// Generate a new FIDO credential
|
/// Generate a new FIDO credential
|
||||||
#[structopt(name = "credential")]
|
#[structopt(name = "credential")]
|
||||||
Credential {
|
Credential {
|
||||||
|
#[structopt(flatten)]
|
||||||
|
authenticator: AuthenticatorParameters,
|
||||||
/// Name to be displayed on the authenticator if it has a display
|
/// Name to be displayed on the authenticator if it has a display
|
||||||
#[structopt(env = "FIDO2LUKS_CREDENTIAL_NAME")]
|
#[structopt(env = "FIDO2LUKS_CREDENTIAL_NAME")]
|
||||||
name: Option<String>,
|
name: Option<String>,
|
||||||
@@ -177,96 +276,209 @@ pub fn parse_cmdline() -> Args {
|
|||||||
pub fn run_cli() -> Fido2LuksResult<()> {
|
pub fn run_cli() -> Fido2LuksResult<()> {
|
||||||
let mut stdout = io::stdout();
|
let mut stdout = io::stdout();
|
||||||
let args = parse_cmdline();
|
let args = parse_cmdline();
|
||||||
|
let interactive = args.interactive;
|
||||||
match &args.command {
|
match &args.command {
|
||||||
Command::Credential { name } => {
|
Command::Credential {
|
||||||
let cred = make_credential_id(name.as_ref().map(|n| n.as_ref()))?;
|
authenticator,
|
||||||
|
name,
|
||||||
|
} => {
|
||||||
|
let pin_string;
|
||||||
|
let pin = if authenticator.pin {
|
||||||
|
pin_string = read_pin()?;
|
||||||
|
Some(pin_string.as_ref())
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let cred = make_credential_id(name.as_ref().map(|n| n.as_ref()), pin)?;
|
||||||
println!("{}", hex::encode(&cred.id));
|
println!("{}", hex::encode(&cred.id));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Command::PrintSecret {
|
Command::PrintSecret {
|
||||||
binary,
|
binary,
|
||||||
ref secret_gen,
|
authenticator,
|
||||||
|
credentials,
|
||||||
|
secret,
|
||||||
} => {
|
} => {
|
||||||
let secret = secret_gen.patch(&args).obtain_secret()?;
|
let pin_string;
|
||||||
if *binary {
|
let pin = if authenticator.pin {
|
||||||
stdout.write(&secret[..])?;
|
pin_string = read_pin()?;
|
||||||
|
Some(pin_string.as_ref())
|
||||||
} else {
|
} else {
|
||||||
stdout.write(hex::encode(&secret[..]).as_bytes())?;
|
None
|
||||||
|
};
|
||||||
|
let salt = if interactive || secret.password_helper == PasswordHelper::Stdin {
|
||||||
|
util::read_password_hashed("Password", false)
|
||||||
|
} else {
|
||||||
|
secret.salt.obtain(&secret.password_helper)
|
||||||
|
}?;
|
||||||
|
let secret = derive_secret(
|
||||||
|
credentials.ids.0.as_slice(),
|
||||||
|
&salt,
|
||||||
|
authenticator.await_time,
|
||||||
|
pin,
|
||||||
|
)?;
|
||||||
|
if *binary {
|
||||||
|
stdout.write_all(&secret[..])?;
|
||||||
|
} else {
|
||||||
|
stdout.write_all(hex::encode(&secret[..]).as_bytes())?;
|
||||||
}
|
}
|
||||||
Ok(stdout.flush()?)
|
Ok(stdout.flush()?)
|
||||||
}
|
}
|
||||||
Command::AddKey {
|
Command::AddKey {
|
||||||
device,
|
luks,
|
||||||
exclusive,
|
authenticator,
|
||||||
keyfile,
|
credentials,
|
||||||
ref secret_gen,
|
secret,
|
||||||
|
luks_mod,
|
||||||
|
existing_secret: other_secret,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
| Command::ReplaceKey {
|
||||||
|
luks,
|
||||||
|
authenticator,
|
||||||
|
credentials,
|
||||||
|
secret,
|
||||||
|
luks_mod,
|
||||||
|
replacement: other_secret,
|
||||||
|
..
|
||||||
} => {
|
} => {
|
||||||
let secret = secret_gen.patch(&args).obtain_secret()?;
|
let pin = if authenticator.pin {
|
||||||
let old_secret = if let Some(keyfile) = keyfile.clone() {
|
Some(read_pin()?)
|
||||||
util::read_keyfile(keyfile.clone())
|
|
||||||
} else {
|
} else {
|
||||||
util::read_password("Old password", false).map(|p| p.as_bytes().to_vec())
|
None
|
||||||
}?;
|
};
|
||||||
let added_slot = luks::add_key(device.clone(), &secret, &old_secret[..], Some(10))?;
|
let salt = |q: &str, verify: bool| -> Fido2LuksResult<[u8; 32]> {
|
||||||
|
if interactive || secret.password_helper == PasswordHelper::Stdin {
|
||||||
|
util::read_password_hashed(q, verify)
|
||||||
|
} else {
|
||||||
|
secret.salt.obtain(&secret.password_helper)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let other_secret = |salt_q: &str, verify: bool| -> Fido2LuksResult<Vec<u8>> {
|
||||||
|
match other_secret {
|
||||||
|
OtherSecret {
|
||||||
|
keyfile: Some(file),
|
||||||
|
..
|
||||||
|
} => util::read_keyfile(file),
|
||||||
|
OtherSecret {
|
||||||
|
fido_device: true, ..
|
||||||
|
} => Ok(derive_secret(
|
||||||
|
&credentials.ids.0,
|
||||||
|
&salt(salt_q, verify)?,
|
||||||
|
authenticator.await_time,
|
||||||
|
pin.as_deref(),
|
||||||
|
)?[..]
|
||||||
|
.to_vec()),
|
||||||
|
_ => Ok(util::read_password(salt_q, verify)?.as_bytes().to_vec()),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let secret = |verify: bool| -> Fido2LuksResult<[u8; 32]> {
|
||||||
|
derive_secret(
|
||||||
|
&credentials.ids.0,
|
||||||
|
&salt("Password", verify)?,
|
||||||
|
authenticator.await_time,
|
||||||
|
pin.as_deref(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
// Non overlap
|
||||||
|
match &args.command {
|
||||||
|
Command::AddKey { exclusive, .. } => {
|
||||||
|
let existing_secret = other_secret("Current password", false)?;
|
||||||
|
let new_secret = secret(true)?;
|
||||||
|
let added_slot = luks::add_key(
|
||||||
|
&luks.device,
|
||||||
|
&new_secret,
|
||||||
|
&existing_secret[..],
|
||||||
|
luks_mod.kdf_time.or(Some(10)),
|
||||||
|
)?;
|
||||||
if *exclusive {
|
if *exclusive {
|
||||||
let destroyed = luks::remove_keyslots(&device, &[added_slot])?;
|
let destroyed = luks::remove_keyslots(&luks.device, &[added_slot])?;
|
||||||
println!(
|
println!(
|
||||||
"Added to key to device {}, slot: {}\nRemoved {} old keys",
|
"Added to key to device {}, slot: {}\nRemoved {} old keys",
|
||||||
device.display(),
|
luks.device.display(),
|
||||||
added_slot,
|
added_slot,
|
||||||
destroyed
|
destroyed
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
println!(
|
println!(
|
||||||
"Added to key to device {}, slot: {}",
|
"Added to key to device {}, slot: {}",
|
||||||
device.display(),
|
luks.device.display(),
|
||||||
added_slot
|
added_slot
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Command::ReplaceKey {
|
Command::ReplaceKey { add_password, .. } => {
|
||||||
device,
|
let existing_secret = secret(false)?;
|
||||||
add_password,
|
let replacement_secret = other_secret("Replacement password", true)?;
|
||||||
keyfile,
|
|
||||||
ref secret_gen,
|
|
||||||
} => {
|
|
||||||
let secret = secret_gen.patch(&args).obtain_secret()?;
|
|
||||||
let new_secret = if let Some(keyfile) = keyfile.clone() {
|
|
||||||
util::read_keyfile(keyfile.clone())
|
|
||||||
} else {
|
|
||||||
util::read_password("Password to add", *add_password).map(|p| p.as_bytes().to_vec())
|
|
||||||
}?;
|
|
||||||
let slot = if *add_password {
|
let slot = if *add_password {
|
||||||
luks::add_key(device, &new_secret[..], &secret, None)
|
luks::add_key(
|
||||||
|
&luks.device,
|
||||||
|
&replacement_secret[..],
|
||||||
|
&existing_secret,
|
||||||
|
luks_mod.kdf_time,
|
||||||
|
)
|
||||||
} else {
|
} else {
|
||||||
luks::replace_key(device, &new_secret[..], &secret, Some(5))
|
luks::replace_key(
|
||||||
|
&luks.device,
|
||||||
|
&replacement_secret[..],
|
||||||
|
&existing_secret,
|
||||||
|
luks_mod.kdf_time,
|
||||||
|
)
|
||||||
}?;
|
}?;
|
||||||
println!(
|
println!(
|
||||||
"Added to password to device {}, slot: {}",
|
"Added to password to device {}, slot: {}",
|
||||||
device.display(),
|
luks.device.display(),
|
||||||
slot
|
slot
|
||||||
);
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
Command::Open {
|
Command::Open {
|
||||||
device,
|
luks,
|
||||||
|
authenticator,
|
||||||
|
credentials,
|
||||||
|
secret,
|
||||||
name,
|
name,
|
||||||
retries,
|
retries,
|
||||||
ref secret_gen,
|
|
||||||
} => {
|
} => {
|
||||||
|
let pin_string;
|
||||||
|
let pin = if authenticator.pin {
|
||||||
|
pin_string = read_pin()?;
|
||||||
|
Some(pin_string.as_ref())
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let salt = |q: &str, verify: bool| -> Fido2LuksResult<[u8; 32]> {
|
||||||
|
if interactive || secret.password_helper == PasswordHelper::Stdin {
|
||||||
|
util::read_password_hashed(q, verify)
|
||||||
|
} else {
|
||||||
|
secret.salt.obtain(&secret.password_helper)
|
||||||
|
}
|
||||||
|
};
|
||||||
let mut retries = *retries;
|
let mut retries = *retries;
|
||||||
loop {
|
loop {
|
||||||
let secret = secret_gen.patch(&args).obtain_secret()?;
|
match derive_secret(
|
||||||
match luks::open_container(&device, &name, &secret) {
|
&credentials.ids.0,
|
||||||
Err(e) => match e {
|
&salt("Password", false)?,
|
||||||
Fido2LuksError::WrongSecret if retries > 0 => {
|
authenticator.await_time,
|
||||||
|
pin,
|
||||||
|
)
|
||||||
|
.and_then(|secret| luks::open_container(&luks.device, &name, &secret, luks.slot))
|
||||||
|
{
|
||||||
|
Err(e) => {
|
||||||
|
match e {
|
||||||
|
Fido2LuksError::WrongSecret if retries > 0 => {}
|
||||||
|
Fido2LuksError::AuthenticatorError { ref cause }
|
||||||
|
if cause.kind() == FidoErrorKind::Timeout && retries > 0 => {}
|
||||||
|
|
||||||
|
e => return Err(e),
|
||||||
|
}
|
||||||
retries -= 1;
|
retries -= 1;
|
||||||
eprintln!("{}", e);
|
eprintln!("{}", e);
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
e => Err(e)?,
|
|
||||||
},
|
|
||||||
res => break res,
|
res => break res,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -24,7 +24,7 @@ impl Default for InputSalt {
|
|||||||
|
|
||||||
impl From<&str> for InputSalt {
|
impl From<&str> for InputSalt {
|
||||||
fn from(s: &str) -> Self {
|
fn from(s: &str) -> Self {
|
||||||
let mut parts = s.split(":").into_iter();
|
let mut parts = s.split(':');
|
||||||
match parts.next() {
|
match parts.next() {
|
||||||
Some("ask") | Some("Ask") => InputSalt::AskPassword,
|
Some("ask") | Some("Ask") => InputSalt::AskPassword,
|
||||||
Some("file") => InputSalt::File {
|
Some("file") => InputSalt::File {
|
||||||
@@ -84,9 +84,10 @@ impl InputSalt {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum PasswordHelper {
|
pub enum PasswordHelper {
|
||||||
Script(String),
|
Script(String),
|
||||||
|
#[allow(dead_code)]
|
||||||
Systemd,
|
Systemd,
|
||||||
Stdin,
|
Stdin,
|
||||||
}
|
}
|
||||||
@@ -134,7 +135,7 @@ impl PasswordHelper {
|
|||||||
Systemd => unimplemented!(),
|
Systemd => unimplemented!(),
|
||||||
Stdin => Ok(util::read_password("Password", true)?),
|
Stdin => Ok(util::read_password("Password", true)?),
|
||||||
Script(password_helper) => {
|
Script(password_helper) => {
|
||||||
let mut helper_parts = password_helper.split(" ");
|
let mut helper_parts = password_helper.split(' ');
|
||||||
|
|
||||||
let password = Command::new((&mut helper_parts).next().unwrap())
|
let password = Command::new((&mut helper_parts).next().unwrap())
|
||||||
.args(helper_parts)
|
.args(helper_parts)
|
||||||
|
128
src/device.rs
128
src/device.rs
@@ -1,91 +1,61 @@
|
|||||||
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: &str = "fido2luks";
|
||||||
|
|
||||||
fn authenticator_options() -> Option<AuthenticatorOptions> {
|
pub fn make_credential_id(
|
||||||
Some(AuthenticatorOptions {
|
name: Option<&str>,
|
||||||
uv: false, //TODO: should get this from config
|
pin: Option<&str>,
|
||||||
rk: true,
|
) -> Fido2LuksResult<FidoCredential> {
|
||||||
})
|
let mut request = FidoCredentialRequestBuilder::default().rp_id(RP_ID);
|
||||||
}
|
if let Some(user_name) = name {
|
||||||
|
request = request.user_name(user_name);
|
||||||
fn authenticator_rp() -> PublicKeyCredentialRpEntity<'static> {
|
|
||||||
PublicKeyCredentialRpEntity {
|
|
||||||
id: RP_ID,
|
|
||||||
name: None,
|
|
||||||
icon: None,
|
|
||||||
}
|
}
|
||||||
}
|
let request = request.build().unwrap();
|
||||||
|
let make_credential = |device: &mut FidoDevice| {
|
||||||
fn authenticator_user(name: Option<&str>) -> PublicKeyCredentialUserEntity {
|
if let Some(pin) = pin {
|
||||||
PublicKeyCredentialUserEntity {
|
device.unlock(pin)?;
|
||||||
id: &[0u8],
|
|
||||||
name: name.unwrap_or(""),
|
|
||||||
icon: None,
|
|
||||||
display_name: name,
|
|
||||||
}
|
}
|
||||||
}
|
device.make_hmac_credential(&request)
|
||||||
|
|
||||||
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();
|
Ok(request_multiple_devices(
|
||||||
match get_devices()? {
|
get_devices()?
|
||||||
ref devs if devs.is_empty() => Err(Fido2LuksError::NoAuthenticatorError)?,
|
.iter_mut()
|
||||||
devs => {
|
.map(|device| (device, &make_credential)),
|
||||||
for mut dev in devs.into_iter() {
|
None,
|
||||||
match dev.get_hmac_assertion(&cred, &sha256(&[&salt[..]]), None, None) {
|
)?)
|
||||||
Ok(secret) => {
|
}
|
||||||
return Ok(secret.0);
|
|
||||||
|
pub fn perform_challenge(
|
||||||
|
credentials: &[&FidoCredential],
|
||||||
|
salt: &[u8; 32],
|
||||||
|
timeout: Duration,
|
||||||
|
pin: Option<&str>,
|
||||||
|
) -> Fido2LuksResult<[u8; 32]> {
|
||||||
|
let request = FidoAssertionRequestBuilder::default()
|
||||||
|
.rp_id(RP_ID)
|
||||||
|
.credentials(credentials)
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
let get_assertion = |device: &mut FidoDevice| {
|
||||||
|
if let Some(pin) = pin {
|
||||||
|
device.unlock(pin)?;
|
||||||
}
|
}
|
||||||
Err(e) => {
|
device.get_hmac_assertion(&request, &util::sha256(&[&salt[..]]), None)
|
||||||
errs.push(e);
|
};
|
||||||
}
|
let (_, (secret, _)) = request_multiple_devices(
|
||||||
}
|
get_devices()?
|
||||||
}
|
.iter_mut()
|
||||||
}
|
.map(|device| (device, &get_assertion)),
|
||||||
}
|
Some(timeout),
|
||||||
Err(errs.pop().ok_or(Fido2LuksError::NoAuthenticatorError)?)?
|
)?;
|
||||||
|
Ok(secret)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_devices() -> Fido2LuksResult<Vec<FidoDevice>> {
|
pub fn get_devices() -> Fido2LuksResult<Vec<FidoDevice>> {
|
||||||
@@ -94,7 +64,7 @@ pub fn get_devices() -> Fido2LuksResult<Vec<FidoDevice>> {
|
|||||||
match FidoDevice::new(&di) {
|
match FidoDevice::new(&di) {
|
||||||
Err(e) => match e.kind() {
|
Err(e) => match e.kind() {
|
||||||
FidoErrorKind::ParseCtap | FidoErrorKind::DeviceUnsupported => (),
|
FidoErrorKind::ParseCtap | FidoErrorKind::DeviceUnsupported => (),
|
||||||
err => Err(FidoError::from(err))?,
|
err => return Err(FidoError::from(err).into()),
|
||||||
},
|
},
|
||||||
Ok(dev) => devices.push(dev),
|
Ok(dev) => devices.push(dev),
|
||||||
}
|
}
|
||||||
|
17
src/luks.rs
17
src/luks.rs
@@ -11,18 +11,18 @@ fn load_device_handle<P: AsRef<Path>>(path: P) -> Fido2LuksResult<CryptDevice> {
|
|||||||
.into_iter()
|
.into_iter()
|
||||||
.fold(None, |res, format| match res {
|
.fold(None, |res, format| match res {
|
||||||
Some(Ok(())) => res,
|
Some(Ok(())) => res,
|
||||||
Some(e) => Some(e.or(load(format))),
|
Some(e) => Some(e.or_else(|_| load(format))),
|
||||||
None => Some(load(format)),
|
None => Some(load(format)),
|
||||||
})
|
})
|
||||||
.unwrap()?;
|
.unwrap()?;
|
||||||
Ok(device)
|
Ok(device)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn open_container<P: AsRef<Path>>(path: P, name: &str, secret: &[u8]) -> Fido2LuksResult<()> {
|
pub fn open_container<P: AsRef<Path>>(path: P, name: &str, secret: &[u8], slot_hint: Option<u32>) -> Fido2LuksResult<()> {
|
||||||
let mut device = load_device_handle(path)?;
|
let mut device = load_device_handle(path)?;
|
||||||
device
|
device
|
||||||
.activate_handle()
|
.activate_handle()
|
||||||
.activate_by_passphrase(Some(name), None, secret, CryptActivateFlags::empty())
|
.activate_by_passphrase(Some(name), slot_hint, secret, CryptActivateFlags::empty())
|
||||||
.map(|_slot| ())
|
.map(|_slot| ())
|
||||||
.map_err(|_e| Fido2LuksError::WrongSecret)
|
.map_err(|_e| Fido2LuksError::WrongSecret)
|
||||||
}
|
}
|
||||||
@@ -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)
|
||||||
}
|
}
|
||||||
@@ -46,10 +45,10 @@ pub fn add_key<P: AsRef<Path>>(
|
|||||||
|
|
||||||
pub fn remove_keyslots<P: AsRef<Path>>(path: P, exclude: &[u32]) -> Fido2LuksResult<u32> {
|
pub fn remove_keyslots<P: AsRef<Path>>(path: P, exclude: &[u32]) -> Fido2LuksResult<u32> {
|
||||||
let mut device = load_device_handle(path)?;
|
let mut device = load_device_handle(path)?;
|
||||||
let mut slot = 0;
|
|
||||||
let mut handle;
|
let mut handle;
|
||||||
let mut destroyed = 0;
|
let mut destroyed = 0;
|
||||||
loop {
|
//TODO: detect how many keyslots there are instead of trying within a given range
|
||||||
|
for slot in 0..1024 {
|
||||||
handle = device.keyslot_handle(Some(slot));
|
handle = device.keyslot_handle(Some(slot));
|
||||||
match handle.status()? {
|
match handle.status()? {
|
||||||
KeyslotInfo::Inactive => continue,
|
KeyslotInfo::Inactive => continue,
|
||||||
@@ -59,11 +58,9 @@ pub fn remove_keyslots<P: AsRef<Path>>(path: P, exclude: &[u32]) -> Fido2LuksRes
|
|||||||
}
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
match handle.status()? {
|
if let KeyslotInfo::ActiveLast = handle.status()? {
|
||||||
KeyslotInfo::ActiveLast => break,
|
break;
|
||||||
_ => (),
|
|
||||||
}
|
}
|
||||||
slot += 1;
|
|
||||||
}
|
}
|
||||||
Ok(destroyed)
|
Ok(destroyed)
|
||||||
}
|
}
|
||||||
|
21
src/main.rs
21
src/main.rs
@@ -16,10 +16,6 @@ mod error;
|
|||||||
mod luks;
|
mod luks;
|
||||||
mod util;
|
mod util;
|
||||||
|
|
||||||
fn assemble_secret(hmac_result: &[u8], salt: &[u8]) -> [u8; 32] {
|
|
||||||
util::sha256(&[salt, hmac_result])
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() -> Fido2LuksResult<()> {
|
fn main() -> Fido2LuksResult<()> {
|
||||||
match run_cli() {
|
match run_cli() {
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -32,20 +28,3 @@ fn main() -> Fido2LuksResult<()> {
|
|||||||
_ => exit(0),
|
_ => exit(0),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod test {
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_assemble_secret() {
|
|
||||||
assert_eq!(
|
|
||||||
assemble_secret(b"abc", b"def"),
|
|
||||||
[
|
|
||||||
46, 82, 82, 140, 142, 159, 249, 196, 227, 160, 142, 72, 151, 77, 59, 62, 180, 36,
|
|
||||||
33, 47, 241, 94, 17, 232, 133, 103, 247, 32, 152, 253, 43, 19
|
|
||||||
]
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@@ -4,7 +4,7 @@ use std::fs::File;
|
|||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
pub fn sha256<'a>(messages: &[&[u8]]) -> [u8; 32] {
|
pub fn sha256(messages: &[&[u8]]) -> [u8; 32] {
|
||||||
let mut digest = digest::Context::new(&digest::SHA256);
|
let mut digest = digest::Context::new(&digest::SHA256);
|
||||||
for m in messages.iter() {
|
for m in messages.iter() {
|
||||||
digest.update(m);
|
digest.update(m);
|
||||||
@@ -23,12 +23,16 @@ pub fn read_password(q: &str, verify: bool) -> Fido2LuksResult<String> {
|
|||||||
{
|
{
|
||||||
Err(Fido2LuksError::AskPassError {
|
Err(Fido2LuksError::AskPassError {
|
||||||
cause: AskPassError::Mismatch,
|
cause: AskPassError::Mismatch,
|
||||||
})?
|
})
|
||||||
}
|
}
|
||||||
pass => Ok(pass),
|
pass => Ok(pass),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn read_password_hashed(q: &str, verify: bool) -> Fido2LuksResult<[u8; 32]> {
|
||||||
|
read_password(q, verify).map(|pass| sha256(&[pass.as_bytes()]))
|
||||||
|
}
|
||||||
|
|
||||||
pub fn read_keyfile<P: Into<PathBuf>>(path: P) -> Fido2LuksResult<Vec<u8>> {
|
pub fn read_keyfile<P: Into<PathBuf>>(path: P) -> Fido2LuksResult<Vec<u8>> {
|
||||||
let mut file = File::open(path.into())?;
|
let mut file = File::open(path.into())?;
|
||||||
let mut key = Vec::new();
|
let mut key = Vec::new();
|
||||||
|
Reference in New Issue
Block a user