Esempio n. 1
0
 def test_normal_principal(self):
     p = Principal("AWS", "arn:aws:iam::AccountNumber-WithoutHyphens:root")
     self.assertEqual(
         p.data, {"AWS": "arn:aws:iam::AccountNumber-WithoutHyphens:root"}
     )
     with self.assertRaises(ValueError):
         p = Principal("AWS")
Esempio n. 2
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]
Esempio n. 3
0
def add_use_dynamodb_role(template: Template) -> Role:
    return template.add_resource(
        Role("usedynamodbrole",
             AssumeRolePolicyDocument=PolicyDocument(Statement=[
                 Statement(Effect=Allow,
                           Action=[AssumeRole],
                           Principal=Principal("Service",
                                               ["lambda.amazonaws.com"])),
                 Statement(Effect=Allow,
                           Action=[AssumeRole],
                           Principal=Principal("Service",
                                               ["apigateway.amazonaws.com"]))
             ]),
             Policies=[
                 Policy(PolicyName="policy_use_dynamodb",
                        PolicyDocument=PolicyDocument(
                            Id="policy_use_dynamodb",
                            Version="2012-10-17",
                            Statement=[
                                Statement(Effect=Allow,
                                          Action=[
                                              DescribeTable, PutItem,
                                              GetRecords, GetItem, DeleteItem,
                                              Scan
                                          ],
                                          Resource=["*"]),
                                Statement(Effect=Allow,
                                          Action=[
                                              CreateLogGroup, CreateLogStream,
                                              PutLogEvents
                                          ],
                                          Resource=["*"])
                            ]))
             ]))
Esempio n. 4
0
File: stack.py Progetto: jpza/ekscli
    def _create_eks_control_plane(self):
        account_id = boto3.client('sts').get_caller_identity().get('Account')
        r = copy(self.RESOURCE_CP_ROLE)
        if self.role:
            role_arn = 'arn:aws:iam::{}:role/{}'.format(account_id, self.role)
            r.status = Status.provided
            r.resource_id = role_arn
        else:
            role = self.tpl.add_resource(
                Role(self.RESOURCE_CP_ROLE.name, RoleName=self.tag_name,
                     AssumeRolePolicyDocument=Policy(Statement=[
                         Statement(Effect=Allow, Action=[AssumeRole],
                                   Principal=Principal('Service', ['eks.amazonaws.com'])),
                         Statement(Effect=Allow, Action=[AssumeRole],
                                   Principal=Principal('AWS', ['arn:aws:iam::{}:root'.format(account_id)])), ], ),
                     ManagedPolicyArns=['arn:aws:iam::aws:policy/AmazonEKSClusterPolicy',
                                        'arn:aws:iam::aws:policy/AmazonEKSServicePolicy']
                     ))
            role_arn = GetAtt(role, 'Arn')

        cp_sg = self.tpl.add_resource(SecurityGroup(
            self.RESOURCE_CP_SG.name,
            GroupDescription='Security Group applied to EKS cluster',
            VpcId=self.tpl.outputs.get(self.OUTPUT_VPC).resource.get('Value'),
            Tags=Tags(Name=self.tag_name)
        ))
        self.tpl.add_output(Output(self.OUTPUT_CP_SG, Value=Ref(self.OUTPUT_CP_SG)))

        self._create_eks_cluster_template(cp_sg, role_arn)
        self.resources.extend([r, copy(self.RESOURCE_CP_SG), copy(self.RESOURCE_EKS_CLUSTER)])
Esempio n. 5
0
 def _get_cloudfront_bucket_policy_statements(self, bucket, oai):
     return [
         Statement(Action=[awacs.s3.GetObject],
                   Effect=Allow,
                   Principal=Principal('CanonicalUser',
                                       oai.get_att('S3CanonicalUserId')),
                   Resource=[Join('', [bucket.get_att('Arn'), '/*'])]),
         Statement(Action=[awacs.s3.ListBucket],
                   Effect=Allow,
                   Principal=Principal('CanonicalUser',
                                       oai.get_att('S3CanonicalUserId')),
                   Resource=[bucket.get_att('Arn')])
     ]
Esempio n. 6
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})))
                    ]),
            ))
Esempio n. 7
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=['*'])
                         ]))
              ]))
