proper error messages
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone/pr Build is failing

This commit is contained in:
shimun 2020-09-29 19:21:34 +02:00
parent fbbf606631
commit f6627d887b
Signed by: shimun
GPG Key ID: E81D8382DC2F971B
3 changed files with 77 additions and 25 deletions

View File

@ -34,6 +34,7 @@ ring = "0.13.5"
failure = "0.1.5" failure = "0.1.5"
rpassword = "4.0.1" rpassword = "4.0.1"
libcryptsetup-rs = "0.4.1" libcryptsetup-rs = "0.4.1"
pamsm = { version = "0.4.1", features = ["libpam"] }
structopt = "0.3.2" structopt = "0.3.2"
[profile.release] [profile.release]

View File

@ -1,10 +1,10 @@
use ctap::FidoError; use ctap::FidoError;
use libcryptsetup_rs::LibcryptErr; use libcryptsetup_rs::LibcryptErr;
use pamsm::PamError;
use std::io; use std::io;
use std::io::ErrorKind; use std::io::ErrorKind;
use std::string::FromUtf8Error; use std::string::FromUtf8Error;
use Fido2LuksError::*; use Fido2LuksError::*;
pub type Fido2LuksResult<T> = Result<T, Fido2LuksError>; pub type Fido2LuksResult<T> = Result<T, Fido2LuksError>;
#[derive(Debug, Fail)] #[derive(Debug, Fail)]
@ -29,6 +29,10 @@ pub enum Fido2LuksError {
WrongSecret, WrongSecret,
#[fail(display = "not an utf8 string")] #[fail(display = "not an utf8 string")]
StringEncodingError { cause: FromUtf8Error }, StringEncodingError { cause: FromUtf8Error },
#[fail(display = "elevated privileges required")]
MissingPrivileges,
#[fail(display = "{}", cause)]
Configuration { cause: ConfigurationError },
} }
impl Fido2LuksError { impl Fido2LuksError {
@ -50,6 +54,20 @@ pub enum AskPassError {
IO(io::Error), IO(io::Error),
#[fail(display = "provided passwords don't match")] #[fail(display = "provided passwords don't match")]
Mismatch, Mismatch,
#[fail(display = "unable to retrieve password: {}", _0)]
Pam(PamError),
}
impl From<PamError> for AskPassError {
fn from(e: PamError) -> Self {
AskPassError::Pam(e)
}
}
impl From<io::Error> for AskPassError {
fn from(e: io::Error) -> Self {
AskPassError::IO(e)
}
} }
#[derive(Debug, Fail)] #[derive(Debug, Fail)]
@ -112,3 +130,16 @@ impl From<FromUtf8Error> for Fido2LuksError {
StringEncodingError { cause: e } StringEncodingError { cause: e }
} }
} }
#[derive(Debug, Fail)]
pub enum ConfigurationError {
#[fail(display = "config is missing some values: {:?}", _0)]
Missing(Vec<String>),
#[fail(display = "config attribute {} contains an invalid value: {}", _1, _0)]
InvalidValue(String, String),
}
impl From<ConfigurationError> for Fido2LuksError {
fn from(cause: ConfigurationError) -> Fido2LuksError {
Fido2LuksError::Configuration { cause }
}
}

View File

