예제 #1
0
def build_cw_cb_role(template=None, role_name="s2nEventsInvokeCodeBuildRole"):
    """
    Create a role for CloudWatch events to trigger Codebuild jobs.
    """
    role_id = template.add_resource(
        Role(
            role_name,
            Path='/',
            AssumeRolePolicyDocument=PolicyDocument(Statement=[
                Statement(Effect=Allow,
                          Action=[
                              Action("sts", "AssumeRole"),
                          ],
                          Principal=Principal("Service",
                                              ["events.amazonaws.com"]))
            ]),
            Policies=[
                Policy(
                    PolicyName=f"EventsInvokeCBRole",
                    PolicyDocument=PolicyDocument(Statement=[
                        Statement(
                            Effect=Allow,
                            Action=[Action("codebuild", "StartBuild")],
                            Resource=[
                                "arn:aws:codebuild:us-west-2:024603541914:project/*",
                            ])
                    ]))
            ]))
    return role_id
예제 #2
0
 def _add_autopush_iam_roles(self):
     firehose_extras = []
     if self.use_firehose:
         # Add in the firehose permissions
         firehose_extras.append(
             Statement(Effect=Allow,
                       Action=[
                           Action("firehose", "PutRecord"),
                           Action("firehose", "PutRecordBatch"),
                       ],
                       Resource=[
                           GetAtt(self.FirehoseLogstream, "Arn"),
                       ]))
     self.PushServerRole = self.add_resource(
         Role(
             "AutopushServerRole",
             AssumeRolePolicyDocument=Policy(
                 Version="2012-10-17",
                 Statement=[
                     Statement(Effect=Allow,
                               Action=[AssumeRole],
                               Principal=Principal("Service",
                                                   "ec2.amazonaws.com"))
                 ]),
             Path="/",
         ))
     self.add_resource(
         PolicyType(
             "AutopushServerRolePolicy",
             PolicyName="AutopushServerRole",
             PolicyDocument=Policy(
                 Version="2012-10-17",
                 Statement=[
                     Statement(
                         Effect=Allow,
                         Action=[
                             ddb.BatchGetItem,
                             ddb.BatchWriteItem,
                             ddb.GetItem,
                             ddb.PutItem,
                             ddb.DeleteItem,
                             ddb.UpdateItem,
                             ddb.Query,
                             ddb.Scan,
                         ],
                         Resource=[
                             Join("", [
                                 "arn:aws:dynamodb:us-east-1:*:table/",
                                 Ref(self.PushTablePrefix), "_*"
                             ])
                         ]),
                     Statement(Effect=Allow,
                               Action=[
                                   ddb.ListTables,
                                   ddb.DescribeTable,
                                   ddb.CreateTable,
                               ],
                               Resource=["*"])
                 ] + firehose_extras),
             Roles=[Ref(self.PushServerRole)]))
예제 #3
0
    def ECR(self, name):
        logger.info(f"Criando o ECR: {name}")
        project_name = f'ECR{name}'
        resource_name = ''.join(e for e in project_name if e.isalnum())
        p_service = Principal("Service", "codebuild.amazonaws.com")
        p_aws = Principal("AWS", [
            Sub("arn:aws:iam::${DevAccount}:root"),
            Sub("arn:aws:iam::${HomologAccount}:root"),
            Sub("arn:aws:iam::${ProdAccount}:root")
        ])

        policydocument = PolicyDocument(Version='2008-10-17',
                                        Statement=[
                                            Statement(
                                                Sid='AllowPushPull',
                                                Effect=Allow,
                                                Principal=p_service,
                                                Action=[Action("ecr", "*")],
                                            ),
                                            Statement(
                                                Sid='AllowPushPull',
                                                Effect=Allow,
                                                Principal=p_aws,
                                                Action=[Action("ecr", "*")],
                                            ),
                                        ])
        resource_ecr = Repository(resource_name,
                                  RepositoryName=name.lower(),
                                  RepositoryPolicyText=policydocument)
        return [resource_ecr]
