-
Notifications
You must be signed in to change notification settings - Fork 0
/
iam.go
1731 lines (1619 loc) · 53.4 KB
/
iam.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
// Copyright 2018, Jon Hadfield <jon@lessknown.co.uk>
// This file is part of ape.
// ape is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// ape is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with ape. If not, see <http://www.gnu.org/licenses/>.
package ape
import (
"fmt"
"encoding/csv"
"io"
"strings"
"time"
"reflect"
"strconv"
"encoding/json"
"net/url"
"sync"
"github.com/Knetic/govaluate"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/iam/iamiface"
h "github.com/jonhadfield/ape/helpers"
r "github.com/jonhadfield/ape/root"
ri "github.com/jonhadfield/ape/root/aws/iam"
"github.com/pkg/errors"
)
type iamUser struct {
iam.User
CRUserCreationTime time.Time
CRPasswordEnabled bool
CRPasswordLastUsed time.Time
CRPasswordLastChanged time.Time
CRPasswordNextRotation time.Time
CRMfaActive bool
CRAccessKey1Active bool
CRAccessKey1LastRotated time.Time
CRAccessKey1LastUsedDate time.Time
CRAccessKey1LastUsedRegion string
CRAccessKey1LastUsedService string
CRAccessKey2Active bool
CRAccessKey2LastRotated time.Time
CRAccessKey2LastUsedDate time.Time
CRAccessKey2LastUsedRegion string
CRAccessKey2LastUsedService string
CRCert1Active bool
CRCert1LastRotated time.Time
CRCert2Active bool
CRCert2LastRotated time.Time
}
type iamUsers []iamUser
type accessKey struct {
iam.AccessKeyMetadata
LastRotated time.Time
LastUsedDate time.Time
LastUsedRegion string
LastUsedService string
}
type accessKeys []accessKey
func getReportItemByArn(arn string, report credentialReport) (result credentialReportItem) {
for i := range report {
item := report[i]
if item.Arn == arn {
result = item
break
}
}
return
}
func getReportItemByUserName(userName string, report credentialReport) (result credentialReportItem) {
for i := range report {
item := report[i]
if item.User == userName {
result = item
break
}
}
return
}
var allUsersByAccount map[string]iamUsers
func getUsers(svc iamiface.IAMAPI, accountID string) (users iamUsers, err error) {
if len(allUsersByAccount[accountID]) > 0 {
// TODO: Log debug/info? "Returning previously generated user list"
users = allUsersByAccount[accountID]
return
}
var report credentialReport
report, err = getCredentialReport(svc)
if err != nil {
return
}
iamUsersOutput, err := svc.ListUsers(&iam.ListUsersInput{})
if err != nil {
err = errors.WithStack(err)
return
}
var user iamUser
for _, u := range iamUsersOutput.Users {
CRByUser := getReportItemByArn(*u.Arn, report)
user.Arn = u.Arn
user.CreateDate = u.CreateDate
user.PasswordLastUsed = u.PasswordLastUsed
user.Path = u.Path
user.UserId = u.UserId
user.UserName = u.UserName
user.CRUserCreationTime = CRByUser.UserCreationTime
user.CRPasswordEnabled = CRByUser.PasswordEnabled
user.CRPasswordLastUsed = CRByUser.PasswordLastUsed
user.CRPasswordLastChanged = CRByUser.PasswordLastChanged
user.CRPasswordNextRotation = CRByUser.PasswordNextRotation
user.CRMfaActive = CRByUser.MfaActive
user.CRAccessKey1Active = CRByUser.AccessKey1Active
user.CRAccessKey1LastRotated = CRByUser.AccessKey1LastRotated
user.CRAccessKey1LastUsedDate = CRByUser.AccessKey1LastUsedDate
user.CRAccessKey1LastUsedRegion = CRByUser.AccessKey1LastUsedRegion
user.CRAccessKey1LastUsedService = CRByUser.AccessKey1LastUsedService
user.CRAccessKey2Active = CRByUser.AccessKey2Active
user.CRAccessKey2LastRotated = CRByUser.AccessKey2LastRotated
user.CRAccessKey2LastUsedDate = CRByUser.AccessKey2LastUsedDate
user.CRAccessKey2LastUsedRegion = CRByUser.AccessKey2LastUsedRegion
user.CRAccessKey2LastUsedService = CRByUser.AccessKey2LastUsedService
user.CRCert1Active = CRByUser.Cert1Active
user.CRCert1LastRotated = CRByUser.Cert1LastRotated
user.CRCert2Active = CRByUser.Cert2Active
user.CRCert2LastRotated = CRByUser.Cert2LastRotated
users = append(users, user)
}
// Add root user
rootItem := getReportItemByUserName("root", report)
rootUser := iamUser{}
rootUser.Arn = &rootItem.Arn
rootUser.CreateDate = &rootItem.UserCreationTime
rootUser.PasswordLastUsed = &rootItem.PasswordLastUsed
rootUser.Path = h.PtrToStr("rootPath")
rootUser.UserId = h.PtrToStr("rootUsedId")
rootUser.UserName = h.PtrToStr("root")
rootUser.CRUserCreationTime = rootItem.UserCreationTime
rootUser.CRPasswordEnabled = rootItem.PasswordEnabled
rootUser.CRPasswordLastUsed = rootItem.PasswordLastUsed
rootUser.CRPasswordLastChanged = rootItem.PasswordLastChanged
rootUser.CRPasswordNextRotation = rootItem.PasswordNextRotation
rootUser.CRMfaActive = rootItem.MfaActive
rootUser.CRAccessKey1Active = rootItem.AccessKey1Active
rootUser.CRAccessKey1LastRotated = rootItem.AccessKey1LastRotated
rootUser.CRAccessKey1LastUsedDate = rootItem.AccessKey1LastUsedDate
rootUser.CRAccessKey1LastUsedRegion = rootItem.AccessKey1LastUsedRegion
rootUser.CRAccessKey1LastUsedService = rootItem.AccessKey1LastUsedService
rootUser.CRAccessKey2Active = rootItem.AccessKey2Active
rootUser.CRAccessKey2LastRotated = rootItem.AccessKey2LastRotated
rootUser.CRAccessKey2LastUsedDate = rootItem.AccessKey2LastUsedDate
rootUser.CRAccessKey2LastUsedRegion = rootItem.AccessKey2LastUsedRegion
rootUser.CRAccessKey2LastUsedService = rootItem.AccessKey2LastUsedService
rootUser.CRCert1Active = rootItem.Cert1Active
rootUser.CRCert1LastRotated = rootItem.Cert1LastRotated
rootUser.CRCert2Active = rootItem.Cert2Active
rootUser.CRCert2LastRotated = rootItem.Cert2LastRotated
users = append(users, rootUser)
// TODO: Log debug/info "Setting GLOBAL Users with: %d entries"
allUsersByAccount[accountID] = users
return
}
func getMFADevices(svc iamiface.IAMAPI, username string) (devices []*iam.MFADevice, err error) {
input := iam.ListMFADevicesInput{}
if username != "" {
input.UserName = &username
}
var output *iam.ListMFADevicesOutput
output, err = svc.ListMFADevices(&input)
if err != nil {
err = errors.WithStack(err)
}
devices = output.MFADevices
return
}
func getAccessKeys(svc iamiface.IAMAPI, user iamUser) (accessKeys accessKeys) {
input := iam.ListAccessKeysInput{}
if !reflect.DeepEqual(user, iamUser{}) {
input.UserName = user.UserName
}
list, _ := svc.ListAccessKeys(&input)
iamKeys := list.AccessKeyMetadata
for i, iamKey := range iamKeys {
mergedAccessKey := accessKey{}
mergedAccessKey.UserName = iamKey.UserName
mergedAccessKey.CreateDate = iamKey.CreateDate
mergedAccessKey.Status = iamKey.Status
mergedAccessKey.AccessKeyId = iamKey.AccessKeyId
if i == 0 {
mergedAccessKey.LastUsedDate = user.CRAccessKey1LastUsedDate
mergedAccessKey.LastRotated = user.CRAccessKey1LastRotated
mergedAccessKey.LastUsedRegion = user.CRAccessKey1LastUsedRegion
mergedAccessKey.LastUsedService = user.CRAccessKey1LastUsedService
} else if i == 1 {
mergedAccessKey.LastUsedDate = user.CRAccessKey2LastUsedDate
mergedAccessKey.LastRotated = user.CRAccessKey2LastRotated
mergedAccessKey.LastUsedRegion = user.CRAccessKey2LastUsedRegion
mergedAccessKey.LastUsedService = user.CRAccessKey2LastUsedService
}
accessKeys = append(accessKeys, mergedAccessKey)
}
return
}
func enforceIAMPolicy(l []interface{}, session *session.Session, planItem PlanItem) (result enforcePolicyOutput, err error) {
var resource string
_, resource, err = h.GetResourceParts(planItem.Policy.Resource)
if err != nil {
return
}
svc := getIAMClient(session, planItem.Target.AccountID)
switch resource {
case "User":
result, err = enforceUserPolicy(l, svc, planItem)
if err != nil {
return
}
case "Role":
result, err = enforceRolePolicy(l, svc, planItem)
if err != nil {
return
}
case "Policy":
result, err = enforcePolicy(l, svc, planItem)
if err != nil {
return
}
case "PasswordPolicy":
result, err = enforcePasswordPolicy(l, svc, planItem)
if err != nil {
return
}
default:
message := fmt.Sprintf("unhandled resource: iam: %s", resource)
err = errors.Wrap(err, message)
}
return
}
type credentialReportItem struct {
User string
Arn string
UserCreationTime time.Time
PasswordEnabled bool
PasswordLastUsed time.Time
PasswordLastChanged time.Time
PasswordNextRotation time.Time
MfaActive bool
AccessKey1Active bool
AccessKey1LastRotated time.Time
AccessKey1LastUsedDate time.Time
AccessKey1LastUsedRegion string
AccessKey1LastUsedService string
AccessKey2Active bool
AccessKey2LastRotated time.Time
AccessKey2LastUsedDate time.Time
AccessKey2LastUsedRegion string
AccessKey2LastUsedService string
Cert1Active bool
Cert1LastRotated time.Time
Cert2Active bool
Cert2LastRotated time.Time
}
type credentialReport []credentialReportItem
var iamClientByAccount map[string]iamiface.IAMAPI
var iamClientByAccountMutex sync.Mutex
func getIAMClient(session *session.Session, accID string) (output iamiface.IAMAPI) {
iamClientByAccountMutex.Lock()
if iamClientByAccount == nil {
iamClientByAccount = make(map[string]iamiface.IAMAPI)
}
if len(s3SClientByAccountAndRegion) == 0 {
iamClientByAccount = make(map[string]iamiface.IAMAPI)
}
if s3SClientByAccountAndRegion[accID] != nil {
output = iamClientByAccount[accID]
} else {
output = iam.New(session)
iamClientByAccount[accID] = output
}
iamClientByAccountMutex.Unlock()
return
}
func stringToBool(input string) (output bool) {
if strings.ToLower(input) == "true" {
output = true
}
return
}
func getCredentialReport(svc iamiface.IAMAPI) (output credentialReport, err error) {
getInput := &iam.GetCredentialReportInput{}
var report *iam.GetCredentialReportOutput
genInput := &iam.GenerateCredentialReportInput{}
var generateCredentialReportOutput *iam.GenerateCredentialReportOutput
for {
generateCredentialReportOutput, err = svc.GenerateCredentialReport(genInput)
if err != nil {
err = errors.WithStack(err)
return
}
if *generateCredentialReportOutput.State != "COMPLETE" {
time.Sleep(500 * time.Millisecond)
continue
} else {
break
}
}
report, err = svc.GetCredentialReport(getInput)
if err != nil {
err = errors.WithStack(err)
return
}
reportContent := string(report.Content)
reader := csv.NewReader(strings.NewReader(reportContent))
var readErr error
var record []string
var credReportItem credentialReportItem
for {
record, readErr = reader.Read()
if len(record) > 0 && record[0] == "user" && record[1] == "arn" {
continue
}
if readErr == io.EOF {
break
}
var userName string
if record[crUser] == "<root_account>" {
userName = "root"
} else {
userName = record[crUser]
}
var (
passwordEnabled, mfaActive, accessKey1Active, accessKey2Active, cert1Active, cert2Active bool
userCreationTime, passwordLastUsed, passwordLastChanged, passwordNextRotation,
accessKey1LastRotated, accessKey1LastUsedDate, accessKey2LastRotated, accessKey2LastUsedDate,
cert1LastRotated, cert2LastRotated time.Time
)
userCreationTime, err = time.Parse(time.RFC3339, record[crUserCreationTime])
if err != nil {
userCreationTime = time.Time{}
}
passwordEnabled = stringToBool(record[crPasswordEnabled])
passwordLastUsed, err = time.Parse(time.RFC3339, record[crPasswordLastUsed])
if err != nil {
passwordLastUsed = time.Time{}
}
passwordLastChanged, err = time.Parse(time.RFC3339, record[crPasswordLastChanged])
if err != nil {
passwordLastChanged = time.Time{}
}
passwordNextRotation, err = time.Parse(time.RFC3339, record[crPasswordNextRotation])
if err != nil {
passwordNextRotation = time.Time{}
}
mfaActive = stringToBool(record[crMfaActive])
accessKey1Active = stringToBool(record[crAccessKey1Active])
accessKey1LastRotated, err = time.Parse(time.RFC3339, record[crAccessKey1LastRotated])
if err != nil {
accessKey1LastRotated = time.Time{}
}
accessKey1LastUsedDate, err = time.Parse(time.RFC3339, record[crAccessKey1LastUsedDate])
if err != nil {
accessKey1LastUsedDate = time.Time{}
}
accessKey2Active = stringToBool(record[crAccessKey2Active])
accessKey2LastRotated, err = time.Parse(time.RFC3339, record[crAccessKey2LastRotated])
if err != nil {
accessKey2LastRotated = time.Time{}
}
accessKey2LastUsedDate, err = time.Parse(time.RFC3339, record[crAccessKey2LastUsedDate])
if err != nil {
accessKey2LastUsedDate = time.Time{}
}
cert1Active = stringToBool(record[crCert1Active])
cert1LastRotated, err = time.Parse(time.RFC3339, record[crCert1LastRotated])
if err != nil {
cert1LastRotated = time.Time{}
}
cert2Active = stringToBool(record[crCert2Active])
cert2LastRotated, err = time.Parse(time.RFC3339, record[crCert2LastRotated])
if err != nil {
cert2LastRotated = time.Time{}
err = nil
}
credReportItem = credentialReportItem{
Arn: record[crArn],
User: userName,
UserCreationTime: userCreationTime,
PasswordEnabled: passwordEnabled,
PasswordLastUsed: passwordLastUsed,
PasswordLastChanged: passwordLastChanged,
PasswordNextRotation: passwordNextRotation,
MfaActive: mfaActive,
AccessKey1Active: accessKey1Active,
AccessKey1LastRotated: accessKey1LastRotated,
AccessKey1LastUsedDate: accessKey1LastUsedDate,
AccessKey1LastUsedRegion: record[crAccessKey1LastUsedRegion],
AccessKey1LastUsedService: record[crAccessKey1LastUsedService],
AccessKey2Active: accessKey2Active,
AccessKey2LastRotated: accessKey2LastRotated,
AccessKey2LastUsedDate: accessKey2LastUsedDate,
AccessKey2LastUsedRegion: record[crAccessKey2LastUsedRegion],
AccessKey2LastUsedService: record[crAccessKey2LastUsedService],
Cert1Active: cert1Active,
Cert1LastRotated: cert1LastRotated,
Cert2Active: cert2Active,
Cert2LastRotated: cert2LastRotated,
}
output = append(output, credReportItem)
}
return
}
func getAccessKeyLastUsed(svc iamiface.IAMAPI, accessKeyID string) (time *time.Time) {
input := iam.GetAccessKeyLastUsedInput{
AccessKeyId: &accessKeyID,
}
output, _ := svc.GetAccessKeyLastUsed(&input)
time = output.AccessKeyLastUsed.LastUsedDate
return
}
func filterUserName(user iamUser, filter *r.Filter) (filterMatch bool) {
if filter.Comparison == "in" {
if h.StringInSlice(*user.UserName, filter.Values) {
filterMatch = true
}
} else if filter.Comparison == "not in" {
if !h.StringInSlice(*user.UserName, filter.Values) {
filterMatch = true
}
} else if filter.Comparison == "==" && *user.UserName == filter.Value {
filterMatch = true
} else if filter.Comparison == "!=" && *user.UserName != filter.Value {
filterMatch = true
}
return
}
func filterHasPassword(svc iamiface.IAMAPI, user iamUser, filter *r.Filter) (filterMatch bool, err error) {
var getLoginProfileOutput *iam.GetLoginProfileOutput
getLoginProfileInput := &iam.GetLoginProfileInput{
UserName: user.UserName,
}
var hasPassword bool
// The user with name root cannot be found.
if *user.UserName == "root" {
if user.CRPasswordEnabled {
hasPassword = true
}
} else {
getLoginProfileOutput, err = svc.GetLoginProfile(getLoginProfileInput)
if err != nil {
// NoSuchEntity means no profile, not a failure. everything else will be though.
if !strings.Contains(err.Error(), "NoSuchEntity") {
err = errors.WithStack(err)
return
}
// reset error as we don't consider it a failure
err = nil
}
if getLoginProfileOutput.LoginProfile != nil {
hasPassword = true
}
}
if filter.Value == "false" && !hasPassword {
filterMatch = true
}
if filter.Value == "true" && hasPassword {
filterMatch = true
}
return
}
func filterHasGroup(svc iamiface.IAMAPI, user iamUser, filter *r.Filter) (filterMatch bool, err error) {
var listGroupsForUserInput = iam.ListGroupsForUserInput{
UserName: user.UserName,
}
var listGroupsForUserOutput *iam.ListGroupsForUserOutput
listGroupsForUserOutput, err = svc.ListGroupsForUser(&listGroupsForUserInput)
for _, group := range listGroupsForUserOutput.Groups {
if *group.GroupName == filter.Value {
filterMatch = true
break
}
}
return
}
func filterDoesNotHaveGroup(svc iamiface.IAMAPI, user iamUser, filter *r.Filter) (filterMatch bool, err error) {
var listGroupsForUserInput = iam.ListGroupsForUserInput{
UserName: user.UserName,
}
var listGroupsForUserOutput *iam.ListGroupsForUserOutput
listGroupsForUserOutput, err = svc.ListGroupsForUser(&listGroupsForUserInput)
filterMatch = true
for _, group := range listGroupsForUserOutput.Groups {
if *group.GroupName == filter.Value {
filterMatch = false
break
}
}
return
}
func filterHasHardwareMFADevice(svc iamiface.IAMAPI, user iamUser, filter *r.Filter) (filterMatch bool, err error) {
// Lack of virtual MFA doesn't necessarily mean no MFA, so first check the user has MFA
var hasMFA bool
hasMFAfilter := &r.Filter{
Criterion: "HasMFADevice",
Value: "true",
}
hasMFA, err = filterHasMFADevice(svc, user, hasMFAfilter)
if err != nil {
return
}
var hasHardwareMFA bool
if hasMFA {
// Get all VIRTUAL MFA devices
var virtualMFADevicesOutput *iam.ListVirtualMFADevicesOutput
virtualMFADevicesOutput, err = svc.ListVirtualMFADevices(&iam.ListVirtualMFADevicesInput{})
if err != nil {
err = errors.WithStack(err)
return
}
virtualMFADevices := virtualMFADevicesOutput.VirtualMFADevices
hasVirtualMFA := false
for _, vmd := range virtualMFADevices {
// Check for root virtual
if *user.UserName == "root" && strings.HasSuffix(*vmd.SerialNumber, "mfa/root-account-mfa-device") {
hasVirtualMFA = true
break
}
if vmd.User != nil && *vmd.User.Arn == *user.Arn {
hasVirtualMFA = true
}
}
if !hasVirtualMFA {
hasHardwareMFA = true
}
}
if filter.Value == "false" && !hasHardwareMFA {
filterMatch = true
}
if filter.Value == "true" && hasHardwareMFA {
filterMatch = true
}
return
}
func filterHasMFADevice(svc iamiface.IAMAPI, user iamUser, filter *r.Filter) (filterMatch bool, err error) {
hasMFADevice := "false"
if *user.UserName == "root" {
if user.CRMfaActive {
hasMFADevice = "true"
}
} else {
var devices []*iam.MFADevice
devices, err = getMFADevices(svc, *user.UserName)
if err != nil {
return
}
if len(devices) > 0 {
hasMFADevice = "true"
}
}
if filter.Value == "false" && hasMFADevice == "false" {
filterMatch = true
}
if filter.Value == "true" && hasMFADevice == "true" {
filterMatch = true
}
return
}
func filterPasswordLastUsed(user iamUser, filter *r.Filter) (filterMatch bool, err error) {
loc, _ := time.LoadLocation("UTC")
var filterValue time.Time
filterValue, err = r.ProcessTimeFilterValue(filter)
if err != nil {
return
}
if user.PasswordLastUsed != nil && !user.PasswordLastUsed.IsZero() {
passwordLastUsed := user.PasswordLastUsed.In(loc)
expressionTxt := fmt.Sprintf("(filterValue %s lastUsed)", filter.Comparison)
var expression *govaluate.EvaluableExpression
expression, err = govaluate.NewEvaluableExpression(expressionTxt)
if err != nil {
err = errors.WithStack(err)
return
}
parameters := make(map[string]interface{}, 8)
parameters["lastUsed"] = passwordLastUsed.Unix()
parameters["filterValue"] = filterValue.Unix()
result, _ := expression.Evaluate(parameters)
if result == true {
filterMatch = true
}
}
return
}
type filterActiveAccessKeysLastUsedInput struct {
svc iamiface.IAMAPI
user iamUser
filter *r.Filter
}
func filterActiveAccessKeysLastUsed(input *filterActiveAccessKeysLastUsedInput) (filterMatch bool, err error) {
loc, _ := time.LoadLocation("UTC")
var filterValue time.Time
filterValue, err = r.ProcessTimeFilterValue(input.filter)
if err != nil {
return
}
keys := getAccessKeys(input.svc, input.user)
for _, key := range keys {
if *key.Status == "Active" {
// Check if key last used > or < date
var keyLastUsed *time.Time
// Have to process root access keys separately
switch *key.AccessKeyId {
case "accessKey1":
keyLastUsed = &input.user.CRAccessKey1LastUsedDate
case "accessKey2":
keyLastUsed = &input.user.CRAccessKey2LastUsedDate
default:
keyLastUsed = getAccessKeyLastUsed(input.svc, *key.AccessKeyId)
}
if keyLastUsed != nil {
keyLastUsedConverted := keyLastUsed.In(loc)
expressionTxt := fmt.Sprintf("(filterValue %s lastUsed)", input.filter.Comparison)
expression, _ := govaluate.NewEvaluableExpression(expressionTxt)
parameters := make(map[string]interface{}, 8)
parameters["lastUsed"] = keyLastUsedConverted.Unix()
parameters["filterValue"] = filterValue.Unix()
result, _ := expression.Evaluate(parameters)
if result == true {
filterMatch = true
break
}
}
}
}
return
}
func filterActiveAccessKeysLastRotated(svc iamiface.IAMAPI, user iamUser, filter *r.Filter) (filterMatch bool, err error) {
loc, _ := time.LoadLocation("UTC")
var filterValue time.Time
filterValue, err = r.ProcessTimeFilterValue(filter)
keys := getAccessKeys(svc, user)
for _, key := range keys {
if *key.Status == "Active" {
// If the check is to see if last rotated greater than a certain time, then check the key is that age yet
var lastRotatedMatch bool
if filter.Comparison == ">" {
// Check if key created > or < date
keyCreated := key.CreateDate.In(loc)
kcExpressionTxt := fmt.Sprintf("(filterValue %s created)", filter.Comparison)
kcExpression, _ := govaluate.NewEvaluableExpression(kcExpressionTxt)
kcParameters := make(map[string]interface{}, 8)
kcParameters["created"] = keyCreated.Unix()
kcParameters["filterValue"] = filterValue.Unix()
kcResult, _ := kcExpression.Evaluate(kcParameters)
if kcResult != true {
continue
}
}
// Check if key last rotated > or < date
keyLastRotated := key.LastRotated.In(loc)
klrExpressionTxt := fmt.Sprintf("(filterValue %s lastRotated)", filter.Comparison)
klrExpression, _ := govaluate.NewEvaluableExpression(klrExpressionTxt)
klrParameters := make(map[string]interface{}, 8)
klrParameters["lastRotated"] = keyLastRotated.Unix()
klrParameters["filterValue"] = filterValue.Unix()
klrResult, _ := klrExpression.Evaluate(klrParameters)
if klrResult == true {
lastRotatedMatch = true
}
if lastRotatedMatch {
filterMatch = true
break
}
}
}
return
}
func filterHasActiveAccessKeyCreatedWithUser(svc iamiface.IAMAPI, user iamUser) (filterMatch bool, err error) {
keys := getAccessKeys(svc, user)
for _, key := range keys {
if *key.CreateDate == *user.CreateDate {
filterMatch = true
return
}
}
return
}
func getRootKeys(user iamUser) (keys accessKeys) {
key1 := accessKey{
LastRotated: user.CRAccessKey1LastRotated,
LastUsedRegion: user.CRAccessKey1LastUsedRegion,
LastUsedService: user.CRAccessKey1LastUsedService,
LastUsedDate: user.CRAccessKey1LastUsedDate,
}
if user.CRAccessKey1Active {
key1.Status = h.PtrToStr("Active")
} else {
key1.Status = h.PtrToStr("Inactive")
}
keys = append(keys, key1)
key2 := accessKey{
LastRotated: user.CRAccessKey2LastRotated,
LastUsedRegion: user.CRAccessKey2LastUsedRegion,
LastUsedService: user.CRAccessKey2LastUsedService,
LastUsedDate: user.CRAccessKey2LastUsedDate,
}
if user.CRAccessKey1Active {
key2.Status = h.PtrToStr("Active")
} else {
key2.Status = h.PtrToStr("Inactive")
}
keys = append(keys, key2)
return
}
func filterHasActiveAccessKey(svc iamiface.IAMAPI, user iamUser, filter *r.Filter) (filterMatch bool, err error) {
var keys accessKeys
if *user.UserName == "root" {
keys = getRootKeys(user)
} else {
keys = getAccessKeys(svc, user)
}
var wanted bool
wanted, err = strconv.ParseBool(filter.Value)
if err != nil {
return
}
foundActive := false
for _, key := range keys {
if *key.Status == "Active" {
foundActive = true
break
}
}
if wanted && foundActive {
filterMatch = true
}
if !wanted && !foundActive {
filterMatch = true
}
return
}
func filterHasUnusedActiveAccessKey(svc iamiface.IAMAPI, user iamUser, filter *r.Filter) (filterMatch bool, err error) {
var keys accessKeys
if *user.UserName == "root" {
key1 := accessKey{
LastRotated: user.CRAccessKey1LastRotated,
LastUsedRegion: user.CRAccessKey1LastUsedRegion,
LastUsedService: user.CRAccessKey1LastUsedService,
LastUsedDate: user.CRAccessKey1LastUsedDate,
}
if user.CRAccessKey1Active {
key1.Status = h.PtrToStr("Active")
} else {
key1.Status = h.PtrToStr("Inactive")
}
keys = append(keys, key1)
key2 := accessKey{
LastRotated: user.CRAccessKey2LastRotated,
LastUsedRegion: user.CRAccessKey2LastUsedRegion,
LastUsedService: user.CRAccessKey2LastUsedService,
LastUsedDate: user.CRAccessKey2LastUsedDate,
}
if user.CRAccessKey1Active {
key2.Status = h.PtrToStr("Active")
} else {
key2.Status = h.PtrToStr("Inactive")
}
keys = append(keys, key2)
} else {
keys = getAccessKeys(svc, user)
}
var wanted bool
wanted, err = strconv.ParseBool(filter.Value)
if err != nil {
return
}
foundUnusedActive := false
for _, key := range keys {
if *key.Status == "Active" && key.LastUsedDate.IsZero() {
foundUnusedActive = true
break
}
}
if wanted && foundUnusedActive {
filterMatch = true
}
if !wanted && !foundUnusedActive {
filterMatch = true
}
return
}
var passwordPolicy = map[string]*iam.GetAccountPasswordPolicyOutput{}
func getAccountPasswordPolicy(svc iamiface.IAMAPI, accountid string) (output *iam.GetAccountPasswordPolicyOutput, err error) {
if passwordPolicy[accountid] != nil {
output = passwordPolicy[accountid]
} else {
output, err = svc.GetAccountPasswordPolicy(&iam.GetAccountPasswordPolicyInput{})
if err != nil {
err = errors.WithStack(err)
return
}
passwordPolicy[accountid] = output
}
return
}
func filterPasswordPolicy(svc iamiface.IAMAPI, planItem PlanItem) (filtersMatch bool, err error) {
accountID := planItem.Target.AccountID
var getPolicyOutput *iam.GetAccountPasswordPolicyOutput
getPolicyOutput, err = getAccountPasswordPolicy(svc, accountID)
if err != nil {
return
}
var filterMatch bool
for _, filter := range planItem.Policy.Filters {
filterMatch = false
switch filter.Criterion {
case "MinimumPasswordLength":
expressionTxt := fmt.Sprintf("(minimumPasswordLength %s filterValue)", filter.Comparison)
expression, govaluateErr := govaluate.NewEvaluableExpression(expressionTxt)
if govaluateErr != nil {
err = govaluateErr
return
}
parameters := make(map[string]interface{}, 8)
parameters["minimumPasswordLength"] = *getPolicyOutput.PasswordPolicy.MinimumPasswordLength
filterVal, _ := strconv.Atoi(filter.Value)
parameters["filterValue"] = filterVal
result, evalErr := expression.Evaluate(parameters)
if evalErr != nil {
err = evalErr
return
}
if result == true {
filterMatch = true
}
case "RequireAtLeastOneUpperCaseLetter":
filterValue, _ := strconv.ParseBool(filter.Value)
if *getPolicyOutput.PasswordPolicy.RequireUppercaseCharacters == filterValue {
filterMatch = true
}
case "RequireAtLeastOneLowerCaseLetter":
filterValue, _ := strconv.ParseBool(filter.Value)
if *getPolicyOutput.PasswordPolicy.RequireLowercaseCharacters == filterValue {
filterMatch = true
}
case "RequireAtLeastOneNumber":
filterValue, _ := strconv.ParseBool(filter.Value)
if *getPolicyOutput.PasswordPolicy.RequireNumbers == filterValue {
filterMatch = true
}
case "RequireAtLeastOneNonAlphanumericCharacter":
filterValue, _ := strconv.ParseBool(filter.Value)
if *getPolicyOutput.PasswordPolicy.RequireSymbols == filterValue {
filterMatch = true
}
case "AllowUsersToChangeTheirOwnPassword":
filterValue, _ := strconv.ParseBool(filter.Value)
if *getPolicyOutput.PasswordPolicy.AllowUsersToChangePassword == filterValue {
filterMatch = true
}
case "PasswordExpirationPeriod":
maxPasswordAge := getPolicyOutput.PasswordPolicy.MaxPasswordAge
onemillion := int64(1000000)
if maxPasswordAge == nil {
maxPasswordAge = &onemillion
}
expressionTxt := fmt.Sprintf("(expirationPeriod %s filterValue)", filter.Comparison)
var expression *govaluate.EvaluableExpression
expression, err = govaluate.NewEvaluableExpression(expressionTxt)
if err != nil {
return
}
parameters := make(map[string]interface{}, 8)
parameters["expirationPeriod"] = *maxPasswordAge
var filterVal int
filterVal, err = strconv.Atoi(filter.Value)
if err != nil {
return
}
parameters["filterValue"] = filterVal
var result interface{}
result, err = expression.Evaluate(parameters)
if err != nil {
return
}
if result == true {
filterMatch = true
}
case "NumberOfPasswordsToRemember":
expressionTxt := fmt.Sprintf("(passwordsToRemember %s filterValue)", filter.Comparison)
var expression *govaluate.EvaluableExpression
expression, err = govaluate.NewEvaluableExpression(expressionTxt)
if err != nil {
return
}
parameters := make(map[string]interface{}, 8)
passwordsToRemember := getPolicyOutput.PasswordPolicy.PasswordReusePrevention
zero := int64(0)
if passwordsToRemember == nil {
passwordsToRemember = &zero
}
parameters["passwordsToRemember"] = *passwordsToRemember
var filterVal int
filterVal, err = strconv.Atoi(filter.Value)
if err != nil {
return
}
parameters["filterValue"] = filterVal
var result interface{}
result, err = expression.Evaluate(parameters)
if err != nil {
return
}
if result == true {
filterMatch = true
}
case "ExpirationRequiresAdministratorReset":
// imp:iam:PasswordPolicy:ExpirationRequiresAdministratorReset