Enforcement of Server-Side Encryption for all S3 buckets
resource "aws_s3_bucket" "bucket" {
bucket = "my-bucket"
acl = "private"
tags = {
Name = "My bucket"
Environment = "Dev"
}
}
In the above code, an S3 bucket is being created with the name "my-bucket". The
acl
is set to "private", which means that the bucket is not public and only certain AWS accounts and users have access to it. The
tags
attribute is used to assign metadata to the bucket in the form of key-value pairs.
However, the issue here is that the
server_side_encryption_configuration
attribute is not defined, which means that Server-Side Encryption (SSE) is not enabled. SSE is a feature provided by AWS S3 that encrypts data at rest, i.e., when the data is stored on disks in AWS data centers.
Without SSE, the data stored in the S3 bucket is not encrypted, making it vulnerable to unauthorized access and data breaches. If an attacker somehow gains access to the S3 bucket, they could read the unencrypted data directly.
To fix this vulnerability, the
server_side_encryption_configuration
attribute should be added to the S3 bucket resource, and the
rule
block should be defined with the
apply_server_side_encryption_by_default
attribute, where the
sse_algorithm
is set to "aws:kms" or "AES256".
resource "aws_s3_bucket" "bucket" {
bucket = "my-bucket"
acl = "private"
server_side_encryption_configuration {
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
tags = {
Name = "My bucket"
Environment = "Dev"
}
}
The updated code block now includes the
server_side_encryption_configuration
argument within the
aws_s3_bucket
resource block. This argument is used to enable server-side encryption for the S3 bucket.
Inside the
server_side_encryption_configuration
block, a
rule
block is defined. This block specifies the encryption rules to be applied to the S3 bucket.
Within the
rule
block, the
apply_server_side_encryption_by_default
block is defined. This block is used to specify the server-side encryption method to be used by default for all new objects in the bucket.
The
sse_algorithm
argument inside the
apply_server_side_encryption_by_default
block is set to
"AES256"
. This means that the Server-Side Encryption with Amazon S3-Managed Keys (SSE-S3) method is used to encrypt the stored objects.
The
tags
block remains unchanged. It is used to assign metadata to the S3 bucket in the form of key-value pairs.
After saving these changes, you can apply the updated Terraform configuration. This will provision the S3 bucket with server-side encryption enabled, ensuring that all stored objects are encrypted at rest. This significantly reduces the risk of data leaks by attackers or unauthorized users.