HANDS-ON LAB Intermediate

Protecting AWS S3 Data Against Ransomware: WORM Object Lock & Lifecycle Rules

Configuring S3 Versioning, Object Lock in Compliance/Governance mode, and automated transition to Glacier to cut cloud storage costs.

Vibe DevOps·· ~11 min read
AWS S3AWS CLIJSONBashIAM

Key Takeaways & Prerequisites

  • Accidental deletion or malicious overwriting can wipe business-critical data; S3 Versioning preserves every version of an object indefinitely.
  • Optimize storage expenses automatically using S3 Lifecycle policies: transition data from Standard to Glacier Flexible Retrieval or Deep Archive after 30/90 days.
  • Enforce S3 Object Lock in Compliance Mode with WORM (Write Once, Read Many) to prevent deletion even by the AWS Root Account during retention windows.
  • Configure Multi-Factor Authentication (MFA) Delete on mission-critical buckets to require physical MFA tokens for permanent version purges.

Architecture & Execution Flow

  1. 01 →S3 VersioningPreserve all updates and delete markers
  2. 02 →Lifecycle TransitionStandard -> Infrequent -> Glacier Deep Archive
  3. 03 →Object Lock (WORM)Compliance Mode protection against ransomware
  4. 04 →MFA Delete EnforcementHardware token requirement for deletion
Table of Contents

In modern cloud architectures, Amazon Simple Storage Service (AWS S3) serves as the primary storage layer for critical enterprise assets: database backups, audit logs, application media, and data lakes. However, operating S3 at production scale presents infrastructure and reliability teams with two conflicting operational challenges: the risk of catastrophic data loss via ransomware or accidental deletion, and uncontrolled storage cost sprawl.

To safeguard backups against unintended overwrites, the intuitive baseline is enabling Versioning. However, versioning introduces a silent cost trap: every time an automated job uploads a new snapshot with an identical key (such as db_dump.sql.gz), S3 does not replace the existing object. Instead, it silently retains the previous file as a noncurrent version. Six months later, you may find yourself paying for hundreds of stale versions that your workload will never read. Worse, if an adversary compromises an IAM identity or a cleanup script issues an erroneous aws s3 rm --recursive, all versions remain vulnerable to deletion if immutable storage controls are not strictly enforced.

This guide provides an end-to-end operational blueprint for implementing a dual-layer defense on AWS S3: enforcing S3 Object Lock via a WORM (Write Once, Read Many) model to neutralize ransomware threats, and engineering intelligent Lifecycle Rules to automatically transition objects to cold Glacier storage, purge noncurrent versions, and abort stranded multipart uploads.

Scope and Execution Prerequisites: All JSON configurations (Lifecycle Policies, Bucket Policies, Object Lock) in this guide have been validated against the Python json parser. Bash snippets have been checked with bash -n. AWS CLI v2 commands are verified against official AWS technical documentation. The guide clearly separates validation tests from resource safety recommendations.

1. Architectural Foundations: WORM Storage and Object Lifecycles

Designing a storage architecture that balances immutability with cost efficiency requires understanding the underlying mechanics of AWS S3 primitives:

1.1. WORM Immutability via S3 Object Lock

S3 Object Lock operates on a WORM (Write Once, Read Many) paradigm. When an object version is placed under a retention period, no identity can delete or overwrite its data until the retention window expires. Object Lock provides two operational modes:

  1. Governance Mode: Objects are protected against deletion by standard IAM users and roles. However, identities granted explicit administrative privileges (s3:BypassGovernanceRetention) can bypass the lock or modify the retention period when operationally necessary (e.g., during emergency maintenance or post-testing teardowns).
  2. Compliance Mode: Absolute, non-negotiable protection. No entity—including the AWS Account Root User or high-privilege IAM administrators—can delete the protected version or shorten the configured retention period. This mode is reserved for strict regulatory and financial mandates (e.g., SEC Rule 17a-4). In sandbox or lab environments, never enable Compliance Mode, as the underlying bucket cannot be deleted until every retention window has elapsed.

1.2. The Hidden Cost Profile of Versioned Buckets

When Versioning is active, executing a standard aws s3 rm command does not delete the payload. Instead, S3 injects a zero-byte Delete Marker as the current version, while the actual underlying data persists as a noncurrent version, continuing to accrue standard storage fees.

Furthermore, when uploading large payloads via the Multipart Upload API, network interruptions or failed transfers leave orphaned byte fragments (incomplete multipart upload parts) in the bucket. These partial uploads are invisible to standard s3 ls commands but persistently drive up monthly billing.

Lifecycle Policy configuration for automatic tiering to Glacier and cleaning up multipart uploads
Figure 1: Implementing a Lifecycle Policy to automatically transition noncurrent versions to Glacier Instant Retrieval and abort incomplete multipart uploads after 7 days.

2. Least-Privilege IAM Provisioning

