TExcelTAD
Home › AWS Cloud › KMS, Shield, WAF and GuardDuty

KMS, Shield, WAF and GuardDuty

Beyond IAM, AWS offers a toolbox of managed security services. This lesson covers the four you meet most often, plus a quick map of the rest.

Service Protects against / provides
AWS KMS (Key Management Service) Creating and controlling encryption keys; used by S3, EBS, RDS and most other services
AWS Shield DDoS attacks. Standard is automatic and free; Advanced adds response team, cost protection, more visibility
AWS WAF (Web Application Firewall) Malicious HTTP requests (SQL injection, XSS, bots, floods) on CloudFront, ALB, API Gateway
Amazon GuardDuty Threat detection: analyses CloudTrail, VPC Flow Logs and DNS logs for suspicious activity
AWS Secrets Manager Storing and rotating database passwords and API keys
AWS Certificate Manager (ACM) Free public TLS certificates, auto-renewed
Amazon Inspector Vulnerability scanning of EC2, container images and Lambda
Amazon Macie Finding sensitive data (PII) in S3
AWS Security Hub One dashboard of findings and best-practice checks

AWS KMS and envelope encryption

KMS keys never leave KMS unencrypted. To encrypt large data, services use envelope encryption:

  1. Ask KMS for a data key: you get it in plaintext and encrypted under your KMS key.
  2. Encrypt the data locally with the plaintext data key, then throw the plaintext key away.
  3. Store the encrypted data together with the encrypted data key.
  4. To decrypt, send the encrypted data key to KMS (which checks IAM and the key policy), get the plaintext key back, decrypt locally.
bash
aws kms create-key --description "tad reports key"
aws kms generate-data-key --key-id alias/tad-reports --key-spec AES_256

Sample output (shortened):

text
{
    "CiphertextBlob": "AQIDAHhBQ...encrypted data key...",
    "Plaintext": "VdzKNHGzUAzJeRBVY+uUmofUGGiDzyB3+i9fVkh3piw=",
    "KeyId": "arn:aws:kms:eu-west-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab"
}

The model below shows the flow of envelope encryption. It uses a toy XOR cipher built from SHA-256 so it runs with the standard library only. Never use a toy cipher for real data; real code uses AES-GCM through a vetted library or the AWS Encryption SDK.

python · try it yourself
import hashlib

def keystream_xor(key, data):              # TOY cipher for illustration only
    out, counter = bytearray(), 0
    while len(out) < len(data):
        out += hashlib.sha256(key + counter.to_bytes(4, "big")).digest()
        counter += 1
    return bytes(a ^ b for a, b in zip(data, out))

class ToyKMS:
    def __init__(self):
        self._root_keys = {"alias/tad-reports": hashlib.sha256(b"root key kept inside KMS").digest()}
        self.calls = []
    def generate_data_key(self, key_id, seed):
        plaintext = hashlib.sha256(seed).digest()
        encrypted = keystream_xor(self._root_keys[key_id], plaintext)
        self.calls.append("GenerateDataKey")
        return plaintext, encrypted
    def decrypt(self, key_id, encrypted_key, caller_allowed):
        self.calls.append("Decrypt")
        if not caller_allowed:
            raise PermissionError("AccessDeniedException: not allowed by key policy")
        return keystream_xor(self._root_keys[key_id], encrypted_key)

kms = ToyKMS()
report = b"Q1 revenue: 1,234,567 EUR"

data_key, encrypted_data_key = kms.generate_data_key("alias/tad-reports", seed=b"demo-seed-1")
ciphertext = keystream_xor(data_key, report)
del data_key                                   # never store the plaintext key
stored = {"ciphertext": ciphertext.hex()[:24] + "...", "encrypted_key": encrypted_data_key.hex()[:16] + "..."}
print("stored:", stored)

key = kms.decrypt("alias/tad-reports", encrypted_data_key, caller_allowed=True)
print("decrypted:", keystream_xor(key, ciphertext).decode())
try:
    kms.decrypt("alias/tad-reports", encrypted_data_key, caller_allowed=False)
except PermissionError as e:
    print("other user:", e)
print("KMS calls:", kms.calls)
stored: {'ciphertext': 'e01a2dd890e68db59d74a94f...', 'encrypted_key': '278794936abd6e26...'}
decrypted: Q1 revenue: 1,234,567 EUR
other user: AccessDeniedException: not allowed by key policy
KMS calls: ['GenerateDataKey', 'Decrypt', 'Decrypt']

Two benefits: large data never travels to KMS (only a 32-byte key does), and every decrypt is an API call checked by IAM and logged in CloudTrail.

AWS WAF

A web ACL holds rules evaluated in priority order. Rules can match IP sets, geographic origin, headers, body patterns (SQL injection, XSS), or rate-based limits per IP. AWS and Marketplace sellers provide managed rule groups (e.g. the core rule set, known bad inputs, bot control).

python · try it yourself
import re

rules = [   # (priority, name, test, action)
    (0, "block-bad-ips", lambda r: r["ip"] in {"203.0.113.66"}, "BLOCK"),
    (1, "sql-injection", lambda r: re.search(r"(?i)('|%27)\s*(or|union)\b|--", r["query"]) is not None, "BLOCK"),
    (2, "rate-limit", lambda r: r["requests_last_5min"] > 2000, "BLOCK"),
    (3, "admin-only-from-office", lambda r: r["path"].startswith("/admin") and not r["ip"].startswith("198.51.100."), "BLOCK"),
]

def web_acl(request, default="ALLOW"):
    for _prio, name, test, action in sorted(rules, key=lambda x: x[0]):
        if test(request):
            return f"{action} by {name}"
    return f"{default} (default action)"

traffic = [
    {"ip": "192.0.2.4",    "path": "/products", "query": "id=7",            "requests_last_5min": 40},
    {"ip": "192.0.2.5",    "path": "/products", "query": "id=7' OR 1=1 --", "requests_last_5min": 3},
    {"ip": "203.0.113.66", "path": "/",         "query": "",                "requests_last_5min": 1},
    {"ip": "192.0.2.9",    "path": "/search",   "query": "q=shoes",         "requests_last_5min": 5000},
    {"ip": "192.0.2.4",    "path": "/admin",    "query": "",                "requests_last_5min": 41},
    {"ip": "198.51.100.8", "path": "/admin",    "query": "",                "requests_last_5min": 12},
]
for r in traffic:
    print(f"{r['ip']:<13} {r['path'] + ('?' + r['query'] if r['query'] else ''):<26} {web_acl(r)}")
192.0.2.4     /products?id=7             ALLOW (default action)
192.0.2.5     /products?id=7' OR 1=1 --  BLOCK by sql-injection
203.0.113.66  /                          BLOCK by block-bad-ips
192.0.2.9     /search?q=shoes            BLOCK by rate-limit
192.0.2.4     /admin                     BLOCK by admin-only-from-office
198.51.100.8  /admin                     ALLOW (default action)

Shield and GuardDuty

  • Shield Standard protects every AWS customer from common network and transport layer DDoS attacks at no cost. Shield Advanced (paid) adds protection for EC2, ELB, CloudFront, Route 53 and Global Accelerator, a 24/7 response team, and credits for scaling costs caused by attacks.
  • GuardDuty is enabled with one click and produces findings such as UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration (credentials from an EC2 role used outside AWS) or CryptoCurrency:EC2/BitcoinTool.B!DNS (an instance talking to mining pools). Findings can trigger EventBridge rules for automatic response.

Test yourself

In envelope encryption, what is stored next to the encrypted data?

  1. The plaintext data key
  2. The KMS root key
  3. The data key encrypted under the KMS key
  4. Nothing

Which service blocks SQL-injection patterns in HTTP requests to an ALB?

  1. AWS Shield Standard
  2. AWS WAF
  3. Amazon GuardDuty
  4. AWS KMS

Which service analyses CloudTrail, VPC Flow Logs and DNS logs to detect threats?

  1. Amazon Inspector
  2. Amazon GuardDuty
  3. AWS Config
  4. Amazon Macie