예제 #4
0
    def create_prediction_service_instance_profile(self):
        t = self.template

        prediction_service_iam_policy = PolicyProperty(
            PolicyName="euro2016-prediction-service-policy",
            PolicyDocument=Policy(Statement=[
                Statement(Effect="Allow",
                          Action=[Action("s3", "ListBucket")],
                          Resource=["arn:aws:s3:::oliviervg1-code"]),
                Statement(Effect="Allow",
                          Action=[Action("s3", "GetObject")],
                          Resource=["arn:aws:s3:::oliviervg1-code/euro2016/*"])
            ]))

        prediction_service_iam_role = t.add_resource(
            Role("Euro2016IamRole",
                 AssumeRolePolicyDocument=Policy(Statement=[
                     Statement(Effect="Allow",
                               Principal=Principal("Service",
                                                   ["ec2.amazonaws.com"]),
                               Action=[Action("sts", "AssumeRole")])
                 ]),
                 Policies=[prediction_service_iam_policy],
                 Path="/"))

        prediction_service_instance_profile = t.add_resource(
            InstanceProfile("Euro2016InstanceProfile",
                            Roles=[Ref(prediction_service_iam_role)],
                            Path="/"))

        return prediction_service_instance_profile
예제 #5
0
    def test_statement_equality(self):
        one = Statement(
            Effect="Allow",
            Action=[
                Action("autoscaling", "DescribeLaunchConfigurations"),
            ],
            Resource=["*"],
        )
        one_again = Statement(
            Effect="Allow",
            Action=[
                Action("autoscaling", "DescribeLaunchConfigurations"),
            ],
            Resource=["*"],
        )
        two = Statement(
            Effect="Allow",
            Action=[
                Action("ec2", "DescribeInstances"),
            ],
            Resource=["*"],
        )

        self.assertEqualWithHash(one, one_again)
        self.assertNotEqualWithHash(one, two)
예제 #6
0
    def add_lambda_role(self, title, extra_permissions):
        perms = self.DEFAULT_PERMISSIONS.union(extra_permissions)
        permissions = [Action(*perm) for perm in perms]

        return self.template.add_resource(
            iam.Role(title + 'LambdaRole',
                     Path='/',
                     Policies=[
                         iam.Policy(
                             PolicyName=title + 'LambdaExecution',
                             PolicyDocument=Policy(
                                 Version='2012-10-17',
                                 Statement=[
                                     Statement(Effect=Allow,
                                               Action=[Action('logs', '*')],
                                               Resource=['arn:aws:logs:*:*:*'
                                                         ]),
                                     Statement(
                                         Effect=Allow,
                                         Action=list(permissions),
                                         Resource=['*'],
                                     )
                                 ]))
                     ],
                     AssumeRolePolicyDocument=get_lambda_assumerole_policy()))
예제 #7
0
 def attach_ssm_policy(self, myrole):
     return super(NCTemplate, self).add_resource(
         iam.PolicyType(
             'policyssm',
             PolicyName='ssmpolicy',
             PolicyDocument=Policy(
                 Version='2012-10-17',
                 Statement=[
                     Statement(Effect=Allow,
                               Action=[Action("ssm", "DescribeParameters")],
                               Resource=["*"]),
                     Statement(
                         Effect=Allow,
                         Action=[Action("ssm", "GetParameters")],
                         Resource=[
                             Join("", [
                                 "arn:aws:ssm", ":",
                                 Ref("AWS::Region"), ":",
                                 Ref("AWS::AccountId"), ":", "parameter/",
                                 Ref("AWS::StackName"), "/*"
                             ]),
                             Join("", [
                                 "arn:aws:ssm", ":",
                                 Ref("AWS::Region"), ":",
                                 Ref("AWS::AccountId"), ":", "parameter/",
                                 "globals", "/*"
                             ]),
                         ]),
                 ]),
             Roles=[Ref(myrole)]))
예제 #8
0
def build_cw_cb_role(template,
                     config,
                     role_name="s2nEventsInvokeCodeBuildRole"):
    """
    Create a role for CloudWatch events to trigger scheduled CodeBuild jobs.
    """
    role_id = template.add_resource(
        Role(
            role_name,
            Path='/',
            AssumeRolePolicyDocument=PolicyDocument(Statement=[
                Statement(Effect=Allow,
                          Action=[
                              Action("sts", "AssumeRole"),
                          ],
                          Principal=Principal("Service",
                                              ["events.amazonaws.com"]))
            ]),
            Policies=[
                Policy(
                    PolicyName=f"EventsInvokeCBRole",
                    PolicyDocument=PolicyDocument(Statement=[
                        Statement(
                            Effect=Allow,
                            Action=[Action("codebuild", "StartBuild")],
                            Resource=[
                                "arn:aws:codebuild:{region}:{account_number}:project/*"
                                .format(region=config.get(
                                    'Global', 'aws_region'),
                                        account_number=config.get(
                                            'CFNRole', 'account_number')),
                            ])
                    ]))
            ]))
    return role_id
