1use crate::{
2 credential::totp::{Totp, TotpAlgo, TotpDigits},
3 idm::server::IdmServerProxyReadTransaction,
4 prelude::*,
5 server::{identity::Identity, keys::KeyProvidersTransaction, QueryServerTransaction},
6};
7use crypto_glue::hmac_s256::HmacSha256Key;
8use kanidm_proto::internal::IdentifyUserResponse;
9use std::sync::Arc;
10use uuid::Uuid;
11
12static TOTP_STEP: u64 = 300;
15
16#[derive(Debug)]
17pub struct IdentifyUserStartEvent {
18 pub target: Uuid,
19 pub ident: Identity,
20}
21
22impl IdentifyUserStartEvent {
23 pub fn new(target: Uuid, ident: Identity) -> Self {
24 IdentifyUserStartEvent { target, ident }
25 }
26}
27pub struct IdentifyUserDisplayCodeEvent {
28 pub target: Uuid,
29 pub ident: Identity,
30}
31
32impl IdentifyUserDisplayCodeEvent {
33 pub fn new(target: Uuid, ident: Identity) -> Self {
34 IdentifyUserDisplayCodeEvent { target, ident }
35 }
36}
37
38pub struct IdentifyUserSubmitCodeEvent {
39 pub code: u32,
40 pub target: Uuid,
41 pub ident: Identity,
42}
43
44impl IdentifyUserSubmitCodeEvent {
45 pub fn new(target: Uuid, ident: Identity, code: u32) -> Self {
46 IdentifyUserSubmitCodeEvent {
47 target,
48 ident,
49 code,
50 }
51 }
52}
53
54impl IdmServerProxyReadTransaction<'_> {
55 pub fn handle_identify_user_start(
56 &mut self,
57 IdentifyUserStartEvent { target, ident }: &IdentifyUserStartEvent,
58 current_time: Duration,
59 ) -> Result<IdentifyUserResponse, OperationError> {
60 let (ident_entry, target_entry) = match self.get_involved_entries(ident, *target) {
61 Ok(tuple) => tuple,
62 Err(early_response) => return Ok(early_response),
63 };
64
65 let response = if ident_entry.get_uuid() < target_entry.get_uuid() {
66 IdentifyUserResponse::WaitForCode
67 } else {
68 let totp_secret = self.get_totp(current_time, &ident_entry, &target_entry)?;
69
70 let totp_value = totp_secret
71 .do_totp_duration_from_epoch(¤t_time)
72 .map_err(|_| OperationError::CryptographyError)?;
73
74 IdentifyUserResponse::ProvideCode {
75 step: TOTP_STEP as u32,
76 totp: totp_value,
77 }
78 };
79 Ok(response)
80 }
81
82 pub fn handle_identify_user_display_code(
83 &mut self,
84 IdentifyUserDisplayCodeEvent { target, ident }: &IdentifyUserDisplayCodeEvent,
85 current_time: Duration,
86 ) -> Result<IdentifyUserResponse, OperationError> {
87 let (ident_entry, target_entry) = match self.get_involved_entries(ident, *target) {
88 Ok(tuple) => tuple,
89 Err(early_response) => return Ok(early_response),
90 };
91
92 let totp_secret = self.get_totp(current_time, &ident_entry, &target_entry)?;
93
94 let totp_value = totp_secret
95 .do_totp_duration_from_epoch(¤t_time)
96 .map_err(|_| OperationError::CryptographyError)?;
97
98 Ok(IdentifyUserResponse::ProvideCode {
99 step: TOTP_STEP as u32,
100 totp: totp_value,
101 })
102 }
103
104 pub fn handle_identify_user_submit_code(
105 &mut self,
106 IdentifyUserSubmitCodeEvent {
107 target,
108 ident,
109 code,
110 }: &IdentifyUserSubmitCodeEvent,
111 current_time: Duration,
112 ) -> Result<IdentifyUserResponse, OperationError> {
113 let (ident_entry, target_entry) = match self.get_involved_entries(ident, *target) {
114 Ok(tuple) => tuple,
115 Err(early_response) => return Ok(early_response),
116 };
117
118 let totp_secret = self.get_totp(current_time, &target_entry, &ident_entry)?;
119
120 if !totp_secret.verify(*code, current_time) {
121 return Ok(IdentifyUserResponse::CodeFailure);
122 }
123
124 let response = if ident_entry.get_uuid() < target_entry.get_uuid() {
127 let totp_secret = self.get_totp(current_time, &ident_entry, &target_entry)?;
128 let totp_value = totp_secret
129 .do_totp_duration_from_epoch(¤t_time)
130 .map_err(|_| OperationError::CryptographyError)?;
131 IdentifyUserResponse::ProvideCode {
132 step: TOTP_STEP as u32,
133 totp: totp_value,
134 }
135 } else {
136 IdentifyUserResponse::Success
137 };
138 Ok(response)
139 }
140
141 fn get_involved_entries(
142 &mut self,
143 ident: &Identity,
144 target: Uuid,
145 ) -> Result<(Arc<EntrySealedCommitted>, Arc<EntrySealedCommitted>), IdentifyUserResponse> {
146 if self
147 .qs_read
148 .get_key_providers()
149 .get_key_object_handle(UUID_DOMAIN_ID_VERIFICATION_KEY)
150 .is_none()
151 {
152 return Err(IdentifyUserResponse::IdentityVerificationUnavailable);
153 }
154
155 let Some(ident_entry) = ident.get_user_entry() else {
156 return Err(IdentifyUserResponse::IdentityVerificationUnavailable);
157 };
158
159 let Ok(target_entry) = self.get_partner_entry(target) else {
160 return Err(IdentifyUserResponse::IdentityVerificationUnavailable);
161 };
162
163 if ident_entry.get_uuid() == target_entry.get_uuid() {
164 return Err(IdentifyUserResponse::IdentityVerificationUnavailable);
165 }
166
167 Ok((ident_entry, target_entry))
168 }
169
170 fn get_partner_entry(
171 &mut self,
172 target: Uuid,
173 ) -> Result<Arc<EntrySealedCommitted>, OperationError> {
174 self.qs_read
175 .internal_search_uuid(target)
176 .inspect_err(|err| error!(?err, ?target, "Failed to retrieve entry",))
177 }
178
179 fn get_totp(
180 &mut self,
181 current_time: Duration,
182 initiating_entry: &EntrySealedCommitted,
183 receiving_entry: &EntrySealedCommitted,
184 ) -> Result<Totp, OperationError> {
185 let key_object = self
186 .qs_read
187 .get_key_providers()
188 .get_key_object_handle(UUID_DOMAIN_ID_VERIFICATION_KEY)
189 .ok_or(OperationError::KP0078KeyObjectNotFound)?;
190
191 let initiating_uuid = initiating_entry.get_uuid();
192 let receiving_uuid = receiving_entry.get_uuid();
193
194 let mut info_bytes: [u8; 32] = [0; 32];
196 info_bytes[..16].copy_from_slice(initiating_uuid.as_bytes());
197 info_bytes[16..].copy_from_slice(receiving_uuid.as_bytes());
198
199 let mut shared_key = HmacSha256Key::default();
200 key_object.hkdf_s256_expand(&info_bytes, shared_key.as_mut_slice(), current_time)?;
201
202 let totp = Totp::new(
203 shared_key.as_slice().to_vec(),
204 TOTP_STEP,
205 TotpAlgo::Sha256,
206 TotpDigits::Six,
207 );
208 Ok(totp)
209 }
210}
211
212#[cfg(test)]
213mod test {
214 use crate::{
215 idm::identityverification::{
216 IdentifyUserDisplayCodeEvent, IdentifyUserStartEvent, IdentifyUserSubmitCodeEvent,
217 },
218 prelude::*,
219 };
220 use kanidm_proto::internal::IdentifyUserResponse;
221
222 #[idm_test]
223 async fn test_identity_verification_unavailable(
224 idms: &IdmServer,
225 _idms_delayed: &IdmServerDelayed,
226 ) {
227 let ct = duration_from_epoch_now();
228 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
229
230 let invalid_user_uuid = Uuid::new_v4();
231 let valid_user_uuid = Uuid::new_v4();
232
233 let e2 = create_valid_user_account(valid_user_uuid, "valid_idv_user");
234
235 let ce = CreateEvent::new_internal(vec![e2]);
236 assert!(idms_prox_write.qs_write.create(&ce).is_ok());
237 assert!(idms_prox_write.commit().is_ok());
238
239 let mut idms_prox_read = idms.proxy_read().await.unwrap();
240
241 let ident = idms_prox_read
242 .qs_read
243 .internal_search_uuid(valid_user_uuid)
244 .map(Identity::from_impersonate_entry_readonly)
245 .expect("Failed to impersonate identity");
246
247 let res = idms_prox_read
249 .handle_identify_user_start(
250 &IdentifyUserStartEvent::new(valid_user_uuid, Identity::from_internal()),
251 ct,
252 )
253 .expect("failed to start id verification");
254
255 assert!(matches!(
256 res,
257 IdentifyUserResponse::IdentityVerificationUnavailable
258 ));
259
260 let res = idms_prox_read
262 .handle_identify_user_start(
263 &IdentifyUserStartEvent::new(valid_user_uuid, ident.clone()),
264 ct,
265 )
266 .expect("failed to start id verification");
267
268 assert!(matches!(
269 res,
270 IdentifyUserResponse::IdentityVerificationUnavailable
271 ));
272
273 let res = idms_prox_read
275 .handle_identify_user_start(
276 &IdentifyUserStartEvent::new(invalid_user_uuid, ident.clone()),
277 ct,
278 )
279 .expect("failed to start id verification");
280
281 assert!(matches!(
282 res,
283 IdentifyUserResponse::IdentityVerificationUnavailable
284 ));
285 }
286
287 #[idm_test]
288 async fn test_idv_flow(idms: &IdmServer, _idms_delayed: &IdmServerDelayed) {
289 let ct = duration_from_epoch_now();
290 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
291 let user_a_uuid = uuid::uuid!("20f44860-7db3-40f4-a2c3-d9f163f855ec");
292 let user_b_uuid = uuid::uuid!("dde1de53-cbd2-439c-a3c9-bde6ee026e78");
293 let e1 = create_valid_user_account(user_a_uuid, "idv_user_a");
294 let e2 = create_valid_user_account(user_b_uuid, "idv_user_b");
295 let ce = CreateEvent::new_internal(vec![e1, e2]);
296
297 assert!(idms_prox_write.qs_write.create(&ce).is_ok());
298 assert!(idms_prox_write.commit().is_ok());
299
300 let mut idms_prox_read = idms.proxy_read().await.unwrap();
301
302 let user_a = idms_prox_read
303 .qs_read
304 .internal_search_uuid(user_a_uuid)
305 .map(Identity::from_impersonate_entry_readonly)
306 .expect("Failed to impersonate identity");
307
308 let user_b = idms_prox_read
309 .qs_read
310 .internal_search_uuid(user_b_uuid)
311 .map(Identity::from_impersonate_entry_readonly)
312 .expect("Failed to impersonate identity");
313
314 let res_higher_user = idms_prox_read
316 .handle_identify_user_start(
317 &IdentifyUserStartEvent::new(user_a_uuid, user_b.clone()),
318 ct,
319 )
320 .expect("Failed to retrieve code.");
321
322 let higher_user_totp = match res_higher_user {
323 IdentifyUserResponse::ProvideCode { totp, .. } => totp,
324 state => {
325 error!(?state);
326 unreachable!()
327 }
328 };
329
330 let res_higher_user = idms_prox_read
332 .handle_identify_user_display_code(
333 &IdentifyUserDisplayCodeEvent::new(user_a_uuid, user_b.clone()),
334 ct,
335 )
336 .expect("Failed to retrieve code.");
337
338 let higher_user_totp_display = match res_higher_user {
339 IdentifyUserResponse::ProvideCode { totp, .. } => totp,
340 state => {
341 error!(?state);
342 unreachable!()
343 }
344 };
345
346 assert_eq!(higher_user_totp_display, higher_user_totp);
347
348 let lower_user_state = idms_prox_read
350 .handle_identify_user_start(
351 &IdentifyUserStartEvent::new(user_b_uuid, user_a.clone()),
352 ct,
353 )
354 .expect("Failed start idv.");
355
356 assert!(matches!(
357 lower_user_state,
358 IdentifyUserResponse::WaitForCode
359 ));
360
361 let lower_user_state = idms_prox_read
363 .handle_identify_user_submit_code(
364 &IdentifyUserSubmitCodeEvent::new(
365 user_b_uuid,
366 user_a.clone(),
367 higher_user_totp + 1,
368 ),
369 ct,
370 )
371 .expect("Failed to retrieve code.");
372
373 match lower_user_state {
374 IdentifyUserResponse::CodeFailure => {}
375 state => {
376 error!(?state);
377 unreachable!()
378 }
379 };
380
381 let lower_user_state = idms_prox_read
383 .handle_identify_user_submit_code(
384 &IdentifyUserSubmitCodeEvent::new(user_b_uuid, user_a.clone(), higher_user_totp),
385 ct,
386 )
387 .expect("Failed to retrieve code.");
388
389 let lower_user_totp = match lower_user_state {
390 IdentifyUserResponse::ProvideCode { totp, .. } => totp,
391 state => {
392 error!(?state);
393 unreachable!()
394 }
395 };
396
397 debug!(?higher_user_totp, ?lower_user_totp);
398 assert_ne!(higher_user_totp, lower_user_totp);
399
400 let lower_user_state = idms_prox_read
402 .handle_identify_user_display_code(
403 &IdentifyUserDisplayCodeEvent::new(user_b_uuid, user_a.clone()),
404 ct,
405 )
406 .expect("Failed to retrieve code.");
407
408 let lower_user_totp_display = match lower_user_state {
409 IdentifyUserResponse::ProvideCode { totp, .. } => totp,
410 state => {
411 error!(?state);
412 unreachable!()
413 }
414 };
415
416 assert_eq!(lower_user_totp_display, lower_user_totp);
417
418 let higher_user_state = idms_prox_read
420 .handle_identify_user_submit_code(
421 &IdentifyUserSubmitCodeEvent::new(user_a_uuid, user_b.clone(), lower_user_totp + 1),
422 ct,
423 )
424 .expect("Failed to retrieve code.");
425
426 match higher_user_state {
427 IdentifyUserResponse::CodeFailure => {}
428 state => {
429 error!(?state);
430 unreachable!()
431 }
432 };
433
434 let higher_user_state = idms_prox_read
436 .handle_identify_user_submit_code(
437 &IdentifyUserSubmitCodeEvent::new(user_a_uuid, user_b.clone(), lower_user_totp),
438 ct,
439 )
440 .expect("Failed to retrieve code.");
441
442 match higher_user_state {
443 IdentifyUserResponse::Success => {}
444 state => {
445 error!(?state);
446 unreachable!()
447 }
448 };
449 }
450
451 fn create_valid_user_account(uuid: Uuid, name: &str) -> EntryInitNew {
452 entry_init!(
453 (Attribute::Class, EntryClass::Object.to_value()),
454 (Attribute::Class, EntryClass::Account.to_value()),
455 (Attribute::Class, EntryClass::Person.to_value()),
456 (Attribute::Name, Value::new_iname(name)),
457 (Attribute::Uuid, Value::Uuid(uuid)),
458 (Attribute::Description, Value::new_utf8s("some valid user")),
459 (Attribute::DisplayName, Value::new_utf8s("Some valid user"))
460 )
461 }
462}