Esempio n. 8
0
def create_iam_role(stack, role_name, managed_policies=(), instance_profile=False):
    """Add IAM role resource."""
    managed_policy_arns = ['arn:aws:iam::aws:policy/{0}'.format(policy)
                           for policy in managed_policies]
    new_role = stack.stack.add_resource(Role(
        '{0}Role'.format(role_name.replace('-', '')),
        RoleName=role_name,
        ManagedPolicyArns=managed_policy_arns,
        AssumeRolePolicyDocument=Policy(
            Statement=[
                Statement(
                    Effect=Allow,
                    Action=[AssumeRole],
                    Principal=Principal('Service', ['ec2.amazonaws.com'])
                )
            ])
        ))

    if instance_profile:
        stack.stack.add_resource(InstanceProfile(
            '{}instanceprofile'.format(role_name.replace('-', '')),
            InstanceProfileName=role_name,
            Roles=[(Ref(new_role))]
        ))
    return new_role
Esempio n. 9
0
    def _create_role(self):
        # TODO set a role name here? Instead of relying on cloudformation to create a random nonsense string for the name
        role_kwargs = {
            "AssumeRolePolicyDocument":
            awacs.aws.Policy(Statement=[
                Statement(Effect=Allow,
                          Action=[AssumeRole],
                          Principal=Principal("Service",
                                              ["lambda.amazonaws.com"]))
            ]),
            "ManagedPolicyArns": [
                "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
            ],
        }
        if len(self._app.allow_policy_permissions) > 0:
            role_kwargs["Policies"] = [
                iam.Policy(
                    PolicyName="ExtraChiliPepperPermissions",
                    PolicyDocument=awacs.aws.Policy(Statement=[
                        p.statement()
                        for p in self._app.allow_policy_permissions
                    ]),
                )
            ]

        return iam.Role("FunctionRole", **role_kwargs)
Esempio n. 10
0
def create_ec2_instance_role(template, name, managed_policy_arns=None, policies=None):
    role_name = name + "Role"
    cfnrole = Role(
        role_name,
        AssumeRolePolicyDocument=Policy(
            Statement=[
                Statement(
                    Effect=Allow,
                    Action=[AssumeRole],
                    Principal=Principal("Service", ["ec2.amazonaws.com"])
                )
            ]
        )
    )
    if policies:
        cfnrole.Policies = policies
    if managed_policy_arns:
        cfnrole.ManagedPolicyArns = managed_policy_arns
    cfnrole = template.add_resource(cfnrole)


    profile_name = name + 'Profile'
    cfninstanceprofile = template.add_resource(InstanceProfile(
        profile_name,
        Roles=[Ref(cfnrole)]
    ))

    return {'role': cfnrole, 'profile': profile_name}
Esempio n. 11
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
    def user_delegate_role_and_policies(self, user, permissions_list):
        "Create and add an account delegate Role to template"
        user_arn = 'arn:aws:iam::{}:user/{}'.format(self.master_account_id,
                                                    user.username)
        assume_role_res = troposphere.iam.Role(
            "UserAccountDelegateRole",
            RoleName="IAM-User-Account-Delegate-Role-{}".format(
                self.create_resource_name(user.name,
                                          filter_id='IAM.Role.RoleName')),
            AssumeRolePolicyDocument=PolicyDocument(
                Version="2012-10-17",
                Statement=[
                    Statement(Effect=Allow,
                              Action=[AssumeRole],
                              Principal=Principal("AWS", [user_arn]),
                              Condition=Condition(
                                  [AWACSBool({MultiFactorAuthPresent: True})]))
                ]))
        # Iterate over permissions and create a delegate role and policices
        for permission_config in permissions_list:
            init_method = getattr(
                self,
                "init_{}_permission".format(permission_config.type.lower()))
            init_method(permission_config, assume_role_res)

        self.template.add_resource(assume_role_res)
        self.template.add_output(
            troposphere.Output(
                title='SigninUrl',
                Value=troposphere.Sub(
                    'https://signin.aws.amazon.com/switchrole?account=${AWS::AccountId}&roleName=${UserAccountDelegateRole}'
                )))
def create_codebuild_project(template) -> cb.Project:
    from troposphere.codebuild import Project, Environment, Artifacts, Source

    environment = Environment(
        ComputeType='BUILD_GENERAL1_SMALL',
        Image='aws/codebuild/standard:3.0',
        Type='LINUX_CONTAINER',
    )

    codebuild_role = template.add_resource(
        Role(
            "CodeBuildRole",
            AssumeRolePolicyDocument=Policy(Statement=[
                Statement(Effect=Allow,
                          Action=[AssumeRole],
                          Principal=Principal("Service",
                                              ["codebuild.amazonaws.com"]))
            ]),
            ManagedPolicyArns=[
                'arn:aws:iam::aws:policy/AmazonS3FullAccess',
                'arn:aws:iam::aws:policy/CloudWatchFullAccess',
                'arn:aws:iam::aws:policy/AWSCodeBuildAdminAccess',
            ],
        ))

    # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html
    return Project("ContinuousCodeBuild",
                   Name="ContinuousCodeBuild",
                   Description='Continous pipeline',
                   Artifacts=Artifacts(Type='CODEPIPELINE'),
                   Environment=environment,
                   Source=Source(Type='CODEPIPELINE'),
                   ServiceRole=Ref(codebuild_role))