예제 #9
0
def build_github_role(template=None, role_name="s2nCodeBuildGithubRole"):
    """
    Create a role for GitHub actions to use for launching CodeBuild jobs.
    This is not attached to any other resource created in this file.
    """
    role_id = template.add_resource(
        Role(
            role_name,
            Path='/',
            AssumeRolePolicyDocument=PolicyDocument(Statement=[
                Statement(
                    Effect=Allow,
                    Action=[
                        Action("logs", "CreateLogGroup"),
                        Action("logs", "CreateLogStream"),
                        Action("logs", "PutLogEvents")
                    ],
                    Resource=[
                        "arn:aws:logs:us-west-2:024603541914:log-group:/aws/codebuild/s2nGithubCodebuild",
                        "arn:aws:logs:us-west-2:024603541914:log-group:/aws/codebuild/s2nGithubCodebuild:*"
                    ])
            ])))
    return Ref(role_id)

    template.add_output([Output(role_name, Value=Ref(role_id))])
    return Ref(role_id)
예제 #10
0
    def test_action_equality(self):
        self.assertEqualWithHash(
            Action('autoscaling', 'DescribeLaunchConfigurations'),
            Action('autoscaling', 'DescribeLaunchConfigurations'))

        self.assertNotEqualWithHash(
            Action('autoscaling', 'DescribeLaunchConfigurations'),
            Action('ec2', 'DescribeInstances'))
    def init_systemsmanagersession_permission(self, permission_config,
                                              assume_role_res):
        if 'ManagedPolicyArns' not in assume_role_res.properties.keys():
            assume_role_res.properties['ManagedPolicyArns'] = []

        resource_group_condition_list = []
        for resource in permission_config.resources:
            resource_ref = Reference(resource)
            # Initialize The network environments that we need access into
            resource_obj = resource_ref.get_model_obj(self.paco_ctx.project)
            if schemas.IResourceGroup.providedBy(resource_obj):
                resource_group_condition_list.append(
                    StringLike({
                        'ssm:resourceTag/Paco-Application-Group-Name':
                        resource_obj.name
                    }))

        if len(resource_group_condition_list) == 0:
            return

        statement_list = []
        statement_list.append(
            Statement(
                Sid='SessionManagerStartSession',
                Effect=Allow,
                Action=[
                    Action('ssm', 'StartSession'),
                ],
                Resource=[
                    'arn:aws:ec2:*:*:instance/*',
                    'arn:aws:ssm:*::document/AWS-StartPortForwardingSession'
                ],
                Condition=Condition(resource_group_condition_list)))
        statement_list.append(
            Statement(
                Sid='SessionManagerPortForward',
                Effect=Allow,
                Action=[
                    Action('ssm', 'StartSession'),
                ],
                Resource=[
                    'arn:aws:ssm:*::document/AWS-StartPortForwardingSession'
                ]))
        statement_list.append(
            Statement(Sid='SessionManagerTerminateSession',
                      Effect=Allow,
                      Action=[
                          Action('ssm', 'TerminateSession'),
                          Action('ssm', 'ResumeSession'),
                      ],
                      Resource=['arn:aws:ssm:*:*:session/${aws:username}-*']))
        managed_policy_res = troposphere.iam.ManagedPolicy(
            title=self.create_cfn_logical_id_join(["SystemsManagerSession"]),
            PolicyDocument=PolicyDocument(Version="2012-10-17",
                                          Statement=statement_list),
            Roles=[troposphere.Ref(assume_role_res)])
        self.template.add_resource(managed_policy_res)
예제 #12
0
    def test_action_equality(self):
        self.assertEqualWithHash(
            Action("autoscaling", "DescribeLaunchConfigurations"),
            Action("autoscaling", "DescribeLaunchConfigurations"),
        )

        self.assertNotEqualWithHash(
            Action("autoscaling", "DescribeLaunchConfigurations"),
            Action("ec2", "DescribeInstances"),
        )
