> ## Documentation Index
> Fetch the complete documentation index at: https://guide.codepure.com/llms.txt
> Use this file to discover all available pages before exploring further.

# AWS Credentials Exposure

> Detecting and preventing AWS access keys and secrets in code

## Common Misconfiguration

AWS credentials hardcoded in source code expose your entire AWS infrastructure to unauthorized access.

### Vulnerable Example

```python theme={null}
# VULNERABLE - Hardcoded AWS credentials
import boto3

# Never do this!
AWS_ACCESS_KEY_ID = "AKIAIOSFODNN7EXAMPLE"
AWS_SECRET_ACCESS_KEY = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
AWS_SESSION_TOKEN = "AQoDYXdzEJr...EXAMPLETOKEN"

s3_client = boto3.client(
    's3',
    aws_access_key_id=AWS_ACCESS_KEY_ID,
    aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
    aws_session_token=AWS_SESSION_TOKEN
)

# Hardcoded RDS password
rds_connection = {
    "host": "mydb.123456789012.us-east-1.rds.amazonaws.com",
    "password": "MyRDSPassword123!",
    "user": "admin",
    "database": "production"
}
```

## Secure Example

```python theme={null}
# SECURE - Using environment variables and IAM roles
import boto3
import os
import json

# Use IAM roles when running on EC2/ECS/Lambda
# Boto3 automatically finds credentials from the instance metadata
s3_client_iam = boto3.client('s3')

# Or use environment variables for local development
# These are set in the shell, NOT in the code
s3_client_env = boto3.client(
    's3',
    aws_access_key_id=os.environ.get('AWS_ACCESS_KEY_ID'),
    aws_secret_access_key=os.environ.get('AWS_SECRET_ACCESS_KEY')
)

# Use AWS Secrets Manager for RDS passwords
def get_rds_credentials():
    secret_name = "prod/rds/credentials"
    secrets_client = boto3.client('secretsmanager')
    try:
        response = secrets_client.get_secret_value(SecretId=secret_name)
        return json.loads(response['SecretString'])
    except Exception as e:
        print(f"Error retrieving secret: {e}")
        return None

rds_connection = get_rds_credentials()
```

## Detection Patterns

* AWS Access Key ID: `(AKIA|ASIA)[0-9A-Z]{16}`
* AWS Secret Access Key: `[A-Za-z0-9/+=]{40}`
* AWS Session Token Prefix: `FwoGZXIvYXdzE[0-9a-zA-Z/+=]+`

## Prevention Best Practices

1. **Use IAM Roles:** Always prefer IAM roles for applications running on EC2, ECS, EKS, and Lambda.

2. **Use Secrets Manager:** Store database credentials, API keys, and other secrets in AWS Secrets Manager or Parameter Store.

3. **Use Temporary Credentials:** For local development or CI/CD, use AWS STS to generate temporary, short-lived credentials.

4. **Least Privilege:** Ensure IAM roles and users have the absolute minimum permissions necessary (e.g., read-only access to a specific S3 bucket).

5. **Enable MFA:** Require Multi-Factor Authentication for all human users.

6. **Rotate Credentials:** Regularly rotate all long-lived access keys.
