mfa.rs (12154B)
1 /* 2 * This file is part of LibEuFin. 3 * Copyright (C) 2026 Taler Systems S.A. 4 5 * LibEuFin is free software; you can redistribute it and/or modify 6 * it under the terms of the GNU Affero General Public License as 7 * published by the Free Software Foundation; either version 3, or 8 * (at your option) any later version. 9 10 * LibEuFin is distributed in the hope that it will be useful, but 11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General 13 * Public License for more details. 14 15 * You should have received a copy of the GNU Affero General Public 16 * License along with LibEuFin; see the file COPYING. If not, see 17 * <http://www.gnu.org/licenses/> 18 */ 19 20 use std::{any::TypeId, marker::PhantomData, str::FromStr as _, sync::Arc, time::Duration}; 21 22 use aws_lc_rs::digest::SHA512; 23 use axum::{ 24 Json, 25 body::Bytes, 26 extract::{FromRequest, FromRequestParts, Request}, 27 http::{HeaderMap, HeaderName, StatusCode}, 28 response::IntoResponse, 29 }; 30 use compact_str::CompactString; 31 use jiff::Timestamp; 32 use rand::random_range; 33 use serde::{Deserialize, Serialize, de::DeserializeOwned}; 34 use sqlx::PgPool; 35 use taler_api::{ 36 constants::SAFE_BODY_LENGTH, 37 error::{ApiError, ApiResult, failure, forbidden}, 38 extract::{Req, decompressed_json_body}, 39 }; 40 use taler_common::{error_code::ErrorCode, types::base32::Base32}; 41 use taler_macros::EnumMeta; 42 use uuid::Uuid; 43 44 use crate::{ 45 TanChannel, 46 api::{ 47 BankState, 48 account::{AccountPasswordChange, AccountReconfiguration, TanInfo}, 49 cashout::CashoutRequest, 50 tan::{Challenge, ChallengeResponse}, 51 token::TokenRequest, 52 tx::TransactionCreateRequest, 53 withdrawal::BankAccountConfirmWithdrawalRequest, 54 }, 55 auth::{UserAuth, UserAuthScope, UserORWScope, UserRWScope, UserTokenScope}, 56 db::account::BankInfo, 57 payto::PaytoCtx, 58 }; 59 60 #[derive( 61 sqlx::Type, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, EnumMeta, Serialize, Deserialize, 62 )] 63 #[sqlx(type_name = "op_enum")] 64 #[enum_meta(Str)] 65 #[allow(non_camel_case_types)] 66 pub enum Operation { 67 account_reconfig, 68 account_delete, 69 account_auth_reconfig, 70 bank_transaction, 71 cashout, 72 withdrawal, 73 create_token, 74 } 75 76 pub type Tans = Vec<(TanChannel, CompactString)>; 77 78 pub trait MfaOp { 79 const OP: Operation; 80 type Scope: UserAuthScope; 81 type Body: DeserializeOwned + Send + 'static; 82 83 fn required_validation(_: &Self::Body, _: &BankInfo) -> ApiResult<Option<Tans>> { 84 Ok(None) 85 } 86 } 87 88 pub struct AccountReconfigOp; 89 90 impl MfaOp for AccountReconfigOp { 91 const OP: Operation = Operation::account_reconfig; 92 type Scope = UserRWScope; 93 type Body = AccountReconfiguration; 94 95 fn required_validation(body: &Self::Body, info: &BankInfo) -> ApiResult<Option<Tans>> { 96 Ok(Some(body.required_validation(info)?)) 97 } 98 } 99 100 pub struct BankTxOp; 101 102 impl MfaOp for BankTxOp { 103 const OP: Operation = Operation::bank_transaction; 104 type Scope = UserORWScope; 105 type Body = TransactionCreateRequest; 106 } 107 108 pub struct TokenOp; 109 110 impl MfaOp for TokenOp { 111 const OP: Operation = Operation::create_token; 112 type Scope = UserTokenScope; 113 type Body = TokenRequest; 114 } 115 116 pub struct AccountDeletionOp; 117 118 impl MfaOp for AccountDeletionOp { 119 const OP: Operation = Operation::account_delete; 120 type Scope = UserRWScope; 121 type Body = Empty; 122 } 123 124 pub struct AccountPasswordOp; 125 126 impl MfaOp for AccountPasswordOp { 127 const OP: Operation = Operation::account_auth_reconfig; 128 type Scope = UserRWScope; 129 type Body = AccountPasswordChange; 130 } 131 132 pub struct CashoutOp; 133 134 impl MfaOp for CashoutOp { 135 const OP: Operation = Operation::cashout; 136 type Scope = UserORWScope; 137 type Body = CashoutRequest; 138 } 139 140 pub struct WithdrawalOp; 141 142 impl MfaOp for WithdrawalOp { 143 const OP: Operation = Operation::withdrawal; 144 type Scope = UserORWScope; 145 type Body = BankAccountConfirmWithdrawalRequest; 146 } 147 148 fn mfa_body_hash(body: &[u8], username: &str, salt: &Base32<16>, ctx: &[u8]) -> Base32<64> { 149 let mut digest = aws_lc_rs::digest::Context::new(&SHA512); 150 digest.update(salt.as_ref()); 151 digest.update(username.as_bytes()); 152 digest.update(ctx); 153 digest.update(body); 154 Base32::try_from(digest.finish().as_ref()).unwrap() 155 } 156 157 #[derive(Debug)] 158 enum Mfa { 159 None, 160 Challenged, 161 Pending(Tans), 162 } 163 164 #[derive(Debug)] 165 pub struct MfaCtx<'a, O: MfaOp> { 166 body: Bytes, 167 ctx: &'a [u8], 168 mfa: Mfa, 169 op: PhantomData<O>, 170 } 171 172 impl<'a, O: MfaOp> MfaCtx<'a, O> { 173 async fn respond_challenges( 174 &self, 175 db: &PgPool, 176 username: &str, 177 tans: &[(TanChannel, CompactString)], 178 ) -> ApiResult<Vec<Challenge>> { 179 const TAN_RETRY_COUNTER: u16 = 3; 180 const TAN_VALIDITY_PERIOD: Duration = Duration::from_mins(30); 181 182 let salt = Base32::secure_rand(); 183 let hash = mfa_body_hash(&self.body, username, &salt, self.ctx); 184 let mut challenges = Vec::new(); 185 186 for (channel, info) in tans { 187 let code = gen_tan_code(); 188 let uuid = super::db::tan::new( 189 db, 190 username, 191 O::OP, 192 &hash, 193 &salt, 194 &code, 195 &Timestamp::now(), 196 TAN_RETRY_COUNTER, 197 TAN_VALIDITY_PERIOD, 198 *channel, 199 info, 200 ) 201 .await?; 202 // Create token is a public challenge 203 let info = if O::OP == Operation::create_token { 204 CompactString::const_new("REDACTED") 205 } else { 206 info.clone() 207 }; 208 challenges.push(Challenge { 209 challenge_id: uuid.to_string(), 210 tan_channel: *channel, 211 tan_info: info, 212 }) 213 } 214 Ok(challenges) 215 } 216 217 /** 218 * Generate a TAN challenge for an [op] request with [body] and 219 * respond to the HTTP request with a TAN challenge. 220 * 221 * If [channel] and [info] are present, they will be used 222 * to send the TAN code, otherwise defaults will be used. 223 */ 224 pub async fn response_mfa( 225 &self, 226 auth: &mut UserAuth<O::Scope>, 227 db: &PgPool, 228 ctx: &PaytoCtx, 229 ) -> ApiResult<axum::response::Response> { 230 let info = auth.bank_info(db, ctx).await?; 231 let challenges = self 232 .respond_challenges(db, &info.username, &info.mfa()) 233 .await?; 234 Ok(( 235 StatusCode::ACCEPTED, 236 Json(ChallengeResponse { 237 challenges, 238 combi_and: false, 239 }), 240 ) 241 .into_response()) 242 } 243 244 pub async fn response_validation( 245 &self, 246 auth: &UserAuth<O::Scope>, 247 db: &PgPool, 248 tans: &[(TanChannel, CompactString)], 249 ) -> ApiResult<axum::response::Response> { 250 let challenges = self.respond_challenges(db, &auth.username, tans).await?; 251 Ok(( 252 StatusCode::ACCEPTED, 253 Json(ChallengeResponse { 254 challenges, 255 combi_and: true, 256 }), 257 ) 258 .into_response()) 259 } 260 261 pub fn pending_mfa(&self) -> Option<&[(TanChannel, CompactString)]> { 262 match &self.mfa { 263 Mfa::None => None, 264 Mfa::Challenged => None, 265 Mfa::Pending(items) => Some(items), 266 } 267 } 268 269 pub fn is_2fa(&self) -> bool { 270 matches!(self.mfa, Mfa::Challenged) 271 } 272 } 273 274 pub const TALER_CHALLENGE_IDS: HeaderName = HeaderName::from_static("taler-challenge-ids"); 275 276 #[must_use] 277 pub struct MfaReq<O: MfaOp> { 278 auth: UserAuth<O::Scope>, 279 body: Bytes, 280 req: O::Body, 281 headers: HeaderMap, 282 } 283 284 impl<O: MfaOp> MfaReq<O> { 285 pub async fn solve<'a>( 286 mut self, 287 state: &Arc<BankState>, 288 ctx: &'a [u8], 289 ) -> ApiResult<(UserAuth<O::Scope>, O::Body, MfaCtx<'a, O>)> { 290 // Check if challenges are used 291 let mfa = match self.headers.get(&TALER_CHALLENGE_IDS) { 292 Some(header) => { 293 let uuids: Option<Vec<Uuid>> = header.to_str().ok().and_then(|s| { 294 s.split(',') 295 .map(|s| Uuid::from_str(s.trim()).ok()) 296 .collect() 297 }); 298 let Some(uuids) = uuids else { 299 return Err(failure( 300 ErrorCode::GENERIC_HTTP_HEADERS_MALFORMED, 301 format_args!("{TALER_CHALLENGE_IDS} does not contains valid challenge ids"), 302 ) 303 .with_path(TALER_CHALLENGE_IDS)); 304 }; 305 let challenges = super::db::tan::challenge(&state.db, &uuids).await?; 306 let mut validated = Vec::new(); 307 for challenge in challenges { 308 if challenge.op != O::OP { 309 return Err(forbidden(format_args!( 310 "Challenge '{}' is for a different operation", 311 challenge.id 312 ))); 313 } else if mfa_body_hash(&self.body, &self.auth.username, &challenge.salt, ctx) 314 != challenge.hash 315 { 316 return Err(forbidden(format_args!( 317 "Challenge '{}' is for a different request", 318 challenge.id 319 ))); 320 } else if challenge.confirmed { 321 validated.push((challenge.channel, challenge.info)); 322 } 323 } 324 325 if !validated.is_empty() { 326 // Check if challenges are solved 327 let info = self.auth.bank_info(&state.db, &state.cfg.ctx).await?; 328 329 if let Some(validation) = O::required_validation(&self.req, info)? { 330 // Check mfa & new TAN validation 331 if validation.iter().all(|it| validated.contains(it)) { 332 Mfa::Challenged 333 } else if info.mfa().iter().any(|it| validated.contains(it)) { 334 Mfa::Pending(validation) 335 } else { 336 Mfa::None 337 } 338 } else { 339 // Check mfa 340 if info.mfa().iter().any(|it| validated.contains(it)) { 341 Mfa::Challenged 342 } else { 343 Mfa::None 344 } 345 } 346 } else { 347 Mfa::None 348 } 349 } 350 None => Mfa::None, 351 }; 352 Ok(( 353 self.auth, 354 self.req, 355 MfaCtx { 356 mfa, 357 op: PhantomData, 358 body: self.body, 359 ctx, 360 }, 361 )) 362 } 363 } 364 365 impl<O: MfaOp> FromRequest<Arc<BankState>> for MfaReq<O> { 366 type Rejection = ApiError; 367 368 async fn from_request(req: Request, state: &Arc<BankState>) -> Result<Self, Self::Rejection> { 369 let (mut parts, body) = req.into_parts(); 370 let auth = UserAuth::from_request_parts(&mut parts, state).await?; 371 let body = if TypeId::of::<O::Body>() == TypeId::of::<Empty>() { 372 Bytes::default() 373 } else { 374 decompressed_json_body::<SAFE_BODY_LENGTH>(&parts.headers, body).await? 375 }; 376 let Req(req) = Req::<O::Body>::try_from(&body)?; 377 Ok(Self { 378 auth, 379 body, 380 req, 381 headers: parts.headers, 382 }) 383 } 384 } 385 386 /// Generate a secure random TAN code 387 pub fn gen_tan_code() -> String { 388 // TODO do we need a more secure rng here ? 389 // Generate a random number between 0 and 99,999,999 390 let rand_val: u32 = random_range(0..100000000); 391 format!("{:08}", rand_val) 392 } 393 394 pub struct Empty; 395 396 impl<'de> Deserialize<'de> for Empty { 397 fn deserialize<D>(_: D) -> Result<Self, D::Error> 398 where 399 D: serde::Deserializer<'de>, 400 { 401 Ok(Self) 402 } 403 }