Exemple #1
0
def ecs_agent_policy():
    p = Policy(Statement=[
        Statement(Effect=Allow,
                  Resource=["*"],
                  Action=[
                      ecs.CreateCluster, ecs.RegisterContainerInstance, ecs.
                      DeregisterContainerInstance, ecs.DiscoverPollEndpoint,
                      ecs.ECSAction("Submit*"), ecs.Poll
                  ])
    ])
    return p
def lambda_vpc_execution_statements():
    """Allow Lambda to manipuate EC2 ENIs for VPC support."""
    return [
        Statement(Effect=Allow,
                  Resource=['*'],
                  Action=[
                      ec2.CreateNetworkInterface,
                      ec2.DescribeNetworkInterfaces,
                      ec2.DeleteNetworkInterface,
                  ])
    ]
Exemple #3
0
def get_ec2_assume_role_policy(ec2_principal):
    return Policy(
        Statement=[
            Statement(
                Effect=Allow, Action=[AssumeRole],
                Principal=Principal(
                    "Service", [ec2_principal]
                )
            )
        ]
    )
def logs_write_policy():
    statements = [
        Statement(
            Effect=Allow,
            Action=[
                awacs.logs.PutLogEvents,
            ],
            Resource=['*'],
        ),
    ]
    return Policy(Statement=statements)
Exemple #5
0
def logs_policy():
    statements = [
        Statement(
            Effect=Allow,
            Action=[
                awacs.logs.CreateLogStream,
            ],
            Resource=['*'],
        ),
    ]
    return Policy(Statement=statements)
def getBuildRole(stage: str = "") -> Role:
    statement = Statement(Action=[Action("*")], Effect=Allow, Resource=["*"])
    policy_doc = awacs.aws.Policy(Statement=[statement])
    policy = Policy(PolicyName=Sub("${AWS::StackName}-TestBuilderPolicy"),
                    PolicyDocument=policy_doc)
    assume = defaultAssumeRolePolicyDocument("codebuild.amazonaws.com")
    return Role("TestBuilderRole" + stage,
                RoleName=Sub("LambdaTestBuilderRole-${AWS::StackName}" +
                             stage),
                AssumeRolePolicyDocument=assume,
                Policies=[policy])
def bucket_policy2():
    return PolicyType(
        'RolePolicies',
        PolicyName="S3Download",
        # PolicyDocument=awacs.aws.Policy(
        PolicyDocument={
            Statement(Action=Action(s3="GetObject"),
                      Effect="Allow",
                      Resource="arn:aws:s3:::tesis.project.files/*")
        },
        Roles=[Ref('InstanceRole')])
Exemple #8
0
 def _get_cloudfront_bucket_policy_statements(  # pylint: disable=no-self-use
         self, bucket, oai):
     return [
         Statement(
             Action=[awacs.s3.GetObject],
             Effect=Allow,
             Principal=Principal("CanonicalUser",
                                 oai.get_att("S3CanonicalUserId")),
             Resource=[Join("", [bucket.get_att("Arn"), "/*"])],
         )
     ]
Exemple #9
0
def vpc_flow_log_cloudwatch_policy(log_group_arn):
    return Policy(Statement=[
        Statement(
            Effect="Allow",
            Action=[logs.DescribeLogGroups],
            Resource=["*"],
        ),
        Statement(
            Effect="Allow",
            Action=[
                logs.CreateLogStream,
                logs.DescribeLogStreams,
                logs.PutLogEvents,
            ],
            Resource=[
                log_group_arn,
                Join('', [log_group_arn, ":*"]),
            ],
        ),
    ])
    def add_extension(self, template, add_resource):

        add_helpers(template)

        def add_policy(policy_statement):
            policy_document = template.resources[LAMBDA_ROLE].Policies[
                0].PolicyDocument

            if policy_statement.properties not in [
                    statement.properties
                    for statement in policy_document.Statement
            ]:
                policy_document.Statement.append(policy_statement)

        add_policy(
            Statement(
                Effect=Allow,
                Action=[Action('route53', 'ChangeResourceRecordSets')],
                Resource=['arn:aws:route53:::hostedzone/*'],
            ))

        role_arn = self.properties.get('Route53RoleArn', None)
        if role_arn is not None:
            add_policy(
                Statement(Effect=Allow,
                          Action=[Action('sts', 'AssumeRole')],
                          Resource=[role_arn]))

        for domain in self.properties.get('DomainValidationOptions', {}):
            if isinstance(domain, DomainValidationOption):
                role_arn = domain.properties.get('Route53RoleArn', None)
            else:
                role_arn = domain.get('Route53RoleArn', None)

            if role_arn is not None:
                add_policy(
                    Statement(Effect=Allow,
                              Action=[Action('sts', 'AssumeRole')],
                              Resource=[role_arn]))

        return add_resource(self)
