cloud · temario
6.16tema 16 de 16

Seguridad en la nube

VPC, Secrets Manager, KMS y least privilege

Seguridad en AWS es defensa en profundidad. La capa más baja es VPC (Virtual Private Cloud): tu propia red aislada del internet. Dentro de la VPC definas subnets (público/privado), security groups (firewall por instancia), network ACLs (firewall por subnet). Una base de datos en subnet privada no tiene internet directo; acceso solo desde aplicaciones en subnet público que pasan por NAT Gateway.

IAM (Identity Access Management) es control de permisos granular. Una función Lambda no necesita acceso a S3 completo ('s3:*'); necesita solo 's3:GetObject' en un bucket específico. El principio de least privilege: cada identidad (usuario, rol, función) tiene SOLO los permisos que necesita, nada más. Una Lambda mal configurada puede exfiltrar todo S3; una bien configurada puede solo leer/escribir su bucket asignado.

Secrets Manager guarda credenciales (API keys, contraseñas DB, tokens) encriptadas. En lugar de hardcodear 'password123' en código, guardas el secret en Secrets Manager y el código hace GetSecretValue() en runtime. Secrets Managers rota credenciales automáticamente (para bases de datos): cada 30 días genera una nueva contraseña sin apagones. Tus aplicaciones siempre usan la versión actual.

KMS (Key Management Service) encripta datos en reposo. Un S3 bucket con SSE-KMS encripta cada objeto con una clave maestra. Si alguien roba un disco duro del data center, los datos están inservibles sin la clave. Logs en CloudWatch pueden encriptarse con KMS. Una DynamoDB puede estar encriptada. El principio: TODO datos sensibles encriptados.

Network seguridad empieza en VPC. Subnets públicas contienen NAT Gateway y Application Load Balancer (acepta internet). Subnets privadas contienen Lambda, RDS, DynamoDB (sin internet directo). Si una Lambda necesita hablar a una API externa, pasa por NAT Gateway (outbound). Si un atacante compromete la Lambda, no puede llegar a la DB sin pasar por security groups.

Los errores comunes son: (1) hardcodear credenciales en código (enviadas a git, leídas en logs), (2) no encriptar datos en reposo (robo físico = total compromise), (3) IAM sobre-permisivo (una Lambda puede leer/escribir TODO S3), (4) security groups abiertos (5432 abierto a 0.0.0.0 = internet accede a base de datos), (5) no usar VPC (recursos en internet público, accesibles a bots de escaneo).

structure.txt
# === AWS VPC & Network Security ===

import boto3

ec2 = boto3.client('ec2')

# === 1. CREATE VPC ===
vpc_response = ec2.create_vpc(
    CidrBlock='10.0.0.0/16'  # private IP range
)
vpc_id = vpc_response['Vpc']['VpcId']

# === 2. CREATE SUBNETS ===

# Public subnet (0.0.0.0/0 can reach it via NAT)
public_subnet = ec2.create_subnet(
    VpcId=vpc_id,
    CidrBlock='10.0.1.0/24',  # 256 IPs
    AvailabilityZone='us-east-1a'
)

# Private subnet (no internet access)
private_subnet = ec2.create_subnet(
    VpcId=vpc_id,
    CidrBlock='10.0.2.0/24',
    AvailabilityZone='us-east-1b'
)

# === 3. SECURITY GROUP (firewall by instance) ===

# Security group for RDS (allows only from app)
db_sg = ec2.create_security_group(
    GroupName='rds-sg',
    Description='Allow PostgreSQL from app only',
    VpcId=vpc_id
)

# Inbound: allow TCP 5432 only from app security group
ec2.authorize_security_group_ingress(
    GroupId=db_sg['GroupId'],
    IpPermissions=[
        {
            'IpProtocol': 'tcp',
            'FromPort': 5432,
            'ToPort': 5432,
            'UserIdGroupPairs': [{'GroupId': 'sg-app-id', 'Description': 'From app'}]
        }
    ]
)

# Outbound: deny all (default allow, so restrict if needed)
ec2.revoke_security_group_egress(
    GroupId=db_sg['GroupId'],
    IpPermissions=[
        {'IpProtocol': '-1', 'CidrIp': '0.0.0.0/0'}  # revoke default
    ]
)

# === 4. IAM LEAST PRIVILEGE ===

iam = boto3.client('iam')

# Create role for Lambda
lambda_role = iam.create_role(
    RoleName='lambda-ml-processor',
    AssumeRolePolicyDocument=json.dumps({
        'Version': '2012-10-17',
        'Statement': [{
            'Effect': 'Allow',
            'Principal': {'Service': 'lambda.amazonaws.com'},
            'Action': 'sts:AssumeRole'
        }]
    })
)

