Sub topic 13
Auditing key use with CloudTrail
This chapter assumes you have created a customer managed key, called Encrypt, Decrypt, and GenerateDataKey, and read a key policy. You should also know what a CloudTrail trail is, at least roughly. Here you learn what KMS records about each use of a key, how to query those records, and how to alert on risky operations.
What KMS writes to CloudTrail
AWS KMS records every API call to CloudTrail as a management event. This covers administrative calls such as CreateKey, PutKeyPolicy, DisableKey and ScheduleKeyDeletion. It also covers cryptographic calls such as Encrypt, Decrypt, GenerateDataKey and CreateGrant. You cannot turn this logging off, and you do not need to configure KMS to get it.
The records answer four questions:
- Who: the
userIdentityblock names the IAM user or assumed role. When an AWS service acts for you, the type isAWSServiceandinvokedBynames the service, for examples3.amazonaws.com. - What:
eventNameandrequestParameters, including the key ID and the encryption context. - Which key: the
resourceslist holds the full key ARN. - Outcome: a failed call carries
errorCodeanderrorMessage.
CloudTrail never records plaintext, data keys, or key material.
{
"eventSource": "kms.amazonaws.com",
"eventName": "Decrypt",
"awsRegion": "us-east-1",
"userIdentity": {
"type": "AssumedRole",
"arn": "arn:aws:sts::111122223333:assumed-role/app-role/i-0abc123"
},
"requestParameters": {
"encryptionContext": { "purpose": "demo" },
"encryptionAlgorithm": "SYMMETRIC_DEFAULT"
},
"resources": [
{
"accountId": "111122223333",
"type": "AWS::KMS::Key",
"ARN": "arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
}
]
}This is a trimmed event. Real events add fields such as eventTime, sourceIPAddress and requestID.
Where the events go
There are two places to read them.
| Source | Retention | Scope | Best for |
|---|---|---|---|
| Event history | 90 days | One Region, one account | Quick investigation |
| A trail delivering to S3 (optionally CloudWatch Logs) | As long as you keep the bucket objects | All Regions, if you choose a multi-Region trail | Compliance and long-term analysis |
KMS events are logged in the Region where the key lives. If you use Multi-Region keys, each replica logs in its own Region. A trail that covers only one Region will miss those calls.
When a principal in one account uses a key in another account, the event appears in the caller's account. The key owner's account also records it. Check both when you investigate cross-account access.
Delivery is not instant. Events typically show up in event history and in the S3 bucket within several minutes.
Querying event history from the CLI
lookup-events filters on one attribute per call. This command finds recent attempts to schedule deletion:
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=EventName,AttributeValue=ScheduleKeyDeletion \
--max-results 10 \
--query 'Events[].{time:EventTime,user:Username,event:EventName}' \
--output tableTo see everything that touched one key, filter on the key ARN instead:
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=ResourceName,AttributeValue=arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab \
--max-results 50lookup-events is rate limited to a small number of requests per second per account and Region. It also returns only management events. For large investigations, query the S3 logs with Amazon Athena.
Summarizing key use with Python
The full event is a JSON string inside the CloudTrailEvent field. This script counts calls per principal and operation for one key. Set KEY_ARN to your key's ARN first.
import json
from collections import Counter
import boto3
KEY_ARN = "arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
cloudtrail = boto3.client("cloudtrail")
pages = cloudtrail.get_paginator("lookup_events").paginate(
LookupAttributes=[{"AttributeKey": "ResourceName", "AttributeValue": KEY_ARN}],
PaginationConfig={"PageSize": 50},
)
counts = Counter()
for page in pages:
for item in page["Events"]:
event = json.loads(item["CloudTrailEvent"])
who = event["userIdentity"].get("arn") or event["userIdentity"].get("invokedBy", "unknown")
outcome = event.get("errorCode", "ok")
counts[(who, event["eventName"], outcome)] += 1
for (who, name, outcome), n in counts.most_common():
print(f"{n:5d} {name:<20} {outcome:<25} {who}")Any row with an outcome other than ok deserves attention. Typical errors are AccessDeniedException for a policy denial, DisabledException for a disabled key, and InvalidCiphertextException when the ciphertext is damaged or the encryption context does not match.
What the logs can and cannot tell you
Auditing KMS has some limits that surprise people.
- Local encryption is invisible. In envelope encryption, the AES-GCM work happens in your process. CloudTrail sees only the calls to
GenerateDataKeyandDecrypt. OneDecryptevent means one data key was unwrapped. It does not tell you how many records that key protected. - Call volume depends on design. If your application caches data keys, it makes fewer KMS calls and the log shows fewer events. S3 Bucket Keys have the same effect. The log shows the bucket-level key use, not each object read.
- Service calls show the service, not the end user. For S3 or EBS,
userIdentityshows the service acting through your permissions. The encryption context often names the resource, for exampleaws:s3:arn. Use it to trace the activity to an object or volume. - Grants hide the original caller. After
CreateGrant, the grantee's later calls appear under the grantee's identity. The grant creation event is where you find who handed out access.
Alerting on risky operations
Most keys see steady Decrypt traffic, which is noise. The events worth alerting on are rare and administrative. An EventBridge rule can match them as they arrive. This event pattern catches deletion scheduling, disabling, and policy changes:
{
"source": ["aws.kms"],
"detail-type": ["AWS API Call via CloudTrail"],
"detail": {
"eventSource": ["kms.amazonaws.com"],
"eventName": [
"ScheduleKeyDeletion",
"DisableKey",
"PutKeyPolicy",
"CreateGrant"
]
}
}Point the rule at an SNS topic or a chat notification. The rule must live in the Region where the event occurs. Create it in each Region where you hold keys.
KMS also publishes its own EventBridge events, such as KMS CMK Rotation and KMS CMK Deletion. Use those to track automatic lifecycle changes. The API-call pattern above does not catch them, because no principal made an API call.
A short investigation workflow
- Find the key's ARN from its alias with
aws kms describe-key --key-id alias/tutorial-key. - Look up events by
ResourceNameand scan for non-okoutcomes. - Group by
userIdentity.arnto find unexpected principals. - Check
requestParameters.encryptionContextagainst what your application should send. - For an unexpected principal, read the key policy and any grants to see how it got access.
Exercise
A security analyst sees thousands of Decrypt events for one key over a day, all from s3.amazonaws.com, each with a different aws:s3:arn in the encryption context. The team then enables S3 Bucket Keys on the bucket. What change should the analyst expect in the log, and why can the same logs not show how many objects a single GenerateDataKey call protected in an application that uses envelope encryption?
Show answer
With Bucket Keys, S3 requests a bucket-level key and reuses it for many objects, so the number of KMS events drops sharply, and the encryption context names the bucket rather than each object. For the envelope encryption question, the data is encrypted locally with the data key, outside KMS. CloudTrail records only the GenerateDataKey and Decrypt calls, so it cannot count how many records one data key encrypted. Your application would have to track that itself.