> ## Documentation Index
> Fetch the complete documentation index at: https://journal.daudaldi.my.id/llms.txt
> Use this file to discover all available pages before exploring further.

# Cloud

# Cloud Hardening

Cloud environments introduced a fundamentally different security model. In a traditional data center, you control the physical hardware, the network, and the OS. In the cloud, you share that responsibility with the provider. Understanding where the provider's responsibility ends and yours begins, the **Shared Responsibility Model**, is the starting point for everything else.

The biggest difference between cloud security failures and traditional ones? Most cloud breaches aren't sophisticated attacks. They're misconfigurations: an S3 bucket left public, an IAM role with `*` permissions, a security group with `0.0.0.0/0` on port 22, a root account with no MFA. The tools attackers use to find these things are the same ones you can use to find and fix them first.

## The Shared Responsibility Model

Before hardening anything, understand what you're responsible for:

| Layer                       | AWS    | Azure  | GCP    | You |
| --------------------------- | ------ | ------ | ------ | --- |
| Physical infrastructure     | ✓      | ✓      | ✓      | -   |
| Hypervisor / Host OS        | ✓      | ✓      | ✓      | -   |
| Network infrastructure      | ✓      | ✓      | ✓      | -   |
| Guest OS (IaaS)             | -      | -      | -      | ✓   |
| Application code            | -      | -      | -      | ✓   |
| Data                        | -      | -      | -      | ✓   |
| IAM / Access control        | Shared | Shared | Shared | ✓   |
| Network config (SGs, NACLs) | -      | -      | -      | ✓   |
| Encryption of data          | Shared | Shared | Shared | ✓   |

"The provider secures the cloud, you secure what's in the cloud." In practice, most cloud breaches fall squarely in your column.

## Identity and Access Management (IAM)

IAM is where most cloud security starts - and where most cloud breaches originate.

### AWS IAM

```bash theme={null}
# Check for root account MFA
aws iam get-account-summary | grep AccountMFAEnabled

# List IAM users without MFA enabled
aws iam generate-credential-report
aws iam get-credential-report --query 'Content' --output text | base64 -d | \
  awk -F, '$4 == "false" && $2 == "true" {print $1}'  # users with console access, no MFA

# Find overly permissive policies (attached policies with *)
aws iam list-policies --scope Local --query \
  'Policies[*].{Name:PolicyName, Arn:Arn}' --output table

# Find access keys older than 90 days
aws iam generate-credential-report
aws iam get-credential-report --query 'Content' --output text | base64 -d | \
  awk -F, '{print $1,$9,$10}' | grep -v N/A
```

### Principles to Enforce

**No root account usage for daily work:**

* Enable MFA on the root account immediately
* Create individual IAM users or use SSO
* Never generate root access keys - if they exist, delete them
* Use root only for tasks that explicitly require it (billing, account closure)

**Least privilege on all IAM entities:**

```json theme={null}
// BAD - full admin on everything
{
  "Effect": "Allow",
  "Action": "*",
  "Resource": "*"
}

// BETTER - specific permissions scoped to specific resources
{
  "Effect": "Allow",
  "Action": ["s3:GetObject", "s3:PutObject"],
  "Resource": "arn:aws:s3:::my-specific-bucket/*"
}
```

**Use roles, not long-lived keys:**

* EC2 instances should use IAM roles to access AWS services - not access keys baked into config files
* Lambda functions should use execution roles with minimal permissions
* If you must use access keys (CI/CD, external systems), rotate them regularly and use short-lived credentials where possible

### Azure RBAC

```bash theme={null}
# List all role assignments (look for overly broad assignments)
az role assignment list --all --output table

# Check for accounts with Owner or Contributor at subscription scope
az role assignment list --all --query \
  "[?roleDefinitionName=='Owner' || roleDefinitionName=='Contributor']" --output table

# List service principals and their permissions
az ad sp list --all --output table
```

### GCP IAM

```bash theme={null}
# List all IAM policies at project level
gcloud projects get-iam-policy YOUR_PROJECT_ID

# Find service accounts with editor/owner roles
gcloud projects get-iam-policy YOUR_PROJECT_ID \
  --flatten="bindings[].members" \
  --filter="bindings.role:roles/editor OR bindings.role:roles/owner"

# List service account keys (should be minimal)
gcloud iam service-accounts list
gcloud iam service-accounts keys list --iam-account=SA_EMAIL
```

## Storage Security

Publicly accessible storage buckets containing sensitive data is one of the most commonly exploited cloud misconfigurations.

### AWS S3