@ -3,8 +3,6 @@ extern crate failure;
extern crate ctap_hmac as ctap; extern crate ctap_hmac as ctap;
#[macro_use] #[macro_use]
extern crate serde_derive; extern crate serde_derive;
#[macro_use]
extern crate pamsm;
use crate::cli_args::{CommaSeparated, HexEncoded}; use crate::cli_args::{CommaSeparated, HexEncoded};
use crate::device::*; use crate::device::*;
use crate::error::*; use crate::error::*;
@ -14,7 +12,6 @@ use failure::_core::time::Duration;
use pamsm::PamLibExt; use pamsm::PamLibExt;
use pamsm::*; use pamsm::*;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::ffi::CStr;
use std::path::Path; use std::path::Path;
use std::str::FromStr; use std::str::FromStr;
use sudo::{self, RunningAs}; use sudo::{self, RunningAs};
@ -45,15 +42,19 @@ impl PamFido2Luks {
}) })
.collect(); .collect();
let credentials = args let credentials = match args.get("credentials").map(|creds| {
.get("credentials") <CommaSeparated<String>>::from_str(creds)
.map(|creds| { .map(|cs| cs.0)
<CommaSeparated<String>>::from_str(creds) .map_err(|_| ConfigurationError::InvalidValue("credentials".into(), creds.into()))
.expect("Invalid credentials") }) {
.0 //TODO: proper error handling Some(creds) => creds?,
}) _ => Vec::new(),
.unwrap_or_default(); };
let pin = args.get("pin"); let pin = args.get("pin");
let pin_prefix = args
.get("pin-prefix")
.map(|p| p.parse::<bool>().unwrap_or_default())
.unwrap_or_default();
let device = args let device = args
.get("device") .get("device")
.map(|device| device.replace("%user%", user.as_str())); .map(|device| device.replace("%user%", user.as_str()));
@ -61,7 +62,7 @@ impl PamFido2Luks {
.get("name") .get("name")
.map(|name| name.replace("%user%", user.as_str())); .map(|name| name.replace("%user%", user.as_str()));
let attempts = args let mut attempts = args
.get("attempts") .get("attempts")
.and_then(|a| a.parse::<usize>().ok()) .and_then(|a| a.parse::<usize>().ok())
.unwrap_or(3); .unwrap_or(3);
@ -73,10 +74,7 @@ impl PamFido2Luks {
} }
// root required to mount luks // root required to mount luks
match sudo::check() { match sudo::check() {
RunningAs::User => { RunningAs::User => return Err(Fido2LuksError::MissingPrivileges),
//err
unimplemented!("no root")
}
_ => { _ => {
sudo::escalate_if_needed().unwrap(); sudo::escalate_if_needed().unwrap();
} }
@ -100,32 +98,54 @@ impl PamFido2Luks {
.collect(); .collect();
let credentials: Vec<&FidoCredential> = credentials.iter().collect(); let credentials: Vec<&FidoCredential> = credentials.iter().collect();
if !credentials.is_empty() { if !credentials.is_empty() {
for _ in 0..attempts { loop {
let salt = util::sha256(&[password().expect("Password").as_bytes()]); let (pin, pass) = if pin_prefix {
let password = password()
.map_err(|e| Fido2LuksError::AskPassError { cause: e.into() })?;
let mut parts = password.split(":");
(
parts.next().map(|p| p.to_string()).or(pin.cloned()),
parts.collect::<Vec<_>>().join(":"),
)
} else {
(
pin.cloned(),
password()
.map_err(|e| Fido2LuksError::AskPassError { cause: e.into() })?,
)
};
let salt = util::sha256(&[pass.as_bytes()]);
let secret = util::sha256(&[ let secret = util::sha256(&[
&salt, &salt,
&perform_challenge( &perform_challenge(
&credentials[..], &credentials[..],
&salt, &salt,
Duration::from_secs(15), Duration::from_secs(15),
pin.map(AsRef::as_ref), pin.as_ref().map(String::as_str),
)? )?
.0[..], .0[..],
]); ]);
device.activate(name.as_str(), &secret[..], None)?; match device.activate(name.as_str(), &secret[..], None) {
Ok(_) => return Ok(()),
_ if attempts > 0 => {
attempts -= 1;
continue;
}
Err(e) => break Err(e),
}
} }
Ok(())
} else { } else {
unimplemented!("custom error") Err(ConfigurationError::Missing(vec!["credentials".into()]).into())
} }
} else { } else {
unimplemented!("custom error") Ok(())
} }
} }
} }
impl PamServiceModule for PamFido2Luks { impl PamServiceModule for PamFido2Luks {
fn authenticate(pamh: Pam, flag: PamFlag, args: Vec<String>) -> PamError { fn authenticate(pamh: Pam, _flag: PamFlag, args: Vec<String>) -> PamError {
let user = match pamh.get_cached_user() { let user = match pamh.get_cached_user() {
Err(_) => return dbg!(PamError::AUTH_ERR), Err(_) => return dbg!(PamError::AUTH_ERR),
Ok(p) => p.map(|s| s.to_str().map(str::to_string).unwrap()), Ok(p) => p.map(|s| s.to_str().map(str::to_string).unwrap()),