예제 #13
0
    def jenkins(name):

        read_only_ec2 = [Action('ec2', 'DescribeInstances'),
                         Action('ec2', 'DescribeImages'),
                         Action('ec2', 'DescribeTags'),
                         Action('ec2', 'DescribeSnapshots')
                         ]
        cisco_cidr_only_condition = Condition(IpAddress({awacs.aws.SourceIp: ALL_CISCO_CIDRS}))
        jenkins_statement = statement(actions=read_only_ec2, resource=['*'], effect=Allow,
                                      condition=cisco_cidr_only_condition)
        jenkins = policy(name=name, statements=[jenkins_statement])
        return jenkins
예제 #14
0
 def _setup_s3writer_custom_resource(self):
     self.S3WriterLambdaCFExecRole = self.add_resource(
         Role(
             "S3WriterLambdaCFRole",
             AssumeRolePolicyDocument=Policy(
                 Version="2012-10-17",
                 Statement=[
                     Statement(Effect=Allow,
                               Action=[AssumeRole],
                               Principal=Principal("Service",
                                                   "lambda.amazonaws.com"))
                 ]),
             Path="/",
         ))
     self.S3WriterCFPolicy = self.add_resource(
         PolicyType("S3WriterCFPolicy",
                    PolicyName="S3WriterLambdaCFRole",
                    PolicyDocument=Policy(
                        Version="2012-10-17",
                        Statement=[
                            Statement(Effect=Allow,
                                      Action=[
                                          Action("logs", "CreateLogGroup"),
                                          Action("logs", "CreateLogStream"),
                                          Action("logs", "PutLogEvents"),
                                      ],
                                      Resource=["arn:aws:logs:*:*:*"]),
                            Statement(Effect=Allow,
                                      Action=[
                                          s3.DeleteObject,
                                          s3.ListBucket,
                                          s3.PutObject,
                                          s3.GetObject,
                                      ],
                                      Resource=["*"])
                        ]),
                    Roles=[Ref(self.S3WriterLambdaCFExecRole)],
                    DependsOn="S3WriterLambdaCFRole"))
     self.S3WriterCFCustomResource = self.add_resource(
         Function(
             "S3WriterCustomResource",
             Description=(
                 "Creates, updates, and deletes S3 Files with custom content"
             ),
             Runtime="python2.7",
             Timeout=300,
             Handler="lambda_function.lambda_handler",
             Role=GetAtt(self.S3WriterLambdaCFExecRole, "Arn"),
             Code=Code(
                 S3Bucket="cloudformation-custom-resources",
                 S3Key="s3writer_lambda.zip",
             ),
             DependsOn="S3WriterCFPolicy"))
예제 #15
0
def logstream_policy():
    """Policy needed for logspout -> kinesis log streaming."""
    p = Policy(Statement=[
        Statement(Effect=Allow,
                  Resource=["*"],
                  Action=[
                      kinesis.CreateStream, kinesis.DescribeStream,
                      Action(kinesis.prefix, "AddTagsToStream"),
                      Action(kinesis.prefix, "PutRecords")
                  ])
    ])
    return p
예제 #16
0
def service_role_policy():
    p = Policy(Statement=[
        Statement(Effect=Allow,
                  Resource=["*"],
                  Action=[
                      ec2.AuthorizeSecurityGroupIngress,
                      Action("ec2", "Describe*"),
                      elb.DeregisterInstancesFromLoadBalancer,
                      Action("elasticloadbalancing", "Describe*"),
                      elb.RegisterInstancesWithLoadBalancer
                  ])
    ])
    return p
예제 #17
0
    def add_module_bucket(self: Template):
        self._bucket = self.add_resource(
            s3.Bucket('TerraformModules',
                      AccessControl='Private',
                      BucketEncryption=s3.BucketEncryption(
                          ServerSideEncryptionConfiguration=[
                              s3.ServerSideEncryptionRule(
                                  ServerSideEncryptionByDefault=s3.
                                  ServerSideEncryptionByDefault(
                                      SSEAlgorithm='AES256'))
                          ]),
                      PublicAccessBlockConfiguration=s3.
                      PublicAccessBlockConfiguration(
                          BlockPublicAcls=True,
                          BlockPublicPolicy=True,
                          IgnorePublicAcls=True,
                          RestrictPublicBuckets=True)))

        self.add_resource(
            s3.BucketPolicy(
                'TerraformModulesBucketPolicy',
                Bucket=Ref(self._bucket),
                PolicyDocument=PolicyDocument(
                    Version='2012-10-17',
                    Statement=[
                        Statement(
                            Effect=Deny,
                            Action=[Action('s3', 'GetObject')],
                            Principal=Principal('*'),
                            Resource=[
                                Join(
                                    '',
                                    ['arn:aws:s3:::',
                                     Ref(self._bucket), '/*'])
                            ],
                            Condition=Condition(
                                Bool({'aws:SecureTransport': False}))),
                        Statement(
                            Effect=Deny,
                            Action=[Action('s3', 'GetObject')],
                            Principal=Principal('*'),
                            Resource=[
                                Join(
                                    '',
                                    ['arn:aws:s3:::',
                                     Ref(self._bucket), '/*'])
                            ],
                            Condition=Condition(
                                Bool({'aws:SecureTransport': False})))
                    ]),
            ))