Esempio n. 14
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
 def add_instance_role(self):
     '''
     Add Instance role
     '''
     self.cfn_template.add_resource(Role(
         title=constants.INST_ROLE,
         AssumeRolePolicyDocument=PolicyDocument(
             Statement=[
                 Statement(
                     Effect=Allow,
                     Action=[AssumeRole],
                     Principal=Principal('Service', ['ec2.amazonaws.com'])
                 )
             ]
         ),
         Policies=[
             Policy(
                 PolicyName='Demo-ECS-Cluster',
                 PolicyDocument=PolicyDocument(
                     Statement=[
                         Statement(
                             Effect=Allow,
                             Action=[
                                 Action('*')
                             ],
                             Resource=['*']
                         )
                     ]
                 )
             )
         ]
     ))
     return self.cfn_template
Esempio n. 16
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()
Esempio n. 17
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
Esempio n. 18
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
Esempio n. 19
0
    def _get_instance_profile(self, chain_context):
        s3readPolicy = iam.Policy(
            PolicyName='S3ReadArtifactBucket',
            PolicyDocument=Policy(Statement=[
                Statement(Effect=Allow,
                          Action=[
                              awacs.s3.GetObject,
                          ],
                          Resource=[s3.ARN(self.bucket_name + "/*")]),
                Statement(Effect=Allow,
                          Action=[
                              awacs.s3.ListBucket,
                          ],
                          Resource=[s3.ARN(self.bucket_name)])
            ]))

        cfnrole = chain_context.template.add_resource(
            Role(EC2_ROLE_NAME,
                 AssumeRolePolicyDocument=Policy(Statement=[
                     Statement(Effect=Allow,
                               Action=[AssumeRole],
                               Principal=Principal("Service",
                                                   ["ec2.amazonaws.com"]))
                 ]),
                 Policies=[s3readPolicy]))

        instance_profile = InstanceProfile(INSTANCE_PROFILE_NAME,
                                           Roles=[Ref(cfnrole)])
        return instance_profile
Esempio n. 20
0
def build_role(template=Template(),
               section="CFNRole",
               project_name: str = None,
               **kwargs) -> Ref:
    """ Build a role with a CodeBuild managed policy. """
    template.set_version('2010-09-09')
    assert project_name
    project_name += 'Role'

    # NOTE: By default CodeBuild manages the policies for this role.  If you delete a CFN stack and try to recreate the project
    # or make changes to it when the Codebuild managed Policy still exists, you'll see an error in the UI:
    # `The policy is attached to 0 entities but it must be attached to a single role`. (CFN fails with fail to update)
    # Orphaned policies created by CodeBuild will have CodeBuildBasePolicy prepended to them; search for policies with this
    # name and no role and delete to clear the error.
    # TODO: Get a CloudFormation feature request to turn this off for project creation- let CFN manage the policy.
    role_id = template.add_resource(
        Role(project_name,
             Path='/',
             AssumeRolePolicyDocument=PolicyDocument(Statement=[
                 Statement(Effect=Allow,
                           Action=[AssumeRole],
                           Principal=Principal("Service",
                                               ["codebuild.amazonaws.com"]))
             ])))

    template.add_output([Output(project_name, Value=Ref(role_id))])
    return Ref(role_id)
Esempio n. 21
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)]))
Esempio n. 22
0
    def create_template(self):
        """Create template (main function called by Stacker)."""
        template = self.template
        template.set_version("2010-09-09")
        template.set_description("Runway Integration Testing - IAM Role")

        # Resources
        template.add_resource(
            iam.Role(
                "CodeBuildRole",
                AssumeRolePolicyDocument=PolicyDocument(
                    Statement=[
                        Statement(
                            Effect=Allow,
                            Action=[awacs.sts.AssumeRole],
                            Principal=Principal("AWS", TESTING_ACCOUNT_ID),
                        )
                    ]
                ),
                Description="Role used for cross account testing in runway",
                ManagedPolicyArns=["arn:aws:iam::aws:policy/AdministratorAccess"],
                RoleName=Join(
                    "-",
                    [
                        "runway-integration-test-role",
                        self.variables["EnvironmentName"].ref,
                    ],
                ),
            )
        )
Esempio n. 23
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"), "/*"])],
                        )
                    ],
                ),
            ))
Esempio n. 24
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'), '/*'])],
                        )
                    ])))
Esempio n. 25
0
    def build_role(self, name, policies=False):
        """
        Generate role for IAM cloudformation template
        :param name: Name of role
        :param policies: List of policies to attach to this role (False = none)
        :return: Ref to new role
        """
        # Build role template
        if policies:
            role = self.__template.add_resource(
                Role(
                    self.name_strip(name),
                    AssumeRolePolicyDocument=Policy(
                        Version=self.VERSION_IAM,
                        Statement=[
                            Statement(
                                Effect=Allow,
                                Principal=Principal("Service",
                                                    self.__role_principals),
                                Action=[AssumeRole],
                            )
                        ]),
                    Path=self.__role_path,
                    ManagedPolicyArns=policies,
                ))
            # Add role to list for default policy
            self.__roles_list.append(troposphere.Ref(role))
        else:
            role = self.__template.add_resource(
                Role(
                    self.name_strip(name),
                    AssumeRolePolicyDocument=Policy(
                        Version=self.VERSION_IAM,
                        Statement=[
                            Statement(
                                Effect=Allow,
                                Principal=Principal("Service",
                                                    self.__role_principals),
                                Action=[AssumeRole],
                            )
                        ]),
                    Path=self.__role_path,
                ))
            # Add role to list for default policy
            self.__roles_list.append(troposphere.Ref(role))

        return role
Esempio n. 26
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"))
Esempio n. 27
0
def queue_policy(sns_arn, sqs_arns):
    return Policy(Statement=[
        Statement(Effect="Allow",
                  Principal=Principal("*"),
                  Action=[awacs.sqs.SendMessage],
                  Resource=sqs_arns,
                  Condition=Condition(ArnEquals({"aws:SourceArn": sns_arn})))
    ])
Esempio n. 28
0
def assume_role_policy_document(service_prinicpal):
    return Policy(Statement=[
        Statement(
            Effect=Allow,
            Action=[sts.AssumeRole],
            Principal=Principal("Service", [service_prinicpal]),
        )
    ])
Esempio n. 29
0
    def get_assumed_role(self, params):
        """Generates JSON for a assumed role statement

        :param dict params: list of parameters
        """
        return Policy(Statement=[
            Statement(Sid='AssumeRolePrincipalService',
                      Effect=Allow,
                      Action=[AssumeRole],
                      Principal=Principal('Service', ['ec2.amazonaws.com'])),
            Statement(
                Sid="AssumeRolePrincipalAWS",
                Effect=Allow,
                Action=[AssumeRole],
                Principal=Principal(
                    'AWS', ["arn:aws:iam::%s:root" % (self.get_account_id())]))
        ])
Esempio n. 30
0
def codebuild_policy_document(input_kwargs, build_data):

    user = "******"
    account = build_data["account_id"]
    region = build_data["region"]
    logs_arn = f"arn:aws:logs:{region}:{account}:log-group:/aws/lambda/*"
    ec2_arn = [
        "arn:aws:s3:::product-images-*", "arn:aws:s3:::product-images-*/*"
    ]

    pd = PolicyDocument(
        Version="2012-10-17",
        Id="Lambda-Common-Permissions",
        Statement=[
            Statement(Effect=Allow,
                      Principal=Principal("AWS", [IAM_ARN(user, '', account)]),
                      Action=[logs.CreateLogStream, logs.PutLogEvents],
                      Resource=[logs_arn]),
            Statement(
                Effect=Allow,
                Principal=Principal("AWS", [IAM_ARN(user, '', account)]),
                Action=[
                    ec2.CreateNetworkInterface, ec2.DescribeNetworkInterfaces,
                    ec2.DeleteNetworkInterface, "ec2:Describe*",
                    ec2.CreateSnapshot, ec2.DeleteSnapshot, ec2.CreateImage,
                    ec2.CopyImage, ec2.DeregisterImage, ce.GetCostAndUsage,
                    events.EnableRule, secretsmanager.GetSecretValue,
                    secretsmanager.DescribeSecret, "kms:*", "cloudwatch:*",
                    "s3:*"
                ],
                Resource=ec2_arn),
            Statement(Effect=Allow,
                      Principal=Principal("AWS", [IAM_ARN(user, '', account)]),
                      Action=[
                          rds.DescribeDBClusterSnapshots,
                          rds.DescribeDBClusters, rds.CopyDBClusterSnapshot,
                          rds.ModifyDBClusterSnapshotAttribute,
                          rds.ListTagsForResource
                      ],
                      Resource=['*'])
        ])

    input_kwargs["policy"] = pd.to_json()

    return input_kwargs