/
login_mfa.go
2835 lines (2401 loc) · 82 KB
/
login_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 vault
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"image/png"
"io/ioutil"
"net/http"
"net/url"
"strings"
"sync"
"time"
duoapi "github.com/duosecurity/duo_api_golang"
"github.com/duosecurity/duo_api_golang/authapi"
"github.com/golang-jwt/jwt/v4"
"github.com/golang/protobuf/proto"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/go-cleanhttp"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-memdb"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/helper/identity"
"github.com/hashicorp/vault/helper/identity/mfa"
"github.com/hashicorp/vault/helper/namespace"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/identitytpl"
"github.com/hashicorp/vault/sdk/helper/jsonutil"
"github.com/hashicorp/vault/sdk/helper/parseutil"
"github.com/hashicorp/vault/sdk/helper/strutil"
"github.com/hashicorp/vault/sdk/logical"
"github.com/hashicorp/vault/vault/quotas"
"github.com/mitchellh/mapstructure"
"github.com/okta/okta-sdk-golang/v2/okta"
"github.com/okta/okta-sdk-golang/v2/okta/query"
"github.com/patrickmn/go-cache"
otplib "github.com/pquerna/otp"
totplib "github.com/pquerna/otp/totp"
)
const (
mfaMethodTypeTOTP = "totp"
mfaMethodTypeDuo = "duo"
mfaMethodTypeOkta = "okta"
mfaMethodTypePingID = "pingid"
memDBLoginMFAConfigsTable = "login_mfa_configs"
memDBMFALoginEnforcementsTable = "login_enforcements"
mfaTOTPKeysPrefix = systemBarrierPrefix + "mfa/totpkeys/"
// loginMFAConfigPrefix is the storage prefix for persisting login MFA method
// configs
loginMFAConfigPrefix = "login-mfa/method/"
mfaLoginEnforcementPrefix = "login-mfa/enforcement/"
)
type totpKey struct {
Key string `json:"key"`
}
// loginMfaPaths returns the API endpoints to configure the new style
// login MFA. The following paths are supported:
// mfa/method/:mfa_method - management of MFA method IDs, which can be used for configuration
// mfa/login_enforcement/:config_name - configures single or two phase MFA auth
func (b *SystemBackend) loginMFAPaths() []*framework.Path {
return []*framework.Path{
{
Pattern: "mfa/validate",
Fields: map[string]*framework.FieldSchema{
"mfa_request_id": {
Type: framework.TypeString,
Description: "ID for this MFA request",
Required: true,
},
"mfa_payload": {
Type: framework.TypeMap,
Description: "A map from MFA method ID to a slice of passcodes or an empty slice if the method does not use passcodes",
Required: true,
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.UpdateOperation: &framework.PathOperation{
Callback: b.Core.loginMFABackend.handleMFALoginValidate,
Summary: "Validates the login for the given MFA methods. Upon successful validation, it returns an auth response containing the client token",
ForwardPerformanceStandby: true,
},
},
},
}
}
func genericOptionalUUIDRegex(name string) string {
return fmt.Sprintf("(/(?P<%s>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))?", name)
}
type MFABackend struct {
Core *Core
mfaLock *sync.RWMutex
db *memdb.MemDB
mfaLogger hclog.Logger
namespacer Namespacer
methodTable string
usedCodes *cache.Cache
}
type LoginMFABackend struct {
*MFABackend
}
func loginMFASchemaFuncs() []func() *memdb.TableSchema {
return []func() *memdb.TableSchema{
loginMFAConfigTableSchema,
loginEnforcementTableSchema,
}
}
func NewLoginMFABackend(core *Core, logger hclog.Logger) *LoginMFABackend {
b := NewMFABackend(core, logger, memDBLoginMFAConfigsTable, loginMFASchemaFuncs())
return &LoginMFABackend{b}
}
func NewMFABackend(core *Core, logger hclog.Logger, prefix string, schemaFuncs []func() *memdb.TableSchema) *MFABackend {
db, _ := SetupMFAMemDB(schemaFuncs)
return &MFABackend{
Core: core,
mfaLock: &sync.RWMutex{},
db: db,
mfaLogger: logger.Named("mfa"),
namespacer: core,
methodTable: prefix,
}
}
func SetupMFAMemDB(schemaFuncs []func() *memdb.TableSchema) (*memdb.MemDB, error) {
mfaSchemas := &memdb.DBSchema{
Tables: make(map[string]*memdb.TableSchema),
}
for _, schemaFunc := range schemaFuncs {
schema := schemaFunc()
if _, ok := mfaSchemas.Tables[schema.Name]; ok {
panic(fmt.Sprintf("duplicate table name: %s", schema.Name))
}
mfaSchemas.Tables[schema.Name] = schema
}
db, err := memdb.NewMemDB(mfaSchemas)
if err != nil {
return nil, err
}
return db, nil
}
func (b *LoginMFABackend) ResetLoginMFAMemDB() error {
var err error
db, err := SetupMFAMemDB(loginMFASchemaFuncs())
if err != nil {
return err
}
b.db = db
return nil
}
func (i *IdentityStore) handleMFAMethodListTOTP(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleMFAMethodList(ctx, req, d, mfaMethodTypeTOTP)
}
func (i *IdentityStore) handleMFAMethodListDuo(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleMFAMethodList(ctx, req, d, mfaMethodTypeDuo)
}
func (i *IdentityStore) handleMFAMethodListOkta(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleMFAMethodList(ctx, req, d, mfaMethodTypeOkta)
}
func (i *IdentityStore) handleMFAMethodListPingID(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleMFAMethodList(ctx, req, d, mfaMethodTypePingID)
}
func (i *IdentityStore) handleMFAMethodListGlobal(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
keys, configInfo, err := i.mfaBackend.mfaMethodList(ctx, "")
if err != nil {
return nil, err
}
return logical.ListResponseWithInfo(keys, configInfo), nil
}
func (i *IdentityStore) handleMFAMethodList(ctx context.Context, req *logical.Request, d *framework.FieldData, methodType string) (*logical.Response, error) {
keys, configInfo, err := i.mfaBackend.mfaMethodList(ctx, methodType)
if err != nil {
return nil, err
}
return logical.ListResponseWithInfo(keys, configInfo), nil
}
func (i *IdentityStore) handleMFAMethodTOTPRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleMFAMethodReadCommon(ctx, req, d, mfaMethodTypeTOTP)
}
func (i *IdentityStore) handleMFAMethodOKTARead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleMFAMethodReadCommon(ctx, req, d, mfaMethodTypeOkta)
}
func (i *IdentityStore) handleMFAMethodDuoRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleMFAMethodReadCommon(ctx, req, d, mfaMethodTypeDuo)
}
func (i *IdentityStore) handleMFAMethodPingIDRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleMFAMethodReadCommon(ctx, req, d, mfaMethodTypePingID)
}
func (i *IdentityStore) handleMFAMethodReadGlobal(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleMFAMethodReadCommon(ctx, req, d, "")
}
func (i *IdentityStore) handleMFAMethodReadCommon(ctx context.Context, req *logical.Request, d *framework.FieldData, methodType string) (*logical.Response, error) {
methodID := d.Get("method_id").(string)
if methodID == "" {
return logical.ErrorResponse("missing method ID"), nil
}
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
respData, err := i.mfaBackend.mfaConfigReadByMethodID(methodID)
if err != nil {
return nil, err
}
if respData == nil {
return nil, nil
}
mfaNs, err := i.namespacer.NamespaceByID(ctx, respData["namespace_id"].(string))
if err != nil {
return nil, err
}
// reading the method config either from the same namespace or from the parent or from the child should all work
if !(ns.ID == mfaNs.ID || mfaNs.HasParent(ns) || ns.HasParent(mfaNs)) {
return logical.ErrorResponse("request namespace does not match method namespace"), logical.ErrPermissionDenied
}
if methodType != "" && respData["type"] != methodType {
return logical.ErrorResponse("failed to find the method ID under MFA type %s.", methodType), nil
}
return &logical.Response{
Data: respData,
}, nil
}
func (i *IdentityStore) handleMFAMethodUpdateCommon(ctx context.Context, req *logical.Request, d *framework.FieldData, methodType string) (*logical.Response, error) {
var err error
var mConfig *mfa.Config
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
methodID := d.Get("method_id").(string)
b := i.mfaBackend
b.mfaLock.Lock()
defer b.mfaLock.Unlock()
if methodID != "" {
mConfig, err = b.MemDBMFAConfigByID(methodID)
if err != nil {
return nil, err
}
// If methodID is specified, but we didn't find anything, return a 404
if mConfig == nil {
return nil, nil
}
}
if mConfig == nil {
configID, err := uuid.GenerateUUID()
if err != nil {
return nil, fmt.Errorf("failed to generate an identifier for MFA config: %v", err)
}
mConfig = &mfa.Config{
ID: configID,
Type: methodType,
NamespaceID: ns.ID,
}
}
mfaNs, err := i.namespacer.NamespaceByID(ctx, mConfig.NamespaceID)
if err != nil {
return nil, err
}
// this logic assumes that the config namespace and the current
// namespace should be the same. Note an ancestor of mfaNs is not allowed
// to create/update methodID
if ns.ID != mfaNs.ID {
return logical.ErrorResponse("request namespace does not match method namespace"), nil
}
mConfig.Type = methodType
usernameRaw, ok := d.GetOk("username_format")
if ok {
mConfig.UsernameFormat = usernameRaw.(string)
}
switch methodType {
case mfaMethodTypeTOTP:
err = parseTOTPConfig(mConfig, d)
if err != nil {
return logical.ErrorResponse(err.Error()), nil
}
case mfaMethodTypeOkta:
err = parseOktaConfig(mConfig, d)
if err != nil {
return logical.ErrorResponse(err.Error()), nil
}
case mfaMethodTypeDuo:
err = parseDuoConfig(mConfig, d)
if err != nil {
return logical.ErrorResponse(err.Error()), nil
}
case mfaMethodTypePingID:
err = parsePingIDConfig(mConfig, d)
if err != nil {
return logical.ErrorResponse(err.Error()), nil
}
default:
return logical.ErrorResponse(fmt.Sprintf("unrecognized type %q", methodType)), nil
}
// Store the config
err = b.putMFAConfigByID(ctx, mConfig)
if err != nil {
return nil, err
}
// Back the config in MemDB
err = b.MemDBUpsertMFAConfig(ctx, mConfig)
if err != nil {
return nil, err
}
if methodID == "" {
return &logical.Response{
Data: map[string]interface{}{
"method_id": mConfig.ID,
},
}, nil
} else {
return nil, nil
}
}
func (i *IdentityStore) handleMFAMethodTOTPUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleMFAMethodUpdateCommon(ctx, req, d, mfaMethodTypeTOTP)
}
func (i *IdentityStore) handleMFAMethodOKTAUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleMFAMethodUpdateCommon(ctx, req, d, mfaMethodTypeOkta)
}
func (i *IdentityStore) handleMFAMethodDuoUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleMFAMethodUpdateCommon(ctx, req, d, mfaMethodTypeDuo)
}
func (i *IdentityStore) handleMFAMethodPingIDUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleMFAMethodUpdateCommon(ctx, req, d, mfaMethodTypePingID)
}
func (i *IdentityStore) handleMFAMethodTOTPDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleMFAMethodDeleteCommon(ctx, req, d, mfaMethodTypeTOTP)
}
func (i *IdentityStore) handleMFAMethodOKTADelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleMFAMethodDeleteCommon(ctx, req, d, mfaMethodTypeOkta)
}
func (i *IdentityStore) handleMFAMethodDUODelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleMFAMethodDeleteCommon(ctx, req, d, mfaMethodTypeDuo)
}
func (i *IdentityStore) handleMFAMethodPingIDDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleMFAMethodDeleteCommon(ctx, req, d, mfaMethodTypePingID)
}
func (i *IdentityStore) handleMFAMethodDeleteCommon(ctx context.Context, req *logical.Request, d *framework.FieldData, methodType string) (*logical.Response, error) {
methodID := d.Get("method_id").(string)
if methodID == "" {
return logical.ErrorResponse("missing method ID"), nil
}
return nil, i.mfaBackend.deleteMFAConfigByMethodID(ctx, methodID, methodType, memDBLoginMFAConfigsTable, loginMFAConfigPrefix)
}
func (i *IdentityStore) handleLoginMFAGenerateUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleLoginMFAGenerateCommon(ctx, req, d.Get("method_id").(string), req.EntityID)
}
func (i *IdentityStore) handleLoginMFAAdminGenerateUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleLoginMFAGenerateCommon(ctx, req, d.Get("method_id").(string), d.Get("entity_id").(string))
}
func (i *IdentityStore) handleLoginMFAGenerateCommon(ctx context.Context, req *logical.Request, methodID, entityID string) (*logical.Response, error) {
if methodID == "" {
return logical.ErrorResponse("missing method ID"), nil
}
if entityID == "" {
return logical.ErrorResponse("missing entityID"), nil
}
mConfig, err := i.mfaBackend.MemDBMFAConfigByID(methodID)
if err != nil {
return nil, err
}
if mConfig == nil {
return logical.ErrorResponse(fmt.Sprintf("configuration for method ID %q does not exist", methodID)), nil
}
if mConfig.ID == "" {
return nil, fmt.Errorf("configuration for method ID %q does not contain an identifier", methodID)
}
entity, err := i.MemDBEntityByID(entityID, true)
if err != nil {
return nil, fmt.Errorf("failed to find entity with ID %q: error: %w", entityID, err)
}
if entity == nil {
return logical.ErrorResponse("invalid entity ID"), nil
}
ns, err := namespace.FromContext(ctx)
if err != nil {
return logical.ErrorResponse("failed to retrieve the namespace"), nil
}
if ns.ID != entity.NamespaceID {
return logical.ErrorResponse("entity namespace ID does not match the current namespace ID"), nil
}
entityNS, err := i.namespacer.NamespaceByID(ctx, entity.NamespaceID)
if err != nil {
return logical.ErrorResponse("entity namespace not found"), nil
}
configNS, err := i.namespacer.NamespaceByID(ctx, mConfig.NamespaceID)
if err != nil {
return logical.ErrorResponse("methodID namespace not found"), nil
}
if configNS.ID != entityNS.ID && !entityNS.HasParent(configNS) {
return logical.ErrorResponse(fmt.Sprintf("entity namespace %s outside of the config namespace %s", entityNS.Path, configNS.Path)), nil
}
switch mConfig.Type {
case mfaMethodTypeTOTP:
return i.mfaBackend.handleMFAGenerateTOTP(ctx, mConfig, entityID)
default:
return logical.ErrorResponse(fmt.Sprintf("generate not available for MFA type %q", mConfig.Type)), nil
}
}
func (i *IdentityStore) handleLoginMFAAdminDestroyUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
var entity *identity.Entity
var err error
methodID := d.Get("method_id").(string)
if methodID == "" {
return logical.ErrorResponse("missing method ID"), nil
}
entityID := d.Get("entity_id").(string)
if entityID == "" {
return logical.ErrorResponse("missing entity ID"), nil
}
entity, err = i.MemDBEntityByID(entityID, true)
if err != nil {
return nil, fmt.Errorf("failed to find entity with ID %q: error: %w", entityID, err)
}
if entity == nil {
return logical.ErrorResponse("invalid entity ID"), nil
}
mConfig, err := i.mfaBackend.MemDBMFAConfigByID(methodID)
if err != nil {
return nil, err
}
if mConfig == nil {
return logical.ErrorResponse(fmt.Sprintf("configuration for method ID %q does not exist", methodID)), nil
}
if mConfig.ID == "" {
return nil, fmt.Errorf("configuration for method ID %q does not contain an identifier", methodID)
}
if mConfig.Type != mfaMethodTypeTOTP {
return nil, fmt.Errorf("method ID does not match TOTP type")
}
ns, err := namespace.FromContext(ctx)
if err != nil {
return logical.ErrorResponse("failed to retrieve the namespace"), nil
}
if ns.ID != entity.NamespaceID {
return logical.ErrorResponse("entity namespace ID does not match the current namespace ID"), nil
}
entityNS, err := i.namespacer.NamespaceByID(ctx, entity.NamespaceID)
if err != nil {
return logical.ErrorResponse("entity namespace not found"), nil
}
configNS, err := i.namespacer.NamespaceByID(ctx, mConfig.NamespaceID)
if err != nil {
return logical.ErrorResponse("methodID namespace not found"), nil
}
if configNS.ID != entityNS.ID && !entityNS.HasParent(configNS) {
return logical.ErrorResponse(fmt.Sprintf("entity namespace %s outside of the current namespace %s", entityNS.Path, ns.Path)), nil
}
// destroying the secret on the entity
if entity.MFASecrets != nil {
delete(entity.MFASecrets, mConfig.ID)
}
err = i.upsertEntity(ctx, entity, nil, true)
if err != nil {
return nil, fmt.Errorf("failed to persist MFA secret in entity, error: %w", err)
}
return nil, nil
}
// loadMFAMethodConfigs loads MFA method configs for login MFA
func (b *LoginMFABackend) loadMFAMethodConfigs(ctx context.Context, ns *namespace.Namespace) error {
b.mfaLogger.Trace("loading login MFA configurations")
barrierView, err := b.Core.barrierViewForNamespace(ns.ID)
if err != nil {
return fmt.Errorf("error getting namespace view, namespaceid %s, error %w", ns.ID, err)
}
existing, err := barrierView.List(ctx, loginMFAConfigPrefix)
if err != nil {
return fmt.Errorf("failed to list MFA configurations for namespace path %s and prefix %s: %w", ns.Path, loginMFAConfigPrefix, err)
}
b.mfaLogger.Trace("methods collected", "num_existing", len(existing))
for _, key := range existing {
b.mfaLogger.Trace("loading method", "method", key)
// Read the config from storage
mConfig, err := b.getMFAConfig(ctx, loginMFAConfigPrefix+key, barrierView)
if err != nil {
return err
}
if mConfig == nil {
b.mfaLogger.Trace("failed to find the config related to a method", "namespace", ns.Path, "prefix", loginMFAConfigPrefix, "method", key)
continue
}
// Load the config in MemDB
err = b.MemDBUpsertMFAConfig(ctx, mConfig)
if err != nil {
return fmt.Errorf("failed to load configuration ID %s prefix %s in MemDB: %w", mConfig.ID, loginMFAConfigPrefix, err)
}
}
b.mfaLogger.Trace("configurations restored", "namespace", ns.Path, "prefix", loginMFAConfigPrefix)
return nil
}
// loadMFAEnforcementConfigs loads MFA method configs for login MFA
func (b *LoginMFABackend) loadMFAEnforcementConfigs(ctx context.Context, ns *namespace.Namespace) ([]*mfa.MFAEnforcementConfig, error) {
b.mfaLogger.Trace("loading login MFA enforcement configurations")
barrierView, err := b.Core.barrierViewForNamespace(ns.ID)
if err != nil {
return nil, fmt.Errorf("error getting namespace view, namespaceid %s, error %w", ns.ID, err)
}
existing, err := barrierView.List(ctx, mfaLoginEnforcementPrefix)
if err != nil {
return nil, fmt.Errorf("failed to list MFA enforcement configurations for namespace %s with prefix %s: %w", ns.Path, mfaLoginEnforcementPrefix, err)
}
b.mfaLogger.Trace("enforcements configs collected", "num_existing", len(existing))
eConfigs := make([]*mfa.MFAEnforcementConfig, 0)
for _, key := range existing {
b.mfaLogger.Trace("loading enforcement", "config", key)
// Read the config from storage
mConfig, err := b.getMFALoginEnforcementConfig(ctx, mfaLoginEnforcementPrefix+key, barrierView)
if err != nil {
return nil, err
}
if mConfig == nil {
b.mfaLogger.Trace("failed to find an enforcement config", "namespace", ns.Path, "prefix", mfaLoginEnforcementPrefix, "config", key)
continue
}
// Load the config in MemDB
err = b.MemDBUpsertMFALoginEnforcementConfig(ctx, mConfig)
if err != nil {
return nil, fmt.Errorf("failed to load enforcement configuration ID %s with prefix %s in MemDB: %w", mConfig.ID, mfaLoginEnforcementPrefix, err)
}
eConfigs = append(eConfigs, mConfig)
}
b.mfaLogger.Trace("enforcement configurations restored", "namespace", ns.Path, "prefix", mfaLoginEnforcementPrefix)
return eConfigs, nil
}
func (b *LoginMFABackend) loginMFAMethodExistenceCheck(eConfig *mfa.MFAEnforcementConfig) error {
var aggErr *multierror.Error
for _, confID := range eConfig.MFAMethodIDs {
config, memErr := b.MemDBMFAConfigByID(confID)
if memErr != nil {
aggErr = multierror.Append(aggErr, memErr)
return aggErr.ErrorOrNil()
}
if config == nil {
aggErr = multierror.Append(aggErr, fmt.Errorf("found an MFA method ID in enforcement config, but failed to find the MFA method config method ID %s", confID))
}
}
return aggErr.ErrorOrNil()
}
func (b *LoginMFABackend) handleMFALoginValidate(ctx context.Context, req *logical.Request, d *framework.FieldData) (retResp *logical.Response, retErr error) {
// mfaReqID is the ID of the login request
mfaReqID := d.Get("mfa_request_id").(string)
if mfaReqID == "" {
return logical.ErrorResponse("missing request ID"), nil
}
// a map of methodID to passcode
methodIDToPasscodeInterface := d.Get("mfa_payload")
if methodIDToPasscodeInterface == nil {
return logical.ErrorResponse("missing mfa payload"), nil
}
var mfaCreds logical.MFACreds
err := mapstructure.Decode(methodIDToPasscodeInterface, &mfaCreds)
if err != nil {
return logical.ErrorResponse("invalid mfa payload"), nil
}
// getting the cached response Auth. We should note that the entry is
// removed from the queue, and if any error happens before the validation
// and creating a token succeed, we need to push the entry back to the queue.
cachedResponseAuth, err := b.Core.PopMFAResponseAuthByID(mfaReqID)
if err != nil || cachedResponseAuth == nil {
return logical.ErrorResponse("invalid request ID"), nil
}
defer func() {
// Only if retErr is NOT nil, then push back the valid entry
if retErr == nil {
return
}
pushErr := b.Core.SaveMFAResponseAuth(cachedResponseAuth)
if pushErr != nil {
retErr = multierror.Append(retErr, pushErr)
}
}()
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, fmt.Errorf("MFA validation failed. Namespace not found. error: %v", err)
}
if ns.ID != cachedResponseAuth.RequestNSID {
return nil, fmt.Errorf("original request was issued in a different namesapce %v, current namespace is %v", cachedResponseAuth.RequestNSPath, ns.Path)
}
entity, _, err := b.Core.fetchEntityAndDerivedPolicies(ctx, ns, cachedResponseAuth.CachedAuth.EntityID, true)
if err != nil || entity == nil {
return nil, fmt.Errorf("MFA validation failed. entity not found: %v", err)
}
// finding the MFAEnforcement config that matches our ns. ns could be root as well
matchedMfaEnforcementList, err := b.Core.buildMFAEnforcementConfigList(ctx, entity, cachedResponseAuth.RequestPath)
if err != nil {
return nil, fmt.Errorf("failed to find MFAEnforcement configuration")
}
if len(matchedMfaEnforcementList) == 0 {
return nil, fmt.Errorf("found nil or empty MFAEnforcement configuration")
}
for _, eConfig := range matchedMfaEnforcementList {
err = b.Core.validateLoginMFA(ctx, eConfig, entity, req.Connection.RemoteAddr, mfaCreds)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf("failed to satisfy enforcement %s. error: %s", eConfig.Name, err.Error())), logical.ErrPermissionDenied
}
}
// MFA validation has passed. Let's generate the token
resp, err := b.Core.LoginMFACreateToken(ctx, cachedResponseAuth.RequestPath, cachedResponseAuth.CachedAuth, req.Data)
if err != nil {
return nil, fmt.Errorf("failed to create a token. error: %v", err)
}
return resp, nil
}
func (c *Core) teardownLoginMFA() error {
if !c.IsDRSecondary() {
// Clear any cached auth response
c.mfaResponseAuthQueueLock.Lock()
c.mfaResponseAuthQueue = nil
c.mfaResponseAuthQueueLock.Unlock()
c.loginMFABackend.usedCodes = nil
if err := c.loginMFABackend.ResetLoginMFAMemDB(); err != nil {
return err
}
}
return nil
}
// LoginMFACreateToken creates a token after the login MFA is validated.
// It also applies the lease quotas on the original login request path.
func (c *Core) LoginMFACreateToken(ctx context.Context, reqPath string, cachedAuth *logical.Auth, loginRequestData map[string]interface{}) (*logical.Response, error) {
auth := cachedAuth
resp := &logical.Response{
Auth: auth,
}
// Determine the source of the login
mountPoint := c.router.MatchingMount(ctx, reqPath)
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, fmt.Errorf("namespace not found: %w", err)
}
// The request successfully authenticated itself. Run the quota checks on
// the original login request path before creating the token.
quotaResp, quotaErr := c.applyLeaseCountQuota(ctx, "as.Request{
Path: reqPath,
MountPath: strings.TrimPrefix(mountPoint, ns.Path),
Role: c.DetermineRoleFromLoginRequest(mountPoint, loginRequestData, ctx),
NamespacePath: ns.Path,
})
if quotaErr != nil {
c.logger.Error("failed to apply quota", "path", reqPath, "error", quotaErr)
return nil, quotaErr
}
if !quotaResp.Allowed {
if c.logger.IsTrace() {
c.logger.Trace("request rejected due to lease count quota violation", "request_path", reqPath)
}
return nil, fmt.Errorf("request path %q: %w", reqPath, quotas.ErrLeaseCountQuotaExceeded)
}
// note that we don't need to handle the error for the following function right away.
// The function takes the response as in input variable and modify it. So, the returned
// arguments are resp and err.
leaseGenerated, resp, err := c.LoginCreateToken(ctx, ns, reqPath, mountPoint, resp, loginRequestData)
if quotaResp.Access != nil {
quotaAckErr := c.ackLeaseQuota(quotaResp.Access, leaseGenerated)
if quotaAckErr != nil {
err = multierror.Append(err, quotaAckErr)
}
}
return resp, err
}
func (i *IdentityStore) handleMFALoginEnforcementList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
keys, configInfo, err := i.mfaBackend.mfaLoginEnforcementList(ctx)
if err != nil {
return nil, err
}
return logical.ListResponseWithInfo(keys, configInfo), nil
}
func (i *IdentityStore) handleMFALoginEnforcementRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name := d.Get("name").(string)
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
respData, err := i.mfaBackend.mfaLoginEnforcementConfigByNameAndNamespace(name, ns.ID)
if err != nil {
return nil, err
}
if respData == nil {
return nil, nil
}
// The config is readable only from the same namespace
if ns.ID != respData["namespace_id"].(string) {
return logical.ErrorResponse("request namespace does not match method namespace"), nil
}
return &logical.Response{
Data: respData,
}, nil
}
func (i *IdentityStore) handleMFALoginEnforcementUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
var err error
var eConfig *mfa.MFAEnforcementConfig
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
name := d.Get("name").(string)
if name == "" {
return logical.ErrorResponse("missing enforcement name"), nil
}
b := i.mfaBackend
b.mfaLock.Lock()
defer b.mfaLock.Unlock()
eConfig, err = b.MemDBMFALoginEnforcementConfigByNameAndNamespace(name, ns.ID)
if err != nil {
return nil, err
}
if eConfig == nil {
configID, err := uuid.GenerateUUID()
if err != nil {
return nil, fmt.Errorf("failed to generate an identifier for MFA login enforcement config: %w", err)
}
eConfig = &mfa.MFAEnforcementConfig{
Name: name,
NamespaceID: ns.ID,
ID: configID,
}
}
mfaMethodIds, ok := d.GetOk("mfa_method_ids")
if !ok {
return logical.ErrorResponse("missing method ids"), nil
}
for _, mmid := range mfaMethodIds.([]string) {
// make sure this method id actually exists
config, err := b.mfaConfigReadByMethodID(mmid)
if err != nil {
return nil, err
}
if config == nil {
return logical.ErrorResponse("one of the provided method ids doesn't exist"), nil
}
mfaNs, err := i.namespacer.NamespaceByID(ctx, config["namespace_id"].(string))
if err != nil {
return logical.ErrorResponse("failed to retrieve config namespace"), nil
}
if ns.ID != mfaNs.ID && !ns.HasParent(mfaNs) {
return logical.ErrorResponse("one of the provided method ids is in an incompatible namespace and can't be used"), nil
}
}
eConfig.MFAMethodIDs = mfaMethodIds.([]string)
oneOfLastFour := false
authMethodAccessors, ok := d.GetOk("auth_method_accessors")
if ok {
for _, accessor := range authMethodAccessors.([]string) {
found, err := b.validateAuthEntriesForAccessorOrType(ctx, ns, func(entry *MountEntry) bool {
return accessor == entry.Accessor
})
if err != nil {
return nil, err
}
if !found {
return logical.ErrorResponse("one of the auth method accessors provided is invalid"), nil
}
}
eConfig.AuthMethodAccessors = authMethodAccessors.([]string)
oneOfLastFour = true
}
authMethodTypes, ok := d.GetOk("auth_method_types")
if ok {
for _, authType := range authMethodTypes.([]string) {
found, err := b.validateAuthEntriesForAccessorOrType(ctx, ns, func(entry *MountEntry) bool {
return authType == entry.Type
})
if err != nil {
return nil, err
}
if !found {
return logical.ErrorResponse("one of the auth method types provided is invalid"), nil
}
}
eConfig.AuthMethodTypes = authMethodTypes.([]string)
oneOfLastFour = true
}
identityGroupIds, ok := d.GetOk("identity_group_ids")
if ok {
for _, groupId := range identityGroupIds.([]string) {
group, err := i.MemDBGroupByID(groupId, true)
if err != nil {
return nil, err
}
if group == nil {
return logical.ErrorResponse("one of the provided group ids doesn't exist"), nil
}
}
eConfig.IdentityGroupIds = identityGroupIds.([]string)
oneOfLastFour = true
}
identityEntityIds, ok := d.GetOk("identity_entity_ids")
if ok {
for _, entityId := range identityEntityIds.([]string) {
entity, err := i.MemDBEntityByID(entityId, true)
if err != nil {
return nil, err
}
if entity == nil {
return logical.ErrorResponse("one of the provided entity ids doesn't exist"), nil
}
}
eConfig.IdentityEntityIDs = identityEntityIds.([]string)
oneOfLastFour = true
}
if !oneOfLastFour {
return logical.ErrorResponse("One of auth_method_accessors, auth_method_types, identity_group_ids, identity_entity_ids must be specified"), nil
}
// Store the config
err = b.putMFALoginEnforcementConfig(ctx, eConfig)
if err != nil {
return nil, err
}
// Back the config in MemDB
return nil, b.MemDBUpsertMFALoginEnforcementConfig(ctx, eConfig)
}
func (i *IdentityStore) handleMFALoginEnforcementDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name := d.Get("name").(string)
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
return nil, i.mfaBackend.deleteMFALoginEnforcementConfigByNameAndNamespace(ctx, name, ns.ID)
}
func (b *LoginMFABackend) validateAuthEntriesForAccessorOrType(ctx context.Context, ns *namespace.Namespace, validFunc func(entry *MountEntry) bool) (bool, error) {
b.Core.authLock.RLock()
defer b.Core.authLock.RUnlock()
for _, entry := range b.Core.auth.Entries {
// only check auth methods in the current namespace
if entry.Namespace().ID != ns.ID {
continue
}
cont, err := b.Core.checkReplicatedFiltering(ctx, entry, credentialRoutePrefix)
if err != nil {
return false, err
}
if cont {
continue
}
if validFunc(entry) {
return true, nil
}
}