Lesson 13 · 60 minutes
Build a posture checker that ranks the findings of an account
- Join the checks of the course into one program with one finding format
- Rank findings by a score that puts exposure to the internet first
- Write a report file and end with an exit code that a pipeline can use
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
The incident is contained. Your lead wants it never to be a surprise again: "You wrote six checkers in six lessons. Nobody will run six programs every morning. Give me one command that reads the snapshot and prints what to fix first, with a report file for the ticket system." A tool that checks the configuration of a cloud account against rules is called a posture checker. Products of this kind are sold as cloud security posture management (CSPM). You will build a small one from your own parts.
Recall
Lesson 12: what is the first action for a leaked key, and why not delete?
Make the key inactive. That stops its use at once, can be undone if a job breaks, and keeps the key in the lists that the investigation needs.
Lesson 6: a security group allows a database port from everywhere, and the machine has no public address. How did the checker report it?
As closed, with the reason "no public address". It is still a finding of medium severity, because one more change would open the port to the world.
The idea
Each checker of this course returns findings in its own way. A common tool needs three decisions.
One format. Every finding is a dictionary with the same keys: severity, code, subject, text, and the area it came from. You wrote iam_audit.py, buckets.py and reach.py with a function that returns such a list. The others return rows or tuples, and the new program turns them into findings.
One order. A list of forty findings in file order is not used. The program gives each finding a score and sorts by it.
| Part of the score | Points |
|---|---|
| Severity | critical 9, high 6, medium 3, low 1 |
| Exposed: anyone on the internet can use it today (a public bucket, an open port, a role that trusts everyone) | 3 more |
You know this way of working from "Security operations basics", lesson 10, where a vulnerability on a system that faces the internet went to the top. The same reasoning holds here: a wide policy needs a stolen credential first, and an open port needs nothing.
One result. A summary on the screen, a report file for people, and an exit code for a pipeline: 1 when a finding is critical.
- Snapshot → Checkers: identity, keys, storage, network, logs, map
- Checkers → Findings: one format for all
- Findings → Rank: severity, and 3 points for exposure
- Rank → Report: screen, file and exit code
A posture checker reads settings. It cannot see an intruder who uses valid rights quietly: that is the job of the audit log and of detection (lesson 7). It is also only as good as its snapshot. Run it on fresh data, every day.
Worked example
1. Write the collector
posture.py imports the six programs of lessons 1 to 7. The function collect calls each one and gives every finding its area. Where a program has no findings function, the collector makes the findings: an old key from the rows of key_report.py, four checks on the settings of the trail, a finding for each gap in the log, and two from the map. In this lab the log holds all regions, so ONE-REGION is a finding about the setting, not a proof of missing records.
def collect(folder):
"""The findings of every area, each with the area it came from."""
iam, inv, records = load(folder, "iam.json"), account_map.load(folder), trail.load(folder)
out = [dict(f, area="identity") for f in iam_audit.audit(iam)]
for row in key_report.key_rows(iam):
if "OLD" in row["flags"]:
out.append(dict(finding("medium", "OLD-KEY", f"user {row['user']}", f"access key {row['id']} is {row['age']} days old"), area="identity"))
out += [dict(f, area="storage") for f in buckets.findings(load(folder, "buckets.json"))]
out += [dict(f, area="network") for f in reach.findings(load(folder, "network.json"))]
for t in load(folder, "trails.json"):
checks = [(not t["IsLogging"], "critical", "TRAIL-OFF", "the trail is not logging"),
(not t["IsMultiRegionTrail"], "medium", "ONE-REGION", "the trail records one region only"),
(not t["LogFileValidationEnabled"], "medium", "NO-VALIDATION", "log file validation is off"),
(not t["KmsKeyId"], "low", "LOG-NO-KMS", "the log files are not encrypted with a key of your own")]
out += [dict(finding(sev, code, f"trail {t['Name']}", text), area="logging") for bad, sev, code, text in checks if bad]
for stop, start, minutes in trail.gaps(records):
out.append(dict(finding("high", "LOG-GAP", "audit log", f"the trail was off from {stop} to {start}"), area="logging"))
outside = account_map.outside(inv)
if outside:
regions = sorted({x["region"] for x in outside})
out.append(dict(finding("high", "REGION", "inventory", f"{len(outside)} resources in {', '.join(regions)}, not approved"), area="inventory"))
if account_map.untagged(inv):
out.append(dict(finding("low", "NO-OWNER", "inventory", f"{len(account_map.untagged(inv))} resources with no owner tag"), area="inventory"))
return outThe four checks on the trail read account/trails.json, which has the field names that CloudTrail uses for a trail: IsMultiRegionTrail, LogFileValidationEnabled, KmsKeyId. IsLogging comes from a separate status call in a real account.
2. Rank the findings
def rank(found):
"""Give each finding a score, sort from the highest, and number them."""
for f in found:
f["score"] = POINTS[f["severity"]] + (3 if f["code"] in EXPOSED else 0)
found.sort(key=lambda f: (-f["score"], f["area"], f["code"], f["subject"]))
for n, f in enumerate(found, 1):
f["id"] = f"F{n:02d}"
return foundThe sort key starts with the score, turned negative so that the highest comes first. The other parts make the order the same on every run.
3. Save the whole program
The rest is the report, a Markdown table, and the main part. Open the block and save the file.
The finished file: posture.py
posture.py
"""posture.py: check the snapshot of a cloud account and rank what to fix first.
python3 posture.py [folder] [report.md] default: account posture-report.md
Exit code 1 when a finding is critical.
"""
import json
import sys
import account_map
import buckets
import iam_audit
import key_report
import reach
import trail
POINTS = {"critical": 9, "high": 6, "medium": 3, "low": 1}
EXPOSED = {"PUBLIC", "OPEN-PORT", "TRUST-ANYONE"} # a stranger can use these today with no credential of yours: 3 points more
def load(folder, name):
with open(f"{folder}/{name}") as src:
return json.load(src)
def finding(severity, code, subject, text):
return {"severity": severity, "code": code, "subject": subject, "text": text}
def collect(folder):
"""The findings of every area, each with the area it came from."""
iam, inv, records = load(folder, "iam.json"), account_map.load(folder), trail.load(folder)
out = [dict(f, area="identity") for f in iam_audit.audit(iam)]
for row in key_report.key_rows(iam):
if "OLD" in row["flags"]:
out.append(dict(finding("medium", "OLD-KEY", f"user {row['user']}", f"access key {row['id']} is {row['age']} days old"), area="identity"))
out += [dict(f, area="storage") for f in buckets.findings(load(folder, "buckets.json"))]
out += [dict(f, area="network") for f in reach.findings(load(folder, "network.json"))]
for t in load(folder, "trails.json"):
checks = [(not t["IsLogging"], "critical", "TRAIL-OFF", "the trail is not logging"),
(not t["IsMultiRegionTrail"], "medium", "ONE-REGION", "the trail records one region only"),
(not t["LogFileValidationEnabled"], "medium", "NO-VALIDATION", "log file validation is off"),
(not t["KmsKeyId"], "low", "LOG-NO-KMS", "the log files are not encrypted with a key of your own")]
out += [dict(finding(sev, code, f"trail {t['Name']}", text), area="logging") for bad, sev, code, text in checks if bad]
for stop, start, minutes in trail.gaps(records):
out.append(dict(finding("high", "LOG-GAP", "audit log", f"the trail was off from {stop} to {start}"), area="logging"))
outside = account_map.outside(inv)
if outside:
regions = sorted({x["region"] for x in outside})
out.append(dict(finding("high", "REGION", "inventory", f"{len(outside)} resources in {', '.join(regions)}, not approved"), area="inventory"))
if account_map.untagged(inv):
out.append(dict(finding("low", "NO-OWNER", "inventory", f"{len(account_map.untagged(inv))} resources with no owner tag"), area="inventory"))
return out
def rank(found):
"""Give each finding a score, sort from the highest, and number them."""
for f in found:
f["score"] = POINTS[f["severity"]] + (3 if f["code"] in EXPOSED else 0)
found.sort(key=lambda f: (-f["score"], f["area"], f["code"], f["subject"]))
for n, f in enumerate(found, 1):
f["id"] = f"F{n:02d}"
return found
def report(found, folder):
lines = [f"# Cloud posture report: {folder}", "", f"{len(found)} findings. Fix from the top.", "",
"| Id | Score | Severity | Area | Code | Subject | Finding |", "|---|---|---|---|---|---|---|"]
lines += [f"| {f['id']} | {f['score']} | {f['severity']} | {f['area']} | {f['code']} | {f['subject']} | {f['text']} |" for f in found]
return "\n".join(lines) + "\n"
if __name__ == "__main__":
folder = sys.argv[1] if len(sys.argv) > 1 else "account"
found = rank(collect(folder))
for f in found[:10]:
print(f"{f['id']} {f['score']:2d} {f['severity']:8s} {f['area']:9s} {f['code']:14s} {f['subject']:24s} {f['text'][:60]}")
path = sys.argv[2] if len(sys.argv) > 2 else "posture-report.md"
with open(path, "w") as out:
out.write(report(found, folder))
areas = sorted({f["area"] for f in found})
print(f"{len(found)} findings: " + ", ".join(f"{a} {sum(f['area'] == a for f in found)}" for a in areas))
print(f"critical {sum(f['severity'] == 'critical' for f in found)}, report in {path}")
sys.exit(1 if any(f["severity"] == "critical" for f in found) else 0)4. Run it on the Larkfield account
The program prints the ten findings with the highest score and writes all of them to the report.
python3 posture.py
echo "exit code $?"F01 12 critical identity TRUST-ANYONE role support-partner any principal of any account may assume it
F02 12 critical network OPEN-PORT instance bastion-1 port 22 is open to the internet (sg-bastion)
F03 12 critical network OPEN-PORT instance legacy-db port 3306 is open to the internet (sg-legacy)
F04 12 critical storage PUBLIC bucket larkfield-backups policy allows s3:GetObject,s3:ListBucket to everyone
F05 12 critical storage PUBLIC bucket larkfield-media policy allows s3:GetObject to everyone
F06 12 critical storage PUBLIC bucket larkfield-uploads ACL gives READ to a public group
F07 6 high identity ESCALATION policy DeployFull iam:PassRole on *
F08 6 high identity ESCALATION policy HelpdeskKeys iam:CreateAccessKey on arn:aws:iam::111122223333:user/*
F09 6 high identity ESCALATION policy HelpdeskKeys iam:UpdateLoginProfile on arn:aws:iam::111122223333:user/*
F10 6 high identity NO-MFA user nadia.temp signs in with a password only and is an administrator
41 findings: identity 17, inventory 2, logging 4, network 3, storage 15
critical 6, report in posture-report.md
exit code 1Identity and storage have the most findings. The top of the ranked list looks different: six findings with the score 12, and each one is something that a stranger can use today, with no credential of yours (a stranger needs only an AWS account of their own to assume the role). That difference is the reason for the score. Count by area to plan work, and rank by score to choose what to do this morning.
5. Read the report file
sed -n '1,9p' prints lines 1 to 9 of a file, and grep -c counts the lines that match.
sed -n '1,9p' posture-report.md | cut -c1-130
grep -c "| low |" posture-report.md# Cloud posture report: account
41 findings. Fix from the top.
| Id | Score | Severity | Area | Code | Subject | Finding |
|---|---|---|---|---|---|---|
| F01 | 12 | critical | identity | TRUST-ANYONE | role support-partner | any principal of any account may assume it |
| F02 | 12 | critical | network | OPEN-PORT | instance bastion-1 | port 22 is open to the internet (sg-bastion) |
| F03 | 12 | critical | network | OPEN-PORT | instance legacy-db | port 3306 is open to the internet (sg-legacy) |
12Many low findings are the missing rule against plain HTTP, one for each bucket. A real tool lets you group such findings, or accept them with an owner and a date. Do not hide them by deleting the check.
6. Check that a fix moves the result
A posture checker earns trust when a repair changes its output. Put the role support-partner, which anyone could assume, behind a named account, in a copy of the snapshot.
cp -r account account-try
python3 -c "
import json
iam = json.load(open('account-try/iam.json'))
role = next(x for x in iam['roles'] if x['name'] == 'support-partner')
role['trust']['Statement'][0]['Principal'] = {'AWS': 'arn:aws:iam::444455556666:root'}
json.dump(iam, open('account-try/iam.json', 'w'), indent=1)"
python3 posture.py account-try try-report.md | tail -n 2
grep -c "TRUST-ANYONE" try-report.md41 findings: identity 17, inventory 2, logging 4, network 3, storage 15
critical 5, report in try-report.md
0One critical finding fewer, and a new low one in its place: the role now trusts another account, which must be known.
Your turn
The checker has no rule that joins the audit log with the keys. Add one. Copy posture.py to posture_more.py and extend collect: for every long-lived access key (the ID starts with AKIA) that signed at least one event from an address outside the known_networks of the inventory, add one finding with the severity high, the code KEY-OUTSIDE, the subject key and the ID, and the area logging. The function trail.outside of lesson 7 does the address test. Keep posture.py as it is: the scenario test uses it.
Run posture_more.py on account and on account2.
Check yourself
Why does a public bucket get a higher score than an administrator policy on a workload role, although both are serious?
The bucket can be read by anyone on the internet today, with no credential. The role needs a first step: a stolen key or a flaw in the workload. The score adds 3 points for exposure so that the findings with no first step are fixed first.
The checker ends with exit code 0 on Monday. What does that prove, and what not?
It proves that none of its rules found a critical setting in Monday's snapshot. It does not prove that the rules are complete, that the snapshot was complete, or that nobody is misusing valid rights. A clean posture report and an active intruder can exist together.
Your new rule fires for a key that a contractor uses from home. What do you do?
Not delete the rule. Decide what is true: either the address belongs on the list of known networks, with an owner and a date, or the contractor should not use a long-lived key from home at all and gets a role with temporary credentials. A finding that is correct and unwanted points at a decision that nobody has made.
Field notes
- The provider's own posture tools are AWS Security Hub with its standards (the CIS AWS Foundations Benchmark is one) and AWS Config. Prowler and ScoutSuite are open tools that check a live account with hundreds of rules. Use them at work. Your own checker is for understanding them and for the rules that are special to your company.
- Map every code of your checker to a control of the benchmark that your auditors use, and keep the mapping in the repository. Then a report answers the auditor's question directly.
- Track the count of findings by severity over time. A number that goes down is the simplest proof of progress that a manager understands.
- Give every accepted finding an owner and an end date, in a file next to the checker, as you did for allow-lists in "Security operations basics", lesson 3.
- Run the checker against every account of the organisation, from a central account with a read-only role. One account that nobody scans is where the next surprise lives.