-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathWebauthnHandler.pas
1279 lines (1076 loc) · 43.8 KB
/
WebauthnHandler.pas
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
// ###################################################################
// #### This file is part of the mathematics library project, and is
// #### offered under the licence agreement described on
// #### http://www.mrsoft.org/
// ####
// #### Copyright:(c) 2019, Michael R. . All rights reserved.
// ####
// #### Unless required by applicable law or agreed to in writing, software
// #### distributed under the License is distributed on an "AS IS" BASIS,
// #### WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// #### See the License for the specific language governing permissions and
// #### limitations under the License.
// ###################################################################
// this unit translates JSON formatted data to and from the Fido2 objects.
// it's based on the the Delphi Json Library "superobject" from
// https://github.com/hgourvest/superobject
// ###########################################
// #### These utility classes can be used to interface the webauthn.js files
// #### provided with this project
// ###########################################
unit WebauthnHandler;
interface
uses SysUtils, Fido2, SuperObject, cbor, authData, winCryptRandom;
type
EFidoDataHandlerException = class(Exception);
// ###########################################
// #### User registration handling
type
TFidoUserStartRegister = class;
IFidoDataHandling = interface
['{B3AF2050-BB60-46DC-8BBA-9102076F2480}']
procedure CleanupPendingChallenges(aChallenge : string = '');
function IsAlreadRegistered( uname : string ) : boolean; overload;
function IsAlreadRegistered( uname : string; var credIDFN : string ) : boolean; overload;
function IsChallengeInitiated( challenge : string; var data : ISuperObject ) : boolean;
function CredentialDataFromId(credId: string; var data : string): TFidoCredentialFmt;
procedure SaveUserInitChallenge( user : TFidoUserStartRegister );
function SaveCred( fmt : string; id : string; userHandle : string; challenge : string; cred : TFidoCredVerify; authData : TAuthData ) : boolean;
function CredToUser(credId: string; var uname: string): boolean;
procedure SaveAssertChallengeData( challenge : ISuperObject );
function LoadAssertChallengeData( challenge : string ) : ISuperObject;
function CheckSigCounter(credId: string; authData: TAuthData): boolean;
end;
// base handler class for all the objects
// the function FidoDataHandler returns either the local handler inserted by setHandler
// or the one set global one if threading is no issue
TBaseFidoDataHandler = class(TObject)
private
fHandler : IFidoDataHandling;
protected
function FidoDataHandler : IFidoDataHandling;
public
procedure SetHandler( handler : IFidoDataHandling );
end;
// ###########################################
// #### Base properties required by the server
TFidoAttestationType = (atDirect, atNone, atIndirect);
TFidoServer = class(TObject)
private
fRelID: string;
fTimeOut: integer;
fRelParty: string;
fAttestationType : TFidoAttestationType;
fResidentKey : boolean;
fUserVerification : boolean;
fMinAttesType: TFidoAttestationType;
public
property RelyingParty : string read fRelParty write fRelParty;
property RelyingPartyId : string read fRelID write fRelId;
property AttestType : TFidoAttestationType read fAttestationType write fAttestationType;
// Although we want direct attestation the client can downgrad. e.g. we want direct but
// webauthn over a third party e.g. PC -> passkey on an Iphone. Returns none
property MinAllowedAttestation : TFidoAttestationType read fMinAttesType write fMinAttesType;
property TimeOut : integer read fTimeOut write fTimeOut;
property RequireResidentKey : boolean read fResidentKey write fResidentKey;
property UserVerification : boolean read fUserVerification write fUserVerification;
function RPIDHash : TFidoSHA256Hash;
function ToJSON : ISuperObject;
constructor Create;
end;
// ###########################################
// #### Enrollment
TFidoUserStartRegister = class(TBaseFidoDataHandler)
private
const cNoUserId : TFidoUserId = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0);
cNoChallange : TFidoChallenge = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0);
private
fDisplName: string;
fUserName: string;
fUserid : TFidoUserId;
fChallenge : TFidoChallenge;
fRand : IRndEngine;
procedure InitUserId;
procedure InitChallenge;
public
property UserName : string read fUserName write fUserName;
property UserDisplName : string read fDisplName write fDisplName;
property UserId : TFidoUserId read fUserId write fUserId;
property Challenge : TFidoChallenge read fChallenge write fChallenge;
function ToJson : ISuperObject;
procedure SaveChallenge;
function CheckUser( uname : string ) : boolean;
constructor Create( UName, displName : string; rand : IRndEngine);
end;
type
TAttestDecodeResult = (tsFailed, tsFullAttestation, tsSurrogateAttestation);
TCustomFidoVerify = class(TBaseFidoDataHandler)
protected
function DecodeAttestationObj( attestStr : string; var alg : integer;
var fmt : string; var sig, authData, x5c : TBytes ) : boolean;
end;
// #### Class to verify the credentials created from the initial starting registering process
type
TFidoUserRegisterVerify = class(TCustomFidoVerify)
public
function VerifyAndSaveCred( credJson : string; var jsonRes, uname : string ) : boolean;
end;
// ###########################################
// #### Assertion
type
TFidoUserAssert = class(TCustomFidoVerify)
private
fRand : IRndEngine;
function CheckCredentials(userHandle: string; origChallenge: ISuperObject;
var credId: string): boolean;
function CoseHashAlgStr( regAuthData : TAuthData ) : string;
function VerifyOKP( signature, sigBase : TBytes; regAuthData : TAuthData ) : boolean;
function VerifyEC2( signature, sigBase : TBytes; regAuthData : TAuthData ) : boolean;
function VerifyRSA( signature, sigBase : TBYtes; regAuthData : TAuthData ) : boolean;
public
function StartAssertion( uname : string ) : string;
function VerifyAssert( assertionStr : string; var resStr : string; var uname : string ) : boolean;
constructor Create(rand : IRndEngine);
end;
function FidoServer : TFidoServer;
function SHA256FromBuf( buf : PByte; len : integer ) : TFidoSHA256Hash;
function Hash( alg : AnsiString; buf : PByte; len : integer ) : TBytes;
procedure SetDefFidoDataHandler( aHandler : IFidoDataHandling );
function GetDefFidoDataHandler : IFidoDataHandling;
implementation
uses syncObjs, strUtils, Classes,
Fido2dll, Windows,
OpenSSL1_1ForWebauthn;
var locServer : TFidoServer = nil;
locDataHandler : IFidoDataHandling = nil;
cs : TCriticalSection;
procedure SetDefFidoDataHandler( aHandler : IFidoDataHandling );
begin
locDataHandler := aHandler;
end;
function GetDefFidoDataHandler : IFidoDataHandling;
begin
Assert( Assigned(locDataHandler), 'Data handler not assigend - call SetFidoDataHandler at first');
Result := locDataHandler;
end;
function FidoDataHandler : IFidoDataHandling;
begin
Assert( Assigned(locDataHandler), 'Data handler not assigend - call SetFidoDataHandler at first');
Result := locDataHandler;
end;
function FidoServer : TFidoServer;
begin
cs.Enter;
try
Result := locServer;
if not Assigned(Result) then
begin
Result := TFidoServer.Create;
locServer := Result;
end;
finally
cs.Leave;
end;
end;
function CredentialToJSon( cred : TFidoCredCreate ) : string;
var clIDHash : TFidoSHA256Hash;
json : ISuperObject;
chArr : TSuperArray;
i : Integer;
obj : ISuperObject;
begin
json := SO;
// ###############################################
// #### Challange
clIDHash := cred.ClientDataHash;
obj := SO;
chArr := obj.AsArray;
for i := 0 to Length(clIDHash) - 1 do
chArr.Add( TSuperObject.Create(clIDHash[i]) );
json.O['Challange'] := obj;
Result := json.AsJSon;
end;
{ TFidoServer }
constructor TFidoServer.Create;
begin
inherited Create;
fRelID := 'fidotest.com';
fRelParty := 'fidotest.com';
fAttestationType := atNone;
fMinAttesType := atNone;
fResidentKey := True;
fTimeOut := 60000;
end;
function TFidoServer.RPIDHash: TFidoSHA256Hash;
var buf : UTF8String;
begin
buf := UTF8String( RelyingPartyId );
FillChar(Result, sizeof(Result), 0);
if buf <> '' then
Result := SHA256FromBuf( @buf[1], Length(buf));
end;
function TFidoServer.ToJSON: ISuperObject;
begin
// an array of the 3 standard encryption algorithm the fido dll supports
// COSE_ES256 = -7;
// COSE_EDDSA = -8;
// COSE_RS256 = -257;
Result := SO('{"publicKey":{"pubKeyCredParams":[{"alg":-7,"type":"public-key"},{"alg":-257,"type":"public-key"},{"alg":-8,"type":"public-key"}]}}');
Result.I['publicKey.Timeout'] := fTimeOut;
Result.S['publicKey.rp.id'] := fRelID;
Result.S['publicKey.rp.name'] := fRelParty;
Result.S['publicKey.authenticatorSelection.authenticatorAttachment'] := 'cross-platform'; // fido dll -> cross platform we don't support TPM or others yet...
case fAttestationType of
atDirect: Result.S['publicKey.attestation'] := 'direct';
atNone: Result.S['publicKey.attestation'] := 'none';
atIndirect: Result.S['publicKey.attestation'] := 'indirect';
end;
Result.B['publicKey.authenticatorSelection.requireResidentKey'] := fResidentKey;
// todo: preferred missing
Result.S['publicKey.authenticatorSelection.userVerification'] := ifthen( fUserVerification, 'required', 'discouraged');
end;
{ TFidoUserStartRegister }
function TFidoUserStartRegister.CheckUser(uname: string): boolean;
begin
Result := not FidoDataHandler.IsAlreadRegistered(uname);
end;
constructor TFidoUserStartRegister.Create(UName, displName: string; rand : IRndEngine);
begin
fRand := rand;
fDisplName := displName;
fUserName := UName;
if fDisplName = '' then
fDisplName := fUserName;
// create a new cahllange and user id
InitChallenge;
InitUserId;
inherited Create;
end;
procedure TFidoUserStartRegister.InitChallenge;
var i : integer;
begin
for i := 0 to Length(fchallenge) - 1 do
fChallenge[i] := fRand.Random;
end;
procedure TFidoUserStartRegister.InitUserId;
var i : integer;
begin
// first byte of the random user ID shall not be one or zero
// see: https://developers.yubico.com/WebAuthn/WebAuthn_Developer_Guide/User_Handle.html
repeat
fUserid[0] := fRand.Random;
until fUserid[0] > 1;
for i := 1 to High(fUserid) do
fUserid[i] := fRand.Random;
end;
procedure TFidoUserStartRegister.SaveChallenge;
begin
assert( Assigned(locDataHandler), 'Error no data handler assigned');
locDataHandler.SaveUserInitChallenge( self );
end;
function TFidoUserStartRegister.ToJson: ISuperObject;
var server : ISuperObject;
begin
// check if the user id and challenge is initialized
if CompareMem( @fUserid[0], @cNoUserId[0], sizeof(fUserid)) then
raise EFidoPropertyException.Create('No User ID created');
// build result
Result := SO('{"publicKey":{}}');
Result.S['publicKey.user.displayName'] := fDisplName;
Result.S['publicKey.user.name'] := fUserName;
Result.S['publicKey.user.id'] := Base64URLEncode( PByte( @fUserid[0] ), sizeof(fUserid) );
Result.S['publicKey.challenge'] := Base64URLEncode( PByte( @fChallenge[0] ), sizeof(fChallenge) );
server := FidoServer.ToJSON;
Result.Merge(server);
end;
function Hash( alg : AnsiString; buf : PByte; len : integer ) : TBytes;
var ctx : PEVP_MD_CTX;
aHashAlg : PEVP_MD;
begin
//if not IdSSLOpenSSLHeaders.Load then
// raise Exception.Create('Failed to load Openssl lib');
aHashAlg := EVP_get_digestbyname(PAnsiChar(alg));
ctx := EVP_MD_CTX_create;
EVP_DigestInit_ex(ctx, aHashAlg, nil);
SetLength(Result, EVP_MD_size(aHashAlg));
EVP_DigestUpdate(ctx, buf, len);
EVP_DigestFinal_ex(ctx, @Result[0], nil);
EVP_MD_CTX_Free(ctx);
end;
function SHA256FromBuf( buf : PByte; len : integer ) : TFidoSHA256Hash;
var ahash : TBytes;
begin
aHash := Hash('sha256', buf, len);
assert(Length(aHash) = Length(Result), 'Wrong result len');
Move(aHash[0], Result, Length(aHash));
end;
{ TCustomFidoVerify }
function TCustomFidoVerify.DecodeAttestationObj(attestStr: string;
var alg: integer; var fmt: string; var sig, authData, x5c: TBytes): boolean;
var cborItem : TCborMap;
restBuf : TBytes;
aName : string;
attStmt : TCborMap;
i, j : integer;
begin
Result := False;
// https://medium.com/webauthnworks/verifying-fido2-packed-attestation-a067a9b2facd
// the link shows how to verify the attestationobj with and without the attStmt object
// attestation object is a cbor encoded raw base64url encoded string
cborItem := TCborDecoding.DecodeBase64UrlEx(attestStr, restBuf) as TCborMap;
// check if there is data left indicating bad cbor format
if Length(restBuf) <> 0 then
exit;
if not Assigned(cborItem) then
exit;
try
alg := 0;
fmt := '';
sig := nil;
authData := nil;
x5c := nil;
for i := 0 to cborItem.Count - 1 do
begin
// check cbor map name format
if not (cborItem.Names[i] is TCborUtf8String) then
exit;
aName := String((cborItem.Names[i] as TCborUtf8String).Value);
if SameText(aName, 'attStmt') then
begin
attStmt := cborItem.Values[i] as TCborMap;
for j := 0 to attStmt.Count - 1 do
begin
// elements for full attestation
aName := String((attStmt.Names[j] as TCborUtf8String).Value);
if SameText(aName, 'alg')
then
alg := (attStmt.Values[j] as TCborNegIntItem).value
else if SameText(aName, 'sig')
then
sig := (attStmt.Values[j] as TCborByteString).ToBytes
else if SameText(aName, 'x5c')
then
x5c := ((attStmt.Values[j] as TCborArr)[0] as TCborByteString).ToBytes;
end;
end
else if SameText(aName, 'authData')
then
authData := (cborItem.Values[i] as TCborByteString).ToBytes
else if SameText(aName, 'fmt')
then
fmt := String( (cborItem.Values[i] as TCborUtf8String).Value );
end;
finally
cborItem.Free;
end;
// minimum requirements for full attestation
// and none attestation
Result := ( (fmt = 'none') and (authData <> nil) ) or
( (fmt = 'packed') and (alg <> 0) and (sig <> nil) and (x5c <> nil) );
end;
{ TFidoUserRegisterVerify }
function TFidoUserRegisterVerify.VerifyAndSaveCred(credJson: string; var jsonRes, uname : string ) : boolean;
var clientData, startData : ISuperObject;
s : string;
credentialId : string;
rawId : TBytes;
credVerify : TFidoCredVerify;
sig : TBytes;
x5c : TBytes;
authData : TBytes;
fmt : string;
alg : integer;
credFMT : TFidoCredentialFmt;
authDataObj : TAuthData;
restBuf : TBytes;
clientDataStr : RawByteString;
clientDataHash : TFidoSHA256Hash;
serverRPIDHash : TFidoSHA256Hash;
rpIDHash : TFidoRPIDHash;
credential : ISuperObject;
clientDataBuf : RawByteString;
userHandle : string;
begin
Result := False;
jsonRes := '{"error":0,"msg":"Error parsing content"}';
credential := SO(credJSON);
if not Assigned(credential) then
exit;
s := credential.S['response.clientDataJSON'];
if s = '' then
exit;
clientDataBuf := Base64URLDecode( s );
ClientData := So( String(clientDataBuf) );
if clientData = nil then
exit;
// ###########################################
// #### Check if the challenge has been initiated and the fields are correct
if not FidoDataHandler.IsChallengeInitiated(ClientData.S['challenge'], startData) then
begin
jsonRes := '{"error":1,"msg":"Client data json parsing error - challenge not initiated"}';
exit;
end;
uname := startData.S['publicKey.user.name'];
if clientData.S['type'] <> 'webauthn.create' then
begin
jsonRes := '{"error":5,"msg":"Client data wrong type"}';
exit;
end;
if Pos(FidoServer.RelyingParty, clientData.S['origin']) = 0 then
begin
jsonRes := '{"error":6,"msg":"Wrong origin field provided"}';
exit;
end;
// calculate hash from clientDataJSON
clientDataStr := Base64URLDecode( credential.S['response.clientDataJSON'] );
if clientDataStr = '' then
begin
jsonRes := '{"error":2,"msg":"Client data json missing"}';
exit;
end;
s := credential.S['response.attestationObject'];
if s = '' then
exit;
// ###########################################
// #### According to format decode:
if not DecodeAttestationObj(s, alg, fmt, sig, authData, x5c) then
begin
jsonRes := '{"error":2,"msg":"Decoding failed"}';
exit;
end;
if Length(restBuf) > 0 then
raise Exception.Create('Decoding error - a rest buffer that should not be');
// decoding seems to have provided somethinge - now check if all fields
// are there according to the format
// we support 'none' and 'packed'
// please note that "none" is not supported by fido2.dll 's fido_veriy procedure!
// none is actually very weak and no verification is performed. Just the
// check if proper keys are provided and store them
if (fmt = 'none') and (FidoServer.MinAllowedAttestation = atNone) then
begin
// just check if the correct fields are there there is nothing to verify
if Length(authData) = 0 then
raise Exception.Create('Missing authdata');
authDataObj := TAuthData.Create( authData );
try
if not authDataObj.HasPublicKey then
raise Exception.Create('No Public key provided');
if not (( authDataObj.PublicKeyAlg = COSE_ES256 ) or (authDataObj.PublicKeyAlg = COSE_EDDSA) or
(authDataObj.PublicKeyAlg = COSE_RS256)) then
raise Exception.Create('Unknown algorithm');
credentialId := credential.S['rawId'];
if s = '' then
raise Exception.Create('No Credential id found');
rawId := Base64URLDecodeToBytes( s );
//credential.SaveTo('D:\credtest.json');
userHandle := credential.S['response.userHandle'];
if userHandle = '' then
userHandle := startData.S['publicKey.user.id'];
Result := FidoDataHandler.SaveCred(fmt, credentialID, userHandle, ClientData.S['challenge'], nil, authDataObj);
finally
authDataObj.Free;
end;
end
else if fmt = 'packed' then
begin
// check if anyhing is in place
if not (( alg = COSE_ES256 ) or (alg = COSE_EDDSA) or (alg = COSE_RS256)) then
raise Exception.Create('Unknown algorithm');
if Length(sig) = 0 then
raise Exception.Create('No sig field provided');
if Length(x5c) = 0 then
raise Exception.Create('No certificate');
if Length(authData) = 0 then
raise Exception.Create('Missing authdata');
credentialId := credential.S['rawId'];
if s = '' then
raise Exception.Create('No Credential id found');
rawId := Base64URLDecodeToBytes( s );
if Length(restBuf) > 0 then
raise Exception.Create('Damend there is a rest buffer that should not be');
authDataObj := TAuthData.Create( authData );
try
if not authDataObj.UserPresent then
begin
jsonRes := '{"error":3,"msg":"Error: parameter user present not set"}';
exit;
end;
if authDataObj.UserVerified <> FidoServer.UserVerification then
begin
jsonRes := '{"error":4,"msg":"Error: parameter user verification not set to the default"}';
exit;
end;
// check rp hash
rpIDHash := authDataObj.rpIDHash;
serverRPIDHash := FidoServer.RPIDHash;
if not CompareMem( @rpIDHash[0], @serverRPIDHash[0], sizeof(rpIDHash)) then
begin
jsonRes := '{"error":7,"msg":"The relying party hash does not match"}';
exit;
end;
if fmt = 'packed'
then
credFmt := fmFido2
else if fmt = 'fido-u2f'
then
credFmt := fmU2F
else if fmt = 'tpm'
then
credFmt := fmTPM
else
credFmt := fmNone;
// create the client hash that is later used in the verification process
clientDataHash := SHA256FromBuf( @clientDataStr[1], Length(clientDataStr) );
// ###########################################
// #### Now bring the fido dll into action
credVerify := TFidoCredVerify.Create( TFidoCredentialType(alg), credFmt,
FidoServer.RelyingPartyId, FidoServer.RelyingParty,
TBaseFido2Credentials.WebAuthNObjDataToAuthData( authData ),
x5c, sig,
FidoServer.RequireResidentKey,
authDataObj.UserVerified, 0, nil) ;
try
Result := credVerify.Verify(clientDataHash);
if Result then
begin
credentialId := credential.S['rawId'];
// ###########################################
// #### save EVERYTHING to a database
userHandle := credential.S['response.userHandle'];
if userHandle = '' then
userHandle := startData.S['publicKey.user.id'];
FidoDataHandler.SaveCred(fmt, credentialId, userHandle, ClientData.S['challenge'], credVerify, authDataObj);
end;
finally
credVerify.Free;
end;
finally
authDataObj.Free;
end;
end
else
begin
jsonRes := '{"error":8,"msg":"unsupported format"}';
exit;
end;
// build result and generate a session
if Result
then
// yeeeha we got it done
jsonRes := '{"verified":true}'
else
jsonRes := '{"verified":false}';
// cleanup challenge if verification succeeded
if Result then
FidoDataHandler.CleanupPendingChallenges(ClientData.S['challenge']);
end;
{ TFidoUserAssert }
function TFidoUserAssert.CoseHashAlgStr(regAuthData: TAuthData): string;
begin
case regAuthData.PublicKeyAlg of
-257: Result := 'sha256';
-258: Result := 'sha384';
-259: Result := 'sha512';
-65535: Result := 'sha1';
-39: Result := 'sha512';
-38: Result := 'sha384';
-37: Result := 'sha256';
-260: Result := 'sha256';
-261: Result := 'sha512';
-7: Result := 'sha256';
-36: Result := 'sha512';
else
Result := 'sha256';
end;
end;
constructor TFidoUserAssert.Create(rand: IRndEngine);
begin
fRand := rand;
if not Assigned(fRand) then
fRand := CreateWinRndObj;
inherited Create;
end;
function TFidoUserAssert.StartAssertion(uname: string): string;
var res : ISuperObject;
challenge : TFidoChallenge;
i: Integer;
credID : string;
credObj : ISuperObject;
begin
credID := '';
// no user name given -> just create a challenge (maybe a user handle is used)
if (uname <> '') and not FidoDataHandler.IsAlreadRegistered(uname, credID) then
exit('{"error":0,"msg":"User not registered"}');
// create a random challenge
for i := 0 to Length(challenge) - 1 do
challenge[i] := fRand.Random;
res := SO('{"publicKey":{"allowCredentials":[]}}');
res.S['publicKey.challenge'] := Base64URLEncode(@challenge[0], length(challenge));
res.I['publicKey.timeout'] := FidoServer.TimeOut;
res.S['publicKey.rpid'] := FidoServer.RelyingPartyId;
res.B['publicKey.userVerificaiton'] := FidoServer.UserVerification;
// return an empty list if no username was provided -> user id required
if credID <> '' then
begin
credObj := SO( '{"type":"public-key"}' );
credObj.S['id'] := credID;
res.A['publicKey.allowCredentials'].Add( credObj );
end;
res.O['extensions'] := SO('{"txAuthSimple":""}');
// ###########################################
// #### Save the challenge for later comparison
FidoDataHandler.SaveAssertChallengeData( res );
Result := res.AsJSon;
end;
// checks if a user with a given user handle was already registered or
// if credentials can be mapped to a given challenge
function TFidoUserAssert.CheckCredentials(userHandle: string;
origChallenge: ISuperObject; var credId : string): boolean;
var cred : TSuperArray;
begin
Result := False;
if userHandle <> '' then
Result := FidoDataHandler.IsAlreadRegistered(userHandle, credId);
if not Result then
begin
cred := origChallenge.A['publicKey.allowCredentials'];
if (cred <> nil) and (cred.Length > 0) then
begin
Result := True;
credId := cred.O[0].S['id'];
end;
end;
end;
function TFidoUserAssert.VerifyAssert(assertionStr: string;
var resStr: string; var uname : string): boolean;
var clientData : ISuperObject;
userHandle : string;
sig : TBytes;
credID : string;
fmt : TFidoCredentialFmt;
clientDataStr : RawByteString;
clientDataHash : TFidoSHA256Hash;
authDataObj : TAuthData;
rpIdHash : TFidoRPIDHash;
serverRPIDHash : TFidoSHA256Hash;
credFmt : TFidoCredentialFmt;
assertVerify : TFidoAssertVerify;
buf : TBytes;
challenge : TFidoChallenge;
authData : TBytes;
origChallenge : ISuperObject;
selCredId : string;
res : ISuperObject;
assertion : ISuperObject;
credData : string;
pkStream : TMemoryStream;
rawPK : RawByteString;
sigBase : TBytes;
regAuthData : TAuthData;
verified : boolean;
begin
Result := False;
resStr := '{"error":0,"msg":"Error parsing content"}';
assertion := SO(assertionStr);
if not Assigned(assertion) then
exit;
clientDataStr := Base64URLDecode( assertion.S['response.clientDataJSON'] );
if clientDataStr = '' then
exit;
ClientData := So( String( clientDataStr ) );
if clientData = nil then
exit;
if clientData.S['type'] <> 'webauthn.get' then
exit;
userhandle := assertion.S['response.userHandle'];
sig := Base64URLDecodeToBytes(assertion.S['response.signature']);
credId := assertion.S['id'];
if assertion.S['type'] <> 'public-key' then
exit;
// ###########################################
// #### Load data from the initialization procedure
origChallenge := FidoDataHandler.LoadAssertChallengeData(clientData.S['challenge']);
if not Assigned(origChallenge) then
begin
resStr := '{"error":1,"msg":"Challenge not initiated"}';
exit;
end;
// create the client hash that is later used in the verification process
clientDataHash := SHA256FromBuf( @clientDataStr[1], Length(clientDataStr) );
authData := Base64URLDecodeToBytes(assertion.S['response.authenticatorData']);
// check if anyhing is in place
//if not (( alg = COSE_ES256 ) or (alg = COSE_EDDSA) or (alg = COSE_RS256)) then
// raise Exception.Create('Unknown algorithm');
if Length(sig) = 0 then
begin
resStr := '{"error":1,"msg":"No sig field provided"}';
exit;
end;
if Length(authData) = 0 then
begin
resStr := '{"error":1,"msg":"Missing authdata"}';
exit;
end;
authDataObj := TAuthData.Create( authData );
try
OutputDebugString( PChar('Guid: ' + GuidToString(authDataObj.AAUID)) );
if not CheckCredentials( userHandle, origChallenge, selCredId ) then
begin
resStr := '{"error":2,"msg":"Credentials not in user list"}';
exit;
end;
if selCredId <> credID then
begin
resStr := '{"error":2,"msg":"Credentials not in user list"}';
exit;
end;
// check user id attached to credential id
if not FidoDataHandler.CredToUser( credId, uname ) then
begin
resStr := '{"error":2,"msg":"Credentials not in user list"}';
exit;
end;
// todo: maybe it's a good idea to check the guid (got from direct attestation)
if not authDataObj.UserPresent then
begin
resStr := '{"error":3,"msg":"Error: parameter user present not set"}';
exit;
end;
if authDataObj.UserVerified <> FidoServer.UserVerification then
begin
resStr := '{"error":4,"msg":"Error: parameter user verification not set to the default"}';
exit;
end;
// check rp hash
rpIDHash := authDataObj.rpIDHash;
serverRPIDHash := FidoServer.RPIDHash;
if not CompareMem( @rpIDHash[0], @serverRPIDHash[0], sizeof(rpIDHash)) then
begin
resStr := '{"error":6,"msg":"The relying party hash does not match"}';
exit;
end;
credFmt := fmFido2;
buf := Base64URLDecodeToBytes( clientData.S['challenge'] );
if Length(buf) <> sizeof(challenge) then
begin
resStr := '{"error":5,"msg":"Challange type failed"}';
exit;
end;
move( buf[0], challenge, sizeof(challenge));
// ###########################################
// #### check assertion according to initial attestation format
fmt := FidoDataHandler.CredentialDataFromId(credId, credData);
if credData = '' then
begin
resStr := '{"error":8,"msg":"Credential data not found"}';
exit;
end;
if fmt = fmNone then
begin
// ###########################################
// #### none attestation - check the signature...
// from https://medium.com/webauthnworks/verifying-fido2-packed-attestation-a067a9b2facd
// 1: concat authData with clientdatahash -> signature base
SetLength(sigBase, Length(clientDataHash) + Length(authData));
Move(authdata[0], sigBase[0], Length(authData));
Move(clientDataHash[0], sigBase[Length(authData)], Length(clientDataHash));
// 2: according to the stored public key verify the given signature
regAuthData := TAuthData.Create( Base64UrlDecodeToBytes(credData) );
if not regAuthData.HasPublicKey then
begin
resStr := '{"error":7,"msg":"No public key - surragate attestation not allowed."}';
exit;
end;
try
try
case regAuthData.KeyType of
COSE_KTY_OKP: verified := VerifyOKP( sig, sigBase, regAuthData );
COSE_KTY_EC2: verified := VerifyEC2( sig, sigBase, regAuthData );
COSE_KTY_RSA: verified := VerifyRSA( sig, sigBase, regAuthData );
else
resStr := '{"error":7,"msg":"No public key - surragate attestation not allowed."}';
exit(False);
end;
except
on F : Exception do
begin
resStr := '{"error":8","msg":"Verification failed badly"}';
exit(False);
end;
end;
finally
regAuthData.Free;
end;
Result := verified;
if verified then
begin
res := SO('{"verified":true}');
res.S['username'] := uname;
resStr := res.AsJSon;
end
else
begin
resStr := '{"verified":false}';
end;
end
else
begin
// packed, tpm and
// ###########################################
// #### Verify with the fido dll
assertVerify := TFidoAssertVerify.Create;
try
assertVerify.RelyingParty := FidoServer.RelyingPartyId;
// ###########################################
// #### now get the private key
clientData := SO(credData);
rawPK := Base64Decode(clientData.S['cert.pk']);