Generate & return webauthn registration challenge
This commit is contained in:
92
src/data/crypto_wrapper.rs
Normal file
92
src/data/crypto_wrapper.rs
Normal file
@ -0,0 +1,92 @@
|
||||
use std::io::ErrorKind;
|
||||
|
||||
use aes_gcm::{Aes256Gcm, Key, Nonce};
|
||||
use aes_gcm::aead::Aead;
|
||||
use aes_gcm::NewAead;
|
||||
use rand::Rng;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::utils::err::Res;
|
||||
|
||||
const NONCE_LEN: usize = 12;
|
||||
const KEY_LEN: usize = 32;
|
||||
|
||||
pub struct CryptoWrapper {
|
||||
key: Vec<u8>,
|
||||
}
|
||||
|
||||
impl CryptoWrapper {
|
||||
/// Generate a new memory wrapper
|
||||
pub fn new_random() -> Self {
|
||||
Self { key: (0..KEY_LEN).map(|_| { rand::random::<u8>() }).collect() }
|
||||
}
|
||||
|
||||
/// Encrypt some data
|
||||
pub fn encrypt<T: Serialize + DeserializeOwned>(&self, data: &T) -> Res<String> {
|
||||
let aes_key = Aes256Gcm::new(Key::from_slice(&self.key));
|
||||
let nonce_bytes = rand::thread_rng().gen::<[u8; NONCE_LEN]>();
|
||||
|
||||
let serialized_data = bincode::serialize(data)?;
|
||||
|
||||
let mut enc = aes_key.encrypt(Nonce::from_slice(&nonce_bytes),
|
||||
serialized_data.as_slice()).unwrap();
|
||||
enc.extend_from_slice(&nonce_bytes);
|
||||
|
||||
|
||||
Ok(base64::encode(enc))
|
||||
}
|
||||
|
||||
/// Decrypt some data previously encrypted using the [`CryptoWrapper::encrypt`] method
|
||||
pub fn decrypt<T: DeserializeOwned>(&self, input: &str) -> Res<T> {
|
||||
let bytes = base64::decode(input)?;
|
||||
|
||||
if bytes.len() < NONCE_LEN {
|
||||
return Err(Box::new(std::io::Error::new(ErrorKind::Other,
|
||||
"Input string is smaller than nonce!")));
|
||||
}
|
||||
|
||||
let (enc, nonce) = bytes.split_at(bytes.len() - NONCE_LEN);
|
||||
assert_eq!(nonce.len(), NONCE_LEN);
|
||||
|
||||
let aes_key = Aes256Gcm::new(Key::from_slice(&self.key));
|
||||
|
||||
let dec = match aes_key.decrypt(Nonce::from_slice(nonce), enc) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
log::error!("Failed to decrypt wrapped data! {:#?}", e);
|
||||
return Err(Box::new(std::io::Error::new(ErrorKind::Other,
|
||||
"Failed to decrypt wrapped data!")));
|
||||
}
|
||||
};
|
||||
|
||||
Ok(bincode::deserialize(&dec)?)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::data::crypto_wrapper::CryptoWrapper;
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug)]
|
||||
struct Message(String);
|
||||
|
||||
#[test]
|
||||
fn encrypt_and_decrypt() {
|
||||
let wrapper = CryptoWrapper::new_random();
|
||||
let msg = Message("Pierre was here".to_string());
|
||||
let enc = wrapper.encrypt(&msg).unwrap();
|
||||
let dec: Message = wrapper.decrypt(&enc).unwrap();
|
||||
|
||||
assert_eq!(dec, msg)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encrypt_and_decrypt_invalid() {
|
||||
let wrapper_1 = CryptoWrapper::new_random();
|
||||
let wrapper_2 = CryptoWrapper::new_random();
|
||||
let msg = Message("Pierre was here".to_string());
|
||||
let enc = wrapper_1.encrypt(&msg).unwrap();
|
||||
wrapper_2.decrypt::<Message>(&enc).unwrap_err();
|
||||
}
|
||||
}
|
@ -12,7 +12,7 @@ pub struct IdToken {
|
||||
/// REQUIRED. Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 client_id of the Relying Party as an audience value. It MAY also contain identifiers for other audiences. In the general case, the aud value is an array of case sensitive strings. In the common special case when there is one audience, the aud value MAY be a single case sensitive string.
|
||||
#[serde(rename = "aud")]
|
||||
pub audience: String,
|
||||
/// REQUIRED. Expiration time on or after which the ID Token MUST NOT be accepted for processing. The processing of this parameter requires that the current date/time MUST be before the expiration date/time listed in the value. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time. See RFC 3339 [RFC3339] for details regarding date/times in general and UTC in particular.
|
||||
/// REQUIRED. Expiration time on or after which the ID Token MUST NOT be accepted for processing. The processing of this parameter requires that the current date/time MUST be before the expiration date/time listed in the value. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time. See RFC 3339 for details regarding date/times in general and UTC in particular.
|
||||
#[serde(rename = "exp")]
|
||||
pub expiration_time: u64,
|
||||
/// REQUIRED. Time at which the JWT was issued. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time.
|
||||
|
@ -12,4 +12,6 @@ pub mod code_challenge;
|
||||
pub mod open_id_user_info;
|
||||
pub mod access_token;
|
||||
pub mod totp_key;
|
||||
pub mod login_redirect;
|
||||
pub mod login_redirect;
|
||||
pub mod webauthn_manager;
|
||||
pub mod crypto_wrapper;
|
@ -34,7 +34,7 @@ impl TotpKey {
|
||||
|
||||
/// Get QrCode URL for user
|
||||
///
|
||||
/// Based on https://github.com/google/google-authenticator/wiki/Key-Uri-Format
|
||||
/// Based on <https://github.com/google/google-authenticator/wiki/Key-Uri-Format>
|
||||
pub fn url_for_user(&self, u: &User, conf: &AppConfig) -> String {
|
||||
format!(
|
||||
"otpauth://totp/{}:{}?secret={}&issuer={}&algorithm=SHA1&digits={}&period={}",
|
||||
|
77
src/data/webauthn_manager.rs
Normal file
77
src/data/webauthn_manager.rs
Normal file
@ -0,0 +1,77 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix_web::web;
|
||||
use webauthn_rs::{RegistrationState, Webauthn, WebauthnConfig};
|
||||
use webauthn_rs::proto::CreationChallengeResponse;
|
||||
|
||||
use crate::constants::APP_NAME;
|
||||
use crate::data::app_config::AppConfig;
|
||||
use crate::data::crypto_wrapper::CryptoWrapper;
|
||||
use crate::data::user::{User, UserID};
|
||||
use crate::utils::err::Res;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct WebAuthnAppConfig {
|
||||
origin: url::Url,
|
||||
relying_party_id: String,
|
||||
}
|
||||
|
||||
impl WebauthnConfig for WebAuthnAppConfig {
|
||||
fn get_relying_party_name(&self) -> &str {
|
||||
APP_NAME
|
||||
}
|
||||
|
||||
fn get_origin(&self) -> &url::Url {
|
||||
&self.origin
|
||||
}
|
||||
|
||||
fn get_relying_party_id(&self) -> &str {
|
||||
&self.relying_party_id
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RegisterKeyRequest {
|
||||
pub opaque_state: String,
|
||||
pub creation_challenge: CreationChallengeResponse,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
struct RegisterKeyOpaqueData {
|
||||
registration_state: RegistrationState,
|
||||
user_id: UserID,
|
||||
}
|
||||
|
||||
pub type WebAuthManagerReq = web::Data<Arc<WebAuthManager>>;
|
||||
|
||||
pub struct WebAuthManager {
|
||||
core: Webauthn<WebAuthnAppConfig>,
|
||||
crypto_wrapper: CryptoWrapper,
|
||||
}
|
||||
|
||||
impl WebAuthManager {
|
||||
pub fn init(conf: &AppConfig) -> Self {
|
||||
Self {
|
||||
core: Webauthn::new(WebAuthnAppConfig {
|
||||
origin: url::Url::parse(&conf.website_origin)
|
||||
.expect("Failed to parse configuration origin!"),
|
||||
relying_party_id: conf.domain_name().to_string(),
|
||||
}),
|
||||
crypto_wrapper: CryptoWrapper::new_random(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_register(&self, user: &User) -> Res<RegisterKeyRequest> {
|
||||
let (creation_challenge, registration_state) = self.core.generate_challenge_register(
|
||||
&user.username,
|
||||
true,
|
||||
)?;
|
||||
|
||||
Ok(RegisterKeyRequest {
|
||||
opaque_state: self.crypto_wrapper.encrypt(&RegisterKeyOpaqueData {
|
||||
registration_state,
|
||||
user_id: user.uid.clone(),
|
||||
})?,
|
||||
creation_challenge,
|
||||
})
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user