예제 #18
0
 def statement_deny_cost_explorer(self) -> Statement:
     """Statement to deny access to Cost Explorer and other associated information."""
     return Statement(
         Action=[
             Action("account", "*"),
             Action("aws-portal", "*"),
             Action("ce", "*"),
             Action("cur", ""),
             Action("savingsplans", "*"),
         ],
         Effect=Deny,
         Resource=["*"],
         Sid="DenyCostAndBilling",
     )
    def deployment_pipeline_codebuild_permissions(self, pipeline_list,
                                                  assume_role_res):
        statement_list = []

        readonly_actions = [
            Action('codebuild', 'BatchGet*'),
            Action('codebuild', 'Get*'),
            Action('codebuild', 'List*'),
            Action('cloudwatch', 'GetMetricStatistics*'),
            Action('events', 'DescribeRule'),
            Action('events', 'ListTargetsByRule'),
            Action('events', 'ListRuleNamesByTarget'),
            Action('logs', 'GetLogEvents')
        ]

        readonly_arn_list = []
        retrystages_arn_list = []
        for pipeline_ctx in pipeline_list:
            if pipeline_ctx == None:
                continue
            if pipeline_ctx['permission'].find(
                    'ReadOnly'
            ) != -1 and pipeline_ctx['pipeline'].build != None:
                for action_name in pipeline_ctx['pipeline'].build:
                    action = pipeline_ctx['pipeline'].build[action_name]
                    if action.type == 'CodeBuild.Build':
                        codebuild_arn = self.paco_ctx.get_ref(action.paco_ref +
                                                              '.project.arn')
                        readonly_arn_list.append(codebuild_arn)
        if len(readonly_arn_list) > 0:
            self.set_codebuild_permissions(readonly_arn_list, assume_role_res,
                                           'DeploymentPipeline')
    def init_codebuild_permission(self, permission_config, assume_role_res):
        """CodeBuild Web Console Permissions"""
        if 'ManagedPolicyArns' not in assume_role_res.properties.keys():
            assume_role_res.properties['ManagedPolicyArns'] = []

        statement_list = []
        #readwrite_codebuild_arns = []
        readonly_codebuild_arns = []
        for resource in permission_config.resources:
            codebuild_ref = Reference(resource.codebuild)
            codebuild_account_ref = 'paco.ref ' + '.'.join(
                codebuild_ref.parts[:-2]) + '.configuration.account'
            codebuild_account_ref = self.paco_ctx.get_ref(
                codebuild_account_ref)
            codebuild_account_id = self.paco_ctx.get_ref(
                codebuild_account_ref + '.id')
            if codebuild_account_id != self.account_id:
                continue

            codebuild_arn = self.paco_ctx.get_ref(resource.codebuild +
                                                  '.project.arn')

            if resource.permission == 'ReadOnly':
                if codebuild_arn not in readonly_codebuild_arns:
                    readonly_codebuild_arns.append(codebuild_arn)

        readonly_codebuild_actions = [
            Action('codebuild', 'BatchGet*'),
            Action('codebuild', 'Get*'),
            Action('codebuild', 'List*'),
            Action('cloudwatch', 'GetMetricStatistics*'),
            Action('events', 'DescribeRule'),
            Action('events', 'ListTargetsByRule'),
            Action('events', 'ListRuleNamesByTarget'),
            Action('logs', 'GetLogEvents')
        ]
        if len(readonly_codebuild_arns) > 0:
            statement_list.append(
                Statement(
                    Sid='CodeBuildReadOnly',
                    Effect=Allow,
                    Action=readonly_codebuild_actions,
                    Resource=['*']  #readonly_codebuild_arns
                ))
            #statement_list.append(
            #    Statement(
            #        Sid='OtherReadOnly',
            #        Effect=Allow,
            #        Action=readonly_other_actions,
            #        Resource=['*']
            #    )
            #)

        managed_policy_res = troposphere.iam.ManagedPolicy(
            title=self.create_cfn_logical_id("CodeBuildPolicy"),
            PolicyDocument=PolicyDocument(Version="2012-10-17",
                                          Statement=statement_list),
            Roles=[troposphere.Ref(assume_role_res)])
        self.template.add_resource(managed_policy_res)  #