Exemple #11
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=["*"])
    ])
    return p
def stmts_vpc():
    return [
        Statement(Effect=Allow,
                  Action=[
                      AttachNetworkInterface, CreateNetworkInterface,
                      DeleteNetworkInterface, DescribeInstances,
                      DescribeNetworkInterfaces, DetachNetworkInterface,
                      ModifyNetworkInterfaceAttribute,
                      ResetNetworkInterfaceAttribute
                  ],
                  Resource=AllResources)
    ]
Exemple #13
0
 def create_allow_policy(self, name, actions, resources):
     awacs_actions = [
         Action(action.split(':')[0],
                action.split(':')[1]) for action in actions
     ]
     return Policy(Version='2012-10-17',
                   Id='{0}{1}'.format(self.project, name),
                   Statement=[
                       Statement(Effect=Allow,
                                 Action=awacs_actions,
                                 Resource=resources)
                   ])
Exemple #14
0
def queue_policy(sns_arn, sqs_arns):
    stmts = []
    for arn in sqs_arns:
        stmts.append(
            Statement(Effect="Allow",
                      Principal=Principal("*"),
                      Action=[awacs.sqs.SendMessage],
                      Resource=[arn],
                      Condition=Condition(ArnEquals({"aws:SourceArn":
                                                     sns_arn}))))

    return Policy(Statement=stmts)
Exemple #15
0
 def statement_deny_assume_role_not_resource(self) -> Statement:
     """Statement to deny AssumeRole if NotResource."""
     return Statement(
         Action=[
             awacs.sts.AssumeRole,
             awacs.sts.AssumeRoleWithSAML,
             awacs.sts.AssumeRoleWithWebIdentity,
         ],
         Effect=Deny,
         NotResource=self.deny_assume_role_not_resources,
         Sid="DenyAssumeRoleNotResource",
     )
    def create_route53_policy(self):
        action = Action("route53", "*")
        route53_arn1 = ROUTE53_ARN(
            resource=self._config['parameters']['UppercaseProjectName'] + '*')
        route53_arn2 = ROUTE53_ARN(
            resource=self._config['parameters']['LowercaseProjectName'] + '*')
        statement = Statement(Sid="Route53Access",
                              Effect=Allow,
                              Action=[action],
                              Resource=[route53_arn1, route53_arn2])

        return statement
