Forty buckets and one afternoon
A college's cloud account has forty buckets, twelve queues and nine tables. Checking every setting by hand takes an afternoon, and it is out of date by the next morning.
A short script can check them all in seconds, every night.
The one rule
Warning
Everything in this module happens in the practice cloud of your own lab. Scanning a cloud account you do not own needs the owner's written permission. In the UK, without it, it can break the Computer Misuse Act 1990.
Quick check: the rule
Have a go
Quick check: the rule
3 questionsBy the end of this lesson
Note
I can write a posture check that lists every failing setting in a cloud account.
Key words
| Word | What it means |
|---|---|
| Posture | how well an account's settings match its rules |
| Misconfiguration | a setting left in an unsafe state |
| Baseline | the written list of settings every resource needs |
| Point-in-time recovery | a table can be put back to any recent second |
| Exit code | the number a program ends with, 0 for success |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
3 questionsA check reads every resource against a baseline
A posture check lists every resource, reads its settings and compares them with the baseline. It prints one PASS or FAIL line for each check.
It only reads, so it is safe to run as often as you like. It ends with exit code 1 when anything fails, so a pipeline can stop.
The baseline in this lesson
| Resource | Check | Why |
|---|---|---|
| Bucket | Block public access on | Nothing goes public by mistake |
| Bucket | No public statement | Nobody unnamed can read |
| Bucket | Plain HTTP refused | Data is encrypted on its way |
| Bucket | Default encryption and versioning | Encrypted at rest, and old copies kept |
| Queue | Encrypted at rest | Messages on disk are unreadable |
| Table | Point-in-time recovery | A deleted row can come back |
The cells students fill in are left blank in this preview.
Try it: count the failures
results = {
"bucket photos": {"encrypted": True, "versioning": False},
"queue orders": {"encrypted": False},
}
failed = 0
for what, checks in results.items():
for check, passed in checks.items():
print("PASS" if passed else "FAIL", what, check)
failed = failed + (0 if passed else 1)
print(failed, "failed")
# Set versioning to True. How many fail now?
Make a free account to save your work and track your progress.
Check
Have a go
Check
3 questionsThree new resources and a check
Make a bucket, a queue and a table, each named with audit-, with no settings at all. Then write posture.py. It asks the aws command for every resource and reads each answer as JSON. Give it a name prefix to check only those.
Point the aws command at your stack
export AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 AWS_ENDPOINT_URL=http://cloud:4566Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Make a bucket, a queue and a table
aws s3 mb s3://audit-files && aws sqs create-queue --queue-name audit-jobs --query QueueUrl --output text && aws dynamodb create-table --table-name audit-users --attribute-definitions AttributeName=id,AttributeType=S --key-schema AttributeName=id,KeyType=HASH --billing-mode PAY_PER_REQUEST --query TableDescription.TableName --output textShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the posture check, part 1
mkdir -p ~/cs && printf '%s\n' 'import json' 'import subprocess' 'import sys' '' '' 'def aws(*args):' ' done = subprocess.run(["aws", *args, "--output", "json"], capture_output=True, text=True)' ' if not done.returncode == 0:' ' return {}' ' return json.loads(done.stdout or "{}")' '' '' 'def bucket_checks(name):' ' block = aws("s3api", "get-public-access-block", "--bucket", name).get("PublicAccessBlockConfiguration", {})' ' text = aws("s3api", "get-bucket-policy", "--bucket", name).get("Policy", "{}")' ' statements = json.loads(text).get("Statement", [])' ' rules = aws("s3api", "get-bucket-encryption", "--bucket", name).get("ServerSideEncryptionConfiguration", {})' ' versioning = aws("s3api", "get-bucket-versioning", "--bucket", name).get("Status")' ' return {' ' "public access blocked": len(block) == 4 and all(block.values()),' > ~/cs/posture.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the posture check, part 2
printf '%s\n' ' "no public statement": not any(s.get("Principal") == "*" and s.get("Effect") == "Allow" for s in statements),' ' "plain HTTP refused": any(s.get("Effect") == "Deny" and "aws:SecureTransport" in json.dumps(s) for s in statements),' ' "encrypted at rest": bool(rules.get("Rules")),' ' "versioning on": versioning == "Enabled",' ' }' '' '' 'def queue_checks(url):' ' attributes = aws("sqs", "get-queue-attributes", "--queue-url", url, "--attribute-names", "All").get("Attributes", {})' ' return {"encrypted at rest": attributes.get("SqsManagedSseEnabled") == "true" or "KmsMasterKeyId" in attributes}' '' '' 'def table_checks(name):' ' backups = aws("dynamodb", "describe-continuous-backups", "--table-name", name)' ' status = backups.get("ContinuousBackupsDescription", {}).get("PointInTimeRecoveryDescription", {})' ' return {"point-in-time recovery": status.get("PointInTimeRecoveryStatus") == "ENABLED"}' '' '' >> ~/cs/posture.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the posture check, part 3
printf '%s\n' 'prefix = sys.argv[1] if len(sys.argv) > 1 else ""' 'results = []' 'for bucket in aws("s3api", "list-buckets").get("Buckets", []):' ' if bucket["Name"].startswith(prefix):' ' results.append(("bucket " + bucket["Name"], bucket_checks(bucket["Name"])))' 'for url in aws("sqs", "list-queues").get("QueueUrls", []):' ' if url.split("/")[-1].startswith(prefix):' ' results.append(("queue " + url.split("/")[-1], queue_checks(url)))' 'for table in aws("dynamodb", "list-tables").get("TableNames", []):' ' if table.startswith(prefix):' ' results.append(("table " + table, table_checks(table)))' 'failed = 0' 'for what, checks in results:' ' for check, passed in checks.items():' ' print("PASS" if passed else "FAIL", what, ":", check)' ' failed = failed + (0 if passed else 1)' 'print(failed, "failed of", sum(len(c) for w, c in results), "checks")' 'sys.exit(1 if failed else 0)' >> ~/cs/posture.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check the three new resources
cd ~/cs && python3 posture.py audit-; echo exit code $?Shown here, not run. Press Start lab to type it into your own lab’s terminal.
A common mistake
Warning
Many people think an account is safe because the posture check passed once. Settings change every day, by people and by scripts. Run the check every night and on every change, and treat each FAIL as a job with an owner.
Check
Have a go
Check
3 questionsFix each FAIL, then check again
Each FAIL names its fix. The bucket needs block public access, encryption, versioning and the TLS policy. The queue needs encryption at rest and the table point-in-time recovery. Then run the check again.
Fix the bucket's settings
aws s3api put-public-access-block --bucket audit-files --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true && aws s3api put-bucket-encryption --bucket audit-files --server-side-encryption-configuration '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"AES256"}}]}' && aws s3api put-bucket-versioning --bucket audit-files --versioning-configuration Status=EnabledShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the bucket's TLS policy
mkdir -p ~/cs && printf '%s\n' '{"Version":"2012-10-17","Statement":[{"Sid":"OnlyTLS","Effect":"Deny","Principal":"*","Action":"s3:*","Resource":["arn:aws:s3:::audit-files","arn:aws:s3:::audit-files/*"],"Condition":{"Bool":{"aws:SecureTransport":"false"}}}]}' > ~/cs/audit-tls.jsonShown here, not run. Press Start lab to type it into your own lab’s terminal.
Put the TLS policy on the bucket
cd ~/cs && aws s3api put-bucket-policy --bucket audit-files --policy file://audit-tls.jsonShown here, not run. Press Start lab to type it into your own lab’s terminal.
Fix the queue and table, check again
aws sqs set-queue-attributes --queue-url $(aws sqs get-queue-url --queue-name audit-jobs --query QueueUrl --output text) --attributes SqsManagedSseEnabled=true && aws dynamodb update-continuous-backups --table-name audit-users --point-in-time-recovery-specification PointInTimeRecoveryEnabled=true --query ContinuousBackupsDescription.PointInTimeRecoveryDescription.PointInTimeRecoveryStatus --output text && cd ~/cs && python3 posture.py audit-; echo exit code $?Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Run it every night and on every change
Run posture.py with no prefix to check everything earlier lessons made. Then run it every night and in the pipeline, which stops on exit code 1.
On AWS, AWS Config and Security Hub run hundreds of such checks, and open-source tools such as Prowler do the same.
Check the whole account
cd ~/cs && python3 posture.py; echo exit code $?Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Assignment: a report and an exit code
Turn posture results into a report and an exit code. Results are a list of (what, {check: True or False}) pairs.
failed(results) gives "<what>: <check>" for each failed check, in order. score(results) is the percentage passed, rounded, and 100 when there are no checks. exit_code(results, allowed=()) is 1 when a failed line is not in allowed, else 0.
def failed(results):
# "<what>: <check>" for every check that is False, in order.
# results is a list of (what, {check: True or False}) pairs.
return []
def score(results):
# The percentage of checks passed, rounded to a whole number. 100 when there are none.
return 0
def exit_code(results, allowed=()):
# 1 when a failed line is not in allowed, else 0.
return 0
Make a free account to save your work and track your progress.
Exit quiz
Have a go