Engineers managing this workflow should operate under least-privilege access rather than broad AdministratorAccess. The following IAM policy grants the exact actions required to configure, test, and tear down these controls:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "S3BucketLifecycleAndLockManagement",
      "Effect": "Allow",
      "Action": [
        "s3:CreateBucket",
        "s3:PutBucketVersioning",
        "s3:GetBucketVersioning",
        "s3:PutLifecycleConfiguration",
        "s3:GetLifecycleConfiguration",
        "s3:PutBucketPolicy",
        "s3:GetBucketPolicy",
        "s3:PutBucketPublicAccessBlock",
        "s3:PutObjectLockConfiguration",
        "s3:GetObjectLockConfiguration",
        "s3:PutObjectRetention",
        "s3:GetObjectRetention",
        "s3:PutObject",
        "s3:GetObject",
        "s3:DeleteObject",
        "s3:DeleteObjectVersion",
        "s3:ListBucket",
        "s3:ListBucketVersions"
      ],
      "Resource": [
        "arn:aws:s3:::vibedevops-backup-lab",
        "arn:aws:s3:::vibedevops-backup-lab/*"
      ]
    },
    {
      "Sid": "AllowBypassGovernanceForAuthorizedRole",
      "Effect": "Allow",
      "Action": "s3:BypassGovernanceRetention",
      "Resource": "arn:aws:s3:::vibedevops-backup-lab/*"
    }
  ]
}

3. Step-by-Step Implementation

Step 1: Initialize Environment Variables and Create an S3 Bucket with Object Lock

Critical architectural constraint: AWS requires that Object Lock be enabled at bucket creation time using the --object-lock-enabled-for-bucket flag. You cannot enable Object Lock on an existing bucket without engaging AWS Support.

export AWS_REGION="ap-southeast-1"
export BUCKET_NAME="vibedevops-backup-lab-$RANDOM"

# Create an S3 bucket with Object Lock enabled
aws s3api create-bucket \
  --bucket "$BUCKET_NAME" \
  --region "$AWS_REGION" \
  --create-bucket-configuration LocationConstraint="$AWS_REGION" \
  --object-lock-enabled-for-bucket

# Enforce Amazon S3 Block Public Access
aws s3api put-public-access-block \
  --bucket "$BUCKET_NAME" \
  --public-access-block-configuration \
  "BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true"

Step 2: Enforce In-Transit Encryption via Bucket Policy (TLS/HTTPS)

Secure data in transit by explicitly denying all requests that do not use HTTPS (TLS 1.2+):

cat << 'EOF' > enforce-tls-policy.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "EnforceTLSRequestsOnly",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::BUCKET_PLACEHOLDER",
        "arn:aws:s3:::BUCKET_PLACEHOLDER/*"
      ],
      "Condition": {
        "Bool": {
          "aws:SecureTransport": "false"
        }
      }
    }
  ]
}
EOF

sed -i "s/BUCKET_PLACEHOLDER/$BUCKET_NAME/g" enforce-tls-policy.json
aws s3api put-bucket-policy --bucket "$BUCKET_NAME" --policy file://enforce-tls-policy.json

Step 3: Configure Lifecycle Rules for Cost Optimization

Define the lifecycle configuration in lifecycle-config.json. This policy enforces three critical cost controls: - Tiering Cold Versions: 30 days after becoming a noncurrent version, the object transitions to GLACIER_IR (Glacier Instant Retrieval), delivering ~68% storage cost savings over S3 Standard while preserving millisecond retrieval latency. - Permanent Expiration: Noncurrent versions are permanently expired and deleted after 90 days. - Multipart Upload Pruning: Aborted or incomplete multipart upload segments are automatically purged after 7 days.

{
  "Rules": [
    {
      "ID": "cost-optimization-and-cleanup",
      "Status": "Enabled",
      "Filter": {
        "Prefix": ""
      },
      "NoncurrentVersionTransitions": [
        {
          "NoncurrentDays": 30,
          "StorageClass": "GLACIER_IR"
        }
      ],
      "NoncurrentVersionExpiration": {
        "NoncurrentDays": 90
      },
      "AbortIncompleteMultipartUpload": {
        "DaysAfterInitiation": 7
      }
    }
  ]
}

Apply the lifecycle configuration to the bucket:

aws s3api put-bucket-lifecycle-configuration \
  --bucket "$BUCKET_NAME" \
  --lifecycle-configuration file://lifecycle-config.json

Step 4: Configure Bucket-Level Default Object Lock Retention

To eliminate the operational risk of client applications failing to set per-object retention metadata during upload, enforce a bucket-level default retention policy of 30 days in GOVERNANCE mode:

aws s3api put-object-lock-configuration \
  --bucket "$BUCKET_NAME" \
  --object-lock-configuration '{
    "ObjectLockEnabled": "Enabled",
    "Rule": {
      "DefaultRetention": {
        "Mode": "GOVERNANCE",
        "Days": 30
      }
    }
  }'

4. Empirical Verification: Simulating a Ransomware Attack

To validate our defenses, we will upload a mock database snapshot and test how S3 Object Lock responds to malicious deletion patterns.

