Sub topic 14
Logging sessions to CloudWatch Logs, S3, and CloudTrail
This chapter assumes you can already start a Session Manager shell with aws ssm start-session. It also assumes you can read an IAM policy and have permission to edit the instance profile role and create a log group and a bucket. By the end you will know which AWS service records which part of a session, how to turn the records on, and where they stop being useful.
Three records, three questions
A session leaves evidence in three places. Each one answers a different question.
| Record | Answers | Written by | Contains command output |
|---|---|---|---|
| CloudTrail | Who started, resumed, or ended a session, from where, and when | The Systems Manager API | No |
| CloudWatch Logs | What was typed and displayed during the session | SSM Agent on the instance | Yes |
| S3 object | The same transcript, stored as one file per session | SSM Agent on the instance | Yes |
The key difference is the writer. CloudTrail records API calls made by the user. The transcript is written by SSM Agent, using the permissions of the instance profile role. A user's IAM policy therefore has no effect on transcript logging, and a missing permission on the instance role silently breaks it.
CloudTrail: the audit trail you already have
CloudTrail needs no setup for the basics. Systems Manager management events are recorded automatically and kept in event history for 90 days. The events that matter for sessions are:
StartSession, which includes the target instance ID and the session ID in the response.ResumeSession, which reconnects a session that dropped.TerminateSession, which ends a session.
The session ID starts with the IAM user name or the role session name, followed by a random suffix, for example alice-0a1b2c3d4e5f67890. This is also why the IAM policy in the earlier chapter can use ${aws:username}-* to limit who may end which sessions. The same ID names the CloudWatch log stream and the S3 object, so you can join all three records on it.
To list recent session starts from the CLI:
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=EventName,AttributeValue=StartSession \
--max-results 10 \
--query "Events[].[EventTime,Username,EventName]" \
--output textEvent history disappears after 90 days. For longer retention, or for events from all Regions in one place, create a trail that delivers to an S3 bucket. If you want an alert whenever someone opens a session on a production instance, route the CloudTrail API event through Amazon EventBridge and match on eventSource of ssm.amazonaws.com and eventName of StartSession.
Transcript logging: what you need first
Transcript logging has three parts: a destination, instance permissions, and the Session Manager preferences that connect them.
1. Create the destinations
Create them in the same account, and preferably in the same Region as the instances.
aws logs create-log-group --log-group-name /ssm/session-logs
aws logs put-retention-policy \
--log-group-name /ssm/session-logs \
--retention-in-days 365
aws s3api create-bucket --bucket my-session-logs-111122223333 --region us-east-1The log group is not created for you. If the name in the preferences points at a group that does not exist, the session still starts, and the transcript is not logged. Set a retention period explicitly, because the default is to keep logs forever and pay for them forever.
2. Allow the instance to write
Add a policy to the instance profile role. Both destinations are written by the agent, so both need permissions here.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "logs:DescribeLogGroups",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"logs:CreateLogStream",
"logs:PutLogEvents",
"logs:DescribeLogStreams"
],
"Resource": "arn:aws:logs:us-east-1:111122223333:log-group:/ssm/session-logs:*"
},
{
"Effect": "Allow",
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::my-session-logs-111122223333/ssm/*"
},
{
"Effect": "Allow",
"Action": "s3:GetEncryptionConfiguration",
"Resource": "arn:aws:s3:::my-session-logs-111122223333"
}
]
}If you encrypt the log group or bucket with a customer managed KMS key, the role also needs kms:GenerateDataKey and kms:Decrypt on that key, and the key policy must allow the role.
3. Set the Session Manager preferences
Preferences are stored in an SSM document of type Session, named SSM-SessionManagerRunShell. The console's Session Manager Preferences tab edits this document for you. To do it from the CLI, write the settings to a file:
{
"schemaVersion": "1.0",
"description": "Session Manager preferences",
"sessionType": "Standard_Stream",
"inputs": {
"s3BucketName": "my-session-logs-111122223333",
"s3KeyPrefix": "ssm/",
"s3EncryptionEnabled": true,
"cloudWatchLogGroupName": "/ssm/session-logs",
"cloudWatchEncryptionEnabled": false,
"cloudWatchStreamingEnabled": true,
"kmsKeyId": "",
"runAsEnabled": false,
"runAsDefaultUser": "",
"idleSessionTimeout": "20",
"maxSessionDuration": "",
"shellProfile": {
"windows": "",
"linux": ""
}
}
}Save it as prefs.json, then create the document. If the document already exists, update it and make the new version the default.
aws ssm create-document \
--name SSM-SessionManagerRunShell \
--document-type Session \
--document-format JSON \
--content file://prefs.json
# If the document already exists:
aws ssm update-document \
--name SSM-SessionManagerRunShell \
--document-format JSON \
--document-version '$LATEST' \
--content file://prefs.json
aws ssm update-document-default-version \
--name SSM-SessionManagerRunShell \
--document-version 2Use the version number returned by update-document. Set cloudWatchEncryptionEnabled to true only when the log group is encrypted with a KMS key. With true and an unencrypted group, the agent refuses to log.
Settings that affect logging:
cloudWatchStreamingEnabled: truesends output to CloudWatch as the session runs. Withfalse, the agent uploads the whole transcript when the session ends.- S3 logs are always uploaded at the end of the session, as
ssm/<session-id>.log. A session that is still open, or an instance that is stopped mid-session, may have no S3 object yet. s3KeyPrefixandkmsKeyIdare optional. An empty string means no prefix and the destination's default encryption.
Start a new session after the change. Preferences are read when a session starts, and sessions already open keep their old settings.
What the transcript contains and what it misses
The transcript is a record of the terminal stream. It captures the commands typed and the output printed, including any secret a command prints to the screen. Treat the log group and bucket as sensitive data. Give read access only to the security team and anyone who investigates incidents.
Three gaps are worth knowing:
- Port forwarding sessions and SSH-over-SSM sessions are not transcribed. For SSH, the traffic inside the tunnel is encrypted end to end, so the agent sees only ciphertext. CloudTrail still records that the session started, but not what moved through it.
- Typed input that the terminal does not echo, such as a password prompt, does not appear in the transcript.
- A user with a shell can run
history -cor similar, but this does not change what the agent already logged.
Making the logs hard to alter
The person being audited often has administrative rights on the instance, so protect the destinations from them:
- Turn on S3 Versioning, and consider S3 Object Lock for retention that cannot be shortened.
- Deny
s3:DeleteObjectandlogs:DeleteLogGroupto everyone except a break-glass role. - Enable CloudTrail log file validation to detect tampering with the trail.
- Keep the log bucket in a separate account if your organization has a security account.
Checking that it works
Open a session, run whoami, then end it. In CloudTrail, find the StartSession event and copy the session ID from the response. Then check the log stream with that name:
aws logs get-log-events \
--log-group-name /ssm/session-logs \
--log-stream-name alice-0a1b2c3d4e5f67890 \
--query "events[].message" \
--output textIf CloudTrail shows the session and the stream does not exist, work through these causes in order:
- The instance role lacks
logs:CreateLogStreamorlogs:PutLogEvents. - The log group name in the preferences has a typo or is in another Region.
- The session began before you saved the preferences.
- Encryption is enabled in the preferences, but the group or key is not set up for it.
Exercise
A user opened a Session Manager shell, ran several commands, and the security team finds the StartSession event in CloudTrail but no log stream in CloudWatch Logs. The log group exists and the preferences name it correctly. Which identity's permissions should you check first, and why?
Show answer
Check the instance profile role, not the user's IAM policy. SSM Agent on the instance writes the transcript to CloudWatch Logs, so the role needs logs:CreateLogStream and logs:PutLogEvents on the log group. The user's permissions only control starting the session, which already worked.
Exercise
A user connects with "aws ssm start-session --document-name AWS-StartPortForwardingSession" and queries a database through the tunnel. Which records exist for this session, and which do not?
Show answer
CloudTrail records the StartSession and TerminateSession API calls, with the user, instance, and time. No CloudWatch Logs or S3 transcript is produced, because port forwarding carries no interactive terminal stream for the agent to log, and its contents are not recorded.