Port rsasl

This commit is contained in:
Nadja Reitzenstein 2022-10-05 17:28:47 +02:00
parent ec1cac9443
commit 3cf152a164
6 changed files with 463 additions and 487 deletions

768
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -113,7 +113,7 @@ shadow-rs = "0.11"
[dependencies.rsasl] [dependencies.rsasl]
git = "https://github.com/dequbed/rsasl.git" git = "https://github.com/dequbed/rsasl.git"
rev = "0b5012d0" branch = "development"
default_features = false default_features = false
features = ["unstable_custom_mechanism", "provider", "registry_static", "plain"] features = ["unstable_custom_mechanism", "provider", "registry_static", "plain"]

View File

@ -2,43 +2,23 @@ mod server;
pub use server::FabFire; pub use server::FabFire;
use rsasl::mechname::Mechname; use rsasl::mechname::Mechname;
use rsasl::registry::{Mechanism, MECHANISMS}; use rsasl::registry::{Mechanism, MECHANISMS, Side};
use rsasl::session::Side;
const MECHNAME: &'static Mechname = &Mechname::const_new_unchecked(b"X-FABFIRE"); const MECHNAME: &'static Mechname = &Mechname::const_new_unchecked(b"X-FABFIRE");
#[linkme::distributed_slice(MECHANISMS)] #[linkme::distributed_slice(MECHANISMS)]
pub static FABFIRE: Mechanism = Mechanism { pub static FABFIRE: Mechanism =
mechanism: MECHNAME, Mechanism::build(MECHNAME, 300, None, Some(FabFire::new_server), Side::Client);
priority: 300,
// In this situation there's one struct for both sides, however you can just as well use
// different types than then have different `impl Authentication` instead of checking a value
// in self.
client: None,
server: Some(FabFire::new_server),
first: Side::Client,
};
use rsasl::property::{Property, PropertyDefinition, PropertyQ};
use std::marker::PhantomData; use std::marker::PhantomData;
use rsasl::property::SizedProperty;
// All Property types must implement Debug. // All Property types must implement Debug.
#[derive(Debug)] #[derive(Debug)]
// The `PhantomData` in the constructor is only used so external crates can't construct this type. // The `PhantomData` in the constructor is only used so external crates can't construct this type.
pub struct FabFireCardKey(PhantomData<()>); pub struct FabFireCardKey(PhantomData<()>);
impl PropertyQ for FabFireCardKey {
// This is the type stored for this property. This could also be the struct itself if you impl SizedProperty<'_> for FabFireCardKey {
// so choose type Value = [u8; 16];
type Item = [u8; 16]; const DESCRIPTION: &'static str = "A AES128 key for a FabFire card";
// You need to return the constant you define below here for things to work properly
fn property() -> Property {
FABFIRECARDKEY
} }
}
// This const is used by your mechanism to query and by your users to set your property. It
// thus needs to be exported from your crate
pub const FABFIRECARDKEY: Property = Property::new(&PropertyDefinition::new(
// Short name, used in `Debug` output
"FabFireCardKey",
// A longer user-facing name used in `Display` output
"A AES128 key for a FabFire card",
));

View File

