-
Notifications
You must be signed in to change notification settings - Fork 388
/
Copy pathmfa.go
1029 lines (907 loc) · 31.7 KB
/
mfa.go
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
package api
import (
"bytes"
"crypto/subtle"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/aaronarduino/goqrsvg"
svg "github.com/ajstarks/svgo"
"github.com/boombuler/barcode/qr"
wbnprotocol "github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/webauthn"
"github.com/gofrs/uuid"
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
"github.com/supabase/auth/internal/api/sms_provider"
"github.com/supabase/auth/internal/conf"
"github.com/supabase/auth/internal/crypto"
"github.com/supabase/auth/internal/hooks"
"github.com/supabase/auth/internal/metering"
"github.com/supabase/auth/internal/models"
"github.com/supabase/auth/internal/storage"
"github.com/supabase/auth/internal/utilities"
)
const DefaultQRSize = 3
type EnrollFactorParams struct {
FriendlyName string `json:"friendly_name"`
FactorType string `json:"factor_type"`
Issuer string `json:"issuer"`
Phone string `json:"phone"`
}
type TOTPObject struct {
QRCode string `json:"qr_code,omitempty"`
Secret string `json:"secret,omitempty"`
URI string `json:"uri,omitempty"`
}
type EnrollFactorResponse struct {
ID uuid.UUID `json:"id"`
Type string `json:"type"`
FriendlyName string `json:"friendly_name"`
TOTP *TOTPObject `json:"totp,omitempty"`
Phone string `json:"phone,omitempty"`
}
type ChallengeFactorParams struct {
Channel string `json:"channel"`
WebAuthn *WebAuthnParams `json:"web_authn,omitempty"`
}
type VerifyFactorParams struct {
ChallengeID uuid.UUID `json:"challenge_id"`
Code string `json:"code"`
WebAuthn *WebAuthnParams `json:"web_authn,omitempty"`
}
type ChallengeFactorResponse struct {
ID uuid.UUID `json:"id"`
Type string `json:"type"`
ExpiresAt int64 `json:"expires_at,omitempty"`
CredentialRequestOptions *wbnprotocol.CredentialAssertion `json:"credential_request_options,omitempty"`
CredentialCreationOptions *wbnprotocol.CredentialCreation `json:"credential_creation_options,omitempty"`
}
type UnenrollFactorResponse struct {
ID uuid.UUID `json:"id"`
}
type WebAuthnParams struct {
RPID string `json:"rp_id,omitempty"`
// Can encode multiple origins as comma separated values like: "origin1,origin2"
RPOrigins string `json:"rp_origins,omitempty"`
AssertionResponse json.RawMessage `json:"assertion_response,omitempty"`
CreationResponse json.RawMessage `json:"creation_response,omitempty"`
}
func (w *WebAuthnParams) GetRPOrigins() []string {
if w.RPOrigins == "" {
return nil
}
return strings.Split(w.RPOrigins, ",")
}
func (w *WebAuthnParams) ToConfig() (*webauthn.WebAuthn, error) {
if w.RPID == "" {
return nil, fmt.Errorf("webAuthn RP ID cannot be empty")
}
origins := w.GetRPOrigins()
if len(origins) == 0 {
return nil, fmt.Errorf("webAuthn RP Origins cannot be empty")
}
var validOrigins []string
var invalidOrigins []string
for _, origin := range origins {
parsedURL, err := url.Parse(origin)
if err != nil || (parsedURL.Scheme != "https" && !(parsedURL.Scheme == "http" && parsedURL.Hostname() == "localhost")) || parsedURL.Host == "" {
invalidOrigins = append(invalidOrigins, origin)
} else {
validOrigins = append(validOrigins, origin)
}
}
if len(invalidOrigins) > 0 {
return nil, fmt.Errorf("invalid RP origins: %s", strings.Join(invalidOrigins, ", "))
}
wconfig := &webauthn.Config{
// DisplayName is optional in spec but required to be non-empty in libary, we use the RPID as a placeholder.
RPDisplayName: w.RPID,
RPID: w.RPID,
RPOrigins: validOrigins,
}
return webauthn.New(wconfig)
}
const (
QRCodeGenerationErrorMessage = "Error generating QR Code"
)
func validateFactors(db *storage.Connection, user *models.User, newFactorName string, config *conf.GlobalConfiguration, session *models.Session) error {
if err := models.DeleteExpiredFactors(db, config.MFA.FactorExpiryDuration); err != nil {
return err
}
if err := db.Load(user, "Factors"); err != nil {
return err
}
factorCount := len(user.Factors)
numVerifiedFactors := 0
for _, factor := range user.Factors {
if factor.FriendlyName == newFactorName {
return unprocessableEntityError(
ErrorCodeMFAFactorNameConflict,
fmt.Sprintf("A factor with the friendly name %q for this user already exists", newFactorName),
)
}
if factor.IsVerified() {
numVerifiedFactors++
}
}
if factorCount >= int(config.MFA.MaxEnrolledFactors) {
return unprocessableEntityError(ErrorCodeTooManyEnrolledMFAFactors, "Maximum number of verified factors reached, unenroll to continue")
}
if numVerifiedFactors >= config.MFA.MaxVerifiedFactors {
return unprocessableEntityError(ErrorCodeTooManyEnrolledMFAFactors, "Maximum number of verified factors reached, unenroll to continue")
}
if numVerifiedFactors > 0 && session != nil && !session.IsAAL2() {
return forbiddenError(ErrorCodeInsufficientAAL, "AAL2 required to enroll a new factor")
}
return nil
}
func (a *API) enrollPhoneFactor(w http.ResponseWriter, r *http.Request, params *EnrollFactorParams) error {
ctx := r.Context()
user := getUser(ctx)
session := getSession(ctx)
db := a.db.WithContext(ctx)
if params.Phone == "" {
return badRequestError(ErrorCodeValidationFailed, "Phone number required to enroll Phone factor")
}
phone, err := validatePhone(params.Phone)
if err != nil {
return badRequestError(ErrorCodeValidationFailed, "Invalid phone number format (E.164 required)")
}
var factorsToDelete []models.Factor
for _, factor := range user.Factors {
if factor.IsPhoneFactor() && factor.Phone.String() == phone {
if factor.IsVerified() {
return unprocessableEntityError(
ErrorCodeMFAVerifiedFactorExists,
"A verified phone factor already exists, unenroll the existing factor to continue",
)
} else if factor.IsUnverified() {
factorsToDelete = append(factorsToDelete, factor)
}
}
}
if err := db.Destroy(&factorsToDelete); err != nil {
return internalServerError("Database error deleting unverified phone factors").WithInternalError(err)
}
if err := validateFactors(db, user, params.FriendlyName, a.config, session); err != nil {
return err
}
factor := models.NewPhoneFactor(user, phone, params.FriendlyName)
err = db.Transaction(func(tx *storage.Connection) error {
if terr := tx.Create(factor); terr != nil {
return terr
}
if terr := models.NewAuditLogEntry(r, tx, user, models.EnrollFactorAction, r.RemoteAddr, map[string]interface{}{
"factor_id": factor.ID,
"factor_type": factor.FactorType,
}); terr != nil {
return terr
}
return nil
})
if err != nil {
return err
}
return sendJSON(w, http.StatusOK, &EnrollFactorResponse{
ID: factor.ID,
Type: models.Phone,
FriendlyName: factor.FriendlyName,
Phone: params.Phone,
})
}
func (a *API) enrollWebAuthnFactor(w http.ResponseWriter, r *http.Request, params *EnrollFactorParams) error {
ctx := r.Context()
user := getUser(ctx)
session := getSession(ctx)
db := a.db.WithContext(ctx)
if err := validateFactors(db, user, params.FriendlyName, a.config, session); err != nil {
return err
}
factor := models.NewWebAuthnFactor(user, params.FriendlyName)
err := db.Transaction(func(tx *storage.Connection) error {
if terr := tx.Create(factor); terr != nil {
return terr
}
if terr := models.NewAuditLogEntry(r, tx, user, models.EnrollFactorAction, r.RemoteAddr, map[string]interface{}{
"factor_id": factor.ID,
"factor_type": factor.FactorType,
}); terr != nil {
return terr
}
return nil
})
if err != nil {
return err
}
return sendJSON(w, http.StatusOK, &EnrollFactorResponse{
ID: factor.ID,
Type: models.WebAuthn,
FriendlyName: factor.FriendlyName,
})
}
func (a *API) enrollTOTPFactor(w http.ResponseWriter, r *http.Request, params *EnrollFactorParams) error {
ctx := r.Context()
user := getUser(ctx)
db := a.db.WithContext(ctx)
config := a.config
session := getSession(ctx)
issuer := ""
if params.Issuer == "" {
u, err := url.ParseRequestURI(config.SiteURL)
if err != nil {
return internalServerError("site url is improperly formatted")
}
issuer = u.Host
} else {
issuer = params.Issuer
}
if err := validateFactors(db, user, params.FriendlyName, config, session); err != nil {
return err
}
var factor *models.Factor
var buf bytes.Buffer
var key *otp.Key
key, err := totp.Generate(totp.GenerateOpts{
Issuer: issuer,
AccountName: user.GetEmail(),
})
if err != nil {
return internalServerError(QRCodeGenerationErrorMessage).WithInternalError(err)
}
svgData := svg.New(&buf)
qrCode, _ := qr.Encode(key.String(), qr.H, qr.Auto)
qs := goqrsvg.NewQrSVG(qrCode, DefaultQRSize)
qs.StartQrSVG(svgData)
if err = qs.WriteQrSVG(svgData); err != nil {
return internalServerError(QRCodeGenerationErrorMessage).WithInternalError(err)
}
svgData.End()
factor = models.NewTOTPFactor(user, params.FriendlyName)
if err := factor.SetSecret(key.Secret(), config.Security.DBEncryption.Encrypt, config.Security.DBEncryption.EncryptionKeyID, config.Security.DBEncryption.EncryptionKey); err != nil {
return err
}
err = db.Transaction(func(tx *storage.Connection) error {
if terr := tx.Create(factor); terr != nil {
return terr
}
if terr := models.NewAuditLogEntry(r, tx, user, models.EnrollFactorAction, r.RemoteAddr, map[string]interface{}{
"factor_id": factor.ID,
}); terr != nil {
return terr
}
return nil
})
if err != nil {
return err
}
return sendJSON(w, http.StatusOK, &EnrollFactorResponse{
ID: factor.ID,
Type: models.TOTP,
FriendlyName: factor.FriendlyName,
TOTP: &TOTPObject{
// See: https://css-tricks.com/probably-dont-base64-svg/
QRCode: buf.String(),
Secret: key.Secret(),
URI: key.URL(),
},
})
}
func (a *API) EnrollFactor(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
user := getUser(ctx)
session := getSession(ctx)
config := a.config
if session == nil || user == nil {
return internalServerError("A valid session and a registered user are required to enroll a factor")
}
params := &EnrollFactorParams{}
if err := retrieveRequestParams(r, params); err != nil {
return err
}
switch params.FactorType {
case models.Phone:
if !config.MFA.Phone.EnrollEnabled {
return unprocessableEntityError(ErrorCodeMFAPhoneEnrollDisabled, "MFA enroll is disabled for Phone")
}
return a.enrollPhoneFactor(w, r, params)
case models.TOTP:
if !config.MFA.TOTP.EnrollEnabled {
return unprocessableEntityError(ErrorCodeMFATOTPEnrollDisabled, "MFA enroll is disabled for TOTP")
}
return a.enrollTOTPFactor(w, r, params)
case models.WebAuthn:
if !config.MFA.WebAuthn.EnrollEnabled {
return unprocessableEntityError(ErrorCodeMFAWebAuthnEnrollDisabled, "MFA enroll is disabled for WebAuthn")
}
return a.enrollWebAuthnFactor(w, r, params)
default:
return badRequestError(ErrorCodeValidationFailed, "factor_type needs to be totp, phone, or webauthn")
}
}
func (a *API) challengePhoneFactor(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
config := a.config
db := a.db.WithContext(ctx)
user := getUser(ctx)
factor := getFactor(ctx)
ipAddress := utilities.GetIPAddress(r)
params := &ChallengeFactorParams{}
if err := retrieveRequestParams(r, params); err != nil {
return err
}
channel := params.Channel
if channel == "" {
channel = sms_provider.SMSProvider
}
if !sms_provider.IsValidMessageChannel(channel, config) {
return badRequestError(ErrorCodeValidationFailed, InvalidChannelError)
}
if factor.IsPhoneFactor() && factor.LastChallengedAt != nil {
if !factor.LastChallengedAt.Add(config.MFA.Phone.MaxFrequency).Before(time.Now()) {
return tooManyRequestsError(ErrorCodeOverSMSSendRateLimit, generateFrequencyLimitErrorMessage(factor.LastChallengedAt, config.MFA.Phone.MaxFrequency))
}
}
otp := crypto.GenerateOtp(config.MFA.Phone.OtpLength)
challenge, err := factor.CreatePhoneChallenge(ipAddress, otp, config.Security.DBEncryption.Encrypt, config.Security.DBEncryption.EncryptionKeyID, config.Security.DBEncryption.EncryptionKey)
if err != nil {
return internalServerError("error creating SMS Challenge")
}
message, err := generateSMSFromTemplate(config.MFA.Phone.SMSTemplate, otp)
if err != nil {
return internalServerError("error generating sms template").WithInternalError(err)
}
if config.Hook.SendSMS.Enabled {
input := hooks.SendSMSInput{
User: user,
SMS: hooks.SMS{
OTP: otp,
SMSType: "mfa",
},
}
output := hooks.SendSMSOutput{}
err := a.invokeHook(a.db, r, &input, &output)
if err != nil {
return internalServerError("error invoking hook")
}
} else {
smsProvider, err := sms_provider.GetSmsProvider(*config)
if err != nil {
return internalServerError("Failed to get SMS provider").WithInternalError(err)
}
// We omit messageID for now, can consider reinstating if there are requests.
if _, err = smsProvider.SendMessage(factor.Phone.String(), message, channel, otp); err != nil {
return internalServerError("error sending message").WithInternalError(err)
}
}
if err := db.Transaction(func(tx *storage.Connection) error {
if terr := factor.WriteChallengeToDatabase(tx, challenge); terr != nil {
return terr
}
if terr := models.NewAuditLogEntry(r, tx, user, models.CreateChallengeAction, r.RemoteAddr, map[string]interface{}{
"factor_id": factor.ID,
"factor_status": factor.Status,
}); terr != nil {
return terr
}
return nil
}); err != nil {
return err
}
return sendJSON(w, http.StatusOK, &ChallengeFactorResponse{
ID: challenge.ID,
Type: factor.FactorType,
ExpiresAt: challenge.GetExpiryTime(config.MFA.ChallengeExpiryDuration).Unix(),
})
}
func (a *API) challengeTOTPFactor(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
config := a.config
db := a.db.WithContext(ctx)
user := getUser(ctx)
factor := getFactor(ctx)
ipAddress := utilities.GetIPAddress(r)
challenge := factor.CreateChallenge(ipAddress)
if err := db.Transaction(func(tx *storage.Connection) error {
if terr := factor.WriteChallengeToDatabase(tx, challenge); terr != nil {
return terr
}
if terr := models.NewAuditLogEntry(r, tx, user, models.CreateChallengeAction, r.RemoteAddr, map[string]interface{}{
"factor_id": factor.ID,
"factor_status": factor.Status,
}); terr != nil {
return terr
}
return nil
}); err != nil {
return err
}
return sendJSON(w, http.StatusOK, &ChallengeFactorResponse{
ID: challenge.ID,
Type: factor.FactorType,
ExpiresAt: challenge.GetExpiryTime(config.MFA.ChallengeExpiryDuration).Unix(),
})
}
func (a *API) challengeWebAuthnFactor(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
db := a.db.WithContext(ctx)
config := a.config
user := getUser(ctx)
factor := getFactor(ctx)
ipAddress := utilities.GetIPAddress(r)
params := &ChallengeFactorParams{}
if err := retrieveRequestParams(r, params); err != nil {
return err
}
if params.WebAuthn == nil {
return badRequestError(ErrorCodeValidationFailed, "web_authn config required")
}
webAuthn, err := params.WebAuthn.ToConfig()
if err != nil {
return err
}
var response *ChallengeFactorResponse
var ws *models.WebAuthnSessionData
var challenge *models.Challenge
if factor.IsUnverified() {
options, session, err := webAuthn.BeginRegistration(user)
if err != nil {
return internalServerError("Failed to generate WebAuthn registration data").WithInternalError(err)
}
ws = &models.WebAuthnSessionData{
SessionData: session,
}
challenge = ws.ToChallenge(factor.ID, ipAddress)
response = &ChallengeFactorResponse{
CredentialCreationOptions: options,
Type: factor.FactorType,
ID: challenge.ID,
}
} else if factor.IsVerified() {
options, session, err := webAuthn.BeginLogin(user)
if err != nil {
return err
}
ws = &models.WebAuthnSessionData{
SessionData: session,
}
challenge = ws.ToChallenge(factor.ID, ipAddress)
response = &ChallengeFactorResponse{
CredentialRequestOptions: options,
Type: factor.FactorType,
ID: challenge.ID,
}
}
if err := factor.WriteChallengeToDatabase(db, challenge); err != nil {
return err
}
response.ExpiresAt = challenge.GetExpiryTime(config.MFA.ChallengeExpiryDuration).Unix()
return sendJSON(w, http.StatusOK, response)
}
func (a *API) validateChallenge(r *http.Request, db *storage.Connection, factor *models.Factor, challengeID uuid.UUID) (*models.Challenge, error) {
config := a.config
currentIP := utilities.GetIPAddress(r)
challenge, err := factor.FindChallengeByID(db, challengeID)
if err != nil {
if models.IsNotFoundError(err) {
return nil, unprocessableEntityError(ErrorCodeMFAFactorNotFound, "MFA factor with the provided challenge ID not found")
}
return nil, internalServerError("Database error finding Challenge").WithInternalError(err)
}
if challenge.VerifiedAt != nil || challenge.IPAddress != currentIP {
return nil, unprocessableEntityError(ErrorCodeMFAIPAddressMismatch, "Challenge and verify IP addresses mismatch.")
}
if challenge.HasExpired(config.MFA.ChallengeExpiryDuration) {
if err := db.Destroy(challenge); err != nil {
return nil, internalServerError("Database error deleting challenge").WithInternalError(err)
}
return nil, unprocessableEntityError(ErrorCodeMFAChallengeExpired, "MFA challenge %v has expired, verify against another challenge or create a new challenge.", challenge.ID)
}
return challenge, nil
}
func (a *API) ChallengeFactor(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
config := a.config
factor := getFactor(ctx)
switch factor.FactorType {
case models.Phone:
if !config.MFA.Phone.VerifyEnabled {
return unprocessableEntityError(ErrorCodeMFAPhoneVerifyDisabled, "MFA verification is disabled for Phone")
}
return a.challengePhoneFactor(w, r)
case models.TOTP:
if !config.MFA.TOTP.VerifyEnabled {
return unprocessableEntityError(ErrorCodeMFATOTPVerifyDisabled, "MFA verification is disabled for TOTP")
}
return a.challengeTOTPFactor(w, r)
case models.WebAuthn:
if !config.MFA.WebAuthn.VerifyEnabled {
return unprocessableEntityError(ErrorCodeMFAWebAuthnVerifyDisabled, "MFA verification is disabled for WebAuthn")
}
return a.challengeWebAuthnFactor(w, r)
default:
return badRequestError(ErrorCodeValidationFailed, "factor_type needs to be totp, phone, or webauthn")
}
}
func (a *API) verifyTOTPFactor(w http.ResponseWriter, r *http.Request, params *VerifyFactorParams) error {
var err error
ctx := r.Context()
user := getUser(ctx)
factor := getFactor(ctx)
config := a.config
db := a.db.WithContext(ctx)
challenge, err := a.validateChallenge(r, db, factor, params.ChallengeID)
if err != nil {
return err
}
secret, shouldReEncrypt, err := factor.GetSecret(config.Security.DBEncryption.DecryptionKeys, config.Security.DBEncryption.Encrypt, config.Security.DBEncryption.EncryptionKeyID)
if err != nil {
return internalServerError("Database error verifying MFA TOTP secret").WithInternalError(err)
}
valid, verr := totp.ValidateCustom(params.Code, secret, time.Now().UTC(), totp.ValidateOpts{
Period: 30,
Skew: 1,
Digits: otp.DigitsSix,
Algorithm: otp.AlgorithmSHA1,
})
if config.Hook.MFAVerificationAttempt.Enabled {
input := hooks.MFAVerificationAttemptInput{
UserID: user.ID,
FactorID: factor.ID,
Valid: valid,
}
output := hooks.MFAVerificationAttemptOutput{}
err := a.invokeHook(nil, r, &input, &output)
if err != nil {
return err
}
if output.Decision == hooks.HookRejection {
if err := models.Logout(db, user.ID); err != nil {
return err
}
if output.Message == "" {
output.Message = hooks.DefaultMFAHookRejectionMessage
}
return forbiddenError(ErrorCodeMFAVerificationRejected, output.Message)
}
}
if !valid {
if shouldReEncrypt && config.Security.DBEncryption.Encrypt {
if err := factor.SetSecret(secret, true, config.Security.DBEncryption.EncryptionKeyID, config.Security.DBEncryption.EncryptionKey); err != nil {
return err
}
if err := db.UpdateOnly(factor, "secret"); err != nil {
return err
}
}
return unprocessableEntityError(ErrorCodeMFAVerificationFailed, "Invalid TOTP code entered").WithInternalError(verr)
}
var token *AccessTokenResponse
err = db.Transaction(func(tx *storage.Connection) error {
var terr error
if terr = models.NewAuditLogEntry(r, tx, user, models.VerifyFactorAction, r.RemoteAddr, map[string]interface{}{
"factor_id": factor.ID,
"challenge_id": challenge.ID,
"factor_type": factor.FactorType,
}); terr != nil {
return terr
}
if terr = challenge.Verify(tx); terr != nil {
return terr
}
if !factor.IsVerified() {
if terr = factor.UpdateStatus(tx, models.FactorStateVerified); terr != nil {
return terr
}
}
if shouldReEncrypt && config.Security.DBEncryption.Encrypt {
es, terr := crypto.NewEncryptedString(factor.ID.String(), []byte(secret), config.Security.DBEncryption.EncryptionKeyID, config.Security.DBEncryption.EncryptionKey)
if terr != nil {
return terr
}
factor.Secret = es.String()
if terr := tx.UpdateOnly(factor, "secret"); terr != nil {
return terr
}
}
user, terr = models.FindUserByID(tx, user.ID)
if terr != nil {
return terr
}
token, terr = a.updateMFASessionAndClaims(r, tx, user, models.TOTPSignIn, models.GrantParams{
FactorID: &factor.ID,
})
if terr != nil {
return terr
}
if terr = models.InvalidateSessionsWithAALLessThan(tx, user.ID, models.AAL2.String()); terr != nil {
return internalServerError("Failed to update sessions. %s", terr)
}
if terr = models.DeleteUnverifiedFactors(tx, user, factor.FactorType); terr != nil {
return internalServerError("Error removing unverified factors. %s", terr)
}
return nil
})
if err != nil {
return err
}
metering.RecordLogin(string(models.MFACodeLoginAction), user.ID)
return sendJSON(w, http.StatusOK, token)
}
func (a *API) verifyPhoneFactor(w http.ResponseWriter, r *http.Request, params *VerifyFactorParams) error {
ctx := r.Context()
config := a.config
user := getUser(ctx)
factor := getFactor(ctx)
db := a.db.WithContext(ctx)
currentIP := utilities.GetIPAddress(r)
challenge, err := a.validateChallenge(r, db, factor, params.ChallengeID)
if err != nil {
return err
}
if challenge.VerifiedAt != nil || challenge.IPAddress != currentIP {
return unprocessableEntityError(ErrorCodeMFAIPAddressMismatch, "Challenge and verify IP addresses mismatch")
}
if challenge.HasExpired(config.MFA.ChallengeExpiryDuration) {
if err := db.Destroy(challenge); err != nil {
return internalServerError("Database error deleting challenge").WithInternalError(err)
}
return unprocessableEntityError(ErrorCodeMFAChallengeExpired, "MFA challenge %v has expired, verify against another challenge or create a new challenge.", challenge.ID)
}
var valid bool
var otpCode string
var shouldReEncrypt bool
if config.Sms.IsTwilioVerifyProvider() {
smsProvider, err := sms_provider.GetSmsProvider(*config)
if err != nil {
return internalServerError("Failed to get SMS provider").WithInternalError(err)
}
if err := smsProvider.VerifyOTP(factor.Phone.String(), params.Code); err != nil {
return forbiddenError(ErrorCodeOTPExpired, "Token has expired or is invalid").WithInternalError(err)
}
valid = true
} else {
otpCode, shouldReEncrypt, err = challenge.GetOtpCode(config.Security.DBEncryption.DecryptionKeys, config.Security.DBEncryption.Encrypt, config.Security.DBEncryption.EncryptionKeyID)
if err != nil {
return internalServerError("Database error verifying MFA TOTP secret").WithInternalError(err)
}
valid = subtle.ConstantTimeCompare([]byte(otpCode), []byte(params.Code)) == 1
}
if config.Hook.MFAVerificationAttempt.Enabled {
input := hooks.MFAVerificationAttemptInput{
UserID: user.ID,
FactorID: factor.ID,
FactorType: factor.FactorType,
Valid: valid,
}
output := hooks.MFAVerificationAttemptOutput{}
err := a.invokeHook(nil, r, &input, &output)
if err != nil {
return err
}
if output.Decision == hooks.HookRejection {
if err := models.Logout(db, user.ID); err != nil {
return err
}
if output.Message == "" {
output.Message = hooks.DefaultMFAHookRejectionMessage
}
return forbiddenError(ErrorCodeMFAVerificationRejected, output.Message)
}
}
if !valid {
if shouldReEncrypt && config.Security.DBEncryption.Encrypt {
if err := challenge.SetOtpCode(otpCode, true, config.Security.DBEncryption.EncryptionKeyID, config.Security.DBEncryption.EncryptionKey); err != nil {
return err
}
if err := db.UpdateOnly(challenge, "otp_code"); err != nil {
return err
}
}
return unprocessableEntityError(ErrorCodeMFAVerificationFailed, "Invalid MFA Phone code entered")
}
var token *AccessTokenResponse
err = db.Transaction(func(tx *storage.Connection) error {
var terr error
if terr = models.NewAuditLogEntry(r, tx, user, models.VerifyFactorAction, r.RemoteAddr, map[string]interface{}{
"factor_id": factor.ID,
"challenge_id": challenge.ID,
"factor_type": factor.FactorType,
}); terr != nil {
return terr
}
if terr = challenge.Verify(tx); terr != nil {
return terr
}
if !factor.IsVerified() {
if terr = factor.UpdateStatus(tx, models.FactorStateVerified); terr != nil {
return terr
}
}
user, terr = models.FindUserByID(tx, user.ID)
if terr != nil {
return terr
}
token, terr = a.updateMFASessionAndClaims(r, tx, user, models.MFAPhone, models.GrantParams{
FactorID: &factor.ID,
})
if terr != nil {
return terr
}
if terr = models.InvalidateSessionsWithAALLessThan(tx, user.ID, models.AAL2.String()); terr != nil {
return internalServerError("Failed to update sessions. %s", terr)
}
if terr = models.DeleteUnverifiedFactors(tx, user, factor.FactorType); terr != nil {
return internalServerError("Error removing unverified factors. %s", terr)
}
return nil
})
if err != nil {
return err
}
metering.RecordLogin(string(models.MFACodeLoginAction), user.ID)
return sendJSON(w, http.StatusOK, token)
}
func (a *API) verifyWebAuthnFactor(w http.ResponseWriter, r *http.Request, params *VerifyFactorParams) error {
ctx := r.Context()
user := getUser(ctx)
factor := getFactor(ctx)
db := a.db.WithContext(ctx)
var webAuthn *webauthn.WebAuthn
var credential *webauthn.Credential
var err error
switch {
case params.WebAuthn == nil:
return badRequestError(ErrorCodeValidationFailed, "WebAuthn config required")
case factor.IsVerified() && params.WebAuthn.AssertionResponse == nil:
return badRequestError(ErrorCodeValidationFailed, "creation_response required to login")
case factor.IsUnverified() && params.WebAuthn.CreationResponse == nil:
return badRequestError(ErrorCodeValidationFailed, "assertion_response required to login")
default:
webAuthn, err = params.WebAuthn.ToConfig()
if err != nil {
return err
}
}
challenge, err := a.validateChallenge(r, db, factor, params.ChallengeID)
if err != nil {
return err
}
webAuthnSession := *challenge.WebAuthnSessionData.SessionData
// Once the challenge is validated, we consume the challenge
if err := db.Destroy(challenge); err != nil {
return internalServerError("Database error deleting challenge").WithInternalError(err)
}
if factor.IsUnverified() {
parsedResponse, err := wbnprotocol.ParseCredentialCreationResponseBody(bytes.NewReader(params.WebAuthn.CreationResponse))
if err != nil {
return badRequestError(ErrorCodeValidationFailed, "Invalid credential_creation_response")
}
credential, err = webAuthn.CreateCredential(user, webAuthnSession, parsedResponse)
if err != nil {
return err
}
} else if factor.IsVerified() {
parsedResponse, err := wbnprotocol.ParseCredentialRequestResponseBody(bytes.NewReader(params.WebAuthn.AssertionResponse))
if err != nil {
return badRequestError(ErrorCodeValidationFailed, "Invalid credential_request_response")
}
credential, err = webAuthn.ValidateLogin(user, webAuthnSession, parsedResponse)
if err != nil {
return internalServerError("Failed to validate WebAuthn MFA response").WithInternalError(err)
}
}
var token *AccessTokenResponse
err = db.Transaction(func(tx *storage.Connection) error {
var terr error
if terr = models.NewAuditLogEntry(r, tx, user, models.VerifyFactorAction, r.RemoteAddr, map[string]interface{}{
"factor_id": factor.ID,
"challenge_id": challenge.ID,
"factor_type": factor.FactorType,
}); terr != nil {
return terr
}
// Challenge verification not needed as the challenge is destroyed on use
if !factor.IsVerified() {
if terr = factor.UpdateStatus(tx, models.FactorStateVerified); terr != nil {
return terr
}
if terr = factor.SaveWebAuthnCredential(tx, credential); terr != nil {
return terr
}
}
user, terr = models.FindUserByID(tx, user.ID)
if terr != nil {
return terr
}
token, terr = a.updateMFASessionAndClaims(r, tx, user, models.MFAWebAuthn, models.GrantParams{
FactorID: &factor.ID,
})
if terr != nil {
return terr
}
if terr = models.InvalidateSessionsWithAALLessThan(tx, user.ID, models.AAL2.String()); terr != nil {
return internalServerError("Failed to update session").WithInternalError(terr)
}
if terr = models.DeleteUnverifiedFactors(tx, user, models.WebAuthn); terr != nil {
return internalServerError("Failed to remove unverified MFA WebAuthn factors").WithInternalError(terr)
}
return nil
})
if err != nil {
return err
}
metering.RecordLogin(string(models.MFACodeLoginAction), user.ID)
return sendJSON(w, http.StatusOK, token)
}
func (a *API) VerifyFactor(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
factor := getFactor(ctx)
config := a.config
params := &VerifyFactorParams{}
if err := retrieveRequestParams(r, params); err != nil {
return err
}
if params.Code == "" && factor.FactorType != models.WebAuthn {
return badRequestError(ErrorCodeValidationFailed, "Code needs to be non-empty")
}
switch factor.FactorType {
case models.Phone:
if !config.MFA.Phone.VerifyEnabled {
return unprocessableEntityError(ErrorCodeMFAPhoneVerifyDisabled, "MFA verification is disabled for Phone")
}
return a.verifyPhoneFactor(w, r, params)
case models.TOTP:
if !config.MFA.TOTP.VerifyEnabled {
return unprocessableEntityError(ErrorCodeMFATOTPVerifyDisabled, "MFA verification is disabled for TOTP")
}
return a.verifyTOTPFactor(w, r, params)
case models.WebAuthn:
if !config.MFA.WebAuthn.VerifyEnabled {
return unprocessableEntityError(ErrorCodeMFAWebAuthnEnrollDisabled, "MFA verification is disabled for WebAuthn")
}
return a.verifyWebAuthnFactor(w, r, params)
default:
return badRequestError(ErrorCodeValidationFailed, "factor_type needs to be totp, phone, or webauthn")
}
}
func (a *API) UnenrollFactor(w http.ResponseWriter, r *http.Request) error {
var err error
ctx := r.Context()
user := getUser(ctx)
factor := getFactor(ctx)
session := getSession(ctx)
db := a.db.WithContext(ctx)
if factor == nil || session == nil || user == nil {
return internalServerError("A valid session and factor are required to unenroll a factor")
}