1use crate::prelude::*;
2
3use crate::{
4 credential::softlock::CredSoftLock,
5 idm::{
6 account::Account,
7 authentication::{AuthState, ReauthRequest},
8 authsession::{AuthSession, AuthSessionData},
9 event::AuthResult,
10 server::IdmServerAuthTransaction,
11 },
12 utils::uuid_from_duration,
13};
14
15use std::sync::Arc;
18use tokio::sync::Mutex;
19
20use kanidm_proto::v1::AuthIssueSession;
21
22use super::server::CredSoftLockMutex;
23
24impl IdmServerAuthTransaction<'_> {
25 pub async fn reauth_init(
26 &mut self,
27 ident: Identity,
28 issue: AuthIssueSession,
29 ct: Duration,
30 client_auth_info: ClientAuthInfo,
31 reauth_req: ReauthRequest,
32 ) -> Result<AuthResult, OperationError> {
33 let Some(entry) = ident.get_user_entry() else {
36 error!("Ident is not a user and has no entry associated. Unable to proceed.");
37 return Err(OperationError::InvalidState);
38 };
39
40 let (account, account_policy) =
42 Account::try_from_entry_with_policy(entry.as_ref(), &mut self.qs_read)?;
43
44 security_info!(
45 spn = %account.spn(),
46 issue = ?issue,
47 uuid = %account.uuid,
48 "Initiating Re-Authentication Session",
49 );
50
51 let session = entry
53 .get_ava_as_session_map(Attribute::UserAuthTokenSession)
54 .and_then(|sessions| sessions.get(&ident.session_id))
55 .ok_or_else(|| {
56 error!("Ident session is not present in entry. Perhaps replication is delayed?");
57 OperationError::InvalidState
58 })?;
59
60 match session.scope {
61 SessionScope::PrivilegeCapable => {
62 }
64 SessionScope::ReadOnly | SessionScope::ReadWrite | SessionScope::Synchronise => {
65 error!("Session scope is not PrivilegeCapable and can not be used in re-auth.");
67 return Err(OperationError::SessionMayNotReauth);
68 }
69 };
70
71 let session_cred_id = session.cred_id;
73
74 let sessionid = uuid_from_duration(ct, self.sid);
79
80 let _session_ticket = self.session_ticket.acquire().await;
82
83 let maybe_slock = account
85 .primary_cred_uuid_and_policy()
86 .and_then(|(cred_uuid, policy)| {
87 if cred_uuid == session_cred_id {
96 let mut softlock_write = self.softlocks.write();
97 let slock_ref: CredSoftLockMutex =
98 if let Some(slock_ref) = softlock_write.get(&cred_uuid) {
99 slock_ref.clone()
100 } else {
101 let slock = Arc::new(Mutex::new(CredSoftLock::new(policy)));
103 softlock_write.insert(cred_uuid, slock.clone());
104 slock
105 };
106 softlock_write.commit();
107 Some(slock_ref)
108 } else {
109 None
110 }
111 });
112
113 let is_valid = if let Some(slock_ref) = maybe_slock {
118 let mut slock = slock_ref.lock().await;
119 slock.apply_time_step(ct, None);
120 slock.is_valid()
121 } else {
122 true
123 };
124
125 if !is_valid {
126 warn!(
127 "Credential {:?} is currently softlocked, unable to proceed",
128 session_cred_id
129 );
130 return Ok(AuthResult {
131 sessionid: ident.get_session_id(),
132 state: AuthState::Denied("Credential is temporarily locked".to_string()),
133 });
134 }
135
136 let asd: AuthSessionData = AuthSessionData {
138 account,
139 account_policy,
140 issue,
141 webauthn: self.webauthn,
142 ct,
143 client_auth_info,
144 oauth2_client_provider: None,
145 };
146
147 let domain_keys = self.qs_read.get_domain_key_object_handle()?;
148
149 let (auth_session, state) = AuthSession::new_reauth(
150 asd,
151 ident.session_id,
152 session,
153 session_cred_id,
154 domain_keys,
155 &reauth_req,
156 );
157
158 match auth_session {
160 Some(auth_session) => {
161 let mut session_write = self.sessions.write();
162 if session_write.contains_key(&sessionid) {
163 Err(OperationError::InvalidSessionState)
166 } else {
167 session_write.insert(sessionid, Arc::new(Mutex::new(auth_session)));
168 debug_assert!(session_write.get(&sessionid).is_some());
170 Ok(())
171 }?;
172 session_write.commit();
173 }
174 None => {
175 security_info!("Authentication Session Unable to begin");
176 }
177 };
178
179 Ok(AuthResult { sessionid, state })
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use crate::{
186 credential::totp::Totp,
187 idm::{
188 audit::AuditEvent,
189 authentication::{AuthState, ReauthRequest},
190 credupdatesession::{InitCredentialUpdateEvent, MfaRegStateStatus},
191 delayed::DelayedAction,
192 event::{AuthEvent, AuthResult},
193 server::IdmServerTransaction,
194 },
195 prelude::*,
196 };
197 use compact_jwt::JwsCompact;
198 use kanidm_proto::v1::{AuthAllowed, AuthIssueSession, AuthMech};
199 use uuid::uuid;
200 use webauthn_authenticator_rs::{softpasskey::SoftPasskey, WebauthnAuthenticator};
201
202 const TESTPERSON_UUID: Uuid = uuid!("cf231fea-1a8f-4410-a520-fd9b1a379c86");
203
204 async fn setup_testaccount(idms: &IdmServer, ct: Duration) {
205 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
206
207 let e2 = entry_init!(
208 (Attribute::Class, EntryClass::Object.to_value()),
209 (Attribute::Class, EntryClass::Account.to_value()),
210 (Attribute::Class, EntryClass::Person.to_value()),
211 (Attribute::Name, Value::new_iname("testperson")),
212 (Attribute::Uuid, Value::Uuid(TESTPERSON_UUID)),
213 (Attribute::Description, Value::new_utf8s("testperson")),
214 (Attribute::DisplayName, Value::new_utf8s("testperson"))
215 );
216
217 let cr = idms_prox_write.qs_write.internal_create(vec![e2]);
218 assert!(cr.is_ok());
219 assert!(idms_prox_write.commit().is_ok());
220 }
221
222 async fn setup_testaccount_passkey(idms: &IdmServer, ct: Duration) -> SoftPasskey {
223 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
224 let testperson = idms_prox_write
225 .qs_write
226 .internal_search_uuid(TESTPERSON_UUID)
227 .expect("failed");
228 let (cust, _c_status) = idms_prox_write
229 .init_credential_update(
230 &InitCredentialUpdateEvent::new_impersonate_entry(testperson),
231 ct,
232 )
233 .expect("Failed to begin credential update.");
234 idms_prox_write.commit().expect("Failed to commit txn");
235
236 let cutxn = idms.cred_update_transaction().await.unwrap();
239 let origin = cutxn.get_origin().clone();
240
241 let mut wa = SoftPasskey::new(true);
242
243 let c_status = cutxn
244 .credential_passkey_init(&cust, ct)
245 .expect("Failed to initiate passkey registration");
246
247 let passkey_chal = match c_status.mfaregstate() {
248 MfaRegStateStatus::Passkey(c) => Some(c),
249 _ => None,
250 }
251 .expect("Unable to access passkey challenge, invalid state");
252
253 let passkey_resp = wa
254 .do_registration(origin.clone(), passkey_chal.clone())
255 .expect("Failed to create soft passkey");
256
257 let label = "softtoken".to_string();
259 let c_status = cutxn
260 .credential_passkey_finish(&cust, ct, label, &passkey_resp)
261 .expect("Failed to initiate passkey registration");
262
263 assert!(c_status.can_commit());
264
265 drop(cutxn);
266 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
267
268 idms_prox_write
269 .commit_credential_update(&cust, ct)
270 .expect("Failed to commit credential update.");
271
272 idms_prox_write.commit().expect("Failed to commit txn");
273
274 wa
275 }
276
277 async fn setup_testaccount_password_totp(idms: &IdmServer, ct: Duration) -> (String, Totp) {
278 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
279 let testperson = idms_prox_write
280 .qs_write
281 .internal_search_uuid(TESTPERSON_UUID)
282 .expect("failed");
283 let (cust, _c_status) = idms_prox_write
284 .init_credential_update(
285 &InitCredentialUpdateEvent::new_impersonate_entry(testperson),
286 ct,
287 )
288 .expect("Failed to begin credential update.");
289 idms_prox_write.commit().expect("Failed to commit txn");
290
291 let cutxn = idms.cred_update_transaction().await.unwrap();
292
293 let pw = crate::utils::password_from_random();
294
295 let _c_status = cutxn
296 .credential_primary_set_password(&cust, ct, &pw)
297 .expect("Failed to update the primary cred password");
298
299 let c_status = cutxn
300 .credential_primary_init_totp(&cust, ct)
301 .expect("Failed to update the primary cred password");
302
303 let totp_token: Totp = match c_status.mfaregstate() {
305 MfaRegStateStatus::TotpCheck(secret) => Some(secret.clone().try_into().unwrap()),
306
307 _ => None,
308 }
309 .expect("Unable to retrieve totp token, invalid state.");
310
311 trace!(?totp_token);
312 let chal = totp_token
313 .do_totp_duration_from_epoch(&ct)
314 .expect("Failed to perform totp step");
315
316 let c_status = cutxn
317 .credential_primary_check_totp(&cust, ct, chal, "totp")
318 .expect("Failed to update the primary cred password");
319
320 assert!(matches!(c_status.mfaregstate(), MfaRegStateStatus::None));
321 assert!(c_status.can_commit());
322
323 drop(cutxn);
324 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
325
326 idms_prox_write
327 .commit_credential_update(&cust, ct)
328 .expect("Failed to commit credential update.");
329
330 idms_prox_write.commit().expect("Failed to commit txn");
331
332 (pw, totp_token)
333 }
334
335 async fn auth_passkey(
336 idms: &IdmServer,
337 ct: Duration,
338 wa: &mut SoftPasskey,
339 idms_delayed: &mut IdmServerDelayed,
340 ) -> Option<JwsCompact> {
341 let mut idms_auth = idms.auth().await.unwrap();
342 let origin = idms_auth.get_origin().clone();
343
344 let auth_init = AuthEvent::named_init("testperson");
345
346 let r1 = idms_auth
347 .auth(&auth_init, ct, Source::Internal.into())
348 .await;
349 let ar = r1.unwrap();
350 let AuthResult { sessionid, state } = ar;
351
352 if !matches!(state, AuthState::Choose(_)) {
353 debug!("Can't proceed - {:?}", state);
354 return None;
355 };
356
357 let auth_begin = AuthEvent::begin_mech(sessionid, AuthMech::Passkey);
358
359 let r2 = idms_auth
360 .auth(&auth_begin, ct, Source::Internal.into())
361 .await;
362 let ar = r2.unwrap();
363 let AuthResult { sessionid, state } = ar;
364
365 trace!(?state);
366
367 let rcr = match state {
368 AuthState::Continue(mut allowed) => match allowed.pop() {
369 Some(AuthAllowed::Passkey(rcr)) => rcr,
370 _ => unreachable!(),
371 },
372 _ => unreachable!(),
373 };
374
375 trace!(?rcr);
376
377 let resp = wa
378 .do_authentication(origin, rcr)
379 .expect("failed to use softtoken to authenticate");
380
381 let passkey_step = AuthEvent::cred_step_passkey(sessionid, resp);
382
383 let r3 = idms_auth
384 .auth(&passkey_step, ct, Source::Internal.into())
385 .await;
386 debug!("r3 ==> {:?}", r3);
387 idms_auth.commit().expect("Must not fail");
388
389 match r3 {
390 Ok(AuthResult {
391 sessionid: _,
392 state: AuthState::Success(token, AuthIssueSession::Token),
393 }) => {
394 let da = idms_delayed.try_recv().expect("invalid");
396 assert!(matches!(da, DelayedAction::WebauthnCounterIncrement(_)));
397 let r = idms.delayed_action(ct, da).await;
398 assert!(r.is_ok());
399
400 let da = idms_delayed.try_recv().expect("invalid");
402 assert!(matches!(da, DelayedAction::AuthSessionRecord(_)));
403 let r = idms.delayed_action(ct, da).await;
406 assert!(r.is_ok());
407
408 Some(*token)
409 }
410 _ => None,
411 }
412 }
413
414 async fn auth_password_totp(
415 idms: &IdmServer,
416 ct: Duration,
417 pw: &str,
418 token: &Totp,
419 idms_delayed: &mut IdmServerDelayed,
420 ) -> Option<JwsCompact> {
421 let mut idms_auth = idms.auth().await.unwrap();
422
423 let auth_init = AuthEvent::named_init("testperson");
424
425 let r1 = idms_auth
426 .auth(&auth_init, ct, Source::Internal.into())
427 .await;
428 let ar = r1.unwrap();
429 let AuthResult { sessionid, state } = ar;
430
431 if !matches!(state, AuthState::Choose(_)) {
432 debug!("Can't proceed - {:?}", state);
433 return None;
434 };
435
436 let auth_begin = AuthEvent::begin_mech(sessionid, AuthMech::PasswordTotp);
437
438 let r2 = idms_auth
439 .auth(&auth_begin, ct, Source::Internal.into())
440 .await;
441 let ar = r2.unwrap();
442 let AuthResult { sessionid, state } = ar;
443
444 assert!(matches!(state, AuthState::Continue(_)));
445
446 let totp = token
447 .do_totp_duration_from_epoch(&ct)
448 .expect("Failed to perform totp step");
449
450 let totp_step = AuthEvent::cred_step_totp(sessionid, totp);
451 let r2 = idms_auth
452 .auth(&totp_step, ct, Source::Internal.into())
453 .await;
454 let ar = r2.unwrap();
455 let AuthResult { sessionid, state } = ar;
456
457 assert!(matches!(state, AuthState::Continue(_)));
458
459 let pw_step = AuthEvent::cred_step_password(sessionid, pw);
460
461 let r3 = idms_auth.auth(&pw_step, ct, Source::Internal.into()).await;
463 debug!("r3 ==> {:?}", r3);
464 idms_auth.commit().expect("Must not fail");
465
466 match r3 {
467 Ok(AuthResult {
468 sessionid: _,
469 state: AuthState::Success(token, AuthIssueSession::Token),
470 }) => {
471 let da = idms_delayed.try_recv().expect("invalid");
473 assert!(matches!(da, DelayedAction::AuthSessionRecord(_)));
474 let r = idms.delayed_action(ct, da).await;
477 assert!(r.is_ok());
478
479 Some(*token)
480 }
481 _ => None,
482 }
483 }
484
485 async fn token_to_ident(
486 idms: &IdmServer,
487 ct: Duration,
488 client_auth_info: ClientAuthInfo,
489 ) -> Identity {
490 let mut idms_prox_read = idms.proxy_read().await.unwrap();
491
492 idms_prox_read
493 .validate_client_auth_info_to_ident(client_auth_info, ct)
494 .expect("Invalid UAT")
495 }
496
497 async fn reauth_passkey(
498 idms: &IdmServer,
499 ct: Duration,
500 ident: &Identity,
501 wa: &mut SoftPasskey,
502 idms_delayed: &mut IdmServerDelayed,
503 reauth_req: ReauthRequest,
504 ) -> Option<JwsCompact> {
505 let mut idms_auth = idms.auth().await.unwrap();
506 let origin = idms_auth.get_origin().clone();
507
508 let auth_allowed = idms_auth
509 .reauth_init(
510 ident.clone(),
511 AuthIssueSession::Token,
512 ct,
513 Source::Internal.into(),
514 reauth_req,
515 )
516 .await
517 .expect("Failed to start reauth.");
518
519 let AuthResult { sessionid, state } = auth_allowed;
520
521 trace!(?state);
522
523 let rcr = match state {
524 AuthState::Continue(mut allowed) => match allowed.pop() {
525 Some(AuthAllowed::Passkey(rcr)) => rcr,
526 _ => return None,
527 },
528 _ => unreachable!(),
529 };
530
531 trace!(?rcr);
532
533 let resp = wa
534 .do_authentication(origin, rcr)
535 .expect("failed to use softtoken to authenticate");
536
537 let passkey_step = AuthEvent::cred_step_passkey(sessionid, resp);
538
539 let r3 = idms_auth
540 .auth(&passkey_step, ct, Source::Internal.into())
541 .await;
542 debug!("r3 ==> {:?}", r3);
543 idms_auth.commit().expect("Must not fail");
544
545 match r3 {
546 Ok(AuthResult {
547 sessionid: _,
548 state: AuthState::Success(token, AuthIssueSession::Token),
549 }) => {
550 let da = idms_delayed.try_recv().expect("invalid");
552 assert!(matches!(da, DelayedAction::WebauthnCounterIncrement(_)));
553 let r = idms.delayed_action(ct, da).await;
554 assert!(r.is_ok());
555
556 Some(*token)
560 }
561 _ => unreachable!(),
562 }
563 }
564
565 async fn reauth_password_totp(
566 idms: &IdmServer,
567 ct: Duration,
568 ident: &Identity,
569 pw: &str,
570 token: &Totp,
571 idms_delayed: &mut IdmServerDelayed,
572 ) -> Option<JwsCompact> {
573 let mut idms_auth = idms.auth().await.unwrap();
574
575 let auth_allowed = idms_auth
576 .reauth_init(
577 ident.clone(),
578 AuthIssueSession::Token,
579 ct,
580 Source::Internal.into(),
581 ReauthRequest::GrantReadWrite,
582 )
583 .await
584 .expect("Failed to start reauth.");
585
586 let AuthResult { sessionid, state } = auth_allowed;
587
588 trace!(?state);
589
590 match state {
591 AuthState::Denied(reason) => {
592 trace!("{}", reason);
593 return None;
594 }
595 AuthState::Continue(mut allowed) => match allowed.pop() {
596 Some(AuthAllowed::Totp) => {}
597 _ => return None,
598 },
599 _ => unreachable!(),
600 };
601
602 let totp = token
603 .do_totp_duration_from_epoch(&ct)
604 .expect("Failed to perform totp step");
605
606 let totp_step = AuthEvent::cred_step_totp(sessionid, totp);
607 let r2 = idms_auth
608 .auth(&totp_step, ct, Source::Internal.into())
609 .await;
610 let ar = r2.unwrap();
611 let AuthResult { sessionid, state } = ar;
612
613 assert!(matches!(state, AuthState::Continue(_)));
614
615 let pw_step = AuthEvent::cred_step_password(sessionid, pw);
616
617 let r3 = idms_auth.auth(&pw_step, ct, Source::Internal.into()).await;
619 debug!("r3 ==> {:?}", r3);
620 idms_auth.commit().expect("Must not fail");
621
622 match r3 {
623 Ok(AuthResult {
624 sessionid: _,
625 state: AuthState::Success(token, AuthIssueSession::Token),
626 }) => {
627 let da = idms_delayed.try_recv().expect("invalid");
629 assert!(matches!(da, DelayedAction::AuthSessionRecord(_)));
630 Some(*token)
631 }
632 _ => None,
633 }
634 }
635
636 #[idm_test]
637 async fn test_idm_reauth_passkey(idms: &IdmServer, idms_delayed: &mut IdmServerDelayed) {
638 let ct = duration_from_epoch_now();
639
640 setup_testaccount(idms, ct).await;
642 let mut passkey = setup_testaccount_passkey(idms, ct).await;
643
644 let token = auth_passkey(idms, ct, &mut passkey, idms_delayed)
646 .await
647 .expect("failed to authenticate with passkey");
648
649 let ident = token_to_ident(idms, ct, token.clone().into()).await;
651
652 debug!(?ident);
654 assert!(matches!(ident.access_scope(), AccessScope::ReadOnly));
655
656 let session = ident.get_session().expect("Unable to access sessions");
660
661 assert!(matches!(session.scope, SessionScope::PrivilegeCapable));
662
663 let token = reauth_passkey(
665 idms,
666 ct,
667 &ident,
668 &mut passkey,
669 idms_delayed,
670 ReauthRequest::GrantReadWrite,
671 )
672 .await
673 .expect("Failed to get new session token");
674
675 let ident = token_to_ident(idms, ct, token.clone().into()).await;
677
678 debug!(?ident);
680 assert!(matches!(ident.access_scope(), AccessScope::ReadWrite));
681
682 let token = reauth_passkey(
684 idms,
685 ct,
686 &ident,
687 &mut passkey,
688 idms_delayed,
689 ReauthRequest::VerifyCredentials,
690 )
691 .await
692 .expect("Failed to get new session token");
693
694 let ident = token_to_ident(idms, ct, token.clone().into()).await;
696
697 debug!(?ident);
699 assert!(matches!(ident.access_scope(), AccessScope::ReadOnly));
700 }
701
702 #[idm_test(audit = 1)]
703 async fn test_idm_reauth_softlocked_pw(
704 idms: &IdmServer,
705 idms_delayed: &mut IdmServerDelayed,
706 idms_audit: &mut IdmServerAudit,
707 ) {
708 let ct = duration_from_epoch_now();
711
712 setup_testaccount(idms, ct).await;
714 let (pw, totp) = setup_testaccount_password_totp(idms, ct).await;
715
716 let token = auth_password_totp(idms, ct, &pw, &totp, idms_delayed)
718 .await
719 .expect("failed to authenticate with passkey");
720
721 let ident = token_to_ident(idms, ct, token.into()).await;
723
724 debug!(?ident);
726 assert!(matches!(ident.access_scope(), AccessScope::ReadOnly));
727
728 let session = ident.get_session().expect("Unable to access sessions");
731
732 assert!(matches!(session.scope, SessionScope::PrivilegeCapable));
733
734 assert!(reauth_password_totp(
736 idms,
737 ct,
738 &ident,
739 "absolutely-wrong-password",
740 &totp,
741 idms_delayed
742 )
743 .await
744 .is_none());
745
746 match idms_audit.audit_rx().try_recv() {
748 Ok(AuditEvent::AuthenticationDenied { .. }) => {}
749 _ => panic!("Oh no"),
750 }
751
752 assert!(
754 reauth_password_totp(idms, ct, &ident, &pw, &totp, idms_delayed)
755 .await
756 .is_none()
757 );
758 }
759}