Exemple #17
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
Exemple #18
0
 def statement_deny_iam(self) -> Statement:
     """Statement to deny access to some IAM calls."""
     return Statement(
         Action=[
             awacs.iam.CreateAccessKey,
             awacs.iam.CreateAccountAlias,
             awacs.iam.CreateInstanceProfile,
             awacs.iam.CreateLoginProfile,
             awacs.iam.CreateOpenIDConnectProvider,
             awacs.iam.CreateSAMLProvider,
             awacs.iam.CreateServiceSpecificCredential,
             awacs.iam.CreateUser,
             awacs.iam.DeactivateMFADevice,
             awacs.iam.DeleteAccessKey,
             awacs.iam.DeleteAccountAlias,
             awacs.iam.DeleteAccountPasswordPolicy,
             awacs.iam.DeleteInstanceProfile,
             awacs.iam.DeleteLoginProfile,
             awacs.iam.DeleteOpenIDConnectProvider,
             awacs.iam.DeleteSAMLProvider,
             awacs.iam.DeleteSSHPublicKey,
             awacs.iam.DeleteServiceLinkedRole,
             awacs.iam.DeleteServiceSpecificCredential,
             awacs.iam.DeleteSigningCertificate,
             awacs.iam.DeleteUser,
             awacs.iam.DeleteUserPermissionsBoundary,
             awacs.iam.DeleteUserPolicy,
             awacs.iam.DeleteVirtualMFADevice,
             awacs.iam.DetachUserPolicy,
             awacs.iam.GetAccountAuthorizationDetails,
             awacs.iam.GetAccountSummary,
             awacs.iam.GetCredentialReport,
             awacs.iam.RemoveUserFromGroup,
             awacs.iam.ResetServiceSpecificCredential,
             awacs.iam.ResyncMFADevice,
             awacs.iam.SetSecurityTokenServicePreferences,
             awacs.iam.UpdateAccessKey,
             awacs.iam.UpdateAccountPasswordPolicy,
             awacs.iam.UpdateLoginProfile,
             awacs.iam.UpdateSAMLProvider,
             awacs.iam.UpdateSSHPublicKey,
             awacs.iam.UpdateServerCertificate,
             awacs.iam.UpdateServiceSpecificCredential,
             awacs.iam.UpdateSigningCertificate,
             awacs.iam.UpdateUser,
             awacs.iam.UploadSSHPublicKey,
             awacs.iam.UploadServerCertificate,
             awacs.iam.UploadSigningCertificate,
         ],
         Effect=Deny,
         Resource=["*"],
         Sid="DenyIam",
     )
Exemple #19
0
    def test_policy_document_equality(self):
        one = PolicyDocument(
            Version="2012-10-17",
            Statement=[
                Statement(
                    Effect="Allow",
                    Action=[
                        Action("autoscaling", "DescribeLaunchConfigurations"),
                    ],
                    Resource=["*"],
                )
            ],
        )
        one_again = PolicyDocument(
            Version="2012-10-17",
            Statement=[
                Statement(
                    Effect="Allow",
                    Action=[
                        Action("autoscaling", "DescribeLaunchConfigurations"),
                    ],
                    Resource=["*"],
                )
            ],
        )

        two = PolicyDocument(
            Version="2012-10-17",
            Statement=[
                Statement(
                    Effect="Allow",
                    Action=[
                        Action("ec2", "DescribeInstances"),
                    ],
                    Resource=["*"],
                )
            ],
        )
        self.assertEqualWithHash(one, one_again)
        self.assertNotEqualWithHash(one, two)
Exemple #20
0
    def create_template(self):
        """Create template (main function called by Stacker)."""
        template = self.template
        # variables = self.get_variables()
        template.add_version('2010-09-09')
        template.add_description('Static Website - Dependencies')

        # Resources
        awslogbucket = template.add_resource(
            s3.Bucket('AWSLogBucket',
                      AccessControl=s3.Private,
                      VersioningConfiguration=s3.VersioningConfiguration(
                          Status='Enabled')))
        template.add_output(
            Output('AWSLogBucketName',
                   Description='Name of bucket storing AWS logs',
                   Value=awslogbucket.ref()))

        template.add_resource(
            s3.BucketPolicy(
                'AllowAWSLogWriting',
                Bucket=awslogbucket.ref(),
                PolicyDocument=Policy(
                    Version='2012-10-17',
                    Statement=[
                        Statement(
                            Action=[awacs.s3.PutObject],
                            Effect=Allow,
                            Principal=AWSPrincipal(
                                Join(':',
                                     ['arn:aws:iam:', AccountId, 'root'])),
                            Resource=[
                                Join('', [
                                    'arn:aws:s3:::',
                                    awslogbucket.ref(), '/*'
                                ])
                            ])
                    ])))
        artifacts = template.add_resource(
            s3.Bucket(
                'Artifacts',
                AccessControl=s3.Private,
                LifecycleConfiguration=s3.LifecycleConfiguration(Rules=[
                    s3.LifecycleRule(NoncurrentVersionExpirationInDays=90,
                                     Status='Enabled')
                ]),
                VersioningConfiguration=s3.VersioningConfiguration(
                    Status='Enabled')))
        template.add_output(
            Output('ArtifactsBucketName',
                   Description='Name of bucket storing artifacts',
                   Value=artifacts.ref()))
