forked from cloud-custodian/cloud-custodian
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iam.py
1940 lines (1568 loc) · 62.3 KB
/
iam.py
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 2016-2017 Capital One Services, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function, unicode_literals
from collections import OrderedDict
import csv
import datetime
import functools
import json
import io
from datetime import timedelta
import itertools
import time
from concurrent.futures import as_completed
from dateutil.tz import tzutc
from dateutil.parser import parse as parse_date
import six
from botocore.exceptions import ClientError
from c7n.actions import BaseAction
from c7n.actions.securityhub import OtherResourcePostFinding
from c7n.exceptions import PolicyValidationError
from c7n.filters import ValueFilter, Filter
from c7n.filters.multiattr import MultiAttrFilter
from c7n.filters.iamaccess import CrossAccountAccessFilter
from c7n.manager import resources
from c7n.query import QueryResourceManager, DescribeSource, TypeInfo
from c7n.resolver import ValuesFrom
from c7n.tags import TagActionFilter, TagDelayedAction, Tag, RemoveTag
from c7n.utils import local_session, type_schema, chunks, filter_empty, QueryParser
from c7n.resources.aws import Arn
@resources.register('iam-group')
class Group(QueryResourceManager):
class resource_type(TypeInfo):
service = 'iam'
arn_type = 'group'
enum_spec = ('list_groups', 'Groups', None)
id = name = 'GroupName'
date = 'CreateDate'
config_type = "AWS::IAM::Group"
# Denotes this resource type exists across regions
global_resource = True
arn = 'Arn'
def get_resources(self, resource_ids, cache=True):
"""For IAM Groups on events, resource ids are Group Names."""
client = local_session(self.session_factory).client('iam')
resources = []
for rid in resource_ids:
try:
result = client.get_group(GroupName=rid)
except client.exceptions.NoSuchEntityException:
continue
group = result.pop('Group')
group['c7n:Users'] = result['Users']
resources.append(group)
return resources
@resources.register('iam-role')
class Role(QueryResourceManager):
class resource_type(TypeInfo):
service = 'iam'
arn_type = 'role'
enum_spec = ('list_roles', 'Roles', None)
detail_spec = ('get_role', 'RoleName', 'RoleName', 'Role')
id = name = 'RoleName'
date = 'CreateDate'
config_type = "AWS::IAM::Role"
# Denotes this resource type exists across regions
global_resource = True
arn = 'Arn'
@Role.action_registry.register('tag')
class RoleTag(Tag):
"""Tag an iam role."""
permissions = ('iam:TagRole',)
def process_resource_set(self, client, roles, tags):
for role in roles:
try:
self.manager.retry(
client.tag_role, RoleName=role['RoleName'], Tags=tags)
except client.exceptions.NoSuchEntityException:
continue
@Role.action_registry.register('remove-tag')
class RoleRemoveTag(RemoveTag):
"""Remove tags from an iam role."""
permissions = ('iam:UntagRole',)
def process_resource_set(self, client, roles, tags):
for role in roles:
try:
self.manager.retry(
client.untag_role, RoleName=role['RoleName'], TagKeys=tags)
except client.exceptions.NoSuchEntityException:
continue
@resources.register('iam-user')
class User(QueryResourceManager):
class resource_type(TypeInfo):
service = 'iam'
arn_type = 'user'
detail_spec = ('get_user', 'UserName', 'UserName', 'User')
enum_spec = ('list_users', 'Users', None)
id = name = 'UserName'
date = 'CreateDate'
config_type = "AWS::IAM::User"
# Denotes this resource type exists across regions
global_resource = True
arn = 'Arn'
def get_source(self, source_type):
if source_type == 'describe':
return DescribeUser(self)
return super(User, self).get_source(source_type)
class DescribeUser(DescribeSource):
def get_resources(self, resource_ids, cache=True):
client = local_session(self.manager.session_factory).client('iam')
results = []
for r in resource_ids:
try:
results.append(client.get_user(UserName=r)['User'])
except client.exceptions.NoSuchEntityException:
continue
return results
@User.action_registry.register('tag')
class UserTag(Tag):
"""Tag an iam user."""
permissions = ('iam:TagUser',)
def process_resource_set(self, client, users, tags):
for u in users:
try:
self.manager.retry(
client.tag_user, UserName=u['UserName'], Tags=tags)
except client.exceptions.NoSuchEntityException:
continue
@User.action_registry.register('remove-tag')
class UserRemoveTag(RemoveTag):
"""Remove tags from an iam user."""
permissions = ('iam:UntagUser',)
def process_resource_set(self, client, users, tags):
for u in users:
try:
self.manager.retry(
client.untag_user, UserName=u['UserName'], TagKeys=tags)
except client.exceptions.NoSuchEntityException:
continue
User.action_registry.register('mark-for-op', TagDelayedAction)
User.filter_registry.register('marked-for-op', TagActionFilter)
@resources.register('iam-policy')
class Policy(QueryResourceManager):
class resource_type(TypeInfo):
service = 'iam'
arn_type = 'policy'
enum_spec = ('list_policies', 'Policies', None)
id = 'PolicyId'
name = 'PolicyName'
date = 'CreateDate'
config_type = "AWS::IAM::Policy"
# Denotes this resource type exists across regions
global_resource = True
arn = 'Arn'
def get_source(self, source_type):
if source_type == 'describe':
return DescribePolicy(self)
return super(Policy, self).get_source(source_type)
class DescribePolicy(DescribeSource):
def resources(self, query=None):
qfilters = PolicyQueryParser.parse(self.manager.data.get('query', []))
query = query or {}
if qfilters:
query = {t['Name']: t['Value'] for t in qfilters}
return super(DescribePolicy, self).resources(query=query)
def get_resources(self, resource_ids, cache=True):
client = local_session(self.manager.session_factory).client('iam')
results = []
for r in resource_ids:
try:
results.append(client.get_policy(PolicyArn=r)['Policy'])
except ClientError as e:
if e.response['Error']['Code'] == 'NoSuchEntityException':
continue
return results
class PolicyQueryParser(QueryParser):
QuerySchema = {
'Scope': ('All', 'AWS', 'Local'),
'PolicyUsageFilter': ('PermissionsPolicy', 'PermissionsBoundary'),
'PathPrefix': six.string_types,
'OnlyAttached': bool
}
multi_value = False
value_key = 'Value'
@resources.register('iam-profile')
class InstanceProfile(QueryResourceManager):
class resource_type(TypeInfo):
service = 'iam'
arn_type = 'instance-profile'
enum_spec = ('list_instance_profiles', 'InstanceProfiles', None)
id = 'InstanceProfileId'
name = 'InstanceProfileId'
date = 'CreateDate'
# Denotes this resource type exists across regions
global_resource = True
arn = 'Arn'
@resources.register('iam-certificate')
class ServerCertificate(QueryResourceManager):
class resource_type(TypeInfo):
service = 'iam'
arn_type = 'server-certificate'
enum_spec = ('list_server_certificates',
'ServerCertificateMetadataList',
None)
id = 'ServerCertificateId'
name = 'ServerCertificateName'
date = 'Expiration'
# Denotes this resource type exists across regions
global_resource = True
@User.filter_registry.register('usage')
@Role.filter_registry.register('usage')
@Group.filter_registry.register('usage')
@Policy.filter_registry.register('usage')
class ServiceUsage(Filter):
"""Filter iam resources by their api/service usage.
Note recent activity (last 4hrs) may not be shown, evaluation
is against the last 365 days of data.
Each service access record is evaluated against all specified
attributes. Attribute filters can be specified in short form k:v
pairs or in long form as a value type filter.
match-operator allows to specify how a resource is treated across
service access record matches. 'any' means a single matching
service record will return the policy resource as matching. 'all'
means all service access records have to match.
Find iam users that have not used any services in the last year
:example:
.. code-block:: yaml
- name: unused-users
resource: iam-user
filters:
- type: usage
match-operator: all
LastAuthenticated: null
Find iam users that have used dynamodb in last 30 days
:example:
.. code-block:: yaml
- name: unused-users
resource: iam-user
filters:
- type: usage
ServiceNamespace: dynamodb
TotalAuthenticatedEntities: 1
LastAuthenticated:
type: value
value_type: age
op: less-than
value: 30
match-operator: any
https://aws.amazon.com/blogs/security/automate-analyzing-permissions-using-iam-access-advisor/
"""
JOB_COMPLETE = 'COMPLETED'
SERVICE_ATTR = set((
'ServiceName', 'ServiceNamespace', 'TotalAuthenticatedEntities',
'LastAuthenticated', 'LastAuthenticatedEntity'))
schema_alias = True
schema_attr = {
sa: {'oneOf': [
{'type': 'string'},
{'type': 'boolean'},
{'type': 'number'},
{'type': 'null'},
{'$ref': '#/definitions/filters/value'}]}
for sa in SERVICE_ATTR}
schema_attr['match-operator'] = {'enum': ['all', 'any']}
schema_attr['poll-delay'] = {'type': 'number'}
schema = type_schema(
'usage',
required=('match-operator',),
**schema_attr)
permissions = ('iam:GenerateServiceLastAccessedDetails',
'iam:GetServiceLastAccessedDetails')
def process(self, resources, event=None):
client = local_session(self.manager.session_factory).client('iam')
job_resource_map = {}
for arn, r in zip(self.manager.get_arns(resources), resources):
jid = self.manager.retry(
client.generate_service_last_accessed_details,
Arn=arn)['JobId']
job_resource_map[jid] = r
conf = dict(self.data)
conf.pop('match-operator')
saf = MultiAttrFilter(conf)
saf.multi_attrs = self.SERVICE_ATTR
results = []
match_operator = self.data.get('match-operator', 'all')
while job_resource_map:
job_results_map = {}
for jid, r in job_resource_map.items():
result = self.manager.retry(
client.get_service_last_accessed_details, JobId=jid)
if result['JobStatus'] != self.JOB_COMPLETE:
continue
job_results_map[jid] = result['ServicesLastAccessed']
for jid, saf_results in job_results_map.items():
r = job_resource_map.pop(jid)
saf_matches = saf.process(saf_results)
if match_operator == 'all' and len(saf_matches) == len(saf_results):
results.append(r)
elif saf_matches:
results.append(r)
time.sleep(self.data.get('poll-delay', 2))
return results
@User.filter_registry.register('check-permissions')
@Group.filter_registry.register('check-permissions')
@Role.filter_registry.register('check-permissions')
@Policy.filter_registry.register('check-permissions')
class CheckPermissions(Filter):
"""Check IAM permissions associated with a resource.
:example:
Find users that can create other users
.. code-block:: yaml
policies:
- name: super-users
resource: iam-user
filters:
- type: check-permissions
match: allowed
actions:
- iam:CreateUser
"""
schema = type_schema(
'check-permissions', **{
'match': {'oneOf': [
{'enum': ['allowed', 'denied']},
{'$ref': '#/definitions/filters/valuekv'},
{'$ref': '#/definitions/filters/value'}]},
'match-operator': {'enum': ['and', 'or']},
'actions': {'type': 'array', 'items': {'type': 'string'}},
'required': ('actions', 'match')})
schema_alias = True
policy_annotation = 'c7n:policy'
eval_annotation = 'c7n:perm-matches'
def get_permissions(self):
if self.manager.type == 'iam-policy':
return ('iam:SimulateCustomPolicy',)
return ('iam:SimulatePrincipalPolicy',)
def process(self, resources, event=None):
client = local_session(self.manager.session_factory).client('iam')
actions = self.data['actions']
matcher = self.get_eval_matcher()
operator = self.data.get('match-operator', 'and') == 'and' and all or any
results = []
eval_cache = {}
for arn, r in zip(self.get_iam_arns(resources), resources):
if arn is None:
continue
if arn in eval_cache:
evaluations = eval_cache[arn]
else:
evaluations = self.get_evaluations(client, arn, r, actions)
eval_cache[arn] = evaluations
matches = []
matched = []
for e in evaluations:
match = matcher(e)
if match:
matched.append(e)
matches.append(match)
if operator(matches):
r[self.eval_annotation] = matched
results.append(r)
return results
def get_iam_arns(self, resources):
return self.manager.get_arns(resources)
def get_evaluations(self, client, arn, r, actions):
if self.manager.type == 'iam-policy':
policy = r.get(self.policy_annotation)
if policy is None:
r['c7n:policy'] = policy = client.get_policy_version(
PolicyArn=r['Arn'],
VersionId=r['DefaultVersionId']).get('PolicyVersion', {})
evaluations = self.manager.retry(
client.simulate_custom_policy,
PolicyInputList=[json.dumps(policy['Document'])],
ActionNames=actions).get('EvaluationResults', ())
else:
evaluations = self.manager.retry(
client.simulate_principal_policy,
PolicySourceArn=arn,
ActionNames=actions).get('EvaluationResults', ())
return evaluations
def get_eval_matcher(self):
if isinstance(self.data['match'], six.string_types):
if self.data['match'] == 'denied':
values = ['explicitDeny', 'implicitDeny']
else:
values = ['allowed']
vf = ValueFilter({'type': 'value', 'key':
'EvalDecision', 'value': values,
'op': 'in'})
else:
vf = ValueFilter(self.data['match'])
vf.annotate = False
return vf
class IamRoleUsage(Filter):
def get_permissions(self):
perms = list(itertools.chain(*[
self.manager.get_resource_manager(m).get_permissions()
for m in ['lambda', 'launch-config', 'ec2']]))
perms.extend(['ecs:DescribeClusters', 'ecs:DescribeServices'])
return perms
def service_role_usage(self):
results = set()
results.update(self.scan_lambda_roles())
results.update(self.scan_ecs_roles())
results.update(self.collect_profile_roles())
return results
def instance_profile_usage(self):
results = set()
results.update(self.scan_asg_roles())
results.update(self.scan_ec2_roles())
return results
def scan_lambda_roles(self):
manager = self.manager.get_resource_manager('lambda')
return [r['Role'] for r in manager.resources() if 'Role' in r]
def scan_ecs_roles(self):
results = []
client = local_session(self.manager.session_factory).client('ecs')
for cluster in client.describe_clusters()['clusters']:
services = client.list_services(
cluster=cluster['clusterName'])['serviceArns']
if services:
for service in client.describe_services(
cluster=cluster['clusterName'],
services=services)['services']:
if 'roleArn' in service:
results.append(service['roleArn'])
return results
def collect_profile_roles(self):
# Collect iam roles attached to instance profiles of EC2/ASG resources
profiles = set()
profiles.update(self.scan_asg_roles())
profiles.update(self.scan_ec2_roles())
manager = self.manager.get_resource_manager('iam-profile')
iprofiles = manager.resources()
results = []
for p in iprofiles:
if p['InstanceProfileName'] not in profiles:
continue
for role in p.get('Roles', []):
results.append(role['RoleName'])
return results
def scan_asg_roles(self):
manager = self.manager.get_resource_manager('launch-config')
return [r['IamInstanceProfile'] for r in manager.resources() if (
'IamInstanceProfile' in r)]
def scan_ec2_roles(self):
manager = self.manager.get_resource_manager('ec2')
results = []
for e in manager.resources():
# do not include instances that have been recently terminated
if e['State']['Name'] == 'terminated':
continue
profile_arn = e.get('IamInstanceProfile', {}).get('Arn', None)
if not profile_arn:
continue
# split arn to get the profile name
results.append(profile_arn.split('/')[-1])
return results
###################
# IAM Roles #
###################
@Role.filter_registry.register('used')
class UsedIamRole(IamRoleUsage):
"""Filter IAM roles that are either being used or not
Checks for usage on EC2, Lambda, ECS only
:example:
.. code-block:: yaml
policies:
- name: iam-role-in-use
resource: iam-role
filters:
- type: used
state: true
"""
schema = type_schema(
'used',
state={'type': 'boolean'})
def process(self, resources, event=None):
roles = self.service_role_usage()
if self.data.get('state', True):
return [r for r in resources if (
r['Arn'] in roles or r['RoleName'] in roles)]
return [r for r in resources if (
r['Arn'] not in roles and r['RoleName'] not in roles)]
@Role.filter_registry.register('unused')
class UnusedIamRole(IamRoleUsage):
"""Filter IAM roles that are either being used or not
This filter has been deprecated. Please use the 'used' filter
with the 'state' attribute to get unused iam roles
Checks for usage on EC2, Lambda, ECS only
:example:
.. code-block:: yaml
policies:
- name: iam-roles-not-in-use
resource: iam-role
filters:
- type: used
state: false
"""
schema = type_schema('unused')
def process(self, resources, event=None):
return UsedIamRole({'state': False}, self.manager).process(resources)
@Role.filter_registry.register('cross-account')
class RoleCrossAccountAccess(CrossAccountAccessFilter):
policy_attribute = 'AssumeRolePolicyDocument'
permissions = ('iam:ListRoles',)
schema = type_schema(
'cross-account',
# white list accounts
whitelist_from=ValuesFrom.schema,
whitelist={'type': 'array', 'items': {'type': 'string'}})
@Role.filter_registry.register('has-inline-policy')
class IamRoleInlinePolicy(Filter):
"""Filter IAM roles that have an inline-policy attached
True: Filter roles that have an inline-policy
False: Filter roles that do not have an inline-policy
:example:
.. code-block:: yaml
policies:
- name: iam-roles-with-inline-policies
resource: iam-role
filters:
- type: has-inline-policy
value: True
"""
schema = type_schema('has-inline-policy', value={'type': 'boolean'})
permissions = ('iam:ListRolePolicies',)
def _inline_policies(self, client, resource):
policies = client.list_role_policies(
RoleName=resource['RoleName'])['PolicyNames']
resource['c7n:InlinePolicies'] = policies
return resource
def process(self, resources, event=None):
c = local_session(self.manager.session_factory).client('iam')
res = []
value = self.data.get('value', True)
for r in resources:
r = self._inline_policies(c, r)
if len(r['c7n:InlinePolicies']) > 0 and value:
res.append(r)
if len(r['c7n:InlinePolicies']) == 0 and not value:
res.append(r)
return res
@Role.filter_registry.register('has-specific-managed-policy')
class SpecificIamRoleManagedPolicy(Filter):
"""Filter IAM roles that has a specific policy attached
For example, if the user wants to check all roles with 'admin-policy':
:example:
.. code-block:: yaml
policies:
- name: iam-roles-have-admin
resource: iam-role
filters:
- type: has-specific-managed-policy
value: admin-policy
"""
schema = type_schema('has-specific-managed-policy', value={'type': 'string'})
permissions = ('iam:ListAttachedRolePolicies',)
def _managed_policies(self, client, resource):
return [r['PolicyName'] for r in client.list_attached_role_policies(
RoleName=resource['RoleName'])['AttachedPolicies']]
def process(self, resources, event=None):
c = local_session(self.manager.session_factory).client('iam')
if self.data.get('value'):
return [r for r in resources if self.data.get('value') in self._managed_policies(c, r)]
return []
@Role.filter_registry.register('no-specific-managed-policy')
class NoSpecificIamRoleManagedPolicy(Filter):
"""Filter IAM roles that do not have a specific policy attached
For example, if the user wants to check all roles without 'ip-restriction':
:example:
.. code-block:: yaml
policies:
- name: iam-roles-no-ip-restriction
resource: iam-role
filters:
- type: no-specific-managed-policy
value: ip-restriction
"""
schema = type_schema('no-specific-managed-policy', value={'type': 'string'})
permissions = ('iam:ListAttachedRolePolicies',)
def _managed_policies(self, client, resource):
return [r['PolicyName'] for r in client.list_attached_role_policies(
RoleName=resource['RoleName'])['AttachedPolicies']]
def process(self, resources, event=None):
c = local_session(self.manager.session_factory).client('iam')
if self.data.get('value'):
return [r for r in resources if not self.data.get('value') in
self._managed_policies(c, r)]
return []
@Role.action_registry.register('set-policy')
class SetPolicy(BaseAction):
"""Set a specific IAM policy as attached or detached on a role.
You will identify the policy by its arn.
Returns a list of roles modified by the action.
For example, if you want to automatically attach a policy to all roles which don't have it...
:example:
.. code-block:: yaml
- name: iam-attach-role-policy
resource: iam-role
filters:
- type: no-specific-managed-policy
value: my-iam-policy
actions:
- type: set-policy
state: attached
arn: arn:aws:iam::123456789012:policy/my-iam-policy
"""
schema = type_schema(
'set-policy',
state={'enum': ['attached', 'detached']},
arn={'type': 'string'},
required=['state', 'arn'])
permissions = ('iam:AttachRolePolicy', 'iam:DetachRolePolicy',)
def process(self, resources):
client = local_session(self.manager.session_factory).client('iam')
policy_arn = self.data['arn']
state = self.data['state']
for r in resources:
if state == 'attached':
client.attach_role_policy(
RoleName=r['RoleName'],
PolicyArn=policy_arn)
elif state == 'detached':
try:
client.detach_role_policy(
RoleName=r['RoleName'],
PolicyArn=policy_arn)
except client.exceptions.NoSuchEntityException:
pass
@Role.action_registry.register('delete')
class RoleDelete(BaseAction):
"""Delete an IAM Role.
For example, if you want to automatically delete an unused IAM role.
:example:
.. code-block:: yaml
- name: iam-delete-unused-role
resource: iam-role
filters:
- type: usage
match-operator: all
LastAuthenticated: null
actions:
- delete
"""
schema = type_schema('delete')
permissions = ('iam:DeleteRole',)
def process(self, resources):
client = local_session(self.manager.session_factory).client('iam')
error = None
for r in resources:
try:
client.delete_role(RoleName=r['RoleName'])
except client.exceptions.DeleteConflictException as e:
self.log.warning(
"Role:%s cannot be deleted, must remove role from instance profile first"
% r['Arn'])
error = e
except client.exceptions.NoSuchEntityException:
continue
except client.exceptions.UnmodifiableEntityException:
continue
if error:
raise error
######################
# IAM Policies #
######################
@Policy.filter_registry.register('used')
class UsedIamPolicies(Filter):
"""Filter IAM policies that are being used
:example:
.. code-block:: yaml
policies:
- name: iam-policy-used
resource: iam-policy
filters:
- type: used
"""
schema = type_schema('used')
permissions = ('iam:ListPolicies',)
def process(self, resources, event=None):
return [r for r in resources if r['AttachmentCount'] > 0]
@Policy.filter_registry.register('unused')
class UnusedIamPolicies(Filter):
"""Filter IAM policies that are not being used
:example:
.. code-block:: yaml
policies:
- name: iam-policy-unused
resource: iam-policy
filters:
- type: unused
"""
schema = type_schema('unused')
permissions = ('iam:ListPolicies',)
def process(self, resources, event=None):
return [r for r in resources if r['AttachmentCount'] == 0]
@Policy.filter_registry.register('has-allow-all')
class AllowAllIamPolicies(Filter):
"""Check if IAM policy resource(s) have allow-all IAM policy statement block.
This allows users to implement CIS AWS check 1.24 which states that no
policy must exist with the following requirements.
Policy must have 'Action' and Resource = '*' with 'Effect' = 'Allow'
The policy will trigger on the following IAM policy (statement).
For example:
.. code-block:: json
{
"Version": "2012-10-17",
"Statement": [{
"Action": "*",
"Resource": "*",
"Effect": "Allow"
}]
}
Additionally, the policy checks if the statement has no 'Condition' or
'NotAction'.
For example, if the user wants to check all used policies and filter on
allow all:
.. code-block:: yaml
- name: iam-no-used-all-all-policy
resource: iam-policy
filters:
- type: used
- type: has-allow-all
Note that scanning and getting all policies and all statements can take
a while. Use it sparingly or combine it with filters such as 'used' as
above.
"""
schema = type_schema('has-allow-all')
permissions = ('iam:ListPolicies', 'iam:ListPolicyVersions')
def has_allow_all_policy(self, client, resource):
statements = client.get_policy_version(
PolicyArn=resource['Arn'],
VersionId=resource['DefaultVersionId']
)['PolicyVersion']['Document']['Statement']
if isinstance(statements, dict):
statements = [statements]
for s in statements:
if ('Condition' not in s and
'Action' in s and
isinstance(s['Action'], six.string_types) and
s['Action'] == "*" and
'Resource' in s and
isinstance(s['Resource'], six.string_types) and
s['Resource'] == "*" and
s['Effect'] == "Allow"):
return True
return False
def process(self, resources, event=None):
c = local_session(self.manager.session_factory).client('iam')
results = [r for r in resources if self.has_allow_all_policy(c, r)]
self.log.info(
"%d of %d iam policies have allow all.",
len(results), len(resources))
return results
@Policy.action_registry.register('delete')
class PolicyDelete(BaseAction):
"""Delete an IAM Policy.
For example, if you want to automatically delete all unused IAM policies.
:example:
.. code-block:: yaml
- name: iam-delete-unused-policies
resource: iam-policy
filters:
- type: unused
actions:
- delete
"""
schema = type_schema('delete')
permissions = ('iam:DeletePolicy',)
def process(self, resources):
client = local_session(self.manager.session_factory).client('iam')