Compare commits

...

3 Commits

Author SHA1 Message Date
d0cb503f50 Update chrono to version 0.4.37
All checks were successful
continuous-integration/drone/push Build is passing
2024-03-27 19:27:30 +01:00
9df0d6da00 Merge branch 'master' of ssh://gitea.communiquons.org:52001/pierre/BasicOIDC 2024-03-27 19:26:28 +01:00
9a79ef701b Need to perform 2FA before modifying factors 2024-03-27 19:26:07 +01:00
11 changed files with 122 additions and 22 deletions

28
Cargo.lock generated
View File

@@ -519,9 +519,9 @@ dependencies = [
[[package]] [[package]]
name = "autocfg" name = "autocfg"
version = "1.1.0" version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" checksum = "f1fdabc7756949593fe60f30ec81974b613357de856987752631dea1e3394c80"
[[package]] [[package]]
name = "backtrace" name = "backtrace"
@@ -792,9 +792,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]] [[package]]
name = "chrono" name = "chrono"
version = "0.4.35" version = "0.4.37"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8eaf5903dcbc0a39312feb77df2ff4c76387d591b9fc7b04a238dcf8bb62639a" checksum = "8a0d04d43504c61aa6c7531f1871dd0d418d91130162063b789da00fd7057a5e"
dependencies = [ dependencies = [
"android-tzdata", "android-tzdata",
"iana-time-zone", "iana-time-zone",
@@ -1635,9 +1635,9 @@ checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3"
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.10" version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b"
[[package]] [[package]]
name = "jobserver" name = "jobserver"
@@ -2281,9 +2281,9 @@ dependencies = [
[[package]] [[package]]
name = "regex-syntax" name = "regex-syntax"
version = "0.8.2" version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56"
[[package]] [[package]]
name = "reqwest" name = "reqwest"
@@ -3384,27 +3384,27 @@ checksum = "525b4ec142c6b68a2d10f01f7bbf6755599ca3f81ea53b8431b7dd348f5fdb2d"
[[package]] [[package]]
name = "zstd" name = "zstd"
version = "0.13.0" version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bffb3309596d527cfcba7dfc6ed6052f1d39dfbd7c867aa2e865e4a449c10110" checksum = "2d789b1514203a1120ad2429eae43a7bd32b90976a7bb8a05f7ec02fa88cc23a"
dependencies = [ dependencies = [
"zstd-safe", "zstd-safe",
] ]
[[package]] [[package]]
name = "zstd-safe" name = "zstd-safe"
version = "7.0.0" version = "7.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43747c7422e2924c11144d5229878b98180ef8b06cca4ab5af37afc8a8d8ea3e" checksum = "1cd99b45c6bc03a018c8b8a86025678c87e55526064e38f9df301989dce7ec0a"
dependencies = [ dependencies = [
"zstd-sys", "zstd-sys",
] ]
[[package]] [[package]]
name = "zstd-sys" name = "zstd-sys"
version = "2.0.9+zstd.1.5.5" version = "2.0.10+zstd.1.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e16efa8a874a0481a574084d34cc26fdb3b99627480f785888deb6386506656" checksum = "c253a4914af5bafc8fa8c86ee400827e83cf6ec01195ec1f1ed8441bf00d65aa"
dependencies = [ dependencies = [
"cc", "cc",
"pkg-config", "pkg-config",

View File

@@ -37,6 +37,6 @@ webauthn-rs = { version = "0.4.8", features = ["danger-allow-state-serialisation
url = "2.5.0" url = "2.5.0"
light-openid = { version = "1.0.1", features = ["crypto-wrapper"] } light-openid = { version = "1.0.1", features = ["crypto-wrapper"] }
bincode = "2.0.0-rc.3" bincode = "2.0.0-rc.3"
chrono = "0.4.35" chrono = "0.4.37"
lazy_static = "1.4.0" lazy_static = "1.4.0"
mailchecker = "6.0.1" mailchecker = "6.0.1"

View File

@@ -29,6 +29,10 @@ pub const MAX_SECOND_FACTOR_NAME_LEN: usize = 25;
/// exempted from this IP address to use 2FA /// exempted from this IP address to use 2FA
pub const SECOND_FACTOR_EXEMPTION_AFTER_SUCCESSFUL_LOGIN: u64 = 7 * 24 * 3600; pub const SECOND_FACTOR_EXEMPTION_AFTER_SUCCESSFUL_LOGIN: u64 = 7 * 24 * 3600;
/// The maximum acceptable interval of time between last two factors authentication of a user and
/// access to a critical route / a critical client
pub const SECOND_FACTOR_EXPIRATION_FOR_CRITICAL_OPERATIONS: u64 = 60 * 10;
/// Minimum password length /// Minimum password length
pub const MIN_PASS_LEN: usize = 4; pub const MIN_PASS_LEN: usize = 4;

View File

@@ -14,7 +14,7 @@ use crate::controllers::base_controller::{
}; };
use crate::data::action_logger::{Action, ActionLogger}; use crate::data::action_logger::{Action, ActionLogger};
use crate::data::force_2fa_auth::Force2FAAuth; use crate::data::force_2fa_auth::Force2FAAuth;
use crate::data::login_redirect::LoginRedirect; use crate::data::login_redirect::{get_2fa_url, LoginRedirect};
use crate::data::provider::{Provider, ProvidersManager}; use crate::data::provider::{Provider, ProvidersManager};
use crate::data::session_identity::{SessionIdentity, SessionStatus}; use crate::data::session_identity::{SessionIdentity, SessionStatus};
use crate::data::user::User; use crate::data::user::User;
@@ -129,10 +129,7 @@ pub async fn login_route(
} }
// Check if the user has to validate a second factor // Check if the user has to validate a second factor
else if SessionIdentity(id.as_ref()).need_2fa_auth() { else if SessionIdentity(id.as_ref()).need_2fa_auth() {
return redirect_user(&format!( return redirect_user(&get_2fa_url(&query.redirect, false));
"/2fa_auth?redirect={}",
query.redirect.get_encoded()
));
} }
// Check if given login is not acceptable // Check if given login is not acceptable
else if req else if req

View File

@@ -7,6 +7,7 @@ use crate::actors::users_actor;
use crate::actors::users_actor::UsersActor; use crate::actors::users_actor::UsersActor;
use crate::constants::MAX_SECOND_FACTOR_NAME_LEN; use crate::constants::MAX_SECOND_FACTOR_NAME_LEN;
use crate::data::action_logger::{Action, ActionLogger}; use crate::data::action_logger::{Action, ActionLogger};
use crate::data::critical_route::CriticalRoute;
use crate::data::current_user::CurrentUser; use crate::data::current_user::CurrentUser;
use crate::data::totp_key::TotpKey; use crate::data::totp_key::TotpKey;
use crate::data::user::{FactorID, TwoFactor, TwoFactorType}; use crate::data::user::{FactorID, TwoFactor, TwoFactorType};
@@ -29,6 +30,7 @@ pub struct AddTOTPRequest {
} }
pub async fn save_totp_factor( pub async fn save_totp_factor(
_critical: CriticalRoute,
user: CurrentUser, user: CurrentUser,
form: web::Json<AddTOTPRequest>, form: web::Json<AddTOTPRequest>,
users: web::Data<Addr<UsersActor>>, users: web::Data<Addr<UsersActor>>,
@@ -77,6 +79,7 @@ pub struct AddWebauthnRequest {
} }
pub async fn save_webauthn_factor( pub async fn save_webauthn_factor(
_critical: CriticalRoute,
user: CurrentUser, user: CurrentUser,
form: web::Json<AddWebauthnRequest>, form: web::Json<AddWebauthnRequest>,
users: web::Data<Addr<UsersActor>>, users: web::Data<Addr<UsersActor>>,
@@ -121,6 +124,7 @@ pub struct DeleteFactorRequest {
} }
pub async fn delete_factor( pub async fn delete_factor(
_critical: CriticalRoute,
user: CurrentUser, user: CurrentUser,
form: web::Json<DeleteFactorRequest>, form: web::Json<DeleteFactorRequest>,
users: web::Data<Addr<UsersActor>>, users: web::Data<Addr<UsersActor>>,
@@ -145,6 +149,7 @@ pub async fn delete_factor(
} }
pub async fn clear_login_history( pub async fn clear_login_history(
_critical: CriticalRoute,
user: CurrentUser, user: CurrentUser,
users: web::Data<Addr<UsersActor>>, users: web::Data<Addr<UsersActor>>,
logger: ActionLogger, logger: ActionLogger,

View File

@@ -9,6 +9,7 @@ use qrcode_generator::QrCodeEcc;
use crate::constants::MAX_SECOND_FACTOR_NAME_LEN; use crate::constants::MAX_SECOND_FACTOR_NAME_LEN;
use crate::controllers::settings_controller::BaseSettingsPage; use crate::controllers::settings_controller::BaseSettingsPage;
use crate::data::app_config::AppConfig; use crate::data::app_config::AppConfig;
use crate::data::critical_route::CriticalRoute;
use crate::data::current_user::CurrentUser; use crate::data::current_user::CurrentUser;
use crate::data::totp_key::TotpKey; use crate::data::totp_key::TotpKey;
use crate::data::user::User; use crate::data::user::User;
@@ -43,7 +44,7 @@ struct AddWebauhtnPage<'a> {
} }
/// Manage two factors authentication methods route /// Manage two factors authentication methods route
pub async fn two_factors_route(user: CurrentUser) -> impl Responder { pub async fn two_factors_route(_critical: CriticalRoute, user: CurrentUser) -> impl Responder {
HttpResponse::Ok().body( HttpResponse::Ok().body(
TwoFactorsPage { TwoFactorsPage {
p: BaseSettingsPage::get("Two factor auth", &user, None, None), p: BaseSettingsPage::get("Two factor auth", &user, None, None),
@@ -56,7 +57,7 @@ pub async fn two_factors_route(user: CurrentUser) -> impl Responder {
} }
/// Configure a new TOTP authentication factor /// Configure a new TOTP authentication factor
pub async fn add_totp_factor_route(user: CurrentUser) -> impl Responder { pub async fn add_totp_factor_route(_critical: CriticalRoute, user: CurrentUser) -> impl Responder {
let key = TotpKey::new_random(); let key = TotpKey::new_random();
let qr_code = qrcode_generator::to_png_to_vec( let qr_code = qrcode_generator::to_png_to_vec(
@@ -87,6 +88,7 @@ pub async fn add_totp_factor_route(user: CurrentUser) -> impl Responder {
/// Configure a new security key factor /// Configure a new security key factor
pub async fn add_webauthn_factor_route( pub async fn add_webauthn_factor_route(
_critical: CriticalRoute,
user: CurrentUser, user: CurrentUser,
manager: WebAuthManagerReq, manager: WebAuthManagerReq,
) -> impl Responder { ) -> impl Responder {

View File

@@ -0,0 +1,32 @@
use crate::data::current_user::CurrentUser;
use crate::data::from_request_redirect::FromRequestRedirect;
use crate::data::login_redirect::{get_2fa_url, LoginRedirect};
use actix_web::dev::Payload;
use actix_web::{FromRequest, HttpRequest};
use std::future::Future;
use std::pin::Pin;
pub struct CriticalRoute;
impl FromRequest for CriticalRoute {
type Error = FromRequestRedirect;
type Future = Pin<Box<dyn Future<Output = Result<Self, Self::Error>>>>;
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
let req = req.clone();
Box::pin(async move {
let current_user = CurrentUser::from_request(&req, &mut Payload::None)
.await
.expect("Failed to extract user identity!");
if current_user.should_request_2fa_for_critical_function() {
let url = get_2fa_url(&LoginRedirect::from_req(&req), true);
return Err(FromRequestRedirect::new(url));
}
Ok(Self)
})
}
}

View File

@@ -10,8 +10,10 @@ use actix_web::{web, Error, FromRequest, HttpRequest};
use crate::actors::users_actor; use crate::actors::users_actor;
use crate::actors::users_actor::UsersActor; use crate::actors::users_actor::UsersActor;
use crate::constants::SECOND_FACTOR_EXPIRATION_FOR_CRITICAL_OPERATIONS;
use crate::data::session_identity::SessionIdentity; use crate::data::session_identity::SessionIdentity;
use crate::data::user::User; use crate::data::user::User;
use crate::utils::time::time;
pub struct CurrentUser { pub struct CurrentUser {
user: User, user: User,
@@ -19,6 +21,16 @@ pub struct CurrentUser {
pub last_2fa_auth: Option<u64>, pub last_2fa_auth: Option<u64>,
} }
impl CurrentUser {
pub fn should_request_2fa_for_critical_function(&self) -> bool {
self.user.has_two_factor()
&& self
.last_2fa_auth
.map(|t| t + SECOND_FACTOR_EXPIRATION_FOR_CRITICAL_OPERATIONS < time())
.unwrap_or(true)
}
}
impl From<CurrentUser> for User { impl From<CurrentUser> for User {
fn from(user: CurrentUser) -> Self { fn from(user: CurrentUser) -> Self {
user.user user.user

View File

@@ -0,0 +1,32 @@
use actix_web::body::BoxBody;
use actix_web::http::StatusCode;
use actix_web::{HttpResponse, ResponseError};
use std::fmt::{Debug, Display, Formatter};
#[derive(Debug)]
pub struct FromRequestRedirect {
url: String,
}
impl FromRequestRedirect {
pub fn new(url: String) -> Self {
Self { url }
}
}
impl Display for FromRequestRedirect {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "Redirect to {}", self.url)
}
}
impl ResponseError for FromRequestRedirect {
fn status_code(&self) -> StatusCode {
StatusCode::FOUND
}
fn error_response(&self) -> HttpResponse<BoxBody> {
HttpResponse::Found()
.insert_header(("Location", self.url.as_str()))
.body("Redirecting...")
}
}

View File

@@ -1,7 +1,13 @@
use actix_web::HttpRequest;
#[derive(serde::Serialize, serde::Deserialize, Debug, Eq, PartialEq, Clone)] #[derive(serde::Serialize, serde::Deserialize, Debug, Eq, PartialEq, Clone)]
pub struct LoginRedirect(String); pub struct LoginRedirect(String);
impl LoginRedirect { impl LoginRedirect {
pub fn from_req(req: &HttpRequest) -> Self {
Self(req.uri().to_string())
}
pub fn get(&self) -> &str { pub fn get(&self) -> &str {
match self.0.starts_with('/') && !self.0.starts_with("//") { match self.0.starts_with('/') && !self.0.starts_with("//") {
true => self.0.as_str(), true => self.0.as_str(),
@@ -19,3 +25,11 @@ impl Default for LoginRedirect {
Self("/".to_string()) Self("/".to_string())
} }
} }
/// Get the URL for 2FA authentication
pub fn get_2fa_url(redir: &LoginRedirect, force_2fa: bool) -> String {
format!(
"/2fa_auth?redirect={}&force_2fa={force_2fa}",
redir.get_encoded()
)
}

View File

@@ -3,9 +3,11 @@ pub mod action_logger;
pub mod app_config; pub mod app_config;
pub mod client; pub mod client;
pub mod code_challenge; pub mod code_challenge;
pub mod critical_route;
pub mod current_user; pub mod current_user;
pub mod entity_manager; pub mod entity_manager;
pub mod force_2fa_auth; pub mod force_2fa_auth;
pub mod from_request_redirect;
pub mod id_token; pub mod id_token;
pub mod jwt_signer; pub mod jwt_signer;
pub mod login_redirect; pub mod login_redirect;