-
Notifications
You must be signed in to change notification settings - Fork 80
/
core.rs
2201 lines (2017 loc) · 121 KB
/
core.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Webauthn-rs - Webauthn for Rust Server Applications
//!
//! Webauthn is a standard allowing communication between servers, browsers and authenticators
//! to allow strong, passwordless, cryptographic authentication to be performed. Webauthn
//! is able to operate with many authenticator types, such as U2F.
//!
//! This library aims to provide a secure Webauthn implementation that you can
//! plug into your application, so that you can provide Webauthn to your users.
//!
//! For examples, see our examples folder.
//!
//! To use this library yourself, you will want to reference the `WebauthnConfig` trait to
//! develop site specific policy and configuration, and the `Webauthn` struct for Webauthn
//! interactions.
#![warn(missing_docs)]
use rand::prelude::*;
use std::convert::TryFrom;
use crate::attestation::{
verify_apple_anonymous_attestation, verify_fidou2f_attestation, verify_none_attestation,
verify_packed_attestation, verify_tpm_attestation, AttestationFormat,
};
use crate::base64_data::Base64UrlSafeData;
use crate::constants::{AUTHENTICATOR_TIMEOUT, CHALLENGE_SIZE_BYTES};
use crate::crypto::compute_sha256;
use crate::error::WebauthnError;
use crate::proto::*;
/// The in progress state of a credential registration attempt. You must persist this associated
/// to the UserID requesting the registration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegistrationState {
policy: UserVerificationPolicy,
exclude_credentials: Vec<CredentialID>,
challenge: Base64UrlSafeData,
}
/// The in progress state of an authentication attempt. You must persist this associated to the UserID
/// requesting the registration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthenticationState {
credentials: Vec<Credential>,
policy: UserVerificationPolicy,
challenge: Base64UrlSafeData,
appid: Option<String>,
}
impl AuthenticationState {
/// set which credentials the user is allowed to authenticate with
pub fn set_allowed_credentials(&mut self, credentials: Vec<Credential>) {
self.credentials = credentials;
}
}
/// This is the core of the Webauthn operations. It provides 4 interfaces that you will likely
/// use the most:
/// * generate_challenge_response
/// * register_credential
/// * generate_challenge_authenticate
/// * authenticate_credential
///
/// Each of these is described in turn, but they will all map to routes in your application.
/// The generate functions return Json challenges that are intended to be processed by the client
/// browser, and the register and authenticate will receive Json that is processed and verified.
///
/// These functions return state that you must store and handle correctly for the authentication
/// or registration to proceed correctly.
///
/// As a result, it's very important you read the function descriptions to understand the process
/// as much as possible.
#[derive(Debug)]
pub struct Webauthn<T> {
config: T,
pkcp: Vec<PubKeyCredParams>,
rp_id_hash: Vec<u8>,
}
impl<T> Webauthn<T> {
/// Create a new Webauthn instance with the supplied configuration. The config type
/// will receive and interact with various callbacks to allow the lifecycle and
/// application handling of Credentials to be customised for your application.
///
/// You should see the Documentation for WebauthnConfig, which is the main part of
/// the code you will interact with for site-specific customisation.
pub fn new(config: T) -> Self
where
T: WebauthnConfig,
{
let pkcp = config
.get_credential_algorithms()
.iter()
.map(|a| PubKeyCredParams {
type_: "public-key".to_string(),
alg: a.into(),
})
.collect();
let rp_id_hash = compute_sha256(config.get_relying_party_id().as_bytes());
Webauthn {
// Use a per-thread csprng
config,
pkcp,
rp_id_hash,
}
}
fn generate_challenge(&self) -> Challenge {
let mut rng = rand::thread_rng();
Challenge::new(rng.gen::<[u8; CHALLENGE_SIZE_BYTES]>().to_vec())
}
/// Generate a new challenge for client registration.
/// Same as `generate_challenge_register_options` but default options
pub fn generate_challenge_register(
&self,
user_name: &str,
user_verification_required: bool,
) -> Result<(CreationChallengeResponse, RegistrationState), WebauthnError>
where
T: WebauthnConfig,
{
let policy = if user_verification_required {
Some(UserVerificationPolicy::Required)
} else {
Some(UserVerificationPolicy::Discouraged)
};
self.generate_challenge_register_options(
user_name.as_bytes().to_vec(),
user_name.to_string(),
user_name.to_string(),
None,
policy,
None,
)
}
/// Generate a new challenge for client registration. This is the first step in
/// the lifecycle of a credential. This function will return the
/// creationchallengeresponse which is suitable for serde json serialisation
/// to be sent to the client.
/// The client (generally a web browser) will pass this JSON
/// structure to the `navigator.credentials.create()` javascript function for registration.
///
/// It also returns a RegistrationState, that you *must*
/// persist. It is strongly advised you associate this RegistrationState with the
/// UserId of the requester.
pub fn generate_challenge_register_options(
&self,
user_id: UserId,
user_name: String,
user_display_name: String,
exclude_credentials: Option<Vec<CredentialID>>,
policy: Option<UserVerificationPolicy>,
extensions: Option<RequestRegistrationExtensions>,
) -> Result<(CreationChallengeResponse, RegistrationState), WebauthnError>
where
T: WebauthnConfig,
{
// Technically this goes against the standard. But it's the correct
// thing to do if no policy was requested.
let policy = policy.unwrap_or(UserVerificationPolicy::Discouraged);
if policy == UserVerificationPolicy::Preferred_DO_NOT_USE {
log::warn!("UserVerificationPolicy::Preferred_DO_NOT_USE is misleading! You should select Discouraged or Required!");
}
if user_id.is_empty() {
return Err(WebauthnError::InvalidUsername);
}
let challenge = self.generate_challenge();
let c = CreationChallengeResponse {
public_key: PublicKeyCredentialCreationOptions {
rp: RelyingParty {
name: self.config.get_relying_party_name().to_owned(),
id: self.config.get_relying_party_id().to_owned(),
},
user: User {
id: Base64UrlSafeData(user_id),
name: user_name,
display_name: user_display_name,
},
challenge: challenge.clone().into(),
pub_key_cred_params: self
.config
.get_credential_algorithms()
.into_iter()
.map(|alg| PubKeyCredParams {
type_: "public-key".to_string(),
alg: alg as i64,
})
.collect(),
timeout: Some(self.config.get_authenticator_timeout()),
attestation: Some(self.config.get_attestation_preference()),
exclude_credentials: exclude_credentials.as_ref().map(|creds| {
creds
.iter()
.cloned()
.map(PublicKeyCredentialDescriptor::from_bytes)
.collect()
}),
authenticator_selection: Some(AuthenticatorSelectionCriteria {
authenticator_attachment: self.config.get_authenticator_attachment(),
require_resident_key: self.config.get_require_resident_key(),
user_verification: policy.clone(),
}),
extensions,
},
};
let wr = RegistrationState {
policy,
exclude_credentials: exclude_credentials.unwrap_or_else(|| Vec::with_capacity(0)),
challenge: challenge.into(),
};
// This should have an opaque type of username + chal + policy
Ok((c, wr))
}
/// Process a credential registration response. This is the output of
/// `navigator.credentials.create()` which is sent to the webserver from the client.
///
/// Given the username you also must provide the associated RegistrationState for this
/// operation to proceed.
///
/// On success this returns a new Credential that you must persist and associate with the
/// user.
///
/// You need to provide a closure that is able to check if any credential of the
/// same id has already been persisted by your server.
pub fn register_credential(
&self,
reg: &RegisterPublicKeyCredential,
state: &RegistrationState,
does_exist_fn: impl Fn(&CredentialID) -> Result<bool, ()>,
) -> Result<(Credential, AuthenticatorData<Registration>), WebauthnError>
where
T: WebauthnConfig,
{
// Decompose our registration state which contains everything we need to proceed.
let RegistrationState {
policy,
exclude_credentials,
challenge,
} = state;
let chal: &ChallengeRef = challenge.into();
// TODO: check the req username matches? I think it's not possible, the caller needs to
// create the linkage between the username and the state.
// send to register_credential_internal
let credential =
self.register_credential_internal(reg, policy.clone(), chal, &exclude_credentials)?;
// Check that the credentialId is not yet registered to any other user. If registration is
// requested for a credential that is already registered to a different user, the Relying
// Party SHOULD fail this registration ceremony, or it MAY decide to accept the registration,
// e.g. while deleting the older registration.
let cred_exist_result = does_exist_fn(&credential.0.cred_id)
.map_err(|_| WebauthnError::CredentialExistCheckError)?;
if cred_exist_result {
return Err(WebauthnError::CredentialAlreadyExists);
}
Ok(credential)
}
pub(crate) fn register_credential_internal(
&self,
reg: &RegisterPublicKeyCredential,
policy: UserVerificationPolicy,
chal: &ChallengeRef,
exclude_credentials: &[CredentialID],
) -> Result<(Credential, AuthenticatorData<Registration>), WebauthnError>
where
T: WebauthnConfig,
{
// ======================================================================
// References:
// Level 2: https://www.w3.org/TR/webauthn-2/#sctn-registering-a-new-credential
// Steps 1 through 4 are performed by the Client, not the RP.
// Let JSONtext be the result of running UTF-8 decode on the value of response.clientDataJSON.
//
// This is done by the calling webserver to give us reg aka JSONText in this case.
//
// Let C, the client data claimed as collected during the credential creation, be the result
// of running an implementation-specific JSON parser on JSONtext.
//
// Now, we actually do a much larger conversion in one shot
// here, where we get the AuthenticatorAttestationResponse
let data = AuthenticatorAttestationResponse::try_from(®.response)?;
// println!("data: {:?}", data);
// Verify that the value of C.type is webauthn.create.
if data.client_data_json.type_ != "webauthn.create" {
return Err(WebauthnError::InvalidClientDataType);
}
// Verify that the value of C.challenge matches the challenge that was sent to the
// authenticator in the create() call.
if data.client_data_json.challenge.0 != chal.as_ref() {
return Err(WebauthnError::MismatchedChallenge);
}
// Verify that the value of C.origin matches the Relying Party's origin.
if data.client_data_json.origin != self.config.get_origin() {
log::debug!(
"{} != {}",
data.client_data_json.origin,
self.config.get_origin()
);
return Err(WebauthnError::InvalidRPOrigin);
}
// ATM most browsers do not send this value, so we must default to
// `false`. See [WebauthnConfig::allow_cross_origin] doc-comment for
// more.
if !self.config.allow_cross_origin() && data.client_data_json.cross_origin.unwrap_or(false)
{
return Err(WebauthnError::CredentialCrossOrigin);
}
// Verify that the value of C.tokenBinding.status matches the state of Token Binding for the
// TLS connection over which the assertion was obtained. If Token Binding was used on that
// TLS connection, also verify that C.tokenBinding.id matches the base64url encoding of the
// Token Binding ID for the connection.
//
// This could be reasonably complex to do, given that we could be behind a load balancer
// or we may not directly know the status of TLS inside this api. I'm open to creative
// suggestions on this topic!
//
// Let hash be the result of computing a hash over response.clientDataJSON using SHA-256
//
// clarifying point - this is the hash of bytes.
//
// First you have to decode this from base64!!! This really could just be implementation
// specific though ...
let client_data_json_hash = compute_sha256(data.client_data_json_bytes.as_slice());
// Perform CBOR decoding on the attestationObject field of the AuthenticatorAttestationResponse
// structure to obtain the attestation statement format fmt, the authenticator data authData,
// and the attestation statement attStmt.
//
// Done as part of try_from
// Verify that the rpIdHash in authData is the SHA-256 hash of the RP ID expected by the
// Relying Party.
//
// NOW: Remember that RP ID https://w3c.github.io/webauthn/#rp-id is NOT THE SAME as the RP name
// it's actually derived from the RP origin.
if data.attestation_object.auth_data.rp_id_hash != self.rp_id_hash {
return Err(WebauthnError::InvalidRPIDHash);
}
// Verify that the User Present bit of the flags in authData is set.
if !data.attestation_object.auth_data.user_present {
return Err(WebauthnError::UserNotPresent);
}
// TODO: Is it possible to verify the attachement policy and resident
// key requirement here?
// If user verification is required for this registration, verify that the User Verified bit
// of the flags in authData is set.
match policy {
UserVerificationPolicy::Required => {
if !data.attestation_object.auth_data.user_verified {
return Err(WebauthnError::UserNotVerified);
}
}
UserVerificationPolicy::Preferred_DO_NOT_USE | UserVerificationPolicy::Discouraged => {}
};
// Verify that the "alg" parameter in the credential public key in authData matches the alg
// attribute of one of the items in options.pubKeyCredParams.
//
// WARNING: This is actually done after attestation as the credential public key
// is NOT available yet!
// Verify that the values of the client extension outputs in clientExtensionResults and the
// authenticator extension outputs in the extensions in authData are as expected,
// considering the client extension input values that were given as the extensions option in
// the create() call. In particular, any extension identifier values in the
// clientExtensionResults and the extensions in authData MUST be also be present as
// extension identifier values in the extensions member of options, i.e., no extensions are
// present that were not requested. In the general case, the meaning of "are as expected" is
// specific to the Relying Party and which extensions are in use.
if let Some(ext) = &data.attestation_object.auth_data.extensions {
log::debug!("ext: {:?}", ext);
} else {
log::debug!("no extensions");
}
// Determine the attestation statement format by performing a USASCII case-sensitive match on
// fmt against the set of supported WebAuthn Attestation Statement Format Identifier values.
// An up-to-date list of registered WebAuthn Attestation Statement Format Identifier values
// is maintained in the IANA registry of the same name [WebAuthn-Registries].
// ( https://tools.ietf.org/html/draft-hodges-webauthn-registries-02 )
//
// https://w3c.github.io/webauthn/#packed-attestation
// https://w3c.github.io/webauthn/#tpm-attestation
// https://w3c.github.io/webauthn/#android-key-attestation
// https://w3c.github.io/webauthn/#android-safetynet-attestation
// https://w3c.github.io/webauthn/#fido-u2f-attestation
// https://w3c.github.io/webauthn/#none-attestation
let attest_format = AttestationFormat::try_from(data.attestation_object.fmt.as_str())?;
// Verify that attStmt is a correct attestation statement, conveying a valid attestation
// signature, by using the attestation statement format fmt’s verification procedure given
// attStmt, authData and the hash of the serialized client data.
let acd = data
.attestation_object
.auth_data
.acd
.as_ref()
.ok_or(WebauthnError::MissingAttestationCredentialData)?;
// Now, match based on the attest_format
// This returns an ParsedAttestationData, containing all the metadata needed for
log::debug!("attestation is: {:?}", &attest_format);
let (attest_result, credential) = match attest_format {
AttestationFormat::FIDOU2F => verify_fidou2f_attestation(
acd,
data.attestation_object.auth_data.counter,
data.attestation_object.auth_data.user_verified,
&data.attestation_object.att_stmt,
&client_data_json_hash,
&data.attestation_object.auth_data.rp_id_hash,
policy,
),
AttestationFormat::Packed => verify_packed_attestation(
acd,
data.attestation_object.auth_data.counter,
data.attestation_object.auth_data.user_verified,
&data.attestation_object.att_stmt,
&data.attestation_object.auth_data_bytes,
&client_data_json_hash,
policy,
),
AttestationFormat::TPM => verify_tpm_attestation(
acd,
data.attestation_object.auth_data.counter,
data.attestation_object.auth_data.user_verified,
&data.attestation_object.att_stmt,
&data.attestation_object.auth_data_bytes,
&client_data_json_hash,
policy,
),
AttestationFormat::AppleAnonymous => verify_apple_anonymous_attestation(
acd,
data.attestation_object.auth_data.counter,
data.attestation_object.auth_data.user_verified,
&data.attestation_object.att_stmt,
&data.attestation_object.auth_data_bytes,
&client_data_json_hash,
policy,
),
AttestationFormat::None => verify_none_attestation(
acd,
data.attestation_object.auth_data.counter,
data.attestation_object.auth_data.user_verified,
policy,
),
_ => {
if self.config.ignore_unsupported_attestation_formats() {
let credential_public_key = COSEKey::try_from(&acd.credential_pk)?;
Ok((
ParsedAttestationData::None,
Credential::new(
acd,
credential_public_key,
data.attestation_object.auth_data.counter,
false,
policy,
),
))
} else {
// No other types are currently implemented
Err(WebauthnError::AttestationNotSupported)
}
}
}?;
// Now based on result ...
// If validation is successful, obtain a list of acceptable trust anchors (attestation
// root certificates or ECDAA-Issuer public keys) for that attestation type and attestation
// statement format fmt, from a trusted source or from policy. For example, the FIDO Metadata
// Service [FIDOMetadataService] provides one way to obtain such information, using the
// aaguid in the attestedCredentialData in authData.
// ⚠️ This is done through the policy verify trust callback that the user of this library
// implements and provides.
// Assess the attestation trustworthiness using the outputs of the verification procedure in step 19, as follows:
//
// * If no attestation was provided, verify that None attestation is acceptable under Relying Party policy.
// * If self attestation was used, verify that self attestation is acceptable under Relying Party policy.
// * Otherwise, use the X.509 certificates returned as the attestation trust path from the verification
// procedure to verify that the attestation public key either correctly chains up to an acceptable
// root certificate, or is itself an acceptable certificate (i.e., it and the root certificate
// obtained in Step 20 may be the same).
let _: () = self
.config
.policy_verify_trust(attest_result)
.map_err(|_e| WebauthnError::AttestationTrustFailure)?;
// Verify that the credential public key alg is one of the allowed algorithms.
let alg_valid = self
.config
.get_credential_algorithms()
.into_iter()
.any(|alg| alg == credential.cred.type_);
if !alg_valid {
return Err(WebauthnError::CredentialAlteredAlgFromRequest);
}
// OUT OF SPEC - exclude any credential that is in our exclude list.
let excluded = exclude_credentials
.iter()
.any(|credid| credid.as_slice() == credential.cred_id.as_slice());
if excluded {
return Err(WebauthnError::CredentialAlteredAlgFromRequest);
}
// If the attestation statement attStmt verified successfully and is found to be trustworthy,
// then register the new credential with the account that was denoted in options.user:
//
// For us, we return the credential for the caller to persist.
// If trust failed, we have already returned an Err before this point.
// TODO: Associate the credentialId with the transport hints returned by calling
// credential.response.getTransports(). This value SHOULD NOT be modified before or after
// storing it. It is RECOMMENDED to use this value to populate the transports of the
// allowCredentials option in future get() calls to help the client know how to find a
// suitable authenticator.
Ok((credential, data.attestation_object.auth_data))
}
// https://w3c.github.io/webauthn/#verifying-assertion
pub(crate) fn verify_credential_internal(
&self,
rsp: &PublicKeyCredential,
policy: UserVerificationPolicy,
chal: &ChallengeRef,
cred: &Credential,
appid: &Option<String>,
) -> Result<AuthenticatorData<Authentication>, WebauthnError>
where
T: WebauthnConfig,
{
// Let cData, authData and sig denote the value of credential’s response's clientDataJSON,
// authenticatorData, and signature respectively.
//
// Let JSONtext be the result of running UTF-8 decode on the value of cData.
let data = AuthenticatorAssertionResponse::try_from(&rsp.response).map_err(|e| {
log::debug!("AuthenticatorAssertionResponse::try_from -> {:?}", e);
e
})?;
let c = &data.client_data;
/*
Let C, the client data claimed as used for the signature, be the result of running an
implementation-specific JSON parser on JSONtext.
Note: C may be any implementation-specific data structure representation, as long as
C’s components are referenceable, as required by this algorithm.
*/
// Verify that the value of C.type is the string webauthn.get.
if c.type_ != "webauthn.get" {
return Err(WebauthnError::InvalidClientDataType);
}
// Verify that the value of C.challenge matches the challenge that was sent to the
// authenticator in the PublicKeyCredentialRequestOptions passed to the get() call.
if c.challenge.0 != chal.as_ref() {
return Err(WebauthnError::MismatchedChallenge);
}
// Verify that the value of C.origin matches the Relying Party's origin.
if c.origin != self.config.get_origin() {
log::debug!("{} != {}", c.origin, self.config.get_origin());
return Err(WebauthnError::InvalidRPOrigin);
}
// Verify that the value of C.tokenBinding.status matches the state of Token Binding for the
// TLS connection over which the attestation was obtained. If Token Binding was used on that
// TLS connection, also verify that C.tokenBinding.id matches the base64url encoding of the
// Token Binding ID for the connection.
// Verify that the rpIdHash in authData is the SHA-256 hash of the RP ID expected by the Relying Party.
// Note that if we have an appid stored in the state and the client indicates it has used the appid extension,
// we also check the hash against this appid in addition to the Relying Party
let has_appid_enabled = rsp.extensions.as_ref().map(|e| e.appid).unwrap_or(false);
let appid_hash = if has_appid_enabled {
appid.as_ref().map(|id| compute_sha256(id.as_bytes()))
} else {
None
};
if !(&data.authenticator_data.rp_id_hash == &self.rp_id_hash
|| Some(&data.authenticator_data.rp_id_hash) == appid_hash.as_ref())
{
return Err(WebauthnError::InvalidRPIDHash);
}
// Verify that the User Present bit of the flags in authData is set.
if !data.authenticator_data.user_present {
return Err(WebauthnError::UserNotPresent);
}
// If user verification is required for this assertion, verify that the User Verified bit of
// the flags in authData is set.
//
// We also check the historical policy too. See designs/authentication-use-cases.md
match (&policy, &cred.registration_policy) {
(UserVerificationPolicy::Required, _) => {
// If we requested required, enforce that.
if !data.authenticator_data.user_verified {
return Err(WebauthnError::UserNotVerified);
}
}
(_, UserVerificationPolicy::Discouraged) => {
// If this token always verifies, even under discouraged, we can enforce that behaviour
// from registration.
if cred.verified && self.config.get_require_uv_consistency() {
// This token always sends UV, so we enforce that.
if !data.authenticator_data.user_verified {
log::debug!("Token registered UV=true with DC, enforcing UV policy.");
return Err(WebauthnError::UserNotVerified);
}
}
}
// Pass - we can not know if verification was requested to the client in the past correctly.
// This means we can't know what it's behaviour is at the moment.
// We must allow unverified tokens now.
_ => {}
}
// Verify that the values of the client extension outputs in clientExtensionResults and the
// authenticator extension outputs in the extensions in authData are as expected, considering
// the client extension input values that were given as the extensions option in the get()
// call. In particular, any extension identifier values in the clientExtensionResults and
// the extensions in authData MUST be also be present as extension identifier values in the
// extensions member of options, i.e., no extensions are present that were not requested. In
// the general case, the meaning of "are as expected" is specific to the Relying Party and
// which extensions are in use.
//
// Note: Since all extensions are OPTIONAL for both the client and the authenticator, the
// Relying Party MUST be prepared to handle cases where none or not all of the requested
// extensions were acted upon.
if let Some(ext) = &data.authenticator_data.extensions {
log::debug!("ext: {:?}", ext);
// we do not need to do any processing here
} else {
log::debug!("no extensions");
}
// Let hash be the result of computing a hash over the cData using SHA-256.
let client_data_json_hash = compute_sha256(data.client_data_bytes.as_slice());
// Using the credential public key, verify that sig is a valid signature
// over the binary concatenation of authData and hash.
// Note: This verification step is compatible with signatures generated by FIDO U2F
// authenticators. See §6.1.2 FIDO U2F Signature Format Compatibility.
let verification_data: Vec<u8> = data
.authenticator_data_bytes
.iter()
.chain(client_data_json_hash.iter())
.copied()
.collect();
let verified = cred
.cred
.verify_signature(&data.signature, &verification_data)?;
if !verified {
return Err(WebauthnError::AuthenticationFailure);
}
Ok(data.authenticator_data)
}
/// Convenience function for `generate_challenge_authenticate_extensions` without extensions
pub fn generate_challenge_authenticate(
&self,
creds: Vec<Credential>,
) -> Result<(RequestChallengeResponse, AuthenticationState), WebauthnError>
where
T: WebauthnConfig,
{
self.generate_challenge_authenticate_options(creds, None)
}
/// Authenticate a single credential, with the ability to override the userVerification
/// policy requested, or extensions in use.
///
/// NOTE: Over-riding the UserVerificationPolicy may have SECURITY consequences. You should
/// understand how this interacts with the single credential in use, and how that may impact
/// your system security.
///
/// If in doubt, do NOT use this function!
pub fn generate_challenge_authenticate_credential(
&self,
cred: Credential,
policy: UserVerificationPolicy,
extensions: Option<RequestAuthenticationExtensions>,
) -> Result<(RequestChallengeResponse, AuthenticationState), WebauthnError>
where
T: WebauthnConfig,
{
self.generate_challenge_authenticate_inner(vec![cred], policy, extensions)
}
/// Generate a challenge for an authenticate request for a user. You must supply the set of
/// credentials that exist for the user that *may* be used in this authentication request. If
/// an empty credential set is supplied, the authentication *will* fail.
///
/// This challenge is supplied to
/// to the client javascript function `navigator.credentials.get()`.
///
/// You must persist the AuthenticationState that is returned. You should associate this by
/// UserId. The AuthenticationState is required for the authenticate_credential function to
/// operate correctly.
///
/// NOTE: `WebauthnError::InconsistentUserVerificationPolicy`
///
/// This error is returning when the set of credentials has a mix of registration
/// user verification policies.
/// This is due to an issue with the webauthn standard
/// as noted at <https://github.com/w3c/webauthn/issues/1510>. What can occur is that
/// when you *register* a credential, you set an expectation as to the verification
/// policy of that credential, and if that credential can soley be a MFA on it's own
/// or requires extra material to function as an MFA. However, when you mix credentials
/// you can have unverified credentials require verification (register discouraged, or
/// u2f on ctap1, then authenticate preferred and ctap2) or verified credentials NOT
/// need verification.
///
/// As a result, this means the set of credentials that is provided must be internally
/// consistent so that the policy can be set to discouraged or required based on
/// the credentials given. This means you *must* consider a UX to allow the user to
/// choose if they wish to use a verified token or not as webauthn as a standard can
/// not make this distinction.
pub fn generate_challenge_authenticate_options(
&self,
creds: Vec<Credential>,
extensions: Option<RequestAuthenticationExtensions>,
) -> Result<(RequestChallengeResponse, AuthenticationState), WebauthnError>
where
T: WebauthnConfig,
{
let (verified, unverified): (Vec<Credential>, Vec<Credential>) = creds
.into_iter()
.partition(|cred| cred.registration_policy == UserVerificationPolicy::Required);
match (verified.len(), unverified.len()) {
(_, 0) => self.generate_challenge_authenticate_inner(
verified,
UserVerificationPolicy::Required,
extensions,
),
(0, _) => self.generate_challenge_authenticate_inner(
unverified,
UserVerificationPolicy::Discouraged,
extensions,
),
(_, _) => Err(WebauthnError::InconsistentUserVerificationPolicy),
}
}
fn generate_challenge_authenticate_inner(
&self,
creds: Vec<Credential>,
policy: UserVerificationPolicy,
extensions: Option<RequestAuthenticationExtensions>,
) -> Result<(RequestChallengeResponse, AuthenticationState), WebauthnError>
where
T: WebauthnConfig,
{
let chal = self.generate_challenge();
// Get the user's existing creds if any.
let ac = creds
.iter()
.map(|cred| AllowCredentials {
type_: "public-key".to_string(),
id: Base64UrlSafeData(cred.cred_id.clone()),
transports: None,
})
.collect();
// Extract the appid from the extensions to store it in the AuthenticationState
let appid = extensions.as_ref().and_then(|e| e.appid.clone());
// Store the chal associated to the user.
// Now put that into the correct challenge format
let r = RequestChallengeResponse::new(
chal.clone(),
self.config.get_authenticator_timeout(),
self.config.get_relying_party_id().to_owned(),
ac,
policy.clone(),
extensions,
);
let st = AuthenticationState {
// username: username.clone(),
credentials: creds,
policy,
challenge: chal.into(),
appid,
};
Ok((r, st))
}
/// Process an authenticate response from the authenticator and browser. This
/// is the output of `navigator.credentials.get()`, which is processed by this
/// function. If the authentication fails, appropriate errors will be returned.
///
/// This requires the associated AuthenticationState that was created by
/// generate_challenge_authenticate
///
/// On successful authentication, an Ok result is returned. The Ok may contain the CredentialID
/// and associated counter, which you *should* update for security purposes. If the Ok returns
/// `None` then the credential does not have a counter.
pub fn authenticate_credential<'a>(
&self,
rsp: &PublicKeyCredential,
state: &'a AuthenticationState,
) -> Result<(&'a CredentialID, AuthenticatorData<Authentication>), WebauthnError>
where
T: WebauthnConfig,
{
// https://w3c.github.io/webauthn/#verifying-assertion
// Lookup challenge
let AuthenticationState {
credentials: creds,
policy,
challenge: chal,
appid,
} = state;
let chal: &ChallengeRef = chal.into();
// If the allowCredentials option was given when this authentication ceremony was initiated,
// verify that credential.id identifies one of the public key credentials that were listed in allowCredentials.
//
// We always supply allowCredentials in this library, so we expect creds as a vec of credentials
// that would be equivalent to what was allowed.
// println!("rsp: {:?}", rsp);
let cred = {
// Identify the user being authenticated and verify that this user is the owner of the public
// key credential source credentialSource identified by credential.id:
//
// If the user was identified before the authentication ceremony was initiated, e.g., via a
// username or cookie,
// verify that the identified user is the owner of credentialSource. If
// credential.response.userHandle is present, let userHandle be its value. Verify that
// userHandle also maps to the same user.
// If the user was not identified before the authentication ceremony was initiated,
// verify that credential.response.userHandle is present, and that the user identified
// by this value is the owner of credentialSource.
//
// Note: User-less mode is handled by calling `AuthenticationState::set_allowed_credentials`
// after the caller extracts the userHandle and verifies the credential Source
// Using credential’s id attribute (or the corresponding rawId, if base64url encoding is
// inappropriate for your use case), look up the corresponding credential public key.
let mut found_cred: Option<&Credential> = None;
for cred in creds {
if cred.cred_id == rsp.raw_id.0 {
found_cred = Some(cred);
break;
}
}
found_cred.ok_or(WebauthnError::CredentialNotFound)?
};
let auth_data = self.verify_credential_internal(rsp, policy.clone(), chal, &cred, appid)?;
let counter = auth_data.counter;
// If the signature counter value authData.signCount is nonzero or the value stored in
// conjunction with credential’s id attribute is nonzero, then run the following sub-step:
if counter > 0 || cred.counter > 0 {
// greater than the signature counter value stored in conjunction with credential’s id attribute.
// Update the stored signature counter value, associated with credential’s id attribute,
// to be the value of authData.signCount.
// less than or equal to the signature counter value stored in conjunction with credential’s id attribute.
// This is a signal that the authenticator may be cloned, i.e. at least two copies
// of the credential private key may exist and are being used in parallel. Relying
// Parties should incorporate this information into their risk scoring. Whether the
// Relying Party updates the stored signature counter value in this case, or not,
// or fails the authentication ceremony or not, is Relying Party-specific.
let counter_shows_compromise = auth_data.counter <= cred.counter;
if self.config.require_valid_counter_value() && counter_shows_compromise {
return Err(WebauthnError::CredentialPossibleCompromise);
}
}
Ok((&cred.cred_id, auth_data))
}
}
/// The WebauthnConfig type allows site-specific customisation of the Webauthn library.
/// This provides a set of callbacks which are used to supply data to various structures
/// and calls, as well as callbacks to manage data persistence and retrieval.
pub trait WebauthnConfig {
/// Returns a reference to your relying parties name. This is generally any text identifier
/// you wish, but should rarely if ever change. Changes to the relying party name may
/// confuse authenticators and will cause their credentials to be lost.
///
/// Examples of names could be `My Awesome Site`, `https://my-awesome-site.com.au`
fn get_relying_party_name(&self) -> &str;
/// Returns a reference to your sites origin. The origin is the URL to your site with
/// protocol and port. This should rarely, if ever change. In production usage this
/// value must always be https://, however http://localhost is acceptable for testing
/// only. We may add warnings or errors for non-https:// urls in the future. Changing this
/// may cause associated authenticators to lose credentials.
///
/// Examples of this value could be. `https://my-site.com.au`, `https://my-site.com.au:8443`
fn get_origin(&self) -> &str;
/// Returns the relying party id. This should never change, and is used as an id
/// in cryptographic operations and credential scoping. This is defined as the domain name
/// of the service, minus all protocol, port and location data. For example:
/// `https://name:port/path -> name`
///
/// If changed, all associated credentials will be lost in all authenticators.
///
/// Examples of this value for the site `https://my-site.com.au/auth` is `my-site.com.au`
fn get_relying_party_id(&self) -> &str;
/// Get the list of valid credential algorithms that this service can accept. Unless you have
/// speific requirements around this, we advise you leave this function to the default
/// implementation.
fn get_credential_algorithms(&self) -> Vec<COSEAlgorithm> {
vec![COSEAlgorithm::ES256, COSEAlgorithm::RS256]
}
/// Return a timeout on how long the authenticator has to respond to a challenge. This value
/// defaults to 60000 milliseconds. You likely won't need to implement this function, and should
/// rely on the defaults.
fn get_authenticator_timeout(&self) -> u32 {
AUTHENTICATOR_TIMEOUT
}
/// Returns the default attestation type. Options are `None`, `Direct` and `Indirect`.
/// Defaults to `None`.
///
/// DANGER: The client *may* alter this value, causing the registration to not contain
/// an attestation. This is *not* a verified property.
///
/// You *must* also implement policy_verify_trust if you change this from `None` else
/// this can be BYPASSED.
fn get_attestation_preference(&self) -> AttestationConveyancePreference {
AttestationConveyancePreference::None
}
/// Get the preferred policy on authenticator attachment hint. Defaults to None (use
/// any attachment method).
///
/// Default of None allows any attachment method.
///
/// WARNING: This is not enforced, as the client may modify the registration request to
/// disregard this, and no part of the registration response indicates attachement. This
/// is purely a hint, and is NOT a security enforcment.
fn get_authenticator_attachment(&self) -> Option<AuthenticatorAttachment> {
None
}
/// Get the site policy on if the registration should use a resident key so that
/// username and other details can be embedded into the authenticator
/// to allow bypassing that part of the interaction flow.