Exemple #21
0
 def _get_cloudfront_bucket_policy_statements(
         bucket: s3.Bucket,
         oai: cloudfront.CloudFrontOriginAccessIdentity) -> List[Statement]:
     return [
         Statement(
             Action=[awacs.s3.GetObject],
             Effect=Allow,
             # S3CanonicalUserId is translated to the ARN when AWS renders this
             Principal=Principal("CanonicalUser",
                                 oai.get_att("S3CanonicalUserId")),
             Resource=[Join("", [bucket.get_att("Arn"), "/*"])],
         )
     ]
Exemple #22
0
 def statement_deny_remove_boundary_policy(self) -> Statement:
     """Statement to deny the removal of the boundary policy."""
     return Statement(
         Action=[
             awacs.iam.DeleteRolePermissionsBoundary,
             awacs.iam.DeleteUserPermissionsBoundary,
         ],
         Condition=Condition(
             StringEquals({"iam:PermissionsBoundary": self.policy_arn})),
         Effect=Deny,
         Resource=["*"],
         Sid="DenyRemovalOfBoundaryFromUserOrRole",
     )
Exemple #23
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
Exemple #24
0
 def statement_deny_alter_boundary_policy(self) -> Statement:
     """Statement to deny alteration of this permission boundary policy."""
     return Statement(
         Action=[
             awacs.iam.CreatePolicyVersion,
             awacs.iam.DeletePolicy,
             awacs.iam.DeletePolicyVersion,
             awacs.iam.SetDefaultPolicyVersion,
         ],
         Effect=Deny,
         Resource=[self.policy_arn],
         Sid="DenyBoundaryPolicyAlteration",
     )
Exemple #25
0
def codepipeline_policy_document(input_kwargs, build_data):

    user = "******"
    account = build_data["account_id"]
    bucket_arn = "arn:aws:s3:::{0}".format(input_kwargs["name"])

    pd = PolicyDocument(
        Version="2012-10-17",
        Id="CodePipeline-Permissions",
        Statement=[
            Statement(Effect=Allow,
                      Principal=Principal("AWS", [IAM_ARN(user, '', account)]),
                      Action=[
                          codebuild.StartBuild, codebuild.BatchGetBuilds,
                          codedeploy.CreateDeployment,
                          codedeploy.GetApplicationRevision,
                          codedeploy.GetDeployment,
                          codedeploy.GetDeploymentConfig,
                          codedeploy.RegisterApplicationRevision, iam.PassRole,
                          iam.GetRole, codecommit.GitPull
                      ],
                      Resource=['*']),
            Statement(Effect=Allow,
                      Principal=Principal("AWS", [IAM_ARN(user, '', account)]),
                      Action=[
                          s3.CreateBucket, s3.GetObject, s3.ListAccessPoints,
                          s3.ListAllMyBuckets, s3.ListBucket,
                          s3.ListBucketByTags, s3.ListBucketMultipartUploads,
                          s3.ListBucketVersions, s3.ListJobs,
                          s3.ListMultipartUploadParts, s3.ListObjects,
                          s3.PutObject, s3.GetBucketAcl, s3.GetBucketLocation,
                          s3.GetObjectVersion
                      ],
                      Resource=[bucket_arn])
        ])

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

    return input_kwargs
Exemple #26
0
def static_website_bucket_policy(bucket):
    """
    Attach this policy directly to an S3 bucket to make it a static website.
    This policy grants read access to **all unauthenticated** users.
    """
    return Policy(Statement=[
        Statement(
            Effect=Allow,
            Principal=Principal("*"),
            Action=[s3.GetObject],
            Resource=[s3_objects_arn(bucket)],
        )
    ])