# Attach MINIMAL permissions: read from specific S3 bucket
iam.put_role_policy(
    RoleName='lambda-ml-processor',
    PolicyName='s3-read-only',
    PolicyDocument=json.dumps({
        'Version': '2012-10-17',
        'Statement': [
            {
                'Effect': 'Allow',
                'Action': ['s3:GetObject'],  # only GetObject, NOT s3:*
                'Resource': 'arn:aws:s3:::ml-data-bucket/input/*'
            },
            {
                'Effect': 'Allow',
                'Action': ['logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:PutLogEvents'],
                'Resource': 'arn:aws:logs:*'
            }
        ]
    })
)

# === 5. SECRETS MANAGER ===

secrets = boto3.client('secretsmanager')

# Store database password
secret = secrets.create_secret(
    Name='prod/rds/password',
    SecretString=json.dumps({
        'username': 'postgres',
        'password': 'super-secret-password',
        'host': 'mydb.c9akciq32.us-east-1.rds.amazonaws.com',
        'port': 5432
    })
)

# Retrieve secret in application (never hardcode)
secret_value = secrets.get_secret_value(SecretId='prod/rds/password')
db_config = json.loads(secret_value['SecretString'])
conn = psycopg2.connect(
    host=db_config['host'],
    user=db_config['username'],
    password=db_config['password']
)

# === 6. KMS ENCRYPTION ===

kms = boto3.client('kms')

# Create master key
key = kms.create_key(
    Description='Master key for ML data encryption',
    KeyUsage='ENCRYPT_DECRYPT'
)
key_id = key['KeyMetadata']['KeyId']

# Encrypt data
plaintext = b'sensitive-model-weights'
encrypted = kms.encrypt(
    KeyId=key_id,
    Plaintext=plaintext
)
ciphertext = encrypted['CiphertextBlob']

# Decrypt (IAM must have kms:Decrypt permission)
decrypted = kms.decrypt(CiphertextBlob=ciphertext)
plaintext_recovered = decrypted['Plaintext']

# S3 SSE-KMS: objects encrypted by default
s3 = boto3.client('s3')
s3.put_bucket_encryption(
    Bucket='ml-data-bucket',
    ServerSideEncryptionConfiguration={
        'Rules': [{
            'ApplyServerSideEncryptionByDefault': {
                'SSEAlgorithm': 'aws:kms',
                'KMSMasterKeyID': key_id
            }
        }]
    }
)

# === 7. NETWORK ACL (subnet-level firewall) ===

# Allow inbound HTTP from internet on public subnet
nacl = ec2.create_network_acl(VpcId=vpc_id)
nacl_id = nacl['NetworkAcl']['NetworkAclId']

# Inbound HTTP (port 80) from 0.0.0.0/0
ec2.create_network_acl_entry(
    NetworkAclId=nacl_id,
    RuleNumber=100,
    Protocol='6',  # TCP
    PortRange={'From': 80, 'To': 80},
    CidrBlock='0.0.0.0/0',
    Egress=False,
    RuleAction='allow'
)

# === 8. AUDIT: CloudTrail ===

cloudtrail = boto3.client('cloudtrail')
cloudtrail.create_trail(
    Name='audit-trail',
    S3BucketName='audit-logs-bucket',
    IncludeGlobalServiceEvents=True
)
# CloudTrail logs all AWS API calls for audit

Katas (5)

Debugging lab

Detecta y corrige el error en el código.

0/6 tests passing0%
  1. 6.16.5.1

    # Hardcoded credentials in Lambda db_password = 'secret123' conn = psycopg2.connect(host='mydb.com', password=db_password) # Visible in code, logs, git history

  2. 6.16.5.2

    # Lambda with overly permissive IAM { 'Effect': 'Allow', 'Action': 's3:*', # access ALL S3 actions 'Resource': '*' # access ALL resources } # If Lambda is compromised, attacker can delete any S3 bucket

  3. 6.16.5.3

    # Database security group open to internet ec2.authorize_security_group_ingress( GroupId='sg-db', IpPermissions=[{ 'IpProtocol': 'tcp', 'FromPort': 5432, 'ToPort': 5432, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}] # anyone can connect! }] )

  4. 6.16.5.4

    # S3 bucket without encryption s3.create_bucket(Bucket='ml-data') # Objects stored in plaintext

  5. 6.16.5.5

    # All resources in public subnet vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16') subnet = ec2.create_subnet(VpcId=vpc, CidrBlock='10.0.1.0/24') # RDS, Lambda in public subnet = accessible from internet

  6. 6.16.5.6

    # Rotate secrets manually # Admin changes password in RDS, must update 5 applications manually