```bash theme={null}
# List all buckets and their public access settings
aws s3api list-buckets --query 'Buckets[*].Name' --output text | \
  xargs -I{} aws s3api get-public-access-block --bucket {}

# Enable block public access at the account level (applies to all buckets)
aws s3control put-public-access-block \
  --account-id YOUR_ACCOUNT_ID \
  --public-access-block-configuration \
    BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true

# Check a specific bucket's ACL
aws s3api get-bucket-acl --bucket YOUR_BUCKET_NAME

# Enable versioning (helps with ransomware recovery)
aws s3api put-bucket-versioning \
  --bucket YOUR_BUCKET_NAME \
  --versioning-configuration Status=Enabled

# Enable server-side encryption
aws s3api put-bucket-encryption \
  --bucket YOUR_BUCKET_NAME \
  --server-side-encryption-configuration \
    '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"aws:kms"}}]}'

# Enable access logging
aws s3api put-bucket-logging \
  --bucket YOUR_BUCKET_NAME \
  --bucket-logging-status \
    '{"LoggingEnabled":{"TargetBucket":"YOUR_LOG_BUCKET","TargetPrefix":"s3-access-logs/"}}'
```

### Azure Blob Storage

```bash theme={null}
# Disable public blob access at storage account level
az storage account update \
  --name YOUR_STORAGE_ACCOUNT \
  --resource-group YOUR_RG \
  --allow-blob-public-access false

# Enable soft delete for blobs (recovery from accidental deletion/ransomware)
az storage blob service-properties delete-policy update \
  --account-name YOUR_STORAGE_ACCOUNT \
  --enable true \
  --days-retained 30

# Enforce HTTPS-only access
az storage account update \
  --name YOUR_STORAGE_ACCOUNT \
  --resource-group YOUR_RG \
  --https-only true
```

## Compute Security

### Security Groups and Firewall Rules

The most common compute misconfiguration: security groups that allow `0.0.0.0/0` on SSH, RDP, or other management ports.

```bash theme={null}
# AWS - Find security groups allowing 0.0.0.0/0 on SSH
aws ec2 describe-security-groups \
  --filters "Name=ip-permission.from-port,Values=22" \
             "Name=ip-permission.to-port,Values=22" \
             "Name=ip-permission.cidr,Values=0.0.0.0/0" \
  --query 'SecurityGroups[*].{ID:GroupId, Name:GroupName}'

# Same for RDP
aws ec2 describe-security-groups \
  --filters "Name=ip-permission.from-port,Values=3389" \
             "Name=ip-permission.to-port,Values=3389" \
             "Name=ip-permission.cidr,Values=0.0.0.0/0" \
  --query 'SecurityGroups[*].{ID:GroupId, Name:GroupName}'

# GCP - List firewall rules allowing SSH from everywhere
gcloud compute firewall-rules list \
  --filter="allowed[].ports:22 AND sourceRanges:0.0.0.0/0"
```

**Fix:** Use **AWS Systems Manager Session Manager**, **Azure Bastion**, or **GCP IAP Tunnel** instead of exposing SSH/RDP at all. These provide audited, authenticated access without opening any inbound ports.

```bash theme={null}
# AWS SSM Session Manager - connect without opening port 22
aws ssm start-session --target i-0123456789abcdef0

# GCP IAP tunnel
gcloud compute ssh INSTANCE_NAME \
  --tunnel-through-iap \
  --project YOUR_PROJECT \
  --zone YOUR_ZONE
```

### Instance Metadata Service (IMDS)

The instance metadata service is a common target for SSRF attacks - an attacker who can make the instance make HTTP requests to `169.254.169.254` can steal instance credentials.

```bash theme={null}
# AWS - Enforce IMDSv2 (token-required mode) on existing instance
aws ec2 modify-instance-metadata-options \
  --instance-id i-0123456789abcdef0 \
  --http-tokens required \
  --http-put-response-hop-limit 1

# Enforce IMDSv2 at account level for all new instances
aws ec2-instance-connect send-ssh-public-key # example - use account policy instead:
# Set account-level default: require IMDSv2 on all new instances
```

## Network Controls in the Cloud

### AWS VPC

```bash theme={null}
# Check if default VPC exists in each region (best practice: delete it or don't use it)
aws ec2 describe-vpcs --filters "Name=isDefault,Values=true" --query 'Vpcs[*].VpcId'

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

# Check Network ACLs - find permissive rules
aws ec2 describe-network-acls \
  --query 'NetworkAcls[*].{ID:NetworkAclId, Entries:Entries}'
```

**VPC design principles:**

* Separate public, private, and database subnets
* Put internet-facing resources (load balancers) in public subnets, application servers in private
* Databases should never be in public subnets
* Use **PrivateLink** or **VPC Endpoints** for AWS service access - keeps traffic off the public internet
* Enable **VPC Flow Logs** - essential for network forensics and anomaly detection

### Security Group Best Practices

```
Security group rules:
- Inbound: Deny all by default, allow only what's needed
- Outbound: Consider restricting outbound too (not just inbound)
- Reference security groups by ID, not IP ranges, for internal traffic
- Use separate security groups for different application tiers
- Never use the "default" security group for production resources
- Document every inbound rule with a purpose/owner
```

## Logging and Monitoring

Without logging, you're flying blind. These are the foundational logging services in each major cloud:

### AWS CloudTrail

```bash theme={null}
# Verify CloudTrail is enabled and logging in all regions
aws cloudtrail describe-trails --include-shadow-trails

# Check if CloudTrail log validation is enabled
aws cloudtrail get-trail-status --name YOUR_TRAIL_NAME \
  --query 'IsLogging'

# Enable CloudTrail in all regions with log file validation
aws cloudtrail create-trail \
  --name all-regions-trail \
  --s3-bucket-name YOUR_CLOUDTRAIL_BUCKET \
  --is-multi-region-trail \
  --enable-log-file-validation

aws cloudtrail start-logging --name all-regions-trail
```

### AWS GuardDuty

GuardDuty is AWS's managed threat detection service - it analyzes CloudTrail, VPC Flow Logs, and DNS logs for threats. It's low-friction and high-value:

```bash theme={null}
# Enable GuardDuty
aws guardduty create-detector --enable --finding-publishing-frequency FIFTEEN_MINUTES

# List active detectors
aws guardduty list-detectors

# List findings
aws guardduty list-findings \
  --detector-id YOUR_DETECTOR_ID \
  --finding-criteria '{"Criterion":{"severity":{"Gte":4}}}'
```

### AWS Security Hub

Aggregates findings from GuardDuty, Inspector, Macie, Config, and third-party tools into a single pane:

```bash theme={null}
# Enable Security Hub
aws securityhub enable-security-hub --enable-default-standards

# Enable specific standards
aws securityhub batch-enable-standards \
  --standards-subscription-requests \
    StandardsArn=arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0

# Get all failed controls
aws securityhub get-findings \
  --filters '{"ComplianceStatus":[{"Value":"FAILED","Comparison":"EQUALS"}]}'
```

### Azure Equivalents

| AWS             | Azure                              |
| --------------- | ---------------------------------- |
| CloudTrail      | Azure Activity Log + Azure Monitor |
| GuardDuty       | Microsoft Defender for Cloud       |
| Security Hub    | Microsoft Defender for Cloud       |
| Config          | Azure Policy                       |
| Macie (S3 data) | Microsoft Purview                  |

### GCP Equivalents

| AWS        | GCP                                         |
| ---------- | ------------------------------------------- |
| CloudTrail | Cloud Audit Logs                            |
| GuardDuty  | Security Command Center                     |
| Config     | Cloud Asset Inventory + Organization Policy |

## Encryption

### Data at Rest

```bash theme={null}
# AWS - Check if EBS volumes are encrypted
aws ec2 describe-volumes \
  --query 'Volumes[?Encrypted==`false`].{ID:VolumeId, State:State}'

# Enforce encryption of all new EBS volumes at account level
aws ec2 enable-ebs-encryption-by-default

# Check RDS encryption status
aws rds describe-db-instances \
  --query 'DBInstances[?StorageEncrypted==`false`].DBInstanceIdentifier'
```

### Data in Transit

* Enforce TLS on all endpoints - no HTTP
* Use ACM (AWS Certificate Manager), Azure Key Vault, or GCP Certificate Manager for certificate management
* Set minimum TLS version to 1.2, prefer 1.3
* Disable weak cipher suites on load balancers and API gateways

```bash theme={null}
# AWS - Check ALB listeners for HTTP (non-HTTPS)
aws elbv2 describe-listeners \
  --query 'Listeners[?Protocol==`HTTP`].{ARN:ListenerArn, Port:Port}'

# Enforce HTTPS-only on an ALB by adding a redirect rule
aws elbv2 create-rule \
  --listener-arn YOUR_HTTP_LISTENER_ARN \
  --conditions Field=path-pattern,Values='/*' \
  --priority 1 \
  --actions Type=redirect,RedirectConfig='{Protocol=HTTPS,Port=443,StatusCode=HTTP_301}'
```

## Posture Management and Scanning Tools

These tools continuously scan your cloud environment for misconfigurations:

### CSPM (Cloud Security Posture Management)