Exemple #27
0
    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
                )
            )

        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)#
    def _add_pipeline_notifications(self, pipeline):
        subscriptions = self._create_sns_subscriptions()
        topic = sns.Topic(
            'AppPipelineDeployments',
            DisplayName='AppPipelineDeployments',
            Subscription=subscriptions,
        )
        self._t.add_resource(topic)

        topic_policy = sns.TopicPolicy(
            'AllowCloudWatchEventsPublish',
            PolicyDocument=Policy(Version='2012-10-17',
                                  Statement=[
                                      Statement(
                                          Sid='AllowCloudWatchEventsToPublish',
                                          Effect=Allow,
                                          Action=[_sns.Publish],
                                          Principal=Principal(
                                              'Service',
                                              'events.amazonaws.com'),
                                          Resource=[topic.Ref()],
                                      )
                                  ]),
            Topics=[topic.Ref()],
        )
        self._t.add_resource(topic_policy)

        sns_target = [events.Target(Id='1', Arn=topic.Ref())]
        cw_event = events.Rule(
            'PipelineEvents',
            Description='CloudWatch Events Rule for app pipeline.',
            EventPattern={
                "source": ["aws.codepipeline"],
                "detail-type": [
                    'CodePipeline Action Execution State Change',
                ],
                'detail': {
                    'type': {
                        # Notify when a deploy fails/succeeds
                        # or when an approval is needed.
                        # We could also add something when any
                        # part of the pipeline fails.
                        'category': ['Deploy', 'Approval'],
                    },
                    'pipeline': [pipeline.Ref()],
                }
            },
            Targets=sns_target,
        )
        self._t.add_resource(cw_event)
        return topic
Exemple #29
0
    def add_lambda_execution_role(
            self,
            name='LambdaExecutionRole',  # type: str
            function_name=''  # type: str
    ):  # noqa: E124
        # type: (...) -> iam.Role
        """Create the Lambda@Edge execution role."""
        variables = self.get_variables()

        lambda_resource = Join('', [
            'arn:', Partition, ':logs:*:', AccountId,
            ':log-group:/aws/lambda/', StackName,
            '-%s-*' % function_name
        ])

        edge_resource = Join('', [
            'arn:',
            Partition,
            ':logs:*:',
            AccountId,
            ':log-group:/aws/lambda/*.',
            StackName,
            '-%s-*' % function_name,
        ])

        return self.template.add_resource(
            iam.Role(
                name,
                AssumeRolePolicyDocument=make_simple_assume_policy(
                    'lambda.amazonaws.com', 'edgelambda.amazonaws.com'),
                PermissionsBoundary=(variables['RoleBoundaryArn']
                                     if self.role_boundary_specified else
                                     NoValue),
                Policies=[
                    iam.Policy(PolicyName="LambdaLogCreation",
                               PolicyDocument=PolicyDocument(
                                   Version='2012-10-17',
                                   Statement=[
                                       Statement(Action=[
                                           awacs.logs.CreateLogGroup,
                                           awacs.logs.CreateLogStream,
                                           awacs.logs.PutLogEvents
                                       ],
                                                 Effect=Allow,
                                                 Resource=[
                                                     lambda_resource,
                                                     edge_resource
                                                 ])
                                   ])),
                ],
            ))
Exemple #30
0
def codebuild_policy_document(input_kwargs, build_data):

    user = "******"
    account = build_data["account_id"]
    region = build_data["region"]
    logs_arn = [
        "arn:aws:logs:*:*:log-group:/aws/rds/*:log-stream:*",
        "arn:aws:logs:*:*:log-group:/aws/docdb/*:log-stream:*",
        "arn:aws:logs:*:*:log-group:/aws/neptune/*:log-stream:*"
    ]
    ec2_arn = ["arn:aws:kinesis:*:*:stream/aws-rds-das-*"]

    pd = PolicyDocument(
        Version="2012-10-17",
        Id="RDS-Monitoring-Permissions",
        Statement=[
            Statement(Effect=Allow,
                      Principal=Principal("AWS", [IAM_ARN(user, '', account)]),
                      Action=[
                          logs.CreateLogDelivery, logs.GetLogDelivery,
                          logs.UpdateLogDelivery, logs.DeleteLogDelivery,
                          logs.ListLogDeliveries
                      ],
                      Resource=[logs_arn]),
            Statement(Effect=Allow,
                      Principal=Principal("AWS", [IAM_ARN(user, '', account)]),
                      Action=[
                          kinesis.CreateStream, kinesis.PutRecord,
                          kinesis.PutRecords, kinesis.DescribeStream,
                          kinesis.SplitShard, kinesis.MergeShards,
                          kinesis.DeleteStream, kinesis.UpdateShardCount
                      ],
                      Resource=["arn:aws:kinesis:*:*:stream/aws-rds-das-*"])
        ])

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

    return input_kwargs