Skip to content

Instantly share code, notes, and snippets.

@yuta-aoyagi
Created May 4, 2020 12:20
Show Gist options
  • Save yuta-aoyagi/23a1229876f0674544b43fb6f982d374 to your computer and use it in GitHub Desktop.
Save yuta-aoyagi/23a1229876f0674544b43fb6f982d374 to your computer and use it in GitHub Desktop.
# Copyright 2020 yuta-aoyagi
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Sandbox for AWS since 2020-04-04
# digraph {
# "sbox-policies-attacher-to-users" -> { "sbox-operator-policy"; "policy-forcing-mfa" }
# "sbox-cfn-role-operating-groups" -> { "sbox-operator-policy"; "policy-forcing-mfa" }
# "sbox-operator-policy" -> "sbox-function"
# "sbox-function" -> "sbox-related" [label="external s3 operation & lambda execution role"]
# {
# edge [style=dashed] /* for cfn */
# "sbox-policies-attacher-to-users" -> "sbox-cfn-role-operating-groups" -> "top-iam"
# { "sbox-operator-policy"; "policy-forcing-mfa" } -> "top-iam"
# "sbox-function" -> "sbox-related" -> "top-iam"
# }
# }
AWSTemplateFormatVersion: "2010-09-09"
Description: Attach the two specified IAM policies to the specified IAM users
Parameters:
Policy0sExportName:
Type: String
Description: The export name for an IAM policy's ARN
Policy1sExportName:
Type: String
Description: The export name for an IAM policy's ARN
ProjectName:
Type: String
AllowedPattern: ^[\u0021-\u007f]{1,256}$
Default: Sbox
Description: Project's name
Users:
Type: CommaDelimitedList
Description: Comma-delimited list of IAM users to be allowed to operate sbox
Resources:
Group:
Type: AWS::IAM::Group
Properties:
ManagedPolicyArns:
- Fn::ImportValue: !Ref Policy0sExportName
- Fn::ImportValue: !Ref Policy1sExportName
Path: !Sub /${ProjectName}/
AddUserToGroup:
Type: AWS::IAM::UserToGroupAddition
Properties:
GroupName: !Ref Group
Users: !Ref Users
---
AWSTemplateFormatVersion: "2010-09-09"
Description: Define CFn service role allowing CFn to operate IAM groups
Parameters:
GroupsDisallowedToOperate:
Type: CommaDelimitedList
Description: A Resource element in an IAM policy, specifying IAM groups disallowed to operate by the IAM roles to be created by this template. Or empty list if there's no such groups
ProjectName:
Type: String
AllowedPattern: ^[\u0021-\u007f]{1,256}$
Default: Sbox
Description: Project's name
Policy0sExportName:
Type: String
Description: The export name for an IAM policy's ARN
Policy1sExportName:
Type: String
Description: The export name for an IAM policy's ARN
Conditions:
NoGroupsAreSpecified: !Equals
- !Join ["", !Ref GroupsDisallowedToOperate]
- ""
Resources:
Policy:
Type: AWS::IAM::ManagedPolicy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- iam:AddUserToGroup
- iam:CreateGroup
- iam:DeleteGroup
- iam:GetGroup
- iam:RemoveUserFromGroup
- iam:UpdateGroup
Resource: !Sub arn:${AWS::Partition}:iam::*:group/${ProjectName}/*
- Effect: Allow
Action: iam:*tachGroupPolicy
Resource: !Sub arn:${AWS::Partition}:iam::*:group/${ProjectName}/*
Condition:
ArnLike:
iam:PolicyARN:
- Fn::ImportValue: !Ref Policy0sExportName
- Fn::ImportValue: !Ref Policy1sExportName
- !If
- NoGroupsAreSpecified
- Effect: Deny
Action: "*"
NotResource: !Sub arn:${AWS::Partition}:iam::*:group/${ProjectName}/*
- Effect: Deny
Action: "*"
Resource: !Ref GroupsDisallowedToOperate
Role:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
Effect: Allow
Principal:
Service: cloudformation.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- !Ref Policy
Path: !Sub /${ProjectName}/
Tags:
- Key: project
Value: !Ref ProjectName
Outputs:
Arn:
Description: The ARN for the created CFn service role
Value: !GetAtt Role.Arn
---
AWSTemplateFormatVersion: "2010-09-09"
Description: Define an IAM policy allowing to operate sbox
Parameters:
FunctionsExportName:
Type: String
Description: The export name for a Lambda function's ARN
Resources:
Policy:
Type: AWS::IAM::ManagedPolicy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action: iam:*AccessKey*
Resource: !Sub arn:${AWS::Partition}:iam::*:user/${!aws:username}
- Effect: Allow
Action: sts:GetSessionToken
Resource: "*"
- Effect: Allow
Action: lambda:InvokeFunction
Resource:
Fn::ImportValue: !Ref FunctionsExportName
Outputs:
Arn:
Description: The ARN for the created IAM policy
Value: !Ref Policy
Export:
Name: !Sub ${AWS::StackName}-Arn
---
AWSTemplateFormatVersion: "2010-09-09"
Description: Define an IAM policy forcing MFA on
Resources:
Policy:
Type: AWS::IAM::ManagedPolicy
Properties:
# https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_examples_aws_my-sec-creds-self-manage-mfa-only.html
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: AllowViewAccountInfo
Effect: Allow
Action: iam:ListVirtualMFADevices
Resource: "*"
- Effect: Allow
Action:
- iam:CreateVirtualMFADevice
- iam:DeleteVirtualMFADevice
Resource: !Sub arn:${AWS::Partition}:iam::*:mfa/${!aws:username}
- Effect: Allow
Action:
- iam:EnableMFADevice
- iam:GetUser
- iam:ListMFADevices
- iam:ResyncMFADevice
Resource: !Sub arn:${AWS::Partition}:iam::*:user/${!aws:username}
- Effect: Allow
Action: iam:DeactivateMFADevice
Resource: !Sub arn:${AWS::Partition}:iam::*:user/${!aws:username}
Condition:
Bool:
aws:MultiFactorAuthPresent: true
- Sid: DenyAllExceptListedIfNoMFA
Effect: Deny
NotAction:
- iam:CreateVirtualMFADevice
- iam:EnableMFADevice
- iam:GetUser
- iam:ListMFADevices
- iam:ListVirtualMFADevices
- iam:ResyncMFADevice
- sts:GetSessionToken
Resource: "*"
Condition:
BoolIfExists:
aws:MultiFactorAuthPresent: false
Outputs:
Arn:
Description: The ARN for the created IAM policy
Value: !Ref Policy
Export:
Name: !Sub ${AWS::StackName}-Arn
---
AWSTemplateFormatVersion: "2010-09-09"
Description: Define a sandbox Lambda function
Parameters:
SboxRelatedStack:
Type: String
AllowedPattern: ^[-0-9A-Za-z]{1,128}$
Description: CFn stack name created from sbox-related.template
CodeS3Key:
Type: String
Description: Amazon S3 key of the deployment package
MaxLength: 1024
Resources:
Function:
Type: AWS::Lambda::Function
Properties:
Code:
S3Bucket:
Fn::ImportValue: !Sub ${SboxRelatedStack}-Bucket
S3Key: !Ref CodeS3Key
Handler: lambda_function.lambda_handler
Role:
Fn::ImportValue: !Sub ${SboxRelatedStack}-LambdaRoleArn
Runtime: ruby2.7
# MemorySize: 128, Timeout: 3 # todo needed?
Outputs:
Arn:
Description: The ARN of the created Lambda function
Value: !GetAtt Function.Arn
Export:
Name: !Sub ${AWS::StackName}-Arn
---
AWSTemplateFormatVersion: "2010-09-09"
Description: Define some of sbox related resources
Parameters:
ProjectName:
Type: String
AllowedPattern: ^[\u0021-\u007f]{1,256}$
Default: Sbox
Description: Project's name
UserName:
Type: String
AllowedPattern: ^[\w+=,.@-]{1,64}$
Description: User's name whom are allowed to operate the objects in the created S3 bucket
TopCFnRoleIDsExportName:
Type: String
Description: The export name for a top CFn service role's unique ID
Resources:
LambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- !Sub arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Path: !Sub /${ProjectName}/
Tags:
- Key: project
Value: !Ref ProjectName
S3Bucket:
Type: AWS::S3::Bucket
Properties:
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
PublicAccessBlockConfiguration:
BlockPublicAcls: TRUE
BlockPublicPolicy: TRUE
IgnorePublicAcls: TRUE
RestrictPublicBuckets: TRUE
VersioningConfiguration:
Status: Enabled
CFnPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action: iam:PassRole
Resource: !GetAtt LambdaRole.Arn
- Effect: Allow
Action: lambda:CreateFunction
Resource: "*"
Condition:
ForAllValues:StringLike:
aws:TagKeys: aws:cloudformation:*
- Effect: Allow
Action:
- lambda:DeleteFunction
- lambda:GetFunction
- lambda:GetFunctionConfiguration
- lambda:UpdateFunctionCode
Resource: "*"
- Effect: Allow
Action: s3:GetObject
Resource: !Sub arn:${AWS::Partition}:s3:::${S3Bucket}/sbox-function-*.zip
CFnRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
Effect: Allow
Principal:
Service: cloudformation.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- !Ref CFnPolicy
Path: !Sub /${ProjectName}/
Tags:
- Key: project
Value: !Ref ProjectName
BucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref S3Bucket
PolicyDocument:
Statement:
- Effect: Deny
NotPrincipal:
AWS:
- !Ref AWS::AccountId
- !Sub arn:${AWS::Partition}:iam::${AWS::AccountId}:user/${UserName}
Action: "*"
Resource:
- !Sub arn:${AWS::Partition}:s3:::${S3Bucket}
- !Sub arn:${AWS::Partition}:s3:::${S3Bucket}/*
Condition:
StringNotLike:
aws:userid:
- !Join
- ""
- - Fn::ImportValue: !Ref TopCFnRoleIDsExportName
- :*
- !Sub ${CFnRole.RoleId}:*
- Effect: Deny
Principal:
AWS:
- !Ref AWS::AccountId
- !Sub arn:${AWS::Partition}:iam::${AWS::AccountId}:user/${UserName}
NotAction: # TODO
- s3:DeleteObject
- s3:GetBucketLocation
- s3:GetBucketPolicy
- s3:GetObject
- s3:GetObjectVersion
- s3:ListBucket
- s3:PutBucketPolicy
- s3:PutObject
Resource:
- !Sub arn:${AWS::Partition}:s3:::${S3Bucket}
- !Sub arn:${AWS::Partition}:s3:::${S3Bucket}/*
- Effect: Deny
Principal: "*"
Action: "*"
NotResource:
- !Sub arn:${AWS::Partition}:s3:::${S3Bucket}
- !Sub arn:${AWS::Partition}:s3:::${S3Bucket}/*.zip
- Effect: Deny
Principal: "*"
Action: "*"
Resource:
- !Sub arn:${AWS::Partition}:s3:::${S3Bucket}
- !Sub arn:${AWS::Partition}:s3:::${S3Bucket}/*
Condition:
Bool:
aws:SecureTransport: "false"
Outputs:
Bucket:
Description: The created S3 bucket's name
Value: !Ref S3Bucket
Export:
Name: !Sub ${AWS::StackName}-Bucket
LambdaRoleArn:
Description: The ARN for the created Lambda execution role
Value: !GetAtt LambdaRole.Arn
Export:
Name: !Sub ${AWS::StackName}-LambdaRoleArn
CFnRoleArn:
Description: The ARN for the created CFn service policy
Value: !GetAtt CFnRole.Arn
---
AWSTemplateFormatVersion: "2010-09-09"
Description: Define CFn service role allowing CFn to operate IAM and S3 resources
Parameters:
BucketsNotAllowedToOperate:
Type: CommaDelimitedList
Description: A Resource element in an IAM policy specifying S3 buckets not allowed to operate by the IAM roles to be created by this template. Or empty if there's no such buckets
ProjectName:
Type: String
AllowedPattern: ^[\u0021-\u007f]{1,256}$
Default: Sbox
Description: Project's name
Mappings:
Mapping:
Key:
S3Actions:
- s3:CreateBucket
- s3:DeleteBucket
- s3:DeleteBucketPolicy
- s3:GetBucketPolicy
- s3:PutBucketPolicy
- s3:PutBucketPublicAccessBlock
- s3:PutBucketVersioning
- s3:PutEncryptionConfiguration
Conditions:
NoBucketsAreSpecified: !Equals
- !Join ["", !Ref BucketsNotAllowedToOperate]
- ""
Resources:
Policy:
Type: AWS::IAM::ManagedPolicy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action: iam:AttachRolePolicy
Resource: !Sub arn:${AWS::Partition}:iam::*:role/${ProjectName}/*
Condition:
StringEqualsIfExists:
iam:ResourceTag/project: !Ref ProjectName
- Effect: Allow
Action:
- iam:CreatePolicy*
- iam:DeletePolicy*
- iam:GetPolicy
- iam:ListPolicyVersions
Resource: "*"
- Effect: Allow
Action:
- iam:CreateRole
Resource: !Sub arn:${AWS::Partition}:iam::*:role/${ProjectName}/*
Condition:
StringEqualsIfExists:
aws:RequestTag/project: !Ref ProjectName
ForAllValues:StringLike:
aws:TagKeys:
- aws:cloudformation:*
- project
- Effect: Allow
Action:
- iam:DeleteRole
- iam:DetachRolePolicy
- iam:GetRole
Resource: !Sub arn:${AWS::Partition}:iam::*:role/${ProjectName}/*
Condition:
StringEquals:
iam:ResourceTag/project: !Ref ProjectName
- Effect: Allow
Action: iam:TagRole
Resource: !Sub arn:${AWS::Partition}:iam::*:role/${ProjectName}/*
Condition:
StringEquals:
aws:RequestTag/project: !Ref ProjectName
ForAllValues:StringLike:
aws:TagKeys:
- aws:cloudformation:*
- project
- !If
- NoBucketsAreSpecified
- Effect: Allow
Action: !FindInMap [Mapping, Key, S3Actions]
Resource: "*"
- Effect: Allow
Action: !FindInMap [Mapping, Key, S3Actions]
NotResource: !Ref BucketsNotAllowedToOperate
- !If
- NoBucketsAreSpecified
- Effect: Allow
Action: s3:PutBucketTagging
Resource: "*"
Condition:
ForAllValues:StringLike:
aws:TagKeys: aws:cloudformation:*
- Effect: Allow
Action: s3:PutBucketTagging
NotResource: !Ref BucketsNotAllowedToOperate
Condition:
ForAllValues:StringLike:
aws:TagKeys: aws:cloudformation:*
Role:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
Effect: Allow
Principal:
Service: cloudformation.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- !Ref Policy
Outputs:
Arn:
Description: The ARN for the created CFn service role
Value: !GetAtt Role.Arn
Id:
Description: The unique ID for the created CFn service role
Value: !GetAtt Role.RoleId
Export:
Name: !Sub ${AWS::StackName}-Id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment