forked from yrccondor/wp-webauthn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwwa-ajax.php
executable file
·1004 lines (868 loc) · 44.6 KB
/
wwa-ajax.php
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
<?php
require_once('vendor/autoload.php');
use Webauthn\Server;
use Webauthn\PublicKeyCredentialRpEntity;
use Webauthn\PublicKeyCredentialUserEntity;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSourceRepository as PublicKeyCredentialSourceRepositoryInterface;
use Webauthn\PublicKeyCredentialSource;
use Webauthn\AuthenticatorSelectionCriteria;
use Nyholm\Psr7\Factory\Psr17Factory;
use Nyholm\Psr7Server\ServerRequestCreator;
/**
* Store all publickeys and pubilckey metas
*/
class PublicKeyCredentialSourceRepository implements PublicKeyCredentialSourceRepositoryInterface {
// Get one credential by credential ID
public function findOneByCredentialId(string $publicKeyCredentialId): ?PublicKeyCredentialSource {
$data = $this->read();
if(isset($data[base64_encode($publicKeyCredentialId)])){
return PublicKeyCredentialSource::createFromArray($data[base64_encode($publicKeyCredentialId)]);
}
return null;
}
// Get one credential's meta by credential ID
public function findOneMetaByCredentialId(string $publicKeyCredentialId): ?array {
$meta = json_decode(wwa_get_option("user_credentials_meta"), true);
if(isset($meta[base64_encode($publicKeyCredentialId)])){
return $meta[base64_encode($publicKeyCredentialId)];
}
return null;
}
// Get all credentials of one user
public function findAllForUserEntity(PublicKeyCredentialUserEntity $publicKeyCredentialUserEntity): array {
$sources = [];
foreach($this->read() as $data){
$source = PublicKeyCredentialSource::createFromArray($data);
if($source->getUserHandle() === $publicKeyCredentialUserEntity->getId()){
$sources[] = $source;
}
}
return $sources;
}
// Save credential into database
public function saveCredentialSource(PublicKeyCredentialSource $publicKeyCredentialSource, bool $usernameless = false): void {
$data = $this->read();
$data_key = base64_encode($publicKeyCredentialSource->getPublicKeyCredentialId());
$data[$data_key] = $publicKeyCredentialSource;
$this->write($data, $data_key, $usernameless);
}
// Update credential's last used
public function updateCredentialLastUsed(string $publicKeyCredentialId): void {
$credential = $this->findOneMetaByCredentialId($publicKeyCredentialId);
if($credential !== null){
$credential["last_used"] = date('Y-m-d H:i:s', current_time('timestamp'));
$meta = json_decode(wwa_get_option("user_credentials_meta"), true);
$meta[base64_encode($publicKeyCredentialId)] = $credential;
wwa_update_option("user_credentials_meta", json_encode($meta));
}
}
// List all authenticators
public function getShowList(PublicKeyCredentialUserEntity $publicKeyCredentialUserEntity): array {
$data = json_decode(wwa_get_option("user_credentials_meta"), true);
$arr = array();
$user_id = $publicKeyCredentialUserEntity->getId();
foreach($data as $key => $value){
if($user_id === $value["user"]){
array_push($arr, array(
"key" => rtrim(strtr(base64_encode($key), '+/', '-_'), '='),
"name" => base64_decode($value["human_name"]),
"type" => $value["authenticator_type"],
"added" => $value["added"],
"usernameless" => isset($value["usernameless"]) ? $value["usernameless"] : false,
"last_used" => isset($value["last_used"]) ? $value["last_used"] : "-"
));
}
}
return array_map(function($item){return array("key" => $item["key"], "name" => $item["name"], "type" => $item["type"], "added" => $item["added"], "usernameless" => $item["usernameless"], "last_used" => $item["last_used"]);}, $arr);
}
// Modify an authenticator
public function modifyAuthenticator(string $id, string $name, PublicKeyCredentialUserEntity $publicKeyCredentialUserEntity, string $action, string $res_id): string {
$keys = $this->findAllForUserEntity($publicKeyCredentialUserEntity);
$user_id = $publicKeyCredentialUserEntity->getId();
// Check if the user has the authenticator
foreach($keys as $item){
if($item->getUserHandle() === $user_id){
if(base64_encode($item->getPublicKeyCredentialId()) === base64_decode(str_pad(strtr($id, '-_', '+/'), strlen($id) % 4, '=', STR_PAD_RIGHT))){
if($action === "rename"){
$this->renameCredential(base64_encode($item->getPublicKeyCredentialId()), $name, $res_id);
}else if($action === "remove"){
$this->removeCredential(base64_encode($item->getPublicKeyCredentialId()), $res_id);
}
wwa_add_log($res_id, "ajax_modify_authenticator: Done");
return "true";
}
}
}
wwa_add_log($res_id, "ajax_modify_authenticator: (ERROR)Authenticator not found, exit");
return "Not Found.";
}
// Rename a credential from database by credential ID
private function renameCredential(string $id, string $name, string $res_id): void {
$meta = json_decode(wwa_get_option("user_credentials_meta"), true);
wwa_add_log($res_id, "ajax_modify_authenticator: Rename \"".base64_decode($meta[$id]["human_name"])."\" -> \"".$name."\"");
$meta[$id]["human_name"] = base64_encode($name);
wwa_update_option("user_credentials_meta", json_encode($meta));
}
// Remove a credential from database by credential ID
private function removeCredential(string $id, string $res_id): void {
$data = $this->read();
unset($data[$id]);
$this->write($data, '');
$meta = json_decode(wwa_get_option("user_credentials_meta"), true);
wwa_add_log($res_id, "ajax_modify_authenticator: Remove \"".base64_decode($meta[$id]["human_name"])."\"");
unset($meta[$id]);
wwa_update_option("user_credentials_meta", json_encode($meta));
}
// Read credential database
private function read(): array {
if(wwa_get_option("user_credentials") !== NULL){
try{
return json_decode(wwa_get_option("user_credentials"), true);
}catch(\Throwable $exception) {
return [];
}
}
return [];
}
// Save credentials data
private function write(array $data, string $key, bool $usernameless = false): void {
if(isset($_POST["type"]) && ($_POST["type"] === "platform" || $_POST["type"] == "cross-platform" || $_POST["type"] === "none") && $key !== ''){
// Save credentials's meta separately
$source = $data[$key]->getUserHandle();
$meta = json_decode(wwa_get_option("user_credentials_meta"), true);
$meta[$key] = array("human_name" => base64_encode(sanitize_text_field($_POST["name"])), "added" => date('Y-m-d H:i:s', current_time('timestamp')), "authenticator_type" => $_POST["type"], "user" => $source, "usernameless" => $usernameless, "last_used" => "-");
wwa_update_option("user_credentials_meta", json_encode($meta));
}
wwa_update_option("user_credentials", json_encode($data));
}
}
// Bind an authenticator
function wwa_ajax_create(){
try{
$res_id = wwa_generate_random_string(5);
if(!session_id()){
wwa_add_log($res_id, "ajax_create: Start session");
session_start();
}
wwa_add_log($res_id, "ajax_create: Start");
if(!current_user_can("read")){
wwa_add_log($res_id, "ajax_create: (ERROR)Permission denied, exit");
wwa_wp_die("Something went wrong.");
}
if(wwa_get_option('website_name') === "" || wwa_get_option('website_domain') ===""){
wwa_add_log($res_id, "ajax_create: (ERROR)Plugin not configured, exit");
wwa_wp_die("Not configured.");
}
// Check queries
if(!isset($_GET["name"]) || !isset($_GET["type"]) || !isset($_GET["usernameless"])){
wwa_add_log($res_id, "ajax_create: (ERROR)Missing parameters, exit");
wwa_wp_die("Bad Request.");
}else{
// Sanitize the input
$wwa_get = array();
$wwa_get["name"] = sanitize_text_field($_GET["name"]);
$wwa_get["type"] = sanitize_text_field($_GET["type"]);
$wwa_get["usernameless"] = sanitize_text_field($_GET["usernameless"]);
wwa_add_log($res_id, "ajax_create: name => \"".$wwa_get["name"]."\", type => \"".$wwa_get["type"]."\", usernameless => \"".$wwa_get["usernameless"]."\"");
}
// Empty authenticator name
if($wwa_get["name"] === ""){
wwa_add_log($res_id, "ajax_create: (ERROR)Empty name, exit");
wwa_wp_die("Bad Request.");
}
// Usernameless authentication not allowed
if($wwa_get["usernameless"] === "true" && wwa_get_option("usernameless_login") !== "true"){
wwa_add_log($res_id, "ajax_create: (ERROR)Usernameless authentication not allowed, exit");
wwa_wp_die("Bad Request.");
}
$rpEntity = new PublicKeyCredentialRpEntity(
wwa_get_option('website_name'),
wwa_get_option('website_domain')
);
$publicKeyCredentialSourceRepository = new PublicKeyCredentialSourceRepository();
$server = new Server(
$rpEntity,
$publicKeyCredentialSourceRepository,
null
);
$user_info = wp_get_current_user();
wwa_add_log($res_id, "ajax_create: user => \"".$user_info->user_login."\"");
// Get user ID or create one
$user_key = "";
if(!isset(wwa_get_option("user_id")[$user_info->user_login])){
wwa_add_log($res_id, "ajax_create: User not initialized, initialize");
$user_array = wwa_get_option("user_id");
$user_key = hash("sha256", $user_info->user_login."-".$user_info->display_name."-".wwa_generate_random_string(10));
$user_array[$user_info->user_login] = $user_key;
wwa_update_option("user_id", $user_array);
}else{
$user_key = wwa_get_option("user_id")[$user_info->user_login];
}
$user = array(
"login" => $user_info->user_login,
"id" => $user_key,
"display" => $user_info->display_name,
"icon" => get_avatar_url($user_info->user_email, array("scheme" => "https"))
);
$userEntity = new PublicKeyCredentialUserEntity(
$user["login"],
$user["id"],
$user["display"],
$user["icon"]
);
$credentialSourceRepository = new PublicKeyCredentialSourceRepository();
$credentialSources = $credentialSourceRepository->findAllForUserEntity($userEntity);
// Convert the Credential Sources into Public Key Credential Descriptors for excluding
$excludeCredentials = array_map(function (PublicKeyCredentialSource $credential) {
return $credential->getPublicKeyCredentialDescriptor();
}, $credentialSources);
wwa_add_log($res_id, "ajax_create: excludeCredentials => ".json_encode($excludeCredentials));
// Set authenticator type
if($wwa_get["type"] === "platform"){
$authenticator_type = AuthenticatorSelectionCriteria::AUTHENTICATOR_ATTACHMENT_PLATFORM;
}else if($wwa_get["type"] === "cross-platform"){
$authenticator_type = AuthenticatorSelectionCriteria::AUTHENTICATOR_ATTACHMENT_CROSS_PLATFORM;
}else{
$authenticator_type = AuthenticatorSelectionCriteria::AUTHENTICATOR_ATTACHMENT_NO_PREFERENCE;
}
// Set user verification
if(wwa_get_option("user_verification") === "true"){
wwa_add_log($res_id, "ajax_create: user_verification => \"true\"");
$user_verification = AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_REQUIRED;
}else{
wwa_add_log($res_id, "ajax_create: user_verification => \"false\"");
$user_verification = AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_DISCOURAGED;
}
$resident_key = false;
// Set usernameless authentication
if($wwa_get["usernameless"] === "true"){
wwa_add_log($res_id, "ajax_create: Usernameless set, user_verification => \"true\"");
$user_verification = AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_REQUIRED;
$resident_key = true;
}
// Create authenticator selection
$authenticatorSelectionCriteria = new AuthenticatorSelectionCriteria(
$authenticator_type,
$resident_key,
$user_verification
);
// Create a creation challenge
$publicKeyCredentialCreationOptions = $server->generatePublicKeyCredentialCreationOptions(
$userEntity,
PublicKeyCredentialCreationOptions::ATTESTATION_CONVEYANCE_PREFERENCE_NONE,
$excludeCredentials,
$authenticatorSelectionCriteria
);
// Save for future use
$_SESSION['wwa_server'] = serialize($server);
$_SESSION['wwa_pkcco'] = base64_encode(serialize($publicKeyCredentialCreationOptions));
$_SESSION['wwa_bind_config'] = array("name" => $wwa_get["name"], "type" => $wwa_get["type"], "usernameless" => $resident_key);
header('Content-Type: application/json');
echo json_encode($publicKeyCredentialCreationOptions);
wwa_add_log($res_id, "ajax_create: Challenge sent");
exit;
}catch(\Exception $exception){
wwa_add_log($res_id, "ajax_create: (ERROR)".$exception->getMessage());
wwa_add_log($res_id, wwa_generate_call_trace($exception));
wwa_add_log($res_id, "ajax_create: (ERROR)Unknown error, exit");
wwa_wp_die("Something went wrong.");
}catch(\Error $error){
wwa_add_log($res_id, "ajax_create: (ERROR)".$error->getMessage());
wwa_add_log($res_id, wwa_generate_call_trace($error));
wwa_add_log($res_id, "ajax_create: (ERROR)Unknown error, exit");
wwa_wp_die("Something went wrong.");
}
}
add_action('wp_ajax_wwa_create' , 'wwa_ajax_create');
// Verify the attestation
function wwa_ajax_create_response(){
try{
$res_id = wwa_generate_random_string(5);
if(!session_id()){
wwa_add_log($res_id, "ajax_create_response: Start session");
session_start();
}
wwa_add_log($res_id, "ajax_create_response: Client response received");
if(!current_user_can("read")){
wwa_add_log($res_id, "ajax_create_response: (ERROR)Permission denied, exit");
wwa_wp_die("Something went wrong.");
}
// Check POST
if(!isset($_POST["data"]) || !isset($_POST["name"]) || !isset($_POST["type"]) || !isset($_POST["usernameless"])){
wwa_add_log($res_id, "ajax_create_response: (ERROR)Missing parameters, exit");
wwa_wp_die("Bad Request.");
}else{
// Sanitize the input
$wwa_post = array();
$wwa_post["name"] = sanitize_text_field($_POST["name"]);
$wwa_post["type"] = sanitize_text_field($_POST["type"]);
$wwa_post["usernameless"] = sanitize_text_field($_POST["usernameless"]);
wwa_add_log($res_id, "ajax_create_response: name => \"".$wwa_post["name"]."\", type => \"".$wwa_post["type"]."\", usernameless => \"".$wwa_post["usernameless"]."\"");
wwa_add_log($res_id, "ajax_create_response: data => ".base64_decode($_POST["data"]));
}
// May not get the challenge yet
if(!isset($_SESSION['wwa_server']) || !isset($_SESSION['wwa_pkcco']) || !isset($_SESSION["wwa_bind_config"])){
wwa_add_log($res_id, "ajax_create_response: (ERROR)Challenge not found in session, exit");
wwa_wp_die("Bad request.");
}
// Check parameters
if($_SESSION["wwa_bind_config"]["type"] !== "platform" && $_SESSION["wwa_bind_config"]["type"] !== "cross-platform" && $_SESSION["wwa_bind_config"]["type"] !== "none"){
wwa_add_log($res_id, "ajax_create_response: (ERROR)Wrong type, exit");
wwa_wp_die("Bad request.");
}
if($_SESSION["wwa_bind_config"]["type"] !== $wwa_post["type"] || $_SESSION["wwa_bind_config"]["name"] !== $wwa_post["name"]){
wwa_add_log($res_id, "ajax_create_response: (ERROR)Wrong parameters, exit");
wwa_wp_die("Bad Request.");
}
// Check global unique credential ID
$credential_id = base64_decode(json_decode(base64_decode($_POST["data"]), true)["rawId"]);
$publicKeyCredentialSourceRepository = new PublicKeyCredentialSourceRepository();
if($publicKeyCredentialSourceRepository->findOneMetaByCredentialId($credential_id) !== null){
wwa_add_log($res_id, "ajax_create_response: (ERROR)Credential ID not unique, ID => \"".base64_encode($credential_id)."\" , exit");
wwa_wp_die("Something went wrong.");
}else{
wwa_add_log($res_id, "ajax_create_response: Credential ID unique check passed");
}
$psr17Factory = new Psr17Factory();
$creator = new ServerRequestCreator(
$psr17Factory,
$psr17Factory,
$psr17Factory,
$psr17Factory
);
$serverRequest = $creator->fromGlobals();
$server = unserialize($_SESSION['wwa_server']);
// Allow to bypass scheme verification when under localhost
$current_domain = wwa_get_option('website_domain');
if($current_domain === "localhost" || $current_domain === "127.0.0.1"){
$server->setSecuredRelyingPartyId([$current_domain]);
wwa_add_log($res_id, "ajax_create_response: Localhost, bypass HTTPS check");
}
// Verify
try {
$publicKeyCredentialSource = $server->loadAndCheckAttestationResponse(
base64_decode($_POST["data"]),
unserialize(base64_decode($_SESSION['wwa_pkcco'])),
$serverRequest
);
wwa_add_log($res_id, "ajax_create_response: Challenge verified");
$publicKeyCredentialSourceRepository->saveCredentialSource($publicKeyCredentialSource, $_SESSION["wwa_bind_config"]['usernameless']);
if($_SESSION["wwa_bind_config"]['usernameless']){
wwa_add_log($res_id, "ajax_create_response: Authenticator added with usernameless authentication feature");
}else{
wwa_add_log($res_id, "ajax_create_response: Authenticator added");
}
// Success
echo 'true';
}catch(\Throwable $exception){
// Failed to verify
wwa_add_log($res_id, "ajax_create_response: (ERROR)".$exception->getMessage());
wwa_add_log($res_id, wwa_generate_call_trace($exception));
wwa_add_log($res_id, "ajax_create_response: (ERROR)Challenge not verified, exit");
wwa_wp_die("Something went wrong.");
}
// Destroy session
wwa_destroy_session();
exit;
}catch(\Exception $exception){
wwa_add_log($res_id, "ajax_create_response: (ERROR)".$exception->getMessage());
wwa_add_log($res_id, wwa_generate_call_trace($exception));
wwa_add_log($res_id, "ajax_create_response: (ERROR)Unknown error, exit");
wwa_wp_die("Something went wrong.");
}catch(\Error $error){
wwa_add_log($res_id, "ajax_create_response: (ERROR)".$error->getMessage());
wwa_add_log($res_id, wwa_generate_call_trace($error));
wwa_add_log($res_id, "ajax_create_response: (ERROR)Unknown error, exit");
wwa_wp_die("Something went wrong.");
}
}
add_action('wp_ajax_wwa_create_response' , 'wwa_ajax_create_response');
// Auth challenge
function wwa_ajax_auth_start(){
try{
$res_id = wwa_generate_random_string(5);
if(!session_id()){
wwa_add_log($res_id, "auth: Start session");
session_start();
}
wwa_add_log($res_id, "ajax_auth: Start");
// Check queries
if(!isset($_GET["type"])){
wwa_add_log($res_id, "ajax_auth: (ERROR)Missing parameters, exit");
wwa_wp_die("Bad Request.");
}else{
// Sanitize the input
$wwa_get = array();
$wwa_get["type"] = sanitize_text_field($_GET["type"]);
if(isset($_GET["user"])){
$wwa_get["user"] = sanitize_text_field($_GET["user"]);
}
if(isset($_GET["usernameless"])){
$wwa_get["usernameless"] = sanitize_text_field($_GET["usernameless"]);
// Usernameless authentication not allowed
if($wwa_get["usernameless"] === "true" && wwa_get_option("usernameless_login") !== "true"){
wwa_add_log($res_id, "ajax_create: (ERROR)Usernameless authentication not allowed, exit");
wwa_wp_die("Bad Request.");
}
}
}
if($wwa_get["type"] === "test" && !current_user_can('read')){
// Test but not logged in
wwa_add_log($res_id, "ajax_auth_response: (ERROR)Permission denied, exit");
wwa_wp_die("Bad request.");
}
$user_key = "";
$usernameless_flag = false;
$user_icon = null;
if($wwa_get["type"] === "test"){
if(isset($wwa_get["usernameless"])){
if($wwa_get["usernameless"] !== "true"){
// Logged in and testing, if the user haven't bound any authenticator yet, exit
$user_info = wp_get_current_user();
wwa_add_log($res_id, "ajax_auth: type => \"test\", user => \"".$user_info->user_login."\", usernameless => \"false\"");
if(!isset(wwa_get_option("user_id")[$user_info->user_login])){
wwa_add_log($res_id, "ajax_auth: (ERROR)User not initialized, exit");
wwa_wp_die("User not inited.");
}else{
$user_key = wwa_get_option("user_id")[$user_info->user_login];
$user_icon = get_avatar_url($user_info->user_email, array("scheme" => "https"));
}
}else{
if(wwa_get_option("usernameless_login") === "true"){
wwa_add_log($res_id, "ajax_auth: type => \"test\", usernameless => \"true\"");
$usernameless_flag = true;
}else{
wwa_add_log($res_id, "ajax_auth: (ERROR)Wrong parameters, exit");
wwa_wp_die("Bad Request.");
}
}
}else{
wwa_add_log($res_id, "ajax_auth: (ERROR)Missing parameters, exit");
wwa_wp_die("Bad Request.");
}
}else{
// Not testing, create a fake user ID if the user does not exist or haven't bound any authenticator yet
if(isset($wwa_get["user"]) && $wwa_get["user"] !== ""){
if(get_user_by('login', $wwa_get["user"])){
$user_info = get_user_by('login', $wwa_get["user"]);
$user_icon = get_avatar_url($user_info->user_email, array("scheme" => "https"));
wwa_add_log($res_id, "ajax_auth: type => \"auth\", user => \"".$user_info->user_login."\"");
if(!isset(wwa_get_option("user_id")[$user_info->user_login])){
wwa_add_log($res_id, "ajax_auth: User not initialized, initialize");
$user_key = hash("sha256", $wwa_get["user"]."-".$wwa_get["user"]."-".wwa_generate_random_string(10));
}else{
$user_key = wwa_get_option("user_id")[$user_info->user_login];
}
}else{
$user_info = new stdClass();
$user_info->user_login = $wwa_get["user"];
$user_info->display_name = $wwa_get["user"];
$user_key = hash("sha256", $wwa_get["user"]."-".$wwa_get["user"]."-".wwa_generate_random_string(10));
wwa_add_log($res_id, "ajax_auth: type => \"auth\", user => \"".$wwa_get["user"]."\"");
wwa_add_log($res_id, "ajax_auth: User not exists, create a fake id");
}
}else{
if(wwa_get_option("usernameless_login") === "true"){
$usernameless_flag = true;
wwa_add_log($res_id, "ajax_auth: Empty username, try usernameless authentication");
}else{
wwa_add_log($res_id, "ajax_auth: (ERROR)Missing parameters, exit");
wwa_wp_die("Bad Request.");
}
}
}
if(!$usernameless_flag){
$userEntity = new PublicKeyCredentialUserEntity(
$user_info->user_login,
$user_key,
$user_info->display_name,
$user_icon
);
}
$credentialSourceRepository = new PublicKeyCredentialSourceRepository();
$rpEntity = new PublicKeyCredentialRpEntity(
wwa_get_option('website_name'),
wwa_get_option('website_domain')
);
$server = new Server(
$rpEntity,
$credentialSourceRepository,
null
);
if($usernameless_flag){
// Usernameless authentication, return empty allowed credentials list
wwa_add_log($res_id, "ajax_auth: Usernameless authentication, allowedCredentials => []");
$allowedCredentials = array();
}else{
// Get the list of authenticators associated to the user
$credentialSources = $credentialSourceRepository->findAllForUserEntity($userEntity);
// Logged in and testing, if the user haven't bind a authenticator yet, exit
if(count($credentialSources) === 0 && $wwa_get["type"] === "test" && current_user_can('read')){
wwa_add_log($res_id, "ajax_auth: (ERROR)No authenticator, exit");
wwa_wp_die("User not inited.");
}
// Convert the Credential Sources into Public Key Credential Descriptors for excluding
$allowedCredentials = array_map(function(PublicKeyCredentialSource $credential){
return $credential->getPublicKeyCredentialDescriptor();
}, $credentialSources);
wwa_add_log($res_id, "ajax_auth: allowedCredentials => ".json_encode($allowedCredentials));
}
// Set user verification
if(wwa_get_option("user_verification") === "true"){
wwa_add_log($res_id, "ajax_auth: user_verification => \"true\"");
$user_verification = AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_REQUIRED;
}else{
wwa_add_log($res_id, "ajax_auth: user_verification => \"false\"");
$user_verification = AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_DISCOURAGED;
}
if($usernameless_flag){
wwa_add_log($res_id, "ajax_auth: Usernameless authentication, user_verification => \"true\"");
$user_verification = AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_REQUIRED;
}
// Create a auth challenge
$publicKeyCredentialRequestOptions = $server->generatePublicKeyCredentialRequestOptions(
$user_verification,
$allowedCredentials
);
// Save for future use
$_SESSION['wwa_server_auth'] = serialize($server);
$_SESSION['wwa_pkcco_auth'] = base64_encode(serialize($publicKeyCredentialRequestOptions));
$_SESSION['wwa_auth_type'] = $wwa_get["type"];
if(!$usernameless_flag){
$_SESSION['wwa_user_name_auth'] = $user_info->user_login;
}
$_SESSION['wwa_usernameless_auth'] = $usernameless_flag;
// Save the user entity if is not logged in and not usernameless
if(!($wwa_get["type"] === "test" && current_user_can('read')) && !$usernameless_flag){
$_SESSION['wwa_user_auth'] = serialize($userEntity);
}
header('Content-Type: application/json');
echo json_encode($publicKeyCredentialRequestOptions);
wwa_add_log($res_id, "ajax_auth: Challenge sent");
exit;
}catch(\Exception $exception){
wwa_add_log($res_id, "ajax_auth: (ERROR)".$exception->getMessage());
wwa_add_log($res_id, wwa_generate_call_trace($exception));
wwa_add_log($res_id, "ajax_auth: (ERROR)Unknown error, exit");
wwa_wp_die("Something went wrong.");
}catch(\Error $error){
wwa_add_log($res_id, "ajax_auth: (ERROR)".$error->getMessage());
wwa_add_log($res_id, wwa_generate_call_trace($error));
wwa_add_log($res_id, "ajax_auth: (ERROR)Unknown error, exit");
wwa_wp_die("Something went wrong.");
}
}
add_action('wp_ajax_wwa_auth_start' , 'wwa_ajax_auth_start');
add_action('wp_ajax_nopriv_wwa_auth_start' , 'wwa_ajax_auth_start');
function wwa_ajax_auth(){
try{
$res_id = wwa_generate_random_string(5);
if(!session_id()){
wwa_add_log($res_id, "auth_response: Start session");
session_start();
}
wwa_add_log($res_id, "ajax_auth_response: Client response received");
// Check POST
if(!isset($_POST["type"]) || !isset($_POST["data"])){
wwa_add_log($res_id, "ajax_auth_response: (ERROR)Missing parameters, exit");
wwa_wp_die("Bad Request.");
}else{
// Sanitize the input
$wwa_post = array();
$wwa_post["type"] = sanitize_text_field($_POST["type"]);
}
if($wwa_post["type"] !== $_SESSION['wwa_auth_type']){
wwa_add_log($res_id, "ajax_auth_response: (ERROR)Wrong parameters, exit");
wwa_wp_die("Bad Request.");
}
// May not get the challenge yet
if(!isset($_SESSION['wwa_server_auth']) || !isset($_SESSION['wwa_pkcco_auth']) || !isset($_SESSION['wwa_usernameless_auth']) || ($wwa_post["type"] !== "test" && $wwa_post["type"] !== "auth")){
wwa_add_log($res_id, "ajax_auth_response: (ERROR)Challenge not found in session, exit");
wwa_wp_die("Bad request.");
}
if($_SESSION['wwa_usernameless_auth'] === false && !isset($_SESSION['wwa_user_name_auth'])){
wwa_add_log($res_id, "ajax_auth_response: (ERROR)Username not found in session, exit");
wwa_wp_die("Bad request.");
}
if($wwa_post["type"] === "test" && !current_user_can('read')){
// Test but not logged in
wwa_add_log($res_id, "ajax_auth_response: (ERROR)Permission denied, exit");
wwa_wp_die("Bad request.");
}
if(!($wwa_post["type"] === "test" && current_user_can('read')) && ($_SESSION['wwa_usernameless_auth'] === false && !isset($_SESSION['wwa_user_auth']))){
wwa_add_log($res_id, "ajax_auth_response: (ERROR)Permission denied, exit");
wwa_wp_die("Bad request.");
}
$usernameless_flag = $_SESSION['wwa_usernameless_auth'];
$psr17Factory = new Psr17Factory();
$creator = new ServerRequestCreator(
$psr17Factory,
$psr17Factory,
$psr17Factory,
$psr17Factory
);
$serverRequest = $creator->fromGlobals();
$publicKeyCredentialSourceRepository = new PublicKeyCredentialSourceRepository();
// If user entity is not saved, read from WordPress
$user_key = "";
if($wwa_post["type"] === "test" && current_user_can('read') && !$usernameless_flag){
$user_info = wp_get_current_user();
if(!isset(wwa_get_option("user_id")[$user_info->user_login])){
wwa_add_log($res_id, "ajax_auth_response: (ERROR)User not initialized, exit");
wwa_wp_die("User not inited.");
}else{
$user_key = wwa_get_option("user_id")[$user_info->user_login];
$user_icon = get_avatar_url($user_info->user_email, array("scheme" => "https"));
}
$userEntity = new PublicKeyCredentialUserEntity(
$user_info->user_login,
$user_key,
$user_info->display_name,
$user_icon
);
wwa_add_log($res_id, "ajax_auth_response: type => \"test\", user => \"".$user_info->user_login."\"");
}else{
if($usernameless_flag){
$data_array = json_decode(base64_decode($_POST["data"]), true);
if(!isset($data_array["response"]["userHandle"]) || !isset($data_array["rawId"])){
wwa_add_log($res_id, "ajax_auth_response: (ERROR)Client data not correct, exit");
wwa_wp_die("Bad request.");
}
wwa_add_log($res_id, "ajax_auth_response: type => \"".$wwa_post["type"]."\"");
wwa_add_log($res_id, "ajax_auth_response: Usernameless authentication, try to find user by credential_id => \"".$data_array["rawId"]."\", userHandle => \"".$data_array["response"]["userHandle"]."\"");
$credential_meta = $publicKeyCredentialSourceRepository->findOneMetaByCredentialId(base64_decode($data_array["rawId"]));
if($credential_meta !== null){
if($credential_meta["usernameless"] === true){
wwa_add_log($res_id, "ajax_auth_response: Credential found, usernameless => \"true\", user_key => \"".$credential_meta["user"]."\"");
// Try to find user
$all_user = wwa_get_option("user_id");
$user_login_name = false;
foreach($all_user as $user => $user_id){
if($user_id === $credential_meta["user"]){
$user_login_name = $user;
break;
}
}
// Match userHandle
if($credential_meta["user"] === base64_decode($data_array["response"]["userHandle"])){
// Found user
if($user_login_name !== false){
wwa_add_log($res_id, "ajax_auth_response: Found user => \"".$user_login_name."\", user_key => \"".$credential_meta["user"]."\"");
// Testing, verify user
if($wwa_post["type"] === "test" && current_user_can('read')){
$user_wp = wp_get_current_user();
if($user_login_name !== $user_wp->user_login){
wwa_add_log($res_id, "ajax_auth_response: (ERROR)Credential found, but user not match, exit");
wwa_wp_die("Bad request.");
}
}
$user_info = get_user_by('login', $user_login_name);
$userEntity = new PublicKeyCredentialUserEntity(
$user_info->user_login,
$credential_meta["user"],
$user_info->display_name,
get_avatar_url($user_info->user_email, array("scheme" => "https"))
);
}else{
wwa_add_log($res_id, "ajax_auth_response: (ERROR)Credential found, but user not found, exit");
wwa_wp_die("Bad request.");
}
}else{
wwa_add_log($res_id, "ajax_auth_response: (ERROR)Credential found, but userHandle not matched, exit");
wwa_wp_die("Bad request.");
}
}else{
wwa_add_log($res_id, "ajax_auth_response: (ERROR)Credential found, but usernameless => \"false\", exit");
wwa_wp_die("Bad request.");
}
}else{
wwa_add_log($res_id, "ajax_auth_response: (ERROR)Credential not found, exit");
wwa_wp_die("Bad request.");
}
}else{
wwa_add_log($res_id, "ajax_auth_response: type => \"auth\", user => \"".$_SESSION['wwa_user_name_auth']."\"");
$userEntity = unserialize($_SESSION['wwa_user_auth']);
}
}
wwa_add_log($res_id, "ajax_auth_response: data => ".base64_decode($_POST["data"]));
$server = unserialize($_SESSION['wwa_server_auth']);
// Allow to bypass scheme verification when under localhost
$current_domain = wwa_get_option('website_domain');
if($current_domain === "localhost" || $current_domain === "127.0.0.1"){
$server->setSecuredRelyingPartyId([$current_domain]);
wwa_add_log($res_id, "ajax_auth_response: Localhost, bypass HTTPS check");
}
// Verify
try {
$publicKeyCredentialSource = $server->loadAndCheckAssertionResponse(
base64_decode($_POST["data"]),
unserialize(base64_decode($_SESSION['wwa_pkcco_auth'])),
$userEntity,
$serverRequest
);
wwa_add_log($res_id, "ajax_auth_response: Challenge verified");
// Success
$publicKeyCredentialSourceRepository->updateCredentialLastUsed(base64_decode(json_decode(base64_decode($_POST["data"]), true)["rawId"]));
if(!($wwa_post["type"] === "test" && current_user_can('read'))){
// Log user in
if (!is_user_logged_in()) {
include('wwa-compatibility.php');
if(!$usernameless_flag){
$user_login = $_SESSION['wwa_user_name_auth'];
}else{
$user_login = $user_login_name;
}
$user = get_user_by('login', $user_login);
$user_id = $user->ID;
wwa_add_log($res_id, "ajax_auth_response: Log in user => \"".$user_login."\"");
wp_set_current_user($user_id, $user_login);
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on'){
wp_set_auth_cookie($user_id, false, true);
}else{
wp_set_auth_cookie($user_id, false);
}
do_action('wp_login', $user_login, $user);
}
}
echo "true";
}catch(\Throwable $exception){
// Failed to verify
wwa_add_log($res_id, "ajax_auth_response: (ERROR)".$exception->getMessage());
wwa_add_log($res_id, wwa_generate_call_trace($exception));
wwa_add_log($res_id, "ajax_auth_response: (ERROR)Challenge not verified, exit");
wwa_wp_die("Something went wrong.");
}
// Destroy session
wwa_destroy_session();
exit;
}catch(\Exception $exception){
wwa_add_log($res_id, "ajax_auth_response: (ERROR)".$exception->getMessage());
wwa_add_log($res_id, wwa_generate_call_trace($exception));
wwa_add_log($res_id, "ajax_auth_response: (ERROR)Unknown error, exit");
wwa_wp_die("Something went wrong.");
}catch(\Error $error){
wwa_add_log($res_id, "ajax_auth_response: (ERROR)".$error->getMessage());
wwa_add_log($res_id, wwa_generate_call_trace($error));
wwa_add_log($res_id, "ajax_auth_response: (ERROR)Unknown error, exit");
wwa_wp_die("Something went wrong.");
}
}
add_action('wp_ajax_wwa_auth' , 'wwa_ajax_auth');
add_action('wp_ajax_nopriv_wwa_auth' , 'wwa_ajax_auth');
// Get authenticator list
function wwa_ajax_authenticator_list(){
$res_id = wwa_generate_random_string(5);
if(!current_user_can("read")){
wwa_add_log($res_id, "ajax_ajax_authenticator_list: (ERROR)Missing parameters, exit");
wwa_wp_die("Something went wrong.");
}
header('Content-Type: application/json');
$user_info = wp_get_current_user();
$user_key = "";
if(!isset(wwa_get_option("user_id")[$user_info->user_login])){
wwa_add_log($res_id, "ajax_ajax_authenticator_list: Empty authenticator list");
// The user haven't bound any authenticator, return empty list
echo "[]";
exit;
}else{
$user_key = wwa_get_option("user_id")[$user_info->user_login];
}
$userEntity = new PublicKeyCredentialUserEntity(
$user_info->user_login,
$user_key,
$user_info->display_name,
get_avatar_url($user_info->user_email, array("scheme" => "https"))
);
$publicKeyCredentialSourceRepository = new PublicKeyCredentialSourceRepository();
echo json_encode($publicKeyCredentialSourceRepository->getShowList($userEntity));
exit;
}
add_action('wp_ajax_wwa_authenticator_list' , 'wwa_ajax_authenticator_list');
// Modify an authenticator
function wwa_ajax_modify_authenticator(){
try{
$res_id = wwa_generate_random_string(5);
wwa_add_log($res_id, "ajax_modify_authenticator: Start");
if(!current_user_can("read")){
wwa_add_log($res_id, "ajax_modify_authenticator: (ERROR)Permission denied, exit");
wwa_wp_die("Bad Request.");
}
if(!isset($_GET["id"]) || !isset($_GET["target"])){
wwa_add_log($res_id, "ajax_modify_authenticator: (ERROR)Missing parameters, exit");
wwa_wp_die("Bad Request.");
}
if($_GET["target"] !== "rename" && $_GET["target"] !== "remove"){
wwa_add_log($res_id, "ajax_modify_authenticator: (ERROR)Wrong target, exit");
wwa_wp_die("Bad Request.");
}
if($_GET["target"] === "rename" && !isset($_GET["name"])){
wwa_add_log($res_id, "ajax_modify_authenticator: (ERROR)Missing parameters, exit");
wwa_wp_die("Bad Request.");
}
$user_info = wp_get_current_user();
$user_key = "";
if(!isset(wwa_get_option("user_id")[$user_info->user_login])){
// The user haven't bound any authenticator, exit
wwa_add_log($res_id, "ajax_modify_authenticator: (ERROR)User not initialized, exit");
wwa_wp_die("User not inited.");
}else{
$user_key = wwa_get_option("user_id")[$user_info->user_login];
}
$userEntity = new PublicKeyCredentialUserEntity(
$user_info->user_login,
$user_key,
$user_info->display_name,
get_avatar_url($user_info->user_email, array("scheme" => "https"))
);
wwa_add_log($res_id, "ajax_modify_authenticator: user => \"".$user_info->user_login."\"");
$publicKeyCredentialSourceRepository = new PublicKeyCredentialSourceRepository();
if($_GET["target"] === "rename"){
echo $publicKeyCredentialSourceRepository->modifyAuthenticator($_GET["id"], sanitize_text_field($_GET["name"]), $userEntity, "rename", $res_id);
}else if($_GET["target"] === "remove"){
echo $publicKeyCredentialSourceRepository->modifyAuthenticator($_GET["id"], "", $userEntity, "remove", $res_id);
}
exit;
}catch(\Exception $exception){
wwa_add_log($res_id, "ajax_modify_authenticator: (ERROR)".$exception->getMessage());
wwa_add_log($res_id, wwa_generate_call_trace($exception));
wwa_add_log($res_id, "ajax_modify_authenticator: (ERROR)Unknown error, exit");
wwa_wp_die("Something went wrong.");
}catch(\Error $error){
wwa_add_log($res_id, "ajax_modify_authenticator: (ERROR)".$error->getMessage());
wwa_add_log($res_id, wwa_generate_call_trace($error));
wwa_add_log($res_id, "ajax_modify_authenticator: (ERROR)Unknown error, exit");
wwa_wp_die("Something went wrong.");
}
}
add_action('wp_ajax_wwa_modify_authenticator' , 'wwa_ajax_modify_authenticator');
// Print log
function wwa_ajax_get_log(){
if(!current_user_can("edit_plugins")){
wwa_wp_die("Bad Request.");
}
header('Content-Type: application/json');
$log = get_option("wwa_log");
if($log === false){
echo "[]";
}else{
echo json_encode($log);
}
exit;
}
add_action('wp_ajax_wwa_get_log' , 'wwa_ajax_get_log');
// Clear log
function wwa_ajax_clear_log(){
if(!current_user_can("edit_plugins")){
wwa_wp_die("Bad Request.");
}
$log = get_option("wwa_log");
if($log !== false){
update_option("wwa_log", array());
}
echo "true";