@ -2,11 +2,10 @@ use desfire::desfire::desfire::MAX_BYTES_PER_TRANSACTION;
use desfire::desfire::Desfire; use desfire::desfire::Desfire;
use desfire::error::Error as DesfireError; use desfire::error::Error as DesfireError;
use desfire::iso7816_4::apduresponse::APDUResponse; use desfire::iso7816_4::apduresponse::APDUResponse;
use rsasl::error::{MechanismError, MechanismErrorKind, SASLError, SessionError}; use rsasl::callback::SessionData;
use rsasl::mechanism::Authentication; use rsasl::mechanism::{Authentication, MechanismError, MechanismErrorKind, State, ThisProvider};
use rsasl::prelude::{MessageSent, SASLConfig, SASLError, SessionError};
use rsasl::property::AuthId; use rsasl::property::AuthId;
use rsasl::session::{SessionData, StepResult};
use rsasl::SASL;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::convert::TryFrom; use std::convert::TryFrom;
use std::fmt::{Debug, Display, Formatter}; use std::fmt::{Debug, Display, Formatter};
@ -63,6 +62,10 @@ impl Display for FabFireError {
} }
} }
impl std::error::Error for FabFireError {
}
impl MechanismError for FabFireError { impl MechanismError for FabFireError {
fn kind(&self) -> MechanismErrorKind { fn kind(&self) -> MechanismErrorKind {
match self { match self {
@ -154,7 +157,7 @@ pub struct FabFire {
const MAGIC: &'static str = "FABACCESS\0DESFIRE\01.0\0"; const MAGIC: &'static str = "FABACCESS\0DESFIRE\01.0\0";
impl FabFire { impl FabFire {
pub fn new_server(_sasl: &SASL) -> Result<Box<dyn Authentication>, SASLError> { pub fn new_server(_sasl: &SASLConfig) -> Result<Box<dyn Authentication>, SASLError> {
Ok(Box::new(Self { Ok(Box::new(Self {
step: Step::New, step: Step::New,
card_info: None, card_info: None,
@ -177,7 +180,7 @@ impl Authentication for FabFire {
session: &mut SessionData, session: &mut SessionData,
input: Option<&[u8]>, input: Option<&[u8]>,
writer: &mut dyn Write, writer: &mut dyn Write,
) -> StepResult { ) -> Result<State, SessionError> {
match self.step { match self.step {
Step::New => { Step::New => {
tracing::trace!("Step: New"); tracing::trace!("Step: New");
@ -216,7 +219,7 @@ impl Authentication for FabFire {
writer writer
.write_all(&send_buf) .write_all(&send_buf)
.map_err(|e| SessionError::Io { source: e })?; .map_err(|e| SessionError::Io { source: e })?;
Ok(rsasl::session::Step::NeedsMore(Some(send_buf.len()))) Ok(State::Running)
} }
Err(e) => { Err(e) => {
tracing::error!("Failed to serialize APDUCommand: {:?}", e); tracing::error!("Failed to serialize APDUCommand: {:?}", e);
@ -282,7 +285,7 @@ impl Authentication for FabFire {
writer writer
.write_all(&send_buf) .write_all(&send_buf)
.map_err(|e| SessionError::Io { source: e })?; .map_err(|e| SessionError::Io { source: e })?;
Ok(rsasl::session::Step::NeedsMore(Some(send_buf.len()))) Ok(State::Running)
} }
Err(e) => { Err(e) => {
tracing::error!("Failed to serialize APDUCommand: {:?}", e); tracing::error!("Failed to serialize APDUCommand: {:?}", e);
@ -365,7 +368,7 @@ impl Authentication for FabFire {
writer writer
.write_all(&send_buf) .write_all(&send_buf)
.map_err(|e| SessionError::Io { source: e })?; .map_err(|e| SessionError::Io { source: e })?;
Ok(rsasl::session::Step::NeedsMore(Some(send_buf.len()))) Ok(State::Running)
} }
Err(e) => { Err(e) => {
tracing::error!("Failed to serialize APDUCommand: {:?}", e); tracing::error!("Failed to serialize APDUCommand: {:?}", e);
@ -452,7 +455,7 @@ impl Authentication for FabFire {
writer writer
.write_all(&send_buf) .write_all(&send_buf)
.map_err(|e| SessionError::Io { source: e })?; .map_err(|e| SessionError::Io { source: e })?;
Ok(rsasl::session::Step::NeedsMore(Some(send_buf.len()))) Ok(State::Running)
} }
Err(e) => { Err(e) => {
tracing::error!("Failed to serialize APDUCommand: {:?}", e); tracing::error!("Failed to serialize APDUCommand: {:?}", e);
@ -491,24 +494,9 @@ impl Authentication for FabFire {
match apdu_response.body { match apdu_response.body {
Some(data) => { Some(data) => {
let token = String::from_utf8(data).unwrap(); let token = String::from_utf8(data).unwrap();
session.set_property::<AuthId>(Arc::new( let prov =
token.trim_matches(char::from(0)).to_string(), ThisProvider::<AuthId>::with(token.trim_matches(char::from(0)));
)); let key = session.need_with::<FabFireCardKey, _, _>(&prov, |key| Ok(Box::from(key.as_slice())))?;
let key = match session.get_property_or_callback::<FabFireCardKey>()
{
Ok(Some(key)) => Box::from(key.as_slice()),
Ok(None) => {
tracing::error!("No keys on file for token");
return Err(FabFireError::InvalidCredentials(
"No keys on file for token".to_string(),
)
.into());
}
Err(e) => {
tracing::error!("Failed to get key: {:?}", e);
return Err(FabFireError::Session(e).into());
}
};
self.key_info = Some(KeyInfo { key_id: 0x01, key }); self.key_info = Some(KeyInfo { key_id: 0x01, key });
} }
None => { None => {
@ -546,7 +534,7 @@ impl Authentication for FabFire {
writer writer
.write_all(&send_buf) .write_all(&send_buf)
.map_err(|e| SessionError::Io { source: e })?; .map_err(|e| SessionError::Io { source: e })?;
Ok(rsasl::session::Step::NeedsMore(Some(send_buf.len()))) Ok(State::Running)
} }
Err(e) => { Err(e) => {
tracing::error!("Failed to serialize command: {:?}", e); tracing::error!("Failed to serialize command: {:?}", e);
@ -616,7 +604,7 @@ impl Authentication for FabFire {
writer writer
.write_all(&send_buf) .write_all(&send_buf)
.map_err(|e| SessionError::Io { source: e })?; .map_err(|e| SessionError::Io { source: e })?;
Ok(rsasl::session::Step::NeedsMore(Some(send_buf.len()))) Ok(State::Running)
} }
Err(e) => { Err(e) => {
tracing::error!("Failed to serialize command: {:?}", e); tracing::error!("Failed to serialize command: {:?}", e);
@ -691,9 +679,7 @@ impl Authentication for FabFire {
writer writer
.write_all(&send_buf) .write_all(&send_buf)
.map_err(|e| SessionError::Io { source: e })?; .map_err(|e| SessionError::Io { source: e })?;
return Ok(rsasl::session::Step::Done(Some( return Ok(State::Finished(MessageSent::Yes));
send_buf.len(),
)));
} }
Err(e) => { Err(e) => {
tracing::error!( tracing::error!(
@ -722,6 +708,6 @@ impl Authentication for FabFire {
} }
} }
return Ok(rsasl::session::Step::Done(None)); return Ok(State::Finished(MessageSent::No));
} }
} }

View File

@ -1,12 +1,10 @@
use crate::users::Users; use crate::users::Users;
use miette::{Context, IntoDiagnostic}; use miette::{Context, IntoDiagnostic};
use rsasl::error::SessionError;
use rsasl::mechname::Mechname;
use rsasl::property::{AuthId, Password};
use rsasl::session::{Session, SessionData};
use rsasl::validate::{validations, Validation};
use rsasl::{Property, SASL};
use std::sync::Arc; use std::sync::Arc;
use rsasl::callback::{CallbackError, Request, SessionCallback, SessionData};
use rsasl::mechanism::SessionError;
use rsasl::prelude::{Mechname, SASLConfig, SASLServer, Session};
use rsasl::property::AuthId;
use crate::authentication::fabfire::FabFireCardKey; use crate::authentication::fabfire::FabFireCardKey;
@ -22,36 +20,22 @@ impl Callback {
Self { users, span } Self { users, span }
} }
} }
impl rsasl::callback::Callback for Callback { impl SessionCallback for Callback {
fn provide_prop( fn callback(&self, session_data: &SessionData, context: &rsasl::callback::Context, request: &mut Request) -> Result<(), SessionError> {
&self, if let Some(authid) = context.get_ref::<AuthId>() {
session: &mut rsasl::session::SessionData, request.satisfy_with::<FabFireCardKey, _>(|| {
property: Property, let user = self.users.get_user(authid).ok_or(CallbackError::NoValue)?;
) -> Result<(), SessionError> { let kv = user.userdata.kv.get("cardkey").ok_or(CallbackError::NoValue)?;
match property {
fabfire::FABFIRECARDKEY => {
let authcid = session.get_property_or_callback::<AuthId>()?;
let user = self
.users
.get_user(authcid.unwrap().as_ref())
.ok_or(SessionError::AuthenticationFailure)?;
let kv = user
.userdata
.kv
.get("cardkey")
.ok_or(SessionError::AuthenticationFailure)?;
let card_key = <[u8; 16]>::try_from( let card_key = <[u8; 16]>::try_from(
hex::decode(kv).map_err(|_| SessionError::AuthenticationFailure)?, hex::decode(kv).map_err(|_| CallbackError::NoValue)?,
) ).map_err(|_| CallbackError::NoValue)?;
.map_err(|_| SessionError::AuthenticationFailure)?; Ok(card_key)
session.set_property::<FabFireCardKey>(Arc::new(card_key)); })?;
}
Ok(()) Ok(())
} }
_ => Err(SessionError::NoProperty { property }),
}
}
fn validate( /*fn validate(
&self, &self,
session: &mut SessionData, session: &mut SessionData,
validation: Validation, validation: Validation,
@ -90,21 +74,21 @@ impl rsasl::callback::Callback for Callback {
Err(SessionError::no_validate(validation)) Err(SessionError::no_validate(validation))
} }
} }
} }*/
} }
struct Inner { struct Inner {
rsasl: SASL, rsasl: Arc<SASLConfig>,
} }
impl Inner { impl Inner {
pub fn new(rsasl: SASL) -> Self { pub fn new(rsasl: Arc<SASLConfig>) -> Self {
Self { rsasl } Self { rsasl }
} }
} }
#[derive(Clone)] #[derive(Clone)]
pub struct AuthenticationHandle { pub struct AuthenticationHandle {
inner: Arc<Inner>, inner: Inner,
} }
impl AuthenticationHandle { impl AuthenticationHandle {
@ -112,11 +96,13 @@ impl AuthenticationHandle {
let span = tracing::debug_span!("authentication"); let span = tracing::debug_span!("authentication");
let _guard = span.enter(); let _guard = span.enter();
let mut rsasl = SASL::new(); let config = SASLConfig::builder()
rsasl.install_callback(Arc::new(Callback::new(userdb))); .with_defaults()
.with_callback(Callback::new(userdb))
.unwrap();
let mechs: Vec<&'static str> = rsasl let mechs: Vec<&'static str> = SASLServer::new(config.clone())
.server_mech_list() .get_available()
.into_iter() .into_iter()
.map(|m| m.mechanism.as_str()) .map(|m| m.mechanism.as_str())
.collect(); .collect();
@ -124,23 +110,20 @@ impl AuthenticationHandle {
tracing::debug!(?mechs, "available mechs"); tracing::debug!(?mechs, "available mechs");
Self { Self {
inner: Arc::new(Inner::new(rsasl)), inner: Inner::new(config),
} }
} }
pub fn start(&self, mechanism: &Mechname) -> miette::Result<Session> { pub fn start(&self, mechanism: &Mechname) -> miette::Result<Session> {
Ok(self Ok(SASLServer::new(self.inner.rsasl.clone())
.inner .start_suggested(mechanism)
.rsasl
.server_start(mechanism)
.into_diagnostic() .into_diagnostic()
.wrap_err("Failed to start a SASL authentication with the given mechanism")?) .wrap_err("Failed to start a SASL authentication with the given mechanism")?)
} }
pub fn list_available_mechs(&self) -> impl IntoIterator<Item = &Mechname> { pub fn list_available_mechs(&self) -> impl IntoIterator<Item = &Mechname> {
self.inner SASLServer::new(self.inner.rsasl.clone())
.rsasl .get_available()
.server_mech_list()
.into_iter() .into_iter()
.map(|m| m.mechanism) .map(|m| m.mechanism)
} }

View File

@ -3,10 +3,11 @@ use capnp::Error;
use capnp_rpc::pry; use capnp_rpc::pry;
use rsasl::mechname::Mechname; use rsasl::mechname::Mechname;
use rsasl::property::AuthId; use rsasl::property::AuthId;
use rsasl::session::{Session, Step};
use std::fmt; use std::fmt;
use std::fmt::{Formatter, Write}; use std::fmt::{Formatter, Write};
use std::io::Cursor; use std::io::Cursor;
use rsasl::prelude::{MessageSent, Session};
use rsasl::prelude::State as SaslState;
use tracing::Span; use tracing::Span;
use crate::capnp::session::APISession; use crate::capnp::session::APISession;
@ -123,7 +124,7 @@ impl AuthenticationSystem for Authentication {
let mut out = Cursor::new(Vec::new()); let mut out = Cursor::new(Vec::new());
match session.step(Some(data), &mut out) { match session.step(Some(data), &mut out) {
Ok(Step::Done(data)) => { Ok(SaslState::Finished(sent)) => {
self.state = State::Finished; self.state = State::Finished;
let uid = pry!(session.get_property::<AuthId>().ok_or_else(|| { let uid = pry!(session.get_property::<AuthId>().ok_or_else(|| {
@ -142,13 +143,13 @@ impl AuthenticationSystem for Authentication {
}; };
let mut builder = builder.init_successful(); let mut builder = builder.init_successful();
if data.is_some() { if sent == MessageSent::Yes {
builder.set_additional_data(out.into_inner().as_slice()); builder.set_additional_data(out.into_inner().as_slice());
} }
APISession::build(session, builder) APISession::build(session, builder)
} }
Ok(Step::NeedsMore(_)) => { Ok(SaslState::Running) => {
self.state = State::Running(session, manager); self.state = State::Running(session, manager);
builder.set_challenge(out.into_inner().as_slice()); builder.set_challenge(out.into_inner().as_slice());