Sub topic 7
Encrypting data at rest and in transit
This chapter assumes you can create an RDS instance (see the provisioning chapter), use the AWS CLI, and know what a KMS key is at a basic level. It covers two separate protections. Encryption at rest protects the storage underneath the database. Encryption in transit protects the network connection between your client and the database. They use different mechanisms and are configured in different places.
Encryption at rest
RDS encryption at rest uses AES-256 with keys managed by AWS Key Management Service (KMS). When you enable it, RDS encrypts:
- the DB instance's storage volumes
- automated backups and manual snapshots
- read replicas
- the Multi-AZ standby copy
- transaction and other logs stored on those volumes
Encryption and decryption happen in the storage layer, so your SQL, drivers, and application code do not change. For current instance classes the performance effect is small. You do not need to plan capacity around it.
Choosing a KMS key
You pick one of two kinds of key.
| Key type | How you select it | Control you get |
|---|---|---|
| AWS managed key `aws/rds` | Default when you set only `--storage-encrypted` | AWS creates and rotates it. You cannot edit its key policy. |
| Customer managed key | Pass `--kms-key-id` | You control the key policy, grants, rotation settings, and can disable the key. |
Use a customer managed key when you need to share encrypted snapshots with another account, or when your policies require you to control or audit key usage. Snapshots encrypted with aws/rds cannot be shared with other accounts, because the other account cannot be granted access to that key.
Create an encrypted instance with a specific key by adding two flags to the creation command from the provisioning chapter:
aws rds create-db-instance \
--db-instance-identifier demo-pg \
--engine postgres \
--db-instance-class db.t4g.micro \
--allocated-storage 20 \
--storage-type gp3 \
--master-username appadmin \
--manage-master-user-password \
--db-subnet-group-name demo-subnets \
--vpc-security-group-ids sg-0123456789abcdef0 \
--no-publicly-accessible \
--storage-encrypted \
--kms-key-id alias/rds-demo \
--backup-retention-period 7The alias alias/rds-demo is a placeholder. You can also pass a key ID or key ARN. If the key is in a different account, use the full ARN.
Rules you cannot work around
- You choose encryption when you create the instance. You cannot turn it on or off for an existing instance.
- You cannot change the KMS key of an existing instance.
- A read replica of an encrypted instance is always encrypted. In the same Region it uses the source's key. For a cross-Region replica you must supply a key that exists in the destination Region.
- A snapshot of an encrypted instance is encrypted, and an instance restored from it is encrypted.
- If RDS loses access to the key, for example because it was disabled or its key policy was changed, the instance moves to the
inaccessible-encryption-credentialsstate and becomes unavailable until access is restored.
The last rule is the one that causes outages. Treat key deletion and key policy edits as production changes. KMS enforces a waiting period of 7 to 30 days before it deletes a key, which gives you time to notice.
Verifying encryption
Check the attributes on the instance rather than assuming:
import boto3
rds = boto3.client("rds")
for db in rds.describe_db_instances()["DBInstances"]:
name = db["DBInstanceIdentifier"]
encrypted = db["StorageEncrypted"]
key = db.get("KmsKeyId", "none")
print(f"{name}: encrypted={encrypted} key={key}")
if not encrypted:
print(f" WARNING: {name} is not encrypted at rest")This script lists every instance in the current Region and flags the unencrypted ones. It paginates nothing, which is fine for small accounts. For large accounts, use a paginator.
Encrypting an existing unencrypted instance
Because you cannot encrypt in place, you copy through a snapshot. The encrypted copy becomes a new instance with a new endpoint.
placeholderReplace that placeholder with the diagram below, which shows the real flow.
The commands:
aws rds create-db-snapshot \
--db-instance-identifier demo-old \
--db-snapshot-identifier demo-old-snap
aws rds wait db-snapshot-available \
--db-snapshot-identifier demo-old-snap
aws rds copy-db-snapshot \
--source-db-snapshot-identifier demo-old-snap \
--target-db-snapshot-identifier demo-old-snap-enc \
--kms-key-id alias/rds-demo
aws rds wait db-snapshot-available \
--db-snapshot-identifier demo-old-snap-enc
aws rds restore-db-instance-from-db-snapshot \
--db-instance-identifier demo-new \
--db-snapshot-identifier demo-old-snap-encWrites made to the old instance after the snapshot are not in the copy. For a live system, stop writes before the snapshot or plan a cutover, for example with a migration tool that replicates changes. Also re-apply settings that a restore does not carry over, such as the security groups, parameter group, and backup retention, by passing them to the restore command or modifying the instance afterward.
Encryption in transit
TLS (Transport Layer Security) encrypts traffic between client and database. RDS instances present a server certificate signed by an Amazon RDS certificate authority (CA). TLS support is available on every engine, but whether it is required depends on your configuration.
Two separate questions
Encrypting the connection and authenticating the server are different things.
- Encryption means the traffic cannot be read on the network.
- Server verification means the client checks that the certificate was issued by the RDS CA and that the hostname matches. Without it, an attacker who can intercept the connection could present their own certificate.
For PostgreSQL, the client's sslmode setting controls this:
| `sslmode` | Encrypts | Verifies CA | Verifies hostname |
|---|---|---|---|
| `disable` | No | No | No |
| `prefer` (default) | If server offers it | No | No |
| `require` | Yes | No | No |
| `verify-ca` | Yes | Yes | No |
| `verify-full` | Yes | Yes | Yes |
Use verify-full in production. Download the RDS CA bundle first:
curl -o global-bundle.pem https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem
psql "host=demo-pg.example.us-east-1.rds.amazonaws.com port=5432 dbname=postgres user=appadmin sslmode=verify-full sslrootcert=global-bundle.pem"The hostname is a placeholder for your instance endpoint. Once connected, confirm the session is encrypted:
SELECT ssl, version, cipher FROM pg_stat_ssl WHERE pid = pg_backend_pid();ssl should be t. MySQL and MariaDB clients use equivalent options. For MySQL, pass --ssl-mode=VERIFY_IDENTITY and --ssl-ca=global-bundle.pem.
Requiring TLS on the server
Client settings only protect clients that set them. To reject unencrypted connections for everyone, set an engine parameter in a custom parameter group (covered in the parameter group chapter):
| Engine | Parameter | Value |
|---|---|---|
| PostgreSQL | `rds.force_ssl` | `1` |
| MySQL | `require_secure_transport` | `ON` |
| MariaDB | `require_secure_transport` | `ON` |
aws rds modify-db-parameter-group \
--db-parameter-group-name demo-pg16 \
--parameters "ParameterName=rds.force_ssl,ParameterValue=1,ApplyMethod=immediate"Recent PostgreSQL major versions enable rds.force_ssl by default, but check your version's default group rather than relying on memory. Check each parameter's apply type in your engine's documentation, since some parameters need a reboot.
Certificate rotation
RDS server certificates expire, and AWS periodically introduces new CA certificates. Each instance has a CA identifier (CACertificateIdentifier) that you can read with describe-db-instances and change with modify-db-instance --ca-certificate-identifier. Clients that verify certificates must trust the CA the instance uses. The global-bundle.pem file contains the certificates for all Regions, so shipping the current bundle with your application and refreshing it periodically avoids most rotation failures.
Common errors:
certificate verify failedorSSL error: unable to get local issuer certificate: the client does not have the CA bundle, or it has an outdated one.server certificate for "..." does not match host name: you connected through an IP address or a CNAME that is not the RDS endpoint, while usingverify-full. Connect with the endpoint name.no pg_hba.conf entry ... no encryption: the server requires TLS and the client did not use it.
Exercises
Exercise
An existing unencrypted RDS instance must become encrypted with a customer managed KMS key. Why can't you run modify-db-instance to do it, and what sequence of operations achieves it?
Show answer
Encryption at rest can only be chosen when an instance is created, so an existing instance cannot be modified to enable it. Create a snapshot of the instance, copy the snapshot with --kms-key-id to produce an encrypted snapshot, and restore that snapshot as a new instance. Then move the application to the new endpoint and delete the old instance.
Exercise
A developer connects to PostgreSQL with sslmode=require. The traffic is encrypted. What risk remains, and which setting removes it?
Show answer
require does not check the server certificate, so a machine that intercepts the connection could present its own certificate and the client would accept it. Using sslmode=verify-full with sslrootcert set to the RDS CA bundle makes the client verify both the certificate chain and the hostname.