Sub topic 19
Encrypting queues and topics
This chapter assumes you can create SQS queues and SNS topics and subscribe a queue to a topic, as covered in the earlier chapters. You should also know what an IAM policy and a KMS key are. The examples use Python with boto3.
Two kinds of protection
Messaging data can be exposed in two places.
- In transit: the bytes travel between your code and the service, and between SNS and SQS.
- At rest: the service stores the message on disk until a consumer deletes it or retention expires.
AWS handles transit encryption through HTTPS endpoints. At-rest encryption is a setting you choose per queue or topic. The sections below cover each case and the permission problems that appear when you combine encrypted topics and queues.
Encryption in transit
SQS and SNS expose HTTPS endpoints, and the AWS SDKs use them by default. Both services also accept plain HTTP on their public endpoints, so a misconfigured client can still send unencrypted traffic. To refuse it, add a Deny statement that checks the aws:SecureTransport condition key in the resource policy.
For SNS-to-SQS delivery inside AWS, SNS calls the SQS API over HTTPS. For HTTP/S subscriptions, use an https:// endpoint so SNS delivers over TLS.
Encryption at rest in SQS
SQS offers three options.
| Option | Key owner | Cost | Notes |
|---|---|---|---|
| SSE-SQS (`SqsManagedSseEnabled`) | SQS | No charge | Default for new queues. No key to manage and no KMS permissions needed. |
| SSE-KMS with `alias/aws/sqs` | AWS managed key | KMS request charges | You cannot edit the key policy, so SNS and some other services cannot use it. |
| SSE-KMS with a customer managed key | You | KMS key and request charges | You control the key policy, rotation, and audit trail in CloudTrail. |
Some behaviors apply to all of them.
- SQS encrypts the message body when it receives the message. Messages already in the queue before you turn on encryption stay unencrypted.
- Message attributes are not encrypted by SSE-KMS, and neither is queue metadata such as the queue name. Do not put secrets in attributes.
- A queue uses either SSE-SQS or SSE-KMS. Setting
SqsManagedSseEnabledandKmsMasterKeyIdtogether is an error. - FIFO and standard queues support the same options.
SSE-KMS and the data key reuse period
With SSE-KMS, SQS asks KMS for a data key and reuses it for a period before asking again. KmsDataKeyReusePeriodSeconds sets that period, from 60 seconds to 86,400 seconds (24 hours). The default is 300 seconds.
A longer period means fewer KMS calls, which lowers cost and avoids KMS throttling on busy queues. A shorter period limits how long one data key stays in use.
Encryption at rest in SNS
SNS topics support SSE-KMS through the KmsMasterKeyId attribute. SNS encrypts the message as it arrives and decrypts it only while delivering to subscribers. Subscribers receive plain content, so the subscriber's own endpoint must protect it. An encrypted topic delivering to an unencrypted queue leaves the message unencrypted in that queue.
Who needs which KMS permissions
Encryption adds an extra permission check on top of the SQS or SNS policies. This is where most failures happen.
- Producer to an encrypted queue: the sender needs
kms:GenerateDataKeyandkms:Decrypton the key. - Consumer from an encrypted queue: the receiver needs
kms:Decrypt. For Lambda, add this to the function's execution role. - SNS publisher to an encrypted topic: the publishing principal needs
kms:GenerateDataKey*andkms:Decrypton the topic's key. - SNS to an encrypted queue: the queue's key policy must let the
sns.amazonaws.comservice principal callkms:GenerateDataKey*andkms:Decrypt. This is why the AWS managed keyalias/aws/sqsfails here. You cannot add that statement to its policy.
Example: an encrypted topic and queue
This script creates a customer managed key and adds a key policy statement for SNS. It creates an encrypted queue and topic, then sets a queue policy that allows only that topic and requires TLS.
import json
import boto3
kms = boto3.client("kms")
sqs = boto3.client("sqs")
sns = boto3.client("sns")
# Customer managed key; the default key policy delegates to IAM
key_id = kms.create_key(Description="orders messaging key")["KeyMetadata"]["KeyId"]
# Let SNS use the key so it can write to the encrypted queue
policy = json.loads(kms.get_key_policy(KeyId=key_id, PolicyName="default")["Policy"])
policy["Statement"].append({
"Sid": "AllowSnsToUseKey",
"Effect": "Allow",
"Principal": {"Service": "sns.amazonaws.com"},
"Action": ["kms:GenerateDataKey*", "kms:Decrypt"],
"Resource": "*",
})
kms.put_key_policy(KeyId=key_id, PolicyName="default", Policy=json.dumps(policy))
# Encrypted queue; reuse each data key for 5 minutes
queue_url = sqs.create_queue(
QueueName="orders-secure",
Attributes={
"KmsMasterKeyId": key_id,
"KmsDataKeyReusePeriodSeconds": "300",
},
)["QueueUrl"]
queue_arn = sqs.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
# Encrypted topic
topic_arn = sns.create_topic(
Name="order-events-secure",
Attributes={"KmsMasterKeyId": key_id},
)["TopicArn"]
# One queue policy: allow only this topic, deny any non-TLS request
queue_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowTopic",
"Effect": "Allow",
"Principal": {"Service": "sns.amazonaws.com"},
"Action": "sqs:SendMessage",
"Resource": queue_arn,
"Condition": {"ArnEquals": {"aws:SourceArn": topic_arn}},
},
{
"Sid": "DenyInsecureTransport",
"Effect": "Deny",
"Principal": "*",
"Action": "sqs:*",
"Resource": queue_arn,
"Condition": {"Bool": {"aws:SecureTransport": "false"}},
},
],
}
sqs.set_queue_attributes(
QueueUrl=queue_url, Attributes={"Policy": json.dumps(queue_policy)}
)
sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=queue_arn)
print("Ready:", topic_arn, "->", queue_arn)set_queue_attributes replaces the whole policy. Put every statement the queue needs into one document, as the script does.
Common errors
KMS.AccessDeniedExceptionon send or receive: the caller's IAM policy or the key policy lackskms:GenerateDataKeyorkms:Decrypt. Check both, because a KMS grant needs permission on the identity side and the key side.- Publishes succeed but the queue stays empty: the queue's key policy does not let
sns.amazonaws.comuse the key. The usual cause isalias/aws/sqs. Switch the queue to a customer managed key, or to SSE-SQS if you do not need your own key. - Lambda event source mapping fails or messages stay in flight: the function's execution role cannot call
kms:Decrypton the queue's key. - Cross-account use: the key policy must trust the other account, and the other account's IAM policy must also allow the KMS actions.
- Unexpected KMS cost or throttling: raise
KmsDataKeyReusePeriodSeconds, or use SSE-SQS if you have no key-control requirement.
Exercise
A topic and a queue both use SSE-KMS with the AWS managed key alias/aws/sqs for the queue. Publishes to the topic succeed, but the subscribed queue receives nothing. What is the likely cause, and what are two fixes?
Show answer
SNS cannot use alias/aws/sqs to encrypt messages for the queue, because you cannot add a statement to an AWS managed key's policy to allow sns.amazonaws.com. Fix 1: use a customer managed KMS key for the queue and add a key policy statement allowing sns.amazonaws.com to call kms:GenerateDataKey* and kms:Decrypt. Fix 2: use SSE-SQS on the queue, which needs no KMS permissions.
Exercise
Which statement in a queue policy forces all clients to use TLS, and which condition key does it test?
Show answer
A Deny statement for sqs: with Principal "" and the condition {"Bool": {"aws:SecureTransport": "false"}}. It rejects any request made over plain HTTP.