# Generate a sample backup file and upload to S3
echo "PostgreSQL Dump Data -- Production 2026-11-01" | gzip > db_backup_20261101.sql.gz

aws s3 cp db_backup_20261101.sql.gz "s3://$BUCKET_NAME/db_backup_20261101.sql.gz"

# Verify the retention metadata of the uploaded object
aws s3api get-object-retention \
  --bucket "$BUCKET_NAME" \
  --key db_backup_20261101.sql.gz

The output confirms a RetainUntilDate set exactly 30 days into the future.

Scenario 1: Standard Deletion Attempt

aws s3 rm "s3://$BUCKET_NAME/db_backup_20261101.sql.gz"

The CLI outputs delete: s3://..., but is the payload destroyed? Inspect the underlying object versions:

aws s3api list-object-versions --bucket "$BUCKET_NAME" --prefix db_backup

S3 merely created a DeleteMarker. The underlying object version containing your data remains completely intact.

Scenario 2: Adversary Attempts Hard Deletion (DeleteObjectVersion)

An attacker locates the specific VersionId of the backup payload and attempts an explicit, permanent deletion:

VERSION_ID=$(aws s3api list-object-versions \
  --bucket "$BUCKET_NAME" \
  --prefix db_backup \
  --query 'Versions[0].VersionId' \
  --output text)

aws s3api delete-object \
  --bucket "$BUCKET_NAME" \
  --key db_backup_20261101.sql.gz \
  --version-id "$VERSION_ID"
S3 Object Lock denying deletion of an object under retention
Figure 2: The S3 API rejects the deletion attempt with AccessDenied: An Object Lock configuration prevents this object from being deleted.

The S3 API instantly terminates the request: An error occurred (AccessDenied) when calling the DeleteObject operation: An Object Lock configuration prevents this object from being deleted.

Even an identity with full s3:DeleteObjectVersion privileges cannot purge this object. The backup payload is cryptographically and operationally protected against unauthorized destruction.

5. Common Operational Pitfalls

  1. Omitting AbortIncompleteMultipartUpload: A common post-mortem finding in cloud cost overruns is uncollected multipart fragments. If large backup archives fail mid-stream due to transient network resets, those multi-gigabyte fragments remain billed indefinitely unless an explicit lifecycle rule cleans them up.
  2. The Glacier Minimum Storage Duration Trap: The GLACIER_IR storage class enforces a 90-day minimum billable storage duration. If your policy sets NoncurrentVersionTransitions to Glacier at day 30, but sets NoncurrentVersionExpiration at day 60 (retaining the object in Glacier for only 30 days), AWS bills you for the full 90-day Glacier minimum. Ensure the delta between transition and expiration is always equal to or greater than 90 days.
  3. Misapplying Compliance Mode: Enabling Compliance Mode outside strictly governed compliance pipelines will lead to administrative deadlocks. If enabled during prototyping or in non-production environments, nobody—including AWS Support—can delete the data or the bucket until the retention window expires.
Using the bypass governance retention flag for controlled data deletion
Figure 3: An authorized administrator leverages the bypass-governance-retention flag to clean up object versions after completing testing.

6. Teardown and Resource Decommissioning

To avoid lingering storage costs after completing this lab, clean up the resources. Because the object version is protected under Governance mode, deletion requires the --bypass-governance-retention flag:

# 1. Delete the locked object version using the bypass flag
aws s3api delete-object \
  --bucket "$BUCKET_NAME" \
  --key db_backup_20261101.sql.gz \
  --version-id "$VERSION_ID" \
  --bypass-governance-retention

# 2. Delete the remaining Delete Marker
MARKER_ID=$(aws s3api list-object-versions \
  --bucket "$BUCKET_NAME" \
  --query 'DeleteMarkers[0].VersionId' \
  --output text)

if [ "$MARKER_ID" != "None" ] && [ -n "$MARKER_ID" ]; then
  aws s3api delete-object \
    --bucket "$BUCKET_NAME" \
    --key db_backup_20261101.sql.gz \
    --version-id "$MARKER_ID"
fi

# 3. Delete the empty bucket
aws s3api delete-bucket --bucket "$BUCKET_NAME" --region "$AWS_REGION"
echo "Bucket $BUCKET_NAME has been successfully deleted."

Conclusion

Pairing S3 Object Lock with carefully planned Lifecycle Rules creates an optimal equilibrium between data resilience and operational cost control: - Mission-critical data is protected by immutable WORM primitives that withstand ransomware and rogue scripts. - Noncurrent versions are automatically offloaded to low-cost Glacier tiers and expired once retention commitments lapse. - Hidden costs from aborted multipart uploads are systematically eradicated.

Audit your production backup buckets and sensitive object stores today to ensure these two foundational layers are active across your infrastructure.

Official References

Read critically, test before applying. Examples reflect Vibe DevOps lab environments; adjust parameters to your infrastructure and verify in staging first.← Back to Hands-on Labs

Next Recommended Labs