예제 #21
0
 def _setup_firehose_custom_resource(self):
     # Setup the FirehoseLambda CloudFormation Custom Resource
     self.FirehoseLambdaCFExecRole = self.add_resource(
         Role(
             "FirehoseLambdaCFRole",
             AssumeRolePolicyDocument=Policy(
                 Version="2012-10-17",
                 Statement=[
                     Statement(Effect=Allow,
                               Action=[AssumeRole],
                               Principal=Principal("Service",
                                                   "lambda.amazonaws.com"))
                 ]),
             Path="/",
         ))
     self.FirehoseLambdaPolicy = self.add_resource(
         PolicyType("FirehoseCFPolicy",
                    PolicyName="FirehoseLambdaCFRole",
                    PolicyDocument=Policy(
                        Version="2012-10-17",
                        Statement=[
                            Statement(Effect=Allow,
                                      Action=[
                                          Action("logs", "CreateLogGroup"),
                                          Action("logs", "CreateLogStream"),
                                          Action("logs", "PutLogEvents"),
                                      ],
                                      Resource=["arn:aws:logs:*:*:*"]),
                            Statement(Effect=Allow,
                                      Action=[
                                          Action("firehose",
                                                 "CreateDeliveryStream"),
                                          Action("firehose",
                                                 "DeleteDeliveryStream"),
                                          Action("firehose",
                                                 "ListDeliveryStreams"),
                                          Action("firehose",
                                                 "DescribeDeliveryStream"),
                                          Action("firehose",
                                                 "UpdateDestination"),
                                      ],
                                      Resource=["*"])
                        ]),
                    Roles=[Ref(self.FirehoseLambdaCFExecRole)],
                    DependsOn="FirehoseLambdaCFRole"))
     self.FirehoseCFCustomResource = self.add_resource(
         Function(
             "FirehoseCustomResource",
             Description=(
                 "Creates, updates, and deletes Firehose delivery streams"),
             Runtime="python2.7",
             Timeout=300,
             Handler="lambda_function.lambda_handler",
             Role=GetAtt(self.FirehoseLambdaCFExecRole, "Arn"),
             Code=Code(
                 S3Bucket="cloudformation-custom-resources",
                 S3Key="firehose_lambda.zip",
             ),
             DependsOn="FirehoseCFPolicy"))
예제 #22
0
def empire_policy():
    p = Policy(Statement=[
        Statement(Effect=Allow,
                  Resource=["*"],
                  Action=[
                      ecs.CreateService, ecs.DeleteService,
                      ecs.DeregisterTaskDefinition,
                      ecs.ECSAction("Describe*"),
                      ecs.ECSAction("List*"), ecs.RegisterTaskDefinition,
                      ecs.RunTask, ecs.StartTask, ecs.StopTask,
                      ecs.SubmitTaskStateChange, ecs.UpdateService
                  ]),
        Statement(
            Effect=Allow,
            # TODO: Limit to specific ELB?
            Resource=["*"],
            Action=[
                elb.DeleteLoadBalancer, elb.CreateLoadBalancer,
                elb.DescribeLoadBalancers, elb.DescribeTags,
                elb.ConfigureHealthCheck, elb.ModifyLoadBalancerAttributes
            ]),
        Statement(Effect=Allow,
                  Resource=["*"],
                  Action=[ec2.DescribeSubnets, ec2.DescribeSecurityGroups]),
        Statement(Effect=Allow,
                  Action=[
                      iam.GetServerCertificate, iam.UploadServerCertificate,
                      iam.DeleteServerCertificate, iam.PassRole
                  ],
                  Resource=["*"]),
        Statement(
            Effect=Allow,
            Action=[
                Action("route53", "ListHostedZonesByName"),
                route53.ChangeResourceRecordSets, route53.ListHostedZones,
                route53.GetHostedZone
            ],
            # TODO: Limit to specific zones
            Resource=["*"]),
        Statement(Effect=Allow,
                  Action=[
                      kinesis.DescribeStream,
                      Action(kinesis.prefix, "Get*"),
                      Action(kinesis.prefix, "List*")
                  ],
                  Resource=["*"]),
    ])
    return p
예제 #23
0
 def vpc_role_adder(self):
     self.k8_master_role = self.template.add_resource(
         Role('k8master',
              AssumeRolePolicyDocument=PolicyDocument(Statement=[
                  Statement(Effect=Allow,
                            Action=[AssumeRole],
                            Principal=Principal("Service",
                                                ["ec2.amazonaws.com"]))
              ]),
              Policies=[
                  Policy(
                      PolicyName='k8master',
                      PolicyDocument=PolicyDocument(Statement=[
                          Statement(Effect=Allow,
                                    Action=[
                                        Action('s3', 'List*'),
                                        Action('s3', 'Get*'),
                                        Action('ecr', '*'),
                                        Action('elasticloadbalancing', '*'),
                                        cloudformation.SignalResource,
                                        Action('ec2', 'Describe*'),
                                    ],
                                    Resource=['*'])
                      ]))
              ]))
     self.k8_worker_role = self.template.add_resource(
         Role('k8worker',
              AssumeRolePolicyDocument=PolicyDocument(Statement=[
                  Statement(Effect=Allow,
                            Action=[AssumeRole],
                            Principal=Principal("Service",
                                                ["ec2.amazonaws.com"]))
              ]),
              Policies=[
                  Policy(PolicyName='worker',
                         PolicyDocument=PolicyDocument(Statement=[
                             Statement(Effect=Allow,
                                       Action=[
                                           Action('s3', 'List*'),
                                           Action('s3', 'Get*'),
                                           Action('ecr', '*'),
                                           cloudformation.SignalResource,
                                           Action('ec2', 'Describe*'),
                                           Action('sns', '*')
                                       ],
                                       Resource=['*'])
                         ]))
              ]))
예제 #24
0
    def init_custompolicy_permission(self, permission_config, assume_role_res):
        for managed_policy in permission_config.managed_policies:
            if 'ManagedPolicyArns' not in assume_role_res.properties.keys():
                assume_role_res.properties['ManagedPolicyArns'] = []
            assume_role_res.properties['ManagedPolicyArns'].append('arn:aws:iam::aws:policy/' + managed_policy)
        for policy in permission_config.policies:
            policy_statements = []
            for policy_statement in policy.statement:
                statement_dict = {
                    'Effect': policy_statement.effect,
                    'Action': [
                        Action(*action.split(':')) for action in policy_statement.action
                    ],
                }

                # Resource
                statement_dict['Resource'] = policy_statement.resource

                policy_statements.append(
                    Statement(**statement_dict)
                )
            # Make the policy
            managed_policy_res = troposphere.iam.ManagedPolicy(
                title=self.create_cfn_logical_id_join(
                    str_list=["CustomPolicy", policy.name],
                    camel_case=True
                ),
                PolicyDocument=PolicyDocument(
                    Version="2012-10-17",
                    Statement=policy_statements
                ),
                Roles=[ troposphere.Ref(assume_role_res) ]
            )
            self.template.add_resource(managed_policy_res)
예제 #25
0
    def add_bucket_policy(self, bucket: s3.Bucket) -> s3.BucketPolicy:
        """Add a policy to the bucket if CloudFront is disabled. Ensure PublicRead.

        Args:
            bucket: The bucket resource to place the policy.

        Returns:
            The Bucket Policy Resource.

        """
        return self.template.add_resource(
            s3.BucketPolicy(
                "BucketPolicy",
                Bucket=bucket.ref(),
                PolicyDocument=Policy(
                    Version="2012-10-17",
                    Statement=[
                        Statement(
                            Effect=Allow,
                            Principal=Principal("*"),
                            Action=[Action("s3", "getObject")],
                            Resource=[Join("", [bucket.get_att("Arn"), "/*"])],
                        )
                    ],
                ),
            ))
예제 #26
0
    def add_bucket_policy(self, bucket):
        # type: (s3.Bucket) -> s3.BucketPolicy
        """Add a policy to the bucket if CloudFront is disabled. Ensure PublicRead.

        Keyword Args:
            bucket (dict): The bucket resource to place the policy

        Returns:
            dict: The Bucket Policy Resource

        """
        return self.template.add_resource(
            s3.BucketPolicy(
                'BucketPolicy',
                Bucket=bucket.ref(),
                PolicyDocument=Policy(
                    Version="2012-10-17",
                    Statement=[
                        Statement(
                            Effect=Allow,
                            Principal=Principal('*'),
                            Action=[Action('s3', 'getObject')],
                            Resource=[Join('', [bucket.get_att('Arn'), '/*'])],
                        )
                    ])))
예제 #27
0
def read_only_s3_bucket_policy_statements(buckets, folder="*"):
    """ Read only policy an s3 bucket. """
    list_buckets = [s3_arn(b) for b in buckets]
    object_buckets = [s3_objects_arn(b, folder) for b in buckets]

    bucket_resources = list_buckets + object_buckets

    return [
        Statement(Effect=Allow,
                  Resource=[s3_arn("*")],
                  Action=[s3.ListAllMyBuckets]),
        Statement(Effect=Allow,
                  Resource=bucket_resources,
                  Action=[Action('s3', 'Get*'),
                          Action('s3', 'List*')])
    ]
예제 #28
0
def role(template):

    role = Role(
        "sgdemorole",
        AssumeRolePolicyDocument=awacs.aws.Policy(Statement=[
            Statement(Effect=Allow,
                      Principal=Principal("Service", ["ec2.amazonaws.com"]),
                      Action=[AssumeRole])
        ],
                                                  Version="2012-10-17"),
        Path="/",
        Policies=[
            Policy(
                PolicyName="sgdemopolicy",
                PolicyDocument=awacs.aws.Policy(
                    Statement=[
                        Statement(Effect=Allow,
                                  Resource=["*"],
                                  Action=[Action("ec2", "DescribeInstances")])
                    ]
                    #Statement = map(allow_stmt, ["ec2", "SNS", "elasticloadbalancing", "cloudwatch", "autoscaling", "iam", "ecr", "s3", "cloudformation"])
                ))
        ])
    template.add_resource(role)
    return role
예제 #29
0
 def _create_kms_deploy_key(self, include_prod):
     statements = [
         Statement(
             Sid='AdminAccess',
             Effect=Allow,
             Principal=self.DEPLOY_ACCOUNT_PRINCIPAL,
             Action=[_kms.Action('*')],
             Resource=['*'],
         )
     ]
     if include_prod:
         statements.append(
             Statement(
                 Sid='KeyUsage',
                 Effect=Allow,
                 Principal=self.PROD_ACCOUNT_PRINCIPAL,
                 Action=[
                     _kms.Encrypt, _kms.Decrypt,
                     Action('kms', 'ReEncrypt*'), _kms.GenerateDataKey,
                     _kms.DescribeKey
                 ],
                 Resource=['*'],
             ))
     deploy_key = kms.Key('DeployKey',
                          KeyPolicy=Policy(
                              Version='2012-10-17',
                              Id='KeyPolicyId',
                              Statement=statements,
                          ))
     self._t.add_resource(deploy_key)
     return deploy_key
예제 #30
0
def ssm_global():
    template = Template()

    ssm_role = iam.Role(
        'SsmRole',
        RoleName="SsmRole",
        ManagedPolicyArns=[
            "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore",
            "arn:aws:iam::aws:policy/AmazonS3FullAccess",
            "arn:aws:iam::aws:policy/AmazonEC2FullAccess"
        ],
        AssumeRolePolicyDocument=PolicyDocument(Statement=[
            Statement(Effect=Allow,
                      Action=[Action("sts", "AssumeRole")],
                      Principal=Principal("Service", "ec2.amazonaws.com"))
        ]))

    ssm_profile = iam.InstanceProfile('SsmProfile',
                                      Roles=[Ref(ssm_role)],
                                      InstanceProfileName="SsmProfile")

    template.add_resource(ssm_role)
    template.add_resource(ssm_profile)

    with open(
            os.path.dirname(os.path.realpath(__file__)) + '/ssm_global.yml',
            'w') as cf_file:
        cf_file.write(template.to_yaml())

    return template.to_yaml()