Skip to main content
AWS cloud security architecture with shield and lock symbols representing cyber protection
Cloud & DevOps

AWS Security Best Practices: Comprehensive Protection Guide

Cesar Adames
•

Implement defense-in-depth AWS security with IAM, VPC, encryption, monitoring, and compliance frameworks to protect your cloud infrastructure.

#aws #security #cloud-security #iam #compliance

AWS Security Best Practices: Comprehensive Protection Guide

Secure your AWS infrastructure with identity management, network isolation, encryption, monitoring, and compliance controls.

Shared Responsibility Model

AWS Responsibilities (Security OF the cloud):

  • Physical data center security
  • Hardware and infrastructure
  • Network infrastructure
  • Hypervisor layer
  • Managed service security

Your Responsibilities (Security IN the cloud):

  • Identity and Access Management (IAM)
  • Data encryption (at rest and in transit)
  • Network configuration (VPC, security groups)
  • Application security
  • Patch management
  • Logging and monitoring
  • Compliance validation

IAM Security Foundation

Root Account Protection

Never use root for daily operations:

  • Enable MFA on root account (hardware key recommended)
  • Delete root access keys
  • Create individual IAM users for admins
  • Store root credentials in secure vault
  • Document root account usage (emergency only)
  • Enable CloudTrail to log root activity

Least Privilege Principle

Grant minimum permissions required:

// BAD: Overly permissive
{
  "Effect": "Allow",
  "Action": "*",
  "Resource": "*"
}

// GOOD: Specific permissions
{
  "Effect": "Allow",
  "Action": [
    "s3:GetObject",
    "s3:PutObject"
  ],
  "Resource": "arn:aws:s3:::my-bucket/app-data/*",
  "Condition": {
    "StringEquals": {
      "aws:PrincipalOrgID": "o-xxxxx"
    }
  }
}

IAM Best Practices

  • No long-term credentials: Use IAM roles for EC2/Lambda/ECS
  • Rotate access keys: 90-day maximum, automate via Secrets Manager
  • Password policy: 14+ characters, complexity requirements, 90-day rotation
  • MFA enforcement: Required for console access, especially admin users
  • Service control policies (SCPs): Organization-wide guardrails
  • Permission boundaries: Limit maximum permissions for roles
  • Access Analyzer: Identify unintended external access

IAM Roles for Cross-Account Access

// Trust policy allowing cross-account assume
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::123456789012:root"
      },
      "Action": "sts:AssumeRole",
      "Condition": {
        "StringEquals": {
          "sts:ExternalId": "unique-external-id"
        }
      }
    }
  ]
}

Network Security (VPC)

VPC Design

Multi-tier architecture:

  • Public subnets: Load balancers, bastion hosts, NAT gateways
  • Private subnets: Application servers, no direct internet access
  • Database subnets: Isolated tier, private only, no internet
  • Multiple availability zones: Redundancy and fault tolerance

Network isolation:

  • Separate VPCs for production/staging/development
  • VPC peering for inter-VPC communication
  • Transit Gateway for hub-and-spoke topology
  • PrivateLink for secure service access

Security Groups (Stateful Firewall)

Whitelist approach - deny by default:

// Web tier security group
Inbound:
- Port 443 (HTTPS) from 0.0.0.0/0 (ALB only)
- Port 80 (HTTP) from 0.0.0.0/0 (redirect to HTTPS)
Outbound:
- All traffic (stateful return traffic allowed)

// App tier security group
Inbound:
- Port 8080 from sg-web-tier (only from web tier)
- Port 22 from sg-bastion (SSH from bastion only)
Outbound:
- Port 5432 to sg-db-tier (PostgreSQL to database tier)
- Port 443 to 0.0.0.0/0 (HTTPS for external APIs)

// Database tier security group
Inbound:
- Port 5432 from sg-app-tier (PostgreSQL from app tier only)
Outbound:
- None (database doesn't initiate outbound)

Best practices:

  • Name rules descriptively
  • Use security group IDs as sources (not CIDR blocks)
  • Separate security groups by function
  • Regular audit of unused security groups
  • No 0.0.0.0/0 for inbound except load balancers

Network ACLs (Stateless Firewall)

Defense in depth - second layer:

  • Stateless (must allow return traffic explicitly)
  • Apply at subnet level
  • Use for broad traffic blocking
  • Default: allow all (unlike security groups)

When to use:

  • Block specific IP ranges (DDoS mitigation)
  • Explicit deny rules (security groups can’t deny)
  • Subnet-level compliance requirements

VPC Flow Logs

Enable for security monitoring:

# Enable VPC Flow Logs
aws ec2 create-flow-logs \
  --resource-type VPC \
  --resource-ids vpc-xxxxx \
  --traffic-type ALL \
  --log-destination-type cloud-watch-logs \
  --log-group-name /aws/vpc/flowlogs

Analyze for:

  • Rejected connections (potential threats)
  • Unusual traffic patterns
  • Data exfiltration attempts
  • Compliance auditing

Data Encryption

Encryption at Rest

S3:

  • SSE-S3: AWS-managed keys (AES-256)
  • SSE-KMS: Customer master keys (CMK), audit trail via CloudTrail
  • SSE-C: Customer-provided keys (you manage keys)
  • Default encryption: Enable bucket-level default

EBS:

  • Enable encryption by default at account/region level
  • Use KMS CMK for encryption keys
  • Encrypted snapshots automatically
  • Can’t encrypt existing unencrypted volumes (create encrypted snapshot)

RDS:

  • Enable encryption at creation (can’t enable later)
  • Encrypted backups and replicas
  • Transparent Data Encryption (TDE) for Oracle/SQL Server
  • KMS key management

DynamoDB:

  • Encryption at rest enabled by default
  • Use KMS for custom keys
  • Backup encryption

Encryption in Transit

TLS/SSL everywhere:

  • Application Load Balancer: HTTPS listeners with ACM certificates
  • CloudFront: Force HTTPS, custom SSL certificates
  • API Gateway: Custom domains with TLS 1.2+
  • RDS: Force SSL connections
  • ElastiCache: Redis in-transit encryption

Certificate management:

  • AWS Certificate Manager (ACM): Free SSL/TLS certificates
  • Auto-renewal for ACM certificates
  • CloudFront: SNI for cost-effective HTTPS
  • Private CA for internal certificates

KMS Best Practices

Key policies:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Enable IAM policies",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::123456789012:root"
      },
      "Action": "kms:*",
      "Resource": "*"
    },
    {
      "Sid": "Allow encryption/decryption",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::123456789012:role/AppRole"
      },
      "Action": [
        "kms:Decrypt",
        "kms:DescribeKey",
        "kms:GenerateDataKey"
      ],
      "Resource": "*"
    }
  ]
}

Key management:

  • Separate keys for different data classifications
  • Key rotation: Enable automatic annual rotation
  • CloudTrail logging of all key usage
  • Cross-account key access with caution
  • Alias naming for easier management

Secrets Management

AWS Secrets Manager:

import boto3
import json

client = boto3.client('secretsmanager')

# Store secret
client.create_secret(
    Name='prod/db/credentials',
    SecretString=json.dumps({
        'username': 'dbuser',
        'password': 'SecureRandomPassword123!',
        'host': 'mydb.rds.amazonaws.com',
        'port': 5432
    }),
    KmsKeyId='alias/secrets-key'
)

# Retrieve secret
response = client.get_secret_value(SecretId='prod/db/credentials')
secret = json.loads(response['SecretString'])

Features:

  • Automatic rotation (Lambda-based)
  • Encryption at rest (KMS)
  • Fine-grained IAM permissions
  • Cross-region replication
  • Version tracking

Systems Manager Parameter Store (alternative):

  • Free tier available
  • Hierarchical organization
  • SecureString type (KMS encryption)
  • Integration with CloudFormation/ECS/Lambda
  • No automatic rotation (manual scripts)

Logging and Monitoring

CloudTrail

Enable organization-wide:

  • All API calls logged
  • Management events + data events
  • S3 bucket with encryption + MFA delete
  • Log file validation
  • Integration with CloudWatch Logs
  • Centralized logging account

Alerts for critical events:

# CloudWatch alarm for root account usage
Metric: Root account login
Condition: >= 1 occurrence
Action: SNS topic → PagerDuty/Slack

CloudWatch Logs

Centralized logging:

  • Application logs (EC2, Lambda, ECS)
  • VPC Flow Logs
  • Route 53 query logs
  • CloudTrail logs
  • WAF logs

Retention policies:

  • Production: 90-365 days
  • Security logs: 2+ years (compliance)
  • Development: 7-30 days
  • Archive to S3 Glacier for long-term storage

AWS Config

Continuous compliance monitoring:

  • Track resource configuration changes
  • Evaluate against compliance rules
  • Automated remediation via SSM Automation
  • Conformance packs for standards (PCI, HIPAA)

Example rules:

  • S3 buckets must have encryption enabled
  • Security groups can’t allow 0.0.0.0/0 on port 22
  • RDS databases must have backup enabled
  • EC2 instances must have approved AMIs

GuardDuty

Threat detection service:

  • Machine learning-based anomaly detection
  • Analyzes CloudTrail, VPC Flow, DNS logs
  • Identifies compromised instances
  • Cryptocurrency mining detection
  • Integration with Security Hub

Findings examples:

  • Unusual API calls from known malicious IPs
  • Compromised EC2 instance
  • Unauthorized IAM user creation
  • Data exfiltration attempts

Application Security

Web Application Firewall (WAF)

Protection layers:

// AWS Managed Rules
{
  "Rules": [
    "AWSManagedRulesCommonRuleSet",
    "AWSManagedRulesKnownBadInputsRuleSet",
    "AWSManagedRulesSQLiRuleSet",
    "AWSManagedRulesLinuxRuleSet"
  ]
}

Custom rules:

  • Rate limiting (IP-based)
  • Geo-blocking
  • Header/query string filtering
  • IP reputation lists
  • Bot control

Integration:

  • CloudFront distributions
  • Application Load Balancers
  • API Gateway
  • AppSync GraphQL APIs

Shield (DDoS Protection)

Shield Standard (free):

  • Layer 3/4 protection
  • Automatic always-on
  • SYN/UDP floods mitigation

Shield Advanced ($3,000/month):

  • Enhanced DDoS protection
  • 24/7 DDoS Response Team (DRT)
  • Cost protection (credits for scaling)
  • Real-time metrics and reports
  • WAF included (no additional charges)

Compliance Frameworks

SOC 2

AWS compliance:

  • AWS inherits SOC 2 Type II certification
  • Customer responsibilities: Access controls, data classification, monitoring

Implementation:

  • IAM for access controls
  • CloudTrail for audit logs
  • Config for compliance monitoring
  • Encryption for data security

PCI DSS

Requirements:

  • Network segmentation (VPC)
  • Encryption in transit and at rest
  • Access control (IAM + MFA)
  • Logging and monitoring (CloudTrail, Config)
  • Vulnerability scanning (Inspector)

AWS services:

  • PCI DSS-compliant services (EC2, RDS, S3, etc.)
  • Use PCI Config conformance pack
  • Regular compliance audits

HIPAA

AWS Business Associate Addendum (BAA):

  • Sign BAA with AWS
  • Use HIPAA-eligible services only
  • Encrypt PHI (S3, RDS, EBS)
  • Access logging and auditing
  • Data backup and disaster recovery

Incident Response

Preparation

  • Runbooks: Document response procedures
  • Automation: Lambda functions for automated response
  • Isolation: Scripts to quarantine compromised resources
  • Forensics: AMI/snapshot for investigation

Detection

  • GuardDuty findings
  • CloudWatch alarms
  • Security Hub aggregation
  • Third-party SIEM integration

Response

# Isolate compromised EC2 instance
aws ec2 modify-instance-attribute \
  --instance-id i-xxxxx \
  --groups sg-isolation

# Create forensic snapshot
aws ec2 create-snapshot \
  --volume-id vol-xxxxx \
  --description "Forensic snapshot for incident IR-2024-001"

# Revoke IAM credentials
aws iam update-access-key \
  --access-key-id AKIAIOSFODNN7EXAMPLE \
  --status Inactive

Recovery

  • Restore from clean backups
  • Patch vulnerabilities
  • Update security groups
  • Rotate credentials

Cost Optimization for Security

Free tier usage:

  • CloudTrail: First trail free
  • AWS Config: First 50 rules free
  • GuardDuty: 30-day free trial
  • Security Hub: Free (pay for integrations)

Cost-effective security:

  • VPC Flow Logs: Sample traffic (not ALL)
  • CloudWatch Logs: Aggressive retention policies
  • S3 Intelligent-Tiering: Old logs to Glacier
  • Reserved capacity: GuardDuty, Config

Security Automation

AWS Lambda for Auto-Remediation

# Auto-remediate S3 bucket public access
import boto3

s3 = boto3.client('s3')

def lambda_handler(event, context):
    bucket = event['detail']['requestParameters']['bucketName']

    # Block public access
    s3.put_public_access_block(
        Bucket=bucket,
        PublicAccessBlockConfiguration={
            'BlockPublicAcls': True,
            'IgnorePublicAcls': True,
            'BlockPublicPolicy': True,
            'RestrictPublicBuckets': True
        }
    )

    # Send SNS notification
    sns = boto3.client('sns')
    sns.publish(
        TopicArn='arn:aws:sns:us-east-1:123456789012:security-alerts',
        Subject='S3 Bucket Public Access Blocked',
        Message=f'Blocked public access on bucket: {bucket}'
    )

EventBridge Rules

Automated security responses:

  • Unauthorized API calls → Disable user
  • Security group changes → Revert + alert
  • Root account login → Multi-channel alert
  • Unencrypted resource → Enable encryption or delete

Third-Party Security Tools

Integration options:

  • SIEM: Splunk, Sumo Logic, Datadog
  • CASB: Netskope, McAfee MVISION
  • Vulnerability scanning: Qualys, Tenable, Rapid7
  • Container security: Aqua, Twistlock, Sysdig
  • CSPM: Prisma Cloud, CloudGuard, Dome9

Security Checklist

Account Level:

  • Root account MFA enabled
  • Root access keys deleted
  • CloudTrail enabled in all regions
  • Config enabled with required rules
  • GuardDuty enabled
  • Security Hub enabled

Identity & Access:

  • No long-term access keys
  • MFA for all IAM users
  • Password policy enforced
  • Least privilege IAM policies
  • Regular access reviews
  • Service roles for EC2/Lambda

Network:

  • Multi-tier VPC architecture
  • Security groups follow whitelist model
  • No 0.0.0.0/0 SSH/RDP access
  • VPC Flow Logs enabled
  • Network segmentation implemented

Data Protection:

  • S3 bucket encryption enabled
  • S3 versioning for critical data
  • EBS encryption by default
  • RDS encryption enabled
  • KMS key rotation enabled
  • TLS/SSL enforced

Monitoring:

  • CloudWatch alarms for critical metrics
  • CloudTrail log file validation
  • Centralized logging
  • Automated security scanning
  • Incident response runbooks

Bottom Line

AWS security requires defense in depth: identity controls, network isolation, encryption everywhere, comprehensive logging, and automated monitoring. Start with IAM and VPC fundamentals, enable CloudTrail and GuardDuty immediately, then layer additional controls based on your compliance requirements and threat model. Security is ongoing—automate where possible and review regularly.

Ready to Transform Your Business?

Let's discuss how our AI and technology solutions can drive revenue growth for your organization.