Chapter 29 Exercises: Cloud Security Testing

Exercise 29.1: Cloud Provider Identification (Beginner)

Given the following DNS records for a target organization, identify which cloud providers and services are in use:

portal.target.com      CNAME  d1abc123.cloudfront.net
api.target.com         CNAME  api-target.us-east-1.elasticbeanstalk.com
mail.target.com        CNAME  target.mail.protection.outlook.com
files.target.com       CNAME  target-files.s3-website-us-east-1.amazonaws.com
auth.target.com        CNAME  target.b2clogin.com
dev.target.com         A      34.102.187.24
status.target.com      CNAME  target.azurewebsites.net

For each record, identify: (a) the cloud provider, (b) the specific service, and (c) the security testing implications.

Exercise 29.2: S3 Bucket Policy Analysis (Beginner)

Analyze the following S3 bucket policy and identify all security issues:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowPublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": ["s3:GetObject", "s3:ListBucket"],
            "Resource": [
                "arn:aws:s3:::medsecure-assets",
                "arn:aws:s3:::medsecure-assets/*"
            ]
        },
        {
            "Sid": "AllowAuthenticatedUpload",
            "Effect": "Allow",
            "Principal": {"AWS": "*"},
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::medsecure-assets/uploads/*"
        }
    ]
}

List each vulnerability, explain why it is dangerous, and provide a corrected policy statement.

Exercise 29.3: IAM Policy Evaluation (Intermediate)

A user named dev-sarah has the following IAM configuration:

  • Inline policy: Allows s3:GetObject on arn:aws:s3:::medsecure-dev/*
  • Group policy (developers group): Allows ec2:Describe*, s3:List*, lambda:List*, lambda:GetFunction
  • Managed policy: arn:aws:iam::123456789012:policy/DevDeployPolicy which allows lambda:UpdateFunctionCode, lambda:UpdateFunctionConfiguration, iam:PassRole

Determine: (a) What privilege escalation path exists? (b) Walk through the exact steps an attacker would take. (c) What is the maximum access achievable? (d) How should the IAM configuration be remediated?

Exercise 29.4: Metadata Service Exploitation (Intermediate)

You have discovered an SSRF vulnerability in a web application running on an EC2 instance. The application takes a URL parameter and fetches the content:

https://portal.medsecure-example.com/proxy?url=http://169.254.169.254/latest/meta-data/

Write a step-by-step exploitation plan that: 1. Determines whether IMDSv1 or IMDSv2 is in use 2. Retrieves IAM role credentials if IMDSv1 is available 3. Enumerates the instance's role and permissions 4. Identifies potential next steps based on the permissions discovered

Exercise 29.5: Cloud Reconnaissance Lab (Intermediate)

Using your home lab AWS account with CloudGoat deployed, perform the following reconnaissance exercise:

  1. Create three S3 buckets with different access configurations (public-read, authenticated-read, private)
  2. Use cloud_enum or manual methods to discover the buckets
  3. Test access from an unauthenticated perspective
  4. Test access from an authenticated but unauthorized perspective
  5. Document your findings in a professional format

Exercise 29.6: ScoutSuite Assessment (Intermediate)

Run ScoutSuite against your lab AWS account and analyze the results:

  1. Install and configure ScoutSuite
  2. Run a full assessment
  3. Categorize findings by severity (Critical, High, Medium, Low)
  4. For each Critical and High finding, write a one-paragraph remediation recommendation
  5. Identify which findings map to CIS AWS Foundations Benchmark controls

Exercise 29.7: IAM Privilege Escalation with Pacu (Advanced)

Using the CloudGoat iam_privesc_by_rollback scenario:

  1. Deploy the scenario
  2. Start with the provided low-privilege credentials
  3. Use Pacu's iam__enum_permissions module to understand your current access
  4. Identify the escalation path (hint: policy version rollback)
  5. Execute the escalation
  6. Document each step with screenshots and command output
  7. Clean up the scenario

Exercise 29.8: Lambda Function Security Review (Intermediate)

Review the following Lambda function code and identify all security issues:

import json
import os
import boto3
import subprocess

def lambda_handler(event, context):
    # Get patient ID from API Gateway event
    patient_id = event['queryStringParameters']['patient_id']

    # Query DynamoDB
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table(os.environ['PATIENT_TABLE'])

    response = table.get_item(Key={'patient_id': patient_id})

    # Generate report
    report_name = event['queryStringParameters'].get('report_name', 'default')
    subprocess.call(f'echo "Report for {report_name}" > /tmp/report.txt', shell=True)

    # Upload to S3
    s3 = boto3.client('s3')
    s3.upload_file('/tmp/report.txt', 'medsecure-reports', f'reports/{patient_id}/{report_name}.txt')

    # Log access
    print(f"Patient record accessed: {patient_id}, API Key: {os.environ.get('API_KEY')}")

    return {
        'statusCode': 200,
        'headers': {'Access-Control-Allow-Origin': '*'},
        'body': json.dumps(response.get('Item', {}), default=str)
    }

Identify at least six security vulnerabilities and provide corrected code.

Exercise 29.9: Container Security Assessment (Intermediate)

Given the following Dockerfile for a MedSecure microservice, identify security issues and provide a hardened version:

FROM ubuntu:latest
RUN apt-get update && apt-get install -y python3 python3-pip curl wget
COPY requirements.txt .
RUN pip3 install -r requirements.txt
COPY . /app
WORKDIR /app
ENV DATABASE_URL=postgresql://admin:SuperSecret123@medsecure-db.cluster-abc.us-east-1.rds.amazonaws.com:5432/patients
ENV AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
ENV AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
EXPOSE 8080
USER root
CMD ["python3", "app.py"]

Exercise 29.10: Cloud Attack Chain Construction (Advanced)

Design a complete attack chain for the following scenario:

ShopStack has the following AWS environment: - A public-facing web application on EC2 behind an ALB - An S3 bucket for static assets (CDN origin) - Lambda functions for order processing - RDS PostgreSQL for customer data - SQS queues for async processing - An exposed Jenkins server for CI/CD

Starting from the Jenkins server, construct a realistic attack chain that leads to customer data exfiltration. For each step, specify: the technique used, the tool(s) employed, the AWS permission or misconfiguration exploited, and the output gained.

Exercise 29.11: Terraform Security Review (Intermediate)

Analyze the following Terraform configuration and identify all security issues:

resource "aws_security_group" "web_sg" {
  name        = "web-sg"
  description = "Web server security group"

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_db_instance" "shopstack_db" {
  identifier           = "shopstack-prod"
  engine               = "mysql"
  instance_class       = "db.t3.medium"
  allocated_storage    = 100
  username             = "admin"
  password             = "ShopStack2024!"
  publicly_accessible  = true
  skip_final_snapshot  = true
  storage_encrypted    = false
}

resource "aws_s3_bucket" "data_bucket" {
  bucket = "shopstack-customer-data"
}

resource "aws_s3_bucket_acl" "data_bucket_acl" {
  bucket = aws_s3_bucket.data_bucket.id
  acl    = "public-read"
}

Identify at least eight security issues and provide corrected Terraform code.

Exercise 29.12: Cross-Cloud Comparison (Beginner)

Create a comparison table mapping equivalent security services across AWS, Azure, and GCP for the following categories: - Identity and Access Management - Storage services and access control - Network security (firewalls, security groups) - Logging and monitoring - Key management - Security assessment/auditing - Container orchestration - Serverless compute

For each category, note key differences in security testing approach.

Exercise 29.13: Prowler Assessment Report (Intermediate)

Run Prowler against your lab AWS account with the following requirements: 1. Run the full CIS benchmark check 2. Additionally run the HIPAA-relevant checks (as MedSecure would require) 3. Export results in CSV format 4. Create a summary report that groups findings by: - IAM findings - Network findings - Storage findings - Logging findings 5. For the top five findings, write detailed remediation steps with AWS CLI commands

Exercise 29.14: Serverless Attack and Defense (Advanced)

Deploy a simple Lambda function (behind API Gateway) in your lab environment that: 1. Accepts a JSON payload with a filename parameter 2. Reads the file from an S3 bucket and returns its contents

Then: 1. Identify injection vulnerabilities in your function 2. Attempt to exploit path traversal to access files outside the intended directory 3. Try to access the Lambda execution environment's credentials 4. Implement defenses: input validation, least-privilege IAM role, VPC configuration 5. Verify that your defenses prevent the attacks

Exercise 29.15: Cloud Incident Response Simulation (Advanced)

Simulate the following cloud security incident and document your investigation:

Scenario: CloudTrail logs show the following sequence of events from an unfamiliar IP address using valid credentials: 1. GetCallerIdentity (STS) 2. ListBuckets (S3) 3. ListObjects on medsecure-patient-records (S3) 4. GetObject — 500 objects downloaded (S3) 5. CreateUser — new user backup-admin created (IAM) 6. AttachUserPolicyAdministratorAccess attached to backup-admin (IAM) 7. CreateAccessKey — new access key created for backup-admin (IAM)

Document: (a) What happened in each step? (b) What is the attacker's likely objective? (c) What immediate containment steps should be taken? (d) What evidence should be preserved? (e) How could this have been prevented?

Exercise 29.16: MedSecure Cloud Security Assessment Plan (Advanced)

Develop a comprehensive cloud security testing plan for MedSecure's AWS environment. Your plan should include:

  1. Pre-engagement checklist (AWS-specific)
  2. Scope definition (accounts, regions, services)
  3. Testing phases with specific tools and techniques for each phase
  4. HIPAA-specific testing requirements
  5. Risk mitigation measures during testing (to avoid disrupting patient care systems)
  6. Deliverables and reporting format
  7. Compliance mapping (CIS, HIPAA, NIST)
  8. Estimated timeline and resource requirements

The plan should be detailed enough to serve as a real engagement proposal.