| Tool                             | Type        | What it covers                                                    |
| -------------------------------- | ----------- | ----------------------------------------------------------------- |
| **Prowler**                      | Open-source | AWS, Azure, GCP - comprehensive checks against CIS, NIST, SOC 2   |
| **ScoutSuite**                   | Open-source | Multi-cloud security auditing                                     |
| **CloudSploit**                  | Open-source | AWS, Azure, GCP, Oracle misconfiguration scanner                  |
| **Steampipe**                    | Open-source | SQL-based cloud security queries across providers                 |
| **Wiz**                          | Commercial  | Deep CNAPP - graph-based risk analysis, widely used in enterprise |
| **Orca Security**                | Commercial  | Agentless cloud security platform                                 |
| **Lacework**                     | Commercial  | Behavior-based anomaly detection + posture                        |
| **AWS Security Hub**             | Native      | AWS-native aggregation of security findings                       |
| **Microsoft Defender for Cloud** | Native      | Azure-native CSPM + workload protection                           |

### Quick Audit with Prowler

```bash theme={null}
# Install Prowler
pip install prowler

# Run against AWS with CIS benchmark
prowler aws --compliance cis_level1_aws

# Run against specific checks
prowler aws --checks s3_bucket_public_access_block

# Output to HTML report
prowler aws --output-formats html --output-directory ./prowler-results
```

## Container and Kubernetes Security

If you're running containers in the cloud, they need their own hardening layer:

```bash theme={null}
# Scan container images for vulnerabilities before pushing
trivy image your-image:tag

# Scan a Kubernetes cluster for misconfigurations
trivy k8s --report all cluster

# Run kube-bench to check CIS Kubernetes benchmark compliance
kubectl apply -f https://raw.githubusercontent.com/aquasecurity/kube-bench/main/job.yaml
kubectl logs job.batch/kube-bench
```

**Key Kubernetes hardening points:**

* Enable RBAC - restrict what service accounts can do
* Use namespaces to isolate workloads
* Apply PodSecurity standards - prevent privileged containers, host namespace usage
* Enable audit logging on the API server
* Use network policies to restrict pod-to-pod communication
* Never run containers as root unless absolutely necessary
* Scan images in CI/CD before they reach production

## CI/CD and Secrets Management

Code pipelines that have cloud credentials are extremely high-value targets:

```bash theme={null}
# Never hardcode credentials in code or pipelines
# BAD:
AWS_ACCESS_KEY_ID=AKIA...
AWS_SECRET_ACCESS_KEY=abc123...

# GOOD: Use IAM roles for EC2/Lambda, OIDC for GitHub Actions/GitLab CI
```

For secrets management:

* **AWS Secrets Manager / Parameter Store** - managed secrets with automatic rotation
* **Azure Key Vault** - certificate, key, and secret management
* **GCP Secret Manager** - similar to AWS Secrets Manager
* **HashiCorp Vault** - open-source, cloud-agnostic secrets management (popular in multi-cloud)

```bash theme={null}
# AWS - Retrieve a secret at runtime (not at deploy time)
aws secretsmanager get-secret-value --secret-id my-db-password

# Rotate a secret
aws secretsmanager rotate-secret --secret-id my-db-password
```

**Scan your code and git history for leaked secrets:**

```bash theme={null}
# Detect secrets in code
pip install detect-secrets
detect-secrets scan --all-files > .secrets.baseline

# Scan git history for leaked credentials
trufflehog git https://github.com/your-org/your-repo
```

## Quick Win Checklist

* [ ] Enable MFA on the root/global admin account - do this first
* [ ] Delete or deactivate root access keys (AWS)
* [ ] Enable CloudTrail / Activity Logs / Cloud Audit Logs in all regions
* [ ] Enable GuardDuty / Defender for Cloud / Security Command Center
* [ ] Block public access to all S3 buckets / Blob storage at account level
* [ ] Audit security groups - remove 0.0.0.0/0 on SSH and RDP
* [ ] Enable VPC Flow Logs
* [ ] Enforce EBS/disk encryption by default
* [ ] Review IAM roles/policies - remove wildcard permissions
* [ ] Run Prowler or ScoutSuite against your environment and fix Level 1 findings
* [ ] Enable automatic secret rotation where supported
* [ ] Scan container images for known vulnerabilities in CI/CD

## Reference

* [Prowler](https://github.com/prowler-cloud/prowler) - Open-source cloud security scanner
* [ScoutSuite](https://github.com/nccgroup/ScoutSuite) - Multi-cloud auditing
* [AWS Security Best Practices](https://aws.amazon.com/architecture/security-identity-compliance/)
* [CIS AWS Foundations Benchmark](https://www.cisecurity.org/benchmark/amazon_web_services)
* [GCP Security Best Practices](https://cloud.google.com/security/best-practices)
* [Microsoft Cloud Security Benchmark](https://aka.ms/azsecbm)
* [Trivy](https://trivy.dev/) - Container and IaC scanner
* [truffleHog](https://github.com/trufflesecurity/trufflehog) - Secret scanning in git history

***

*Cloud security misconfigurations are the new open port. The tools to find them are free, the fixes are usually configuration changes, and the impact of getting it wrong is a publicly accessible S3 bucket on the front page of the news.*
