Skip to content

Instantly share code, notes, and snippets.

@wolfeidau
Created October 11, 2020 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolfeidau/06b07ef85b14d956d4189eda75e31076 to your computer and use it in GitHub Desktop.
Save wolfeidau/06b07ef85b14d956d4189eda75e31076 to your computer and use it in GitHub Desktop.
Example program which creates a secure S3 bucket using the v2 Go SDK for AWS
package main
import (
"context"
"fmt"
"log"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
)
var (
bucketName = "testbucket"
)
func main() {
cfg, err := config.LoadDefaultConfig()
if err != nil {
log.Fatalf("%v", err)
}
ctx := context.Background()
s3client := s3.NewFromConfig(cfg)
// create the bucket
_, err = s3client.CreateBucket(ctx, &s3.CreateBucketInput{
Bucket: &bucketName,
})
if err != nil {
log.Fatalf("%v", err)
}
// enable bucket encryption, here we are just enabling the default server side encryption using AES256
_, err = s3client.PutBucketEncryption(ctx, &s3.PutBucketEncryptionInput{
Bucket: aws.String(bucketName),
ServerSideEncryptionConfiguration: &types.ServerSideEncryptionConfiguration{
Rules: []*types.ServerSideEncryptionRule{{
ApplyServerSideEncryptionByDefault: &types.ServerSideEncryptionByDefault{
SSEAlgorithm: types.ServerSideEncryptionAes256,
},
}},
},
})
if err != nil {
log.Fatalf("%v", err)
}
// add a public access block for this bucket to avoid accidents
_, err = s3client.PutPublicAccessBlock(ctx, &s3.PutPublicAccessBlockInput{
Bucket: aws.String(bucketName),
PublicAccessBlockConfiguration: &types.PublicAccessBlockConfiguration{
BlockPublicAcls: aws.Bool(true),
IgnorePublicAcls: aws.Bool(true),
RestrictPublicBuckets: aws.Bool(true),
BlockPublicPolicy: aws.Bool(true),
},
})
if err != nil {
log.Fatalf("%v", err)
}
// add a policy to the bucket which disallows non SSL requests to bucket objects
_, err = s3client.PutBucketPolicy(ctx,
&s3.PutBucketPolicyInput{
Bucket: aws.String(bucketName),
Policy: aws.String(fmt.Sprintf(
`{"Id": "RainBucketPolicy","Version": "2012-10-17","Statement":[{"Sid": "AllowSSLRequestsOnly","Action":["s3:*"],"Effect":"Deny","Resource":["arn:aws:s3:::%s/*","arn:aws:s3:::%s"],"Condition":{"Bool":{"aws:SecureTransport":"false"}},"Principal": "*"}]}`,
bucketName,
bucketName,
)),
},
)
if err != nil {
log.Fatalf("%v", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment