Cloud Secret Management and Where Secrets Hide
Every cloud has a secret manager (AWS Secrets Manager and Systems Manager Parameter Store, Azure Key Vault, Google Secret Manager), and most accounts use one. Most accounts also have the database password in a Lambda environment variable, an API token in an instance's user data and the whole set in a Terraform state file in a bucket. Attackers know these places well: the first thing a stolen read-only key is used for is often to describe functions, instances and stacks, because "read-only" permissions on configuration are read permissions on whatever secrets were pasted into it. This lesson maps where secrets hide in a cloud account, who can read them there, and how a secret manager closes the gap. Vault, SOPS, rotation and secret scanning in repositories are covered in Secrets & Policy as Code; this lesson is the cloud-account view.
Places secrets end up, and who can read them
| Location | Readable with | Notes |
|---|---|---|
| Lambda environment variables | lambda:GetFunctionConfiguration (part of many read-only policies) |
encrypted at rest, but shown in plaintext to anyone with that permission |
| ECS task definitions, container env | ecs:DescribeTaskDefinition |
same; also in every container's /proc/<pid>/environ |
| EC2 user data | ec2:DescribeInstanceAttribute (userData), and from inside the instance via IMDS |
user data is not a secret store |
| CloudFormation parameters and outputs | cloudformation:DescribeStacks |
unless the parameter has NoEcho |
| Terraform state | read access to the state bucket | contains every resource attribute, including generated passwords, in plaintext |
SSM Parameter Store String |
ssm:GetParameter |
SecureString adds KMS: the reader also needs kms:Decrypt |
| Kubernetes Secrets | get/list on secrets in the namespace |
base64, not encryption (Kubernetes Secrets) |
| Images, AMIs, snapshots | pull / describe / copy | layers keep deleted files (Image Hardening) |
| A secret manager | secretsmanager:GetSecretValue + the KMS key |
the only row designed for it: access logged per read, rotation built in |
A configuration-secret finder
The program walks a synthetic export of the lab account's configuration (the kind a CSPM tool or describe-* calls produce), flags values that look like secrets (by key name, known formats and a randomness estimate), and prints who could read each location. All values are invented.
import math, re
from collections import Counter
inventory = {
"lambda:report-gen": {"where": "Lambda env", "read_by": "lambda:GetFunctionConfiguration",
"data": {"DB_HOST": "db.lab.test", "DB_PASSWORD": "Wq7!vR2#kd9Lp0sZ", "LOG_LEVEL": "info"}},
"lambda:thumbnailer": {"where": "Lambda env", "read_by": "lambda:GetFunctionConfiguration",
"data": {"DB_SECRET_ARN": "arn:aws:secretsmanager:eu-west-1:123456789012:secret:lab/db-Ab12Cd"}},
"ec2:i-0abc12 userData": {"where": "EC2 user data", "read_by": "ec2:DescribeInstanceAttribute",
"data": {"line3": "export PAYMENTS_TOKEN=pk_lab_51HxQ8z2mK7rT4vN9bW3cY6"}},
"cfn:shop-stack": {"where": "CloudFormation parameter", "read_by": "cloudformation:DescribeStacks",
"data": {"AdminEmail": "ops@lab.test", "SmtpPassword": "hunter2-but-longer"}},
"s3:lab-tfstate/prod.tfstate": {"where": "Terraform state", "read_by": "s3:GetObject on the state bucket",
"data": {"aws_db_instance.main.password": "zX9#qL2!mN8$wR5t"}},
"ssm:/shop/feature-flags": {"where": "SSM String", "read_by": "ssm:GetParameter",
"data": {"value": "checkout_v2=on"}},
}
NAME_HINT = re.compile(r"pass(word)?|secret|token|api[_-]?key|private", re.I)
FORMATS = {"Stripe-style key": re.compile(r"\b[ps]k_[a-z]+_[0-9A-Za-z]{16,}\b"),
"AWS access key id": re.compile(r"\b(AKIA|ASIA)[0-9A-Z]{16}\b")}
def entropy(s):
counts = Counter(s)
return -sum(c / len(s) * math.log2(c / len(s)) for c in counts.values())
findings = 0
for resource, item in inventory.items():
for key, value in item["data"].items():
reasons = []
if NAME_HINT.search(key) and not value.startswith("arn:"):
reasons.append("secret-like name")
reasons += [f"format: {name}" for name, rx in FORMATS.items() if rx.search(value)]
token = value.split("=")[-1]
if len(token) >= 12 and entropy(token) > 3.6 and not token.startswith("arn:"):
reasons.append(f"high-entropy ({entropy(token):.1f} bits/char)")
if reasons:
findings += 1
print(f"{item['where']:24} {resource:30} {key}")
print(f"{'':24} why: {', '.join(reasons)}; readable with {item['read_by']}")
print(f"{findings} secrets outside a secret manager")Lambda env lambda:report-gen DB_PASSWORD
why: secret-like name, high-entropy (4.0 bits/char); readable with lambda:GetFunctionConfiguration
EC2 user data ec2:i-0abc12 userData line3
why: format: Stripe-style key, high-entropy (4.8 bits/char); readable with ec2:DescribeInstanceAttribute
CloudFormation parameter cfn:shop-stack SmtpPassword
why: secret-like name; readable with cloudformation:DescribeStacks
Terraform state s3:lab-tfstate/prod.tfstate aws_db_instance.main.password
why: secret-like name, high-entropy (4.0 bits/char); readable with s3:GetObject on the state bucket
4 secrets outside a secret manager
The thumbnailer function stores only the ARN of a secret and reads the value at run time with its role: that is the pattern to copy, and the finder correctly ignores it. The feature-flag parameter isn't secret. The rest are findings, and each comes with the permission that exposes it, which is what makes the severity: lambda:GetFunctionConfiguration and cloudformation:DescribeStacks are in the AWS managed ReadOnlyAccess policy, so every auditor, dashboard and monitoring integration with read-only access can read those passwords.
The entropy test is a heuristic: SmtpPassword is caught only by its name, and a scanner relying on randomness alone would miss human-chosen passwords. Real secret scanners combine all three signals, as Trivy does on files in the next lesson.
How a secret manager changes the picture
- The secret lives in one place; configurations hold a reference (an ARN, a Key Vault URI, a Secret Manager resource name).
- Reading it requires a specific permission on that secret (and on its KMS key), granted to the workload's own identity only (Workload Identity).
- Every read is an audit event (
GetSecretValuein CloudTrail,SecretGetin Key Vault logs,AccessSecretVersionin GCP Data Access logs, which must be enabled). - Rotation can be automatic (Secrets Manager rotation functions, managed database credentials), so a leaked value has a short life.
How secrets in configuration are detected
- Run a finder like the one above over configuration exports on a schedule, and CSPM rules for "secrets in Lambda environment", "user data contains credentials".
- Scan IaC and state:
NoEchomissing on password parameters,password = "..."literals in Terraform, state buckets readable by more than the pipeline. - Watch CloudTrail for bulk configuration reads by one principal (
GetFunctionConfigurationacross all functions,DescribeInstanceAttributewithuserData): it is a typical post-compromise discovery pattern.
How it is fixed
- Move each secret into the secret manager, replace it in configuration with a reference, grant the workload
GetSecretValueon that one secret. - Rotate every secret that was ever in configuration: it has been readable by every read-only principal for as long as it was there.
- Protect Terraform state as a secret store: encrypted bucket, narrow access, versioning, and generated passwords managed by the provider instead (for example RDS-managed master passwords in Secrets Manager).
- Remove the configuration read permissions from roles that don't need them, or use read-only policies without "describe configuration" actions for dashboards.
Pitfalls
- "It's encrypted at rest" for Lambda environment variables: true, and irrelevant to anyone with
GetFunctionConfiguration. - Moving the secret to a secret manager but granting
secretsmanager:GetSecretValueon*to every role. - Forgetting rotation after cleanup: a secret that was exposed is compromised until rotated, whatever its new home.
Practice
1. Change SmtpPassword to SmtpPass. Is it still found? Why?
Yes: pass matches the name pattern pass(word)?. Rename it to SmtpCred and it is missed (its value hunter2-but-longer has only about 3.5 bits per character, under the 3.6 threshold), which shows the limits of heuristics.
2. The Terraform state finding: which three changes close it?
Let RDS manage the master password in Secrets Manager (manage_master_user_password = true) so it never enters state; restrict and encrypt the state bucket; rotate the current password.
3. Which read-only role in the account would you check first, and for what?
The broadest one: the auditor or monitoring role with ReadOnlyAccess. It can read every Lambda environment, stack parameter and user data in the account. Check its trust policy (who can assume it, from where) and whether it can be replaced by a narrower policy: a custom one without configuration-content reads, or a managed one such as SecurityAudit after checking its current action list for the same reads.
Test yourself
Who can read a password stored in a Lambda environment variable?
- Only the function
- Anyone with lambda:GetFunctionConfiguration, including many read-only roles
- Nobody, it is encrypted
- Only the account root
Why did the finder ignore DB_SECRET_ARN?
- It was empty
- It holds a reference (an ARN) to a secret manager entry, not the secret
- Lambda values are never checked
- Its entropy was too high
What must happen to a secret found in configuration, besides moving it?
- Nothing
- Rotate it, because it was readable for as long as it was exposed
- Base64-encode it
- Rename the variable