Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

A posture check over a cloud account

After this lesson: I can write a posture check that lists every failing setting in a cloud account.

65 min lesson11 commandsCloud lab: practise S3 buckets, SQS queues and DynamoDB tables with the AWS command line

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

By the end of this lesson

Note

I can write a posture check that lists every failing setting in a cloud account.

Key words

WordWhat it means
Posturehow well an account's settings match its rules
Misconfigurationa setting left in an unsafe state
Baselinethe written list of settings every resource needs
Point-in-time recoverya table can be put back to any recent second
Exit codethe 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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A 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

ResourceCheckWhy
BucketBlock public access onNothing goes public by mistake
BucketNo public statementNobody unnamed can read
BucketPlain HTTP refusedData is encrypted on its way
BucketDefault encryption and versioningEncrypted at rest, and old copies kept
QueueEncrypted at restMessages on disk are unreadable
TablePoint-in-time recoveryA deleted row can come back

The cells students fill in are left blank in this preview.

Try it: count the failures

Code: python
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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Three 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

Command
export AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 AWS_ENDPOINT_URL=http://cloud:4566

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Make a bucket, a queue and a table

Command
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 text

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the posture check, part 1

Command
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.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the posture check, part 2

Command
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.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the posture check, part 3

Command
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.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check the three new resources

Command
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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Fix 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

Command
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=Enabled

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the bucket's TLS policy

Command
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.json

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Put the TLS policy on the bucket

Command
cd ~/cs && aws s3api put-bucket-policy --bucket audit-files --policy file://audit-tls.json

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Fix the queue and table, check again

Command
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

Command
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.

Code: python
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

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.