Added --await-dev flag
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
shimun 2020-01-13 23:23:45 +01:00
parent 7429706920
commit c4e08413c0
Signed by: shimun
GPG Key ID: E81D8382DC2F971B
3 changed files with 55 additions and 15 deletions

View File

@ -9,7 +9,7 @@ MOUNT=$(command -v mount)
UMOUNT=$(command -v umount) UMOUNT=$(command -v umount)
TIMEOUT=120 TIMEOUT=120
CON_MSG="Please connect your authenicator" CON_MSG="Please connect your authenticator"
generate_service () { generate_service () {
local credential_id=$1 target_uuid=$2 timeout=$3 sd_dir=${4:-$NORMAL_DIR} local credential_id=$1 target_uuid=$2 timeout=$3 sd_dir=${4:-$NORMAL_DIR}
@ -19,6 +19,10 @@ generate_service () {
local crypto_target_service="systemd-cryptsetup@luks\x2d${sd_target_uuid}.service" local crypto_target_service="systemd-cryptsetup@luks\x2d${sd_target_uuid}.service"
local sd_service="${sd_dir}/luks-2fa@luks\x2d${sd_target_uuid}.service" local sd_service="${sd_dir}/luks-2fa@luks\x2d${sd_target_uuid}.service"
local fido2luks_args="--bin"
if [ ! -z "$timeout" ]; then
fido2luks_args="$fido2luks_args --await-dev ${timeout}"
fi
{ {
printf -- "[Unit]" printf -- "[Unit]"
printf -- "\nDescription=%s" "2fa for luks" printf -- "\nDescription=%s" "2fa for luks"
@ -27,18 +31,15 @@ generate_service () {
printf -- "\nBefore=%s umount.target luks-2fa.target" "$crypto_target_service" printf -- "\nBefore=%s umount.target luks-2fa.target" "$crypto_target_service"
printf -- "\nConflicts=umount.target" printf -- "\nConflicts=umount.target"
printf -- "\nDefaultDependencies=no" printf -- "\nDefaultDependencies=no"
printf -- "\nJobTimeoutSec=%s" "$timeout" [ ! -z "$timeout" ] && printf -- "\nJobTimeoutSec=%s" "$timeout"
printf -- "\n\n[Service]" printf -- "\n\n[Service]"
printf -- "\nType=oneshot" printf -- "\nType=oneshot"
printf -- "\nRemainAfterExit=yes" printf -- "\nRemainAfterExit=yes"
printf -- "\nEnvironmentFile=%s" "/etc/fido2luks.conf" printf -- "\nEnvironmentFile=%s" "/etc/fido2luks.conf"
printf -- "\nEnvironment=FIDO2LUKS_CREDENTIAL_ID='%s'" "$credential_id" [ ! -z "$credential_id" ] && printf -- "\nEnvironment=FIDO2LUKS_CREDENTIAL_ID='%s'" "$credential_id"
printf -- "\nKeyringMode=%s" "shared" printf -- "\nKeyringMode=%s" "shared"
printf -- "\nExecStartPre=-/usr/bin/plymouth display-message --text \"${CON_MSG}\"" printf -- "\nExecStartPre=-/usr/bin/plymouth display-message --text \"${CON_MSG}\""
printf -- "\nExecStartPre=-/bin/bash -c \"while ! ${FIDO2LUKS} connected; do /usr/bin/sleep 1; done\"" printf -- "\nExecStart=/bin/bash -c \"${FIDO2LUKS} print-secret $fido2luks_args | ${CRYPTSETUP} attach 'luks-%s' '/dev/disk/by-uuid/%s' '/dev/stdin'\"" "$target_uuid" "$target_uuid"
printf -- "\nExecStartPre=-/usr/bin/plymouth hide-message --text \"${CON_MSG}\""
printf -- "\nExecStart=/bin/bash -c \"${FIDO2LUKS} print-secret --bin | ${CRYPTSETUP} attach 'luks-%s' '/dev/disk/by-uuid/%s' '/dev/stdin'\"" "$target_uuid" "$target_uuid"
printf -- "\nExecStop=${CRYPTSETUP} detach 'luks-%s'" "$target_uuid" printf -- "\nExecStop=${CRYPTSETUP} detach 'luks-%s'" "$target_uuid"
} > "$sd_service" } > "$sd_service"

View File

@ -8,9 +8,16 @@ use cryptsetup_rs::{CryptDevice, Luks1CryptDevice};
use libcryptsetup_sys::crypt_keyslot_info; use libcryptsetup_sys::crypt_keyslot_info;
use structopt::StructOpt; use structopt::StructOpt;
use failure::_core::fmt::{Error, Formatter};
use failure::_core::str::FromStr;
use failure::_core::time::Duration;
use std::io::Write; use std::io::Write;
use std::process::exit;
use std::io::stdout;
use std::process::exit;
use std::thread;
use std::time::SystemTime;
pub fn add_key_to_luks( pub fn add_key_to_luks(
device: PathBuf, device: PathBuf,
secret: &[u8; 32], secret: &[u8; 32],
@ -70,6 +77,23 @@ pub fn add_password_to_luks(
Ok(slot) Ok(slot)
} }
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct HexEncoded(Vec<u8>);
impl std::fmt::Display for HexEncoded {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
f.write_str(&hex::encode(&self.0))
}
}
impl FromStr for HexEncoded {
type Err = hex::FromHexError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(HexEncoded(hex::decode(s)?))
}
}
#[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
@ -83,7 +107,7 @@ pub struct Args {
pub struct SecretGeneration { pub struct SecretGeneration {
/// FIDO credential id, generate using fido2luks credential /// FIDO credential id, generate using fido2luks credential
#[structopt(name = "credential-id", env = "FIDO2LUKS_CREDENTIAL_ID")] #[structopt(name = "credential-id", env = "FIDO2LUKS_CREDENTIAL_ID")]
pub credential_id: String, pub credential_id: HexEncoded,
/// Salt for secret generation, defaults to 'ask' /// Salt for secret generation, defaults to 'ask'
/// ///
/// Options:{n} /// Options:{n}
@ -104,6 +128,10 @@ 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")]
pub await_authenticator: Option<u64>,
} }
impl SecretGeneration { impl SecretGeneration {
@ -117,8 +145,20 @@ impl SecretGeneration {
pub fn obtain_secret(&self) -> Fido2LuksResult<[u8; 32]> { pub fn obtain_secret(&self) -> Fido2LuksResult<[u8; 32]> {
let salt = self.salt.obtain(&self.password_helper)?; let salt = self.salt.obtain(&self.password_helper)?;
if let Some(timeout) = self.await_authenticator.map(Duration::from_secs) {
let start = SystemTime::now();
while start
.elapsed()
.map(|el| el < timeout)
.ok()
.and_then(|el| get_devices().map(|devs| el && devs.is_empty()).ok())
.unwrap_or(false)
{
thread::sleep(Duration::from_millis(500));
}
}
Ok(assemble_secret( Ok(assemble_secret(
&perform_challenge(&self.credential_id, &salt)?, &perform_challenge(&self.credential_id.0, &salt)?,
&salt, &salt,
)) ))
} }
@ -142,13 +182,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 a password /// Use a keyfile instead of typing a previous password
#[structopt(short = "d", long = "keyfile")] #[structopt(short = "d", long = "keyfile")]
keyfile: Option<PathBuf>, keyfile: Option<PathBuf>,
#[structopt(flatten)] #[structopt(flatten)]
secret_gen: SecretGeneration, secret_gen: SecretGeneration,
}, },
/// 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 {
@ -157,7 +196,7 @@ 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 a password /// Use a keyfile instead of typing a previous password
#[structopt(short = "d", long = "keyfile")] #[structopt(short = "d", long = "keyfile")]
keyfile: Option<PathBuf>, keyfile: Option<PathBuf>,
#[structopt(flatten)] #[structopt(flatten)]

View File

@ -64,9 +64,9 @@ pub fn make_credential_id(name: Option<&str>) -> Fido2LuksResult<FidoHmacCredent
Err(errs.pop().ok_or(Fido2LuksError::NoAuthenticatorError)?)? Err(errs.pop().ok_or(Fido2LuksError::NoAuthenticatorError)?)?
} }
pub fn perform_challenge(credential_id: &str, salt: &[u8; 32]) -> Fido2LuksResult<[u8; 32]> { pub fn perform_challenge(credential_id: &[u8], salt: &[u8; 32]) -> Fido2LuksResult<[u8; 32]> {
let cred = FidoHmacCredential { let cred = FidoHmacCredential {
id: hex::decode(credential_id).unwrap(), id: credential_id.to_vec(),
rp_id: RP_ID.to_string(), rp_id: RP_ID.to_string(),
}; };
let mut errs = Vec::new(); let mut errs = Vec::new();