Time: ~2 hours · Difficulty: Beginner · You need: a terminal, Python 3.10 or newer, and some practice reading code in any language. No AWS account: the lab runs on your computer, and nothing on this page talks to AWS.
How this page was checked: a script extracted every code block from this page and ran it in order, in zsh on macOS, with boto3 1.43.123 and moto 5.2.5 on Python 3.12.16 and 3.13.18. Every output shown is pasted from that run, and a planted error made the same script fail, so the check can fail. The Azure and Google Cloud notes were checked against azure-identity 1.27.0, azure-mgmt-resource-subscriptions 1.0.0, google-auth 2.62.1 and google-cloud-compute 1.56.0 with their network calls replaced by fakes, and against Microsoft's and Google's documentation. They were not run against a real subscription or project. The EventBridge results come from moto's pattern matcher, which the lab connects to TestEventPattern; they match what EventBridge's documentation gives for those patterns, and were not run against EventBridge.
Python for security automation
Much of cloud security work is answering questions that cover everything a company runs in the cloud. Which access keys has nobody used in 90 days? Which firewall rules let in the whole internet? A company's cloud can span dozens of AWS accounts, each with resources spread across Regions (the separate locations around the world where AWS runs its services), so nobody answers these by clicking through AWS's web console. Someone writes a short script instead.
The script asks the cloud provider's API (application programming interface, the way one program asks another for something) the same question once for each account and Region, and prints whatever matches. In Python those calls go through the provider's SDK (software development kit), a library that turns each API call into an ordinary Python function call: boto3 for AWS (Amazon Web Services), the Azure SDK for Python, and the Google Cloud client libraries. The learning path asks for one scripting language, Python by default, and sets the bar at reading and changing other people's scripts. This page is pitched at that bar. It is not a Python course: it explains each piece of Python as the scripts use it.
The Python in these scripts is short and plain. The hard part is that a script with a mistake in it rarely crashes. It prints a shorter list. A script that looked in one Region, when the open firewall rule is in another, prints nothing at all, and an empty list of findings looks like good news. The walk-through shows five mistakes like that, each in a script that runs without an error and gives the wrong answer, and then the change that fixes it.
boto3 comes first because it has the most of these traps and because the lab can run it for free. Where Azure or Google Cloud has the same trap, a short paragraph says what it looks like there. A last section turns from scripts that ask to code that is sent events: the EventBridge rules that pass GuardDuty findings to a function, and how to test them.
On this page
How to use this guide
Beginner here means new to Python and to the cloud SDKs. You should be comfortable typing commands into a terminal and have read a little code in some language, even a shell script. You do not need an AWS account, and you do not need to know AWS well: the AWS terms the scripts depend on are explained as they come up, and terms with a glossary entry link to it.
Read it in order, because each part uses the one before. The warm-up needs nothing installed. The five questions after it are the idea the rest of the page is built on. In the walk-through, steps 1 and 2 install two Python packages and start the lab in one terminal, and steps 3 to 7 each take one of the five questions in a second terminal: a short script that looks right, the wrong answer it gives with no error, and the change that makes it either right or clear about what it could not check. The exercises then ask you to combine the steps to answer common audit questions yourself, with each answer hidden until you open it.
A code block labelled BASH is something to paste into your terminal, and each one has a copy button. The unlabelled block under it, when there is one, shows what your terminal should print. Most commands start with a line such as cat > roles.py <<'EOF', which writes every line down to the one that says only EOF into a file called roles.py; the block's last line then runs that file. Paste the whole block at once, the EOF line included. Run each one yourself: your output should match the page line for line, apart from the IDs starting sg- in the exercises, which moto makes up afresh each time.
Two things can wait for a second reading. The paragraphs and sentences about Azure and Google Cloud say how the same mistake looks on those clouds, so skip them on a first pass if you work in AWS. And step 2's long lab.py only builds the pretend organization, so paste it without reading it.
From step 3 on, if your output differs from the page, check the terminal you ran it in. Its prompt should start with (.venv), which means the virtual environment from step 1 is active, and you should have run the first line of step 3 in it. Then check that the lab is still running in the other terminal. You can stop between any two steps: Ctrl-C in the lab's terminal stops the lab and forgets the organization, and cd ~/sdk-lab && . .venv/bin/activate && python3 lab.py builds the same organization again from scratch. If you also closed the second terminal, open a new one, run the first line of step 3, and if you are past step 3 run export AWS_PROFILE=auditor as well.
Warm-up: what an API answer looks like in Python
A boto3 call asks AWS a question and hands back AWS's answer as plain Python data, so start by reading some of that data, before installing anything. The block below runs a few lines of Python against a made-up answer typed into the script, and needs only Python itself. Its first line, python3 - <<'PY', runs every line down to PY as a Python program without saving it to a file.
python3 - <<'PY'
response = {
"SecurityGroups": [
{"GroupName": "debug-ssh", "IpPermissions": [
{"IpProtocol": "tcp", "FromPort": 22, "ToPort": 22, "IpRanges": [{"CidrIp": "0.0.0.0/0"}]}]},
{"GroupName": "office-ssh", "IpPermissions": []},
],
"NextToken": "page-2-starts-here",
}
for group in response["SecurityGroups"]:
rules = group["IpPermissions"]
print(f"{group['GroupName']}: {len(rules)} inbound rule(s)")
print("more pages?", "NextToken" in response)
print("Marker:", response.get("Marker"))
PYdebug-ssh: 1 inbound rule(s) office-ssh: 0 inbound rule(s) more pages? True Marker: None
That is a cut-down version of what AWS's describe_security_groups call returns. A security group is AWS's virtual firewall for servers and other resources: IpPermissions holds its inbound rules, and 0.0.0.0/0 means every address on the internet, so debug-ssh lets anyone on the internet reach port 22, where SSH logins happen.
Now the Python. Curly braces make a dictionary, which maps names (keys) to values, and square brackets make a list. response["SecurityGroups"] reads a key and stops the script with a KeyError if it is missing; response.get("Marker") reads one and gives None, Python's "nothing", if it is missing. for runs the indented lines once per item, and in Python the indentation is what marks the lines that belong to the loop. An f"..." string fills in whatever is in {braces}, and in asks "is this key here?".
The last two lines show the first way a script can miss something. AWS hands back long lists a page at a time, and NextToken is its note that another page exists. Nothing makes a script ask for that page, and a script that never asks reports whatever happened to be on the first one. Step 4 shows it happening to a real count.
Five questions to ask before you trust a result
Suppose a script checks every security group for SSH open to the internet and prints nothing. It is tempting to report that there are none. That is only true if the script looked everywhere you meant it to, and its output does not say where it looked. So before you trust a result, and an empty one most of all, ask five questions about how it was made:
- Whose credentials did it run with? boto3 finds credentials in several places and uses the first it comes to, which is not always the identity you asked for. (Step 3)
- Did it read every page? As the warm-up showed, long lists arrive a page at a time. (Step 4)
- Did it look in every Region? A script looks in one Region unless it is written to look in more, and an account can have Regions turned on that nobody remembers. (Step 5)
- Did every call work? A call that AWS refused can end up reported the same way as one that found nothing. (Step 6)
- Did it cover every account? Credentials belong to one account, and a script sees only that one until it is written to step into the others. (Step 7)
Put together, every result is a claim with five conditions attached: as this identity, on the pages it read, in these Regions, among the calls that worked, in these accounts. An empty list is good news only when all five are what you meant. Each step of the walk-through takes one condition, runs a script that gets it wrong without complaint, and then changes the script so that it either gets it right or says what it could not check.
Walk-through: a pretend organization, five silent failures
The lab runs inside moto, an open-source AWS emulator for Python, on your computer. It holds an AWS organization: a group of AWS accounts run together from one management account. You are in the management account, 123456789012, and the organization has three member accounts: prod, dev and sandbox.
The management account holds what the scripts audit. In IAM (Identity and Access Management) it has 137 roles, which are identities that people and programs take on for a while, and six users, each with access keys (the key pairs scripts sign their requests with) of various ages. It has security groups in four Regions, one of them an opt-in Region, and four S3 (Simple Storage Service) buckets, one of which your audit identity is not allowed to read. GuardDuty, AWS's threat detection service, is turned on in five Regions, with the EventBridge rules that the section after the walk-through tests. You audit it all as a user called auditor.
1. Install boto3 and moto
Run python3 --version first. boto3 and moto need Python 3.10 or newer, and the python3 that comes with macOS is older. If yours is, install a newer Python from python.org or your package manager and use its name (for example python3.12) instead of python3 on the second line.
mkdir -p ~/sdk-lab && cd ~/sdk-lab python3 -m venv .venv && . .venv/bin/activate pip install --quiet 'boto3==1.43.123' 'moto[server]==5.2.5' python3 -c "import boto3, moto; print(boto3.__version__, moto.__version__)"
1.43.123 5.2.5
The second line makes a private Python for the lab (a virtual environment) and switches to it, so nothing is installed system-wide. In a new terminal, cd ~/sdk-lab && . .venv/bin/activate switches back. Keep the version pins: boto3 releases several times a week, and moto's behaviour changes between releases. The quotes around moto[server] matter in zsh, which otherwise reads the square brackets as a file-name pattern and refuses the command.
2. Start the lab
Paste the whole block, including the final EOF line. It writes lab.py and starts it. You do not need to follow every line: it is scaffolding, and none of it appears in the scripts you write.
cat > lab.py <<'EOF'
"""lab.py: a pretend AWS organization on your own computer.
Starts moto, an AWS emulator, at http://localhost:8101, fills it with the
accounts, users, security groups, buckets and EventBridge rules this guide
audits, then waits.
Ctrl-C stops it, and everything in it is forgotten. Nothing here talks to AWS.
"""
import datetime, json, logging, pathlib, time
import boto3
import moto.organizations.utils
from moto import settings
from moto.core.responses import ActionResult
from moto.core.utils import utcnow
from moto.ec2.models.availability_zones_and_regions import Region, RegionsAndZonesBackend
from moto.ec2.responses.availability_zones_and_regions import AvailabilityZonesAndRegions
from moto.events.models import EventPattern, EventPatternParser
from moto.events.responses import EventsHandler
from moto.iam.access_control import IAMRequest
from moto.iam.models import AccessKeyLastUsed, iam_backends
from moto.organizations.models import organizations_backends
from moto.server import ThreadedMotoServer
URL = "http://localhost:8101"
MGMT, PROD, DEV, SANDBOX = "123456789012", "111111111111", "222222222222", "333333333333"
HERE = pathlib.Path(__file__).resolve().parent
# Moto lists every Region as usable. A real account can use the 17 Regions
# AWS enables by default plus any opt-in Region someone has turned on, so
# the lab copies that: me-central-1 (UAE) is opted in, other opt-in Regions are not.
DEFAULT_ON = {"us-east-1", "us-east-2", "us-west-1", "us-west-2", "ca-central-1",
"sa-east-1", "eu-west-1", "eu-west-2", "eu-west-3", "eu-central-1",
"eu-north-1", "ap-south-1", "ap-northeast-1", "ap-northeast-2",
"ap-northeast-3", "ap-southeast-1", "ap-southeast-2"}
RegionsAndZonesBackend.regions = [
Region(r, f"ec2.{r}.amazonaws.com",
"opt-in-not-required" if r in DEFAULT_ON else
"opted-in" if r == "me-central-1" else "not-opted-in")
for r in boto3.session.Session().get_available_regions("ec2")]
def describe_regions(self):
regions = self.ec2_backend.describe_regions(self._get_param("RegionNames", []))
if not self._get_bool_param("AllRegions", False):
regions = [r for r in regions if r.opt_in_status != "not-opted-in"]
return ActionResult({"Regions": regions})
AvailabilityZonesAndRegions.describe_regions = describe_regions
# Moto does not answer EventBridge's TestEventPattern call, so the lab answers it
# with moto's own pattern matcher. In an exact match EventBridge compares numbers
# as they are written, so 8 and 8.0 differ; Written keeps each number's text.
class Written(float):
def __new__(cls, text):
number = super().__new__(cls, text)
number.text = text
return number
def __eq__(self, other):
return isinstance(other, Written) and self.text == other.text
def __ne__(self, other):
return not self == other
__hash__ = float.__hash__
def test_event_pattern(self):
def load(name):
return json.loads(self._get_param(name), parse_int=Written, parse_float=Written)
pattern, event = load("EventPattern"), load("Event")
EventPatternParser(None)._validate_event_pattern(pattern)
matcher = EventPattern(None, pattern)
return json.dumps({"Result": matcher._does_event_match(matcher._flatten_dict(event), pattern)})
EventsHandler.test_event_pattern = test_event_pattern
# When moto checks the signature on a GET request, such as GuardDuty's list and
# get calls, it signs the request's headers as if they were its body. A GET
# request has no body, so the lab removes it before checking.
signed_request = IAMRequest._create_aws_request
def without_body(self):
request = signed_request(self)
if self._method == "GET":
request.data = b""
return request
IAMRequest._create_aws_request = without_body
logging.getLogger("werkzeug").setLevel(logging.ERROR)
ThreadedMotoServer(ip_address="127.0.0.1", port=8101, verbose=False).start()
def client(service, region="us-east-1", creds=None):
creds = creds or {"aws_access_key_id": "lab", "aws_secret_access_key": "lab"}
return boto3.client(service, region_name=region, endpoint_url=URL, **creds)
def into(account):
c = client("sts").assume_role(RoleArn=f"arn:aws:iam::{account}:role/OrganizationAccountAccessRole",
RoleSessionName="lab-setup")["Credentials"]
return {"aws_access_key_id": c["AccessKeyId"], "aws_secret_access_key": c["SecretAccessKey"],
"aws_session_token": c["SessionToken"]}
def policy(*statements):
return json.dumps({"Version": "2012-10-17", "Statement": list(statements)})
READ = {"Effect": "Allow", "Resource": "*",
"Action": ["iam:Get*", "iam:List*", "ec2:Describe*", "s3:Get*", "s3:List*",
"organizations:Describe*", "organizations:List*", "guardduty:Get*",
"guardduty:List*", "events:Describe*", "events:List*", "events:TestEventPattern"]}
def open_group(name, port, region, creds=None, cidr="0.0.0.0/0"):
ec2 = client("ec2", region, creds)
gid = ec2.create_security_group(GroupName=name, Description=name)["GroupId"]
rng = {"Ipv6Ranges": [{"CidrIpv6": cidr}]} if ":" in cidr else {"IpRanges": [{"CidrIp": cidr}]}
perm = {"IpProtocol": "-1"} if port is None else {"IpProtocol": "tcp", "FromPort": port, "ToPort": port}
ec2.authorize_security_group_ingress(GroupId=gid, IpPermissions=[{**perm, **rng}])
# The organization: you are in the management account, 123456789012.
org = client("organizations")
org.create_organization(FeatureSet="ALL")
organizations_backends[MGMT]["aws"].accounts[0].name = "management"
moto.organizations.utils.make_random_account_id = iter([PROD, DEV, SANDBOX]).__next__
for name in ["prod", "dev", "sandbox"]:
org.create_account(Email=f"{name}@example.com", AccountName=name)
# An audit role in each member account, trusting the auditor user.
for account in [PROD, DEV, SANDBOX]:
iam = client("iam", creds=into(account))
iam.create_role(RoleName="audit-readonly", AssumeRolePolicyDocument=policy(
{"Effect": "Allow", "Action": "sts:AssumeRole",
"Principal": {"AWS": f"arn:aws:iam::{MGMT}:user/auditor"}}))
iam.put_role_policy(RoleName="audit-readonly", PolicyName="read", PolicyDocument=policy(READ))
open_group("prod-bastion", 22, "us-west-2", into(PROD))
open_group("sandbox-test", None, "us-east-1", into(SANDBOX))
# IAM in the management account: 137 roles, so the list is longer than one page.
iam = client("iam")
for n in range(1, 138):
iam.create_role(RoleName=f"workload-{n:03d}", AssumeRolePolicyDocument=policy(
{"Effect": "Allow", "Action": "sts:AssumeRole", "Principal": {"Service": "ec2.amazonaws.com"}}))
# Users and their keys. Moto cannot create old keys, so the lab ages them:
# (user, days since the key was created, days since it was last used, active?)
KEYS = [("alice", 400, 2, True), ("bob", 300, 120, True), ("carol", 5, None, True),
("dave", 150, None, True), ("dave", 500, 400, False),
("build-bot", 200, 0, True), ("auditor", 0, None, True)]
creds = {}
for user, created, used, active in KEYS:
if user not in iam_backends[MGMT]["global"].users:
iam.create_user(UserName=user)
key = iam.create_access_key(UserName=user)["AccessKey"]
creds[user] = (key["AccessKeyId"], key["SecretAccessKey"])
if not active:
iam.update_access_key(UserName=user, AccessKeyId=key["AccessKeyId"], Status="Inactive")
stored = iam_backends[MGMT]["global"].users[user].access_keys[-1]
stored.create_date = utcnow() - datetime.timedelta(days=created)
if used is not None:
stored.last_used = AccessKeyLastUsed(utcnow() - datetime.timedelta(days=used), "iam", "us-east-1")
iam.put_user_policy(UserName="auditor", PolicyName="audit", PolicyDocument=policy(
READ,
# The auditor may assume the audit role in prod and dev. sandbox joined the
# organization after this list was written, and nobody added it.
{"Effect": "Allow", "Action": "sts:AssumeRole",
"Resource": [f"arn:aws:iam::{PROD}:role/audit-readonly", f"arn:aws:iam::{DEV}:role/audit-readonly"]},
{"Effect": "Deny", "Action": "s3:*", "Resource": ["arn:aws:s3:::csoh-lab-payroll-exports",
"arn:aws:s3:::csoh-lab-payroll-exports/*"]}))
iam.put_user_policy(UserName="build-bot", PolicyName="ci", PolicyDocument=policy(
{"Effect": "Allow", "Action": "s3:PutObject", "Resource": "arn:aws:s3:::csoh-lab-build-artifacts/*"}))
# Security groups in four Regions, one of them opt-in.
open_group("web-public", 443, "us-east-1")
open_group("debug-ssh", 22, "us-east-1")
open_group("legacy-rdp", 3389, "eu-west-1")
open_group("ipv6-everything", None, "ap-southeast-2", cidr="::/0")
open_group("temp-postgres", 5432, "me-central-1")
client("ec2").create_security_group(GroupName="office-ssh", Description="office-ssh")
# Buckets: Block Public Access on, off, partly on, and one the auditor may not read.
s3 = client("s3")
ALL_ON = dict.fromkeys(["BlockPublicAcls", "IgnorePublicAcls", "BlockPublicPolicy", "RestrictPublicBuckets"], True)
for bucket, bpa in [("csoh-lab-cloudtrail", ALL_ON), ("csoh-lab-web-assets", None),
("csoh-lab-build-artifacts", {**ALL_ON, "BlockPublicPolicy": False}),
("csoh-lab-payroll-exports", ALL_ON)]:
s3.create_bucket(Bucket=bucket)
if bpa:
s3.put_public_access_block(Bucket=bucket, PublicAccessBlockConfiguration=bpa)
s3.put_bucket_policy(Bucket="csoh-lab-cloudtrail", Policy=policy(
{"Effect": "Allow", "Principal": {"Service": "cloudtrail.amazonaws.com"},
"Action": "s3:PutObject", "Resource": "arn:aws:s3:::csoh-lab-cloudtrail/*"}))
# GuardDuty in five Regions, and the EventBridge rules meant to pass its findings on:
# Region -> [(rule name, event pattern, enabled?, target or None)].
FINDING = {"source": ["aws.guardduty"], "detail-type": ["GuardDuty Finding"]}
RULES = {
"us-east-1": [("guardduty-high", {**FINDING, "detail": {"severity": [{"numeric": [">=", 7]}]}},
True, f"arn:aws:lambda:us-east-1:{MGMT}:function:isolate-instance"),
("ec2-state-changes", {"source": ["aws.ec2"]}, True,
f"arn:aws:logs:us-east-1:{MGMT}:log-group:ec2-state")],
"us-west-2": [("guardduty-all", {"source": ["aws.guardduty"]}, True, None)],
"eu-west-1": [("guardduty-to-soc", FINDING, False, f"arn:aws:sns:eu-west-1:{MGMT}:soc-alerts")],
"ap-southeast-2": [("guardduty-alerts", {**FINDING, "detail": {"severity": [5, 8]}}, True,
f"arn:aws:sns:ap-southeast-2:{MGMT}:soc-alerts")],
"me-central-1": [],
}
for region, rules in RULES.items():
client("guardduty", region).create_detector(Enable=True)
for name, pattern, enabled, target in rules:
client("events", region).put_rule(Name=name, EventPattern=json.dumps(pattern),
State="ENABLED" if enabled else "DISABLED")
if target:
client("events", region).put_targets(Rule=name, Targets=[{"Id": "1", "Arn": target}])
# From here on every request is checked against the caller's IAM policies.
settings.INITIAL_NO_AUTH_ACTION_COUNT = 0
(HERE / "aws").mkdir(exist_ok=True)
(HERE / "aws" / "config").write_text(
"[default]\nregion = us-east-1\n\n[profile auditor]\nregion = us-east-1\n")
(HERE / "aws" / "credentials").write_text("".join(
f"[{profile}]\naws_access_key_id = {creds[user][0]}\naws_secret_access_key = {creds[user][1]}\n\n"
for profile, user in [("default", "alice"), ("auditor", "auditor")]))
(HERE / "build-bot.env").write_text(
f"export AWS_ACCESS_KEY_ID={creds['build-bot'][0]}\nexport AWS_SECRET_ACCESS_KEY={creds['build-bot'][1]}\n")
(HERE / "lab.env").write_text(
"unset AWS_PROFILE AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_REGION AWS_DEFAULT_REGION\n"
f"export AWS_ENDPOINT_URL={URL}\n"
f"export AWS_CONFIG_FILE={HERE}/aws/config\n"
f"export AWS_SHARED_CREDENTIALS_FILE={HERE}/aws/credentials\n")
print(f"Lab running at {URL}. Leave this terminal open; Ctrl-C stops it.", flush=True)
try:
while True:
time.sleep(3600)
except KeyboardInterrupt:
print("Lab stopped.")
EOF
python3 lab.pyLab running at http://localhost:8101. Leave this terminal open; Ctrl-C stops it.
The lab listens only on your own computer, at localhost port 8101 (moto's usual port, 5000, is often taken on a Mac by macOS's AirPlay Receiver). It builds the organization, then writes four files beside itself: an AWS config file and credentials file under aws/, build-bot.env, which step 3 uses, and lab.env, which points every AWS tool in a terminal at the lab. Five parts of it change moto rather than fill it: moto lists every Region as usable and ignores the difference between default and opt-in Regions, it cannot create an access key that is already old, it gives new accounts random IDs, it does not answer EventBridge's TestEventPattern call, and once it checks permissions it refuses GuardDuty's read calls with a signature error. The lab corrects all five so the walk-through behaves like a real account and your output matches this page. The last setting before the files makes moto check every request against the caller's IAM policies, so an AccessDenied in the lab is a real refusal.
3. Find out who you are (identity)
Leave the lab running and open a second terminal. Everything from here on runs there. The last command on the first line loads lab.env, which clears any AWS settings already in that terminal and points boto3 at the lab. Skip it and these scripts read whatever AWS account your own credentials point at.
cd ~/sdk-lab && . .venv/bin/activate && . ./lab.env
cat > whoami.py <<'EOF'
import boto3
session = boto3.Session()
me = session.client("sts").get_caller_identity()
print("account: ", me["Account"])
print("identity:", me["Arn"])
print("found in:", session.get_credentials().method)
print("region: ", session.region_name)
EOF
python3 whoami.pyaccount: 123456789012 identity: arn:aws:iam::123456789012:user/alice found in: shared-credentials-file region: us-east-1
get_caller_identity asks AWS STS (Security Token Service) which identity signed the request. It needs no permissions, so it works for any valid credentials, and every script that reports on an account should call it first and print the answer. This one ran as alice, the [default] profile in the credentials file, and not as the auditor. found in is where boto3 found the credentials, and region is the Region its clients will talk to unless told otherwise. Ask for the auditor's profile:
AWS_PROFILE=auditor python3 whoami.py
account: 123456789012 identity: arn:aws:iam::123456789012:user/auditor found in: shared-credentials-file region: us-east-1
That is the identity the rest of the page needs. Now repeat a common afternoon: earlier you were debugging the CI (continuous integration) pipeline and exported its access key into this terminal, and now you run the audit with the auditor's profile.
. ./build-bot.env AWS_PROFILE=auditor python3 whoami.py
account: 123456789012 identity: arn:aws:iam::123456789012:user/build-bot found in: env region: us-east-1
You asked for the auditor and got build-bot. boto3 tries a fixed list of places for credentials and stops at the first that has some. Environment variables (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY) come third in boto3's credential order, ahead of the profiles in the credentials file, and AWS_PROFILE does not override them. Passing the profile in code, boto3.Session(profile_name="auditor"), does override them: botocore removes the environment-variable step when a profile is given that way. The AWS CLI (command-line interface) behaves the same way, and --profile on its command line does override environment keys. In this lab the mix-up shows at once, because build-bot may only upload to one bucket, so any audit that lists anything fails. A build identity with read access everywhere would produce a complete, plausible report about the wrong permissions. Clear the leftover keys and set the auditor for the rest of the page:
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY export AWS_PROFILE=auditor python3 whoami.py
account: 123456789012 identity: arn:aws:iam::123456789012:user/auditor found in: shared-credentials-file region: us-east-1
A script that should only ever run against one account can go further and stop when the account ID is not the one it expects.
On Azure, DefaultAzureCredential from the azure-identity library has the same shape of chain: a service principal set in environment variables comes first, then workload identity, then managed identity, and your Azure CLI login comes well after those, so leftover service-principal variables such as AZURE_CLIENT_SECRET win over the account you think you logged in with, and so does a virtual machine's managed identity when the script runs on one. At INFO log level it says which one it used, in a line that reads DefaultAzureCredential acquired a token from ....
On Google Cloud, Application Default Credentials (ADC) take the credentials file named by GOOGLE_APPLICATION_CREDENTIALS before the credentials that gcloud auth application-default login saved, and the account you signed in with through plain gcloud auth login is not one of the places ADC looks. google.auth.default() returns the credentials it chose and their project, so print them.
4. Read every page
A list call returns one page of results. IAM's ListRoles returns up to 100 roles per call unless asked for a different number, says whether more exist in IsTruncated, and hands back a Marker to continue from. Count the roles three ways:
cat > roles.py <<'EOF'
import boto3
iam = boto3.client("iam")
first = iam.list_roles()
print("one call: ", len(first["Roles"]), "roles, IsTruncated =", first["IsTruncated"])
roles, extra = [], {}
while True:
page = iam.list_roles(**extra)
roles.extend(page["Roles"])
if "NextToken" not in page:
break
extra = {"NextToken": page["NextToken"]}
print("hand-written loop:", len(roles), "roles")
roles = []
for page in iam.get_paginator("list_roles").paginate():
roles.extend(page["Roles"])
print("paginator: ", len(roles), "roles")
EOF
python3 roles.pyone call: 100 roles, IsTruncated = True hand-written loop: 100 roles paginator: 137 roles
The single call stops at 100 and says so in a field the script never checks. The hand-written loop is the kind people copy from an EC2 (Elastic Compute Cloud) script: EC2 and many other services call their continuation field NextToken, IAM calls it Marker, so the loop sees no NextToken after the first page and stops, as if it had finished. (while True: repeats until break, and **extra passes the dictionary's contents as named arguments.) A paginator knows each operation's own field names and keeps calling until the last page, so get_paginator(...).paginate() is the habit: when client.can_paginate("operation_name") is True, use it.
"No more pages" is a signal only the API can give, and two details make guessing it worse. IAM's documentation says it may return fewer than the page size even when more results exist, so a short page is not a last page. AWS Organizations goes further: its list calls can occasionally return an empty page while more results remain, and only a missing NextToken means you are done. A loop that stops on an empty page is wrong there, and a paginator is not.
The Azure SDK and Google's google-cloud-* libraries page for you: the ItemPaged object an Azure list method returns follows nextLink as you loop over it, and Google's pagers follow next_page_token. The one-page bug comes back when a script skips the SDK, calls the REST (representational state transfer) API with requests and ignores nextLink or nextPageToken, or uses Google's older googleapiclient discovery client, where each execute() returns one page.
5. Cover every enabled Region
A boto3 client talks to one Region: the region_name you pass, or else the AWS_DEFAULT_REGION environment variable, or else the profile's region setting. boto3 ignores AWS_REGION, which the AWS CLI does read, so in a terminal where only AWS_REGION is set, the CLI and your script can be looking at different Regions. Security groups, like most resources, live in a Region. This script lists the non-default groups in the client's Region, then in every Region the account has enabled:
cat > regions.py <<'EOF'
import boto3
def group_names(ec2):
names = []
for page in ec2.get_paginator("describe_security_groups").paginate():
for group in page["SecurityGroups"]:
if group["GroupName"] != "default":
names.append(group["GroupName"])
return names
ec2 = boto3.client("ec2")
print(f"{ec2.meta.region_name} only: {group_names(ec2)}")
enabled = [r["RegionName"] for r in ec2.describe_regions()["Regions"]]
print(len(enabled), "Regions enabled for this account:")
for region in sorted(enabled):
names = group_names(boto3.client("ec2", region_name=region))
if names:
print(f" {region}: {names}")
EOF
python3 regions.pyus-east-1 only: ['web-public', 'debug-ssh', 'office-ssh'] 18 Regions enabled for this account: ap-southeast-2: ['ipv6-everything'] eu-west-1: ['legacy-rdp'] me-central-1: ['temp-postgres'] us-east-1: ['web-public', 'debug-ssh', 'office-ssh']
def defines a function, a named block that runs when called and hands back what return gives it. Here it lets the same code run once per Region. The first line is what a script that never names a Region sees: three groups, and nothing about the three Regions it did not look at. describe_regions returns the Regions enabled for the account, and AllRegions=True adds the disabled ones, each with an OptInStatus.
One of the 18 needs explaining. AWS enables 17 Regions in every commercial account, the ones launched before 20 March 2019. Newer Regions are opt-in: disabled until someone turns them on, and then as usable as any other. The lab account has opted in to me-central-1 (United Arab Emirates), and a database port is open to the internet there. A script with a hard-coded list of the usual Regions never looks there, and neither does a reviewer who knows the account "only uses us-east-1". Ask the account, every run.
Not everything is regional. IAM and Organizations are global, so one client covers them, and S3's list_buckets returns every bucket whatever its Region. Azure draws the line elsewhere: a subscription is the unit, and calls such as network_security_groups.list_all() in azure-mgmt-network return a subscription's resources in every Azure region at once. On Google Cloud, VPC (virtual private cloud) firewall rules are global within a project, though organization, folder and network firewall policies also decide what gets in and have list calls of their own, and for regional and zonal resources the Compute library's aggregated_list covers every region and zone of one project. On both, the boundary a script forgets is the subscription or the project, which step 7 comes back to.
6. Let errors say what they could not check
When a call fails, boto3 raises ClientError, and the error code AWS sent is in err.response["Error"]["Code"]. Some codes are answers: NoSuchBucketPolicy means the bucket has no bucket policy, the access rules attached to the bucket itself. Others mean the script did not find out, such as AccessDenied or a throttling code after the retries run out. This script treats them alike:
cat > policies_naive.py <<'EOF'
import boto3
s3 = boto3.client("s3")
for bucket in s3.list_buckets()["Buckets"]:
try:
s3.get_bucket_policy(Bucket=bucket["Name"])
print(bucket["Name"], "has a bucket policy")
except Exception:
print(bucket["Name"], "has no bucket policy")
EOF
python3 policies_naive.pycsoh-lab-cloudtrail has a bucket policy csoh-lab-web-assets has no bucket policy csoh-lab-build-artifacts has no bucket policy csoh-lab-payroll-exports has no bucket policy
The last line is false. The auditor is not allowed to read anything about csoh-lab-payroll-exports, so the call was refused, and except Exception: turned the refusal into an answer. try: runs the indented lines, and when one of them raises an error Python jumps to the except block that matches it; Exception matches nearly everything, so no failure can get past it. Catch only ClientError, act on the codes that are answers, and keep a list of everything else:
cat > policies.py <<'EOF'
import sys
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
s3 = boto3.client("s3", config=Config(retries={"mode": "standard", "total_max_attempts": 10}))
has_policy, no_policy, not_checked = [], [], []
for page in s3.get_paginator("list_buckets").paginate():
for bucket in page["Buckets"]:
name = bucket["Name"]
try:
s3.get_bucket_policy(Bucket=name)
has_policy.append(name)
except ClientError as err:
code = err.response["Error"]["Code"]
if code == "NoSuchBucketPolicy":
no_policy.append(name)
else:
not_checked.append(f"{name} ({code})")
print("has a policy:", has_policy)
print("no policy: ", no_policy)
print("NOT CHECKED: ", not_checked)
sys.exit(1 if not_checked else 0)
EOF
python3 policies.py; echo "exit code: $?"has a policy: ['csoh-lab-cloudtrail'] no policy: ['csoh-lab-web-assets', 'csoh-lab-build-artifacts'] NOT CHECKED: ['csoh-lab-payroll-exports (AccessDenied)'] exit code: 1
The bucket is now reported as not checked, with the reason, and the script exits with code 1, so a scheduler or CI job that runs it sees an incomplete result as a failure. sys.exit(1 if not_checked else 0) is a one-line if-else: 1 when the list has anything in it, 0 when it is empty. The bucket listing now uses a paginator too: AWS strongly recommends paginated ListBuckets requests and rejects unpaginated ones from accounts allowed more than 10,000 buckets.
The Config line sets the retry behaviour instead of leaving it to the default. In the version pinned here, boto3's default is legacy retry mode, which makes at most five attempts in all and retries a shorter list of throttling codes than standard mode does. In this botocore release a new environment variable can already switch the default, so setting the mode yourself keeps the behaviour from changing under you. Use total_max_attempts, which counts every attempt, rather than max_attempts, which in a Config counts only the retries. When the attempts run out, the throttling code (such as Throttling, RequestLimitExceeded or SlowDown) lands in the NOT CHECKED list with everything else.
Not every failure needs catching. Run the same script as alice, who has no permissions, and the very first call fails outside the try:
AWS_PROFILE=default python3 policies.py 2>&1 | tail -n 1
botocore.errorfactory.AccessDenied: An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied
A crash with a traceback is a loud failure, which is fine. The failure to fear is the quiet one. A network failure is loud in the same way: botocore raises it as a BotoCoreError, such as EndpointConnectionError, not as a ClientError, so this script stops on one instead of listing it. (2>&1 | tail -n 1 sends the error output through tail, which keeps only the last line of the traceback.) Azure has the same split: the SDK raises HttpResponseError from azure.core.exceptions with a status_code, 403 for a refusal and 404 for something that does not exist, while Google's client libraries raise exceptions from google.api_core.exceptions, such as Forbidden and PermissionDenied for a refusal and NotFound for a missing resource. A broad except turns all of them into "nothing found".
7. Cover every account in the organization
One identity normally sees one account. To audit an organization you list its accounts, then in each one assume a role that trusts your audit identity, and use the temporary credentials that assume_role returns. This script counts the IAM roles in every account:
cat > org_roles.py <<'EOF'
import sys
import boto3
from botocore.exceptions import ClientError
ROLE = "audit-readonly"
home = boto3.Session()
my_account = home.client("sts").get_caller_identity()["Account"]
def session_in(account_id):
if account_id == my_account:
return home
creds = home.client("sts").assume_role(
RoleArn=f"arn:aws:iam::{account_id}:role/{ROLE}",
RoleSessionName="security-audit")["Credentials"]
return boto3.Session(aws_access_key_id=creds["AccessKeyId"],
aws_secret_access_key=creds["SecretAccessKey"],
aws_session_token=creds["SessionToken"],
region_name=home.region_name)
def count_roles(session):
iam = session.client("iam")
return sum(len(page["Roles"]) for page in iam.get_paginator("list_roles").paginate())
not_checked = []
for page in home.client("organizations").get_paginator("list_accounts").paginate():
for account in page["Accounts"]:
label = f"{account['Name']} ({account['Id']})"
if account["State"] != "ACTIVE":
print(f"{label}: skipped, state is {account['State']}")
continue
try:
print(f"{label}: {count_roles(session_in(account['Id']))} roles")
except ClientError as err:
not_checked.append(label)
print(f"{label}: NOT CHECKED, {err.response['Error']['Code']}")
sys.exit(1 if not_checked else 0)
EOF
python3 org_roles.py; echo "exit code: $?"management (123456789012): 137 roles prod (111111111111): 2 roles dev (222222222222): 2 roles sandbox (333333333333): NOT CHECKED, AccessDenied exit code: 1
session_in() returns a boto3 session for any account: the one you are in already, or a new session built from the role's temporary credentials. The auditor's own policy lets it assume the audit role in prod and dev only. sandbox joined later, nobody added it, so AWS refused the role and the script says so. AssumeRole is also refused when the role does not exist under that exact name (role names are case sensitive when you assume one), when its trust policy does not name you, or when you fail one of its conditions, and IAM's troubleshooting guide lists what to check. Write that loop with except Exception: continue and it prints three accounts and exits 0.
Three details from the AWS documentation shape this loop. First, read State and not Status: AWS said it would retire the account Status field from the Organizations API on 9 September 2026. A script that tests account.get("Status") != "ACTIVE" gets None once the field is gone, and its "skip inactive accounts" line then skips every account. Second, list_accounts works only from the management account or from a member account that is a delegated administrator, so an audit that runs from a separate security account needs that account registered as one. Third, accounts created through Organizations come with a role named OrganizationAccountAccessRole by default, but it grants full administrator access, and accounts invited into the organization do not get it unless someone creates it. Many organizations deploy their own read-only audit role to every account instead, as the lab does. Then every account that joins later needs the role, and in the lab it also needs adding to the auditor's policy.
On Azure, the subscription is the boundary: SubscriptionClient(credential).subscriptions.list() lists the subscriptions your credential can see, and the rest of a script runs per subscription. In azure-mgmt-resource 25.0.0 that client moved into its own package, azure-mgmt-resource-subscriptions, which azure-mgmt-resource does not install for you. Older scripts that import it from azure.mgmt.resource fail until you install that package and import from azure.mgmt.resource.subscriptions. On Google Cloud the project is the boundary, and ProjectsClient().search_projects() in google-cloud-resource-manager lists the projects you can see. On both clouds a subscription or project your identity cannot see is missing from that list, with no error at all, so compare the count with what the organization says it has.
Findings that go nowhere: EventBridge event patterns
Everything so far pulls: a script asks the API a question and reports the answer. Security automation also runs the other way. GuardDuty, AWS's threat detection service, sends every finding to Amazon EventBridge as an event, a JSON document whose detail field holds the finding. An EventBridge rule holds an event pattern, and for every event the pattern matches, EventBridge sends the event to the rule's targets, often a Lambda function written in Python, which receives the event as a dictionary. When an event matches no rule, EventBridge takes no action. No error appears anywhere, so a pattern that never matches looks exactly like a quiet week.
EventBridge's TestEventPattern call says whether a pattern matches an event, without creating anything. This script tests three patterns against four GuardDuty findings, cut down to the fields TestEventPattern requires plus a finding type and a severity:
cat > patterns.py <<'EOF'
import json
import boto3
events = boto3.client("events")
def finding(severity):
return json.dumps({
"version": "0", "id": "4e2b0c1a-6f3d-4c8e-9a71-0d5b2f8e7c19",
"detail-type": "GuardDuty Finding", "source": "aws.guardduty",
"account": "123456789012", "time": "2026-11-05T09:00:00Z",
"region": "us-east-1", "resources": [],
"detail": {"type": "UnauthorizedAccess:EC2/SSHBruteForce", "severity": severity}})
PATTERNS = {
"AWS's CLI example": {"source": ["aws.guardduty"], "detail-type": ["GuardDuty Finding"],
"detail": {"severity": [5, 8]}},
"one letter off": {"source": ["aws.guardduty"], "detail-type": ["GuardDuty Findings"]},
"numeric, 7 and up": {"source": ["aws.guardduty"], "detail-type": ["GuardDuty Finding"],
"detail": {"severity": [{"numeric": [">=", 7]}]}},
}
SEVERITIES = [5, 7.5, 8, 8.0]
print(" " * 18 + "".join(f"{severity!r:>7}" for severity in SEVERITIES))
for name, pattern in PATTERNS.items():
row = ""
for severity in SEVERITIES:
answer = events.test_event_pattern(EventPattern=json.dumps(pattern), Event=finding(severity))
row += f"{'match' if answer['Result'] else '-':>7}"
print(f"{name:18}{row}")
EOF
python3 patterns.py5 7.5 8 8.0 AWS's CLI example match - match - one letter off - - - - numeric, 7 and up - match match match
The first pattern is the example in GuardDuty's own guide for matching findings "with the severity of either 5 or 8", and it does exactly that. GuardDuty scores a High finding anywhere from 7.0 to 8.9, and a Critical one from 9.0 to 10.0, so a High finding at 7.5 never arrives. The pattern also misses 8.0, because in an exact match EventBridge compares numbers as they are written: to it, 8, 8.0 and 8.0e0 are three different values. GuardDuty's API defines severity as a decimal number without saying how it writes a whole one, and the same guide's console example lists both 4 and 4.0, then every tenth up to 10.0. The third pattern uses numeric, which compares values as numbers, and has neither problem. In the script, Python keeps 8 (a whole number, an int) and 8.0 (a float) apart, json.dumps writes each the way Python holds it, and {severity!r:>7} prints it the same way, right-aligned in seven characters.
The second pattern is one letter off. The detail type is GuardDuty Finding, singular, and EventBridge compares strings character by character without ignoring case, so this rule would never send anything. A mistake EventBridge can see is refused instead: a value that is not in a list, such as "source": "aws.guardduty", fails with InvalidEventPatternException, which is loud and fine.
Keep a few sample events beside each pattern, and run TestEventPattern over them whenever a pattern changes, as a test in CI, checking that the events you want match and the others do not. The EventBridge console's sandbox does the same by hand and offers a GuardDuty sample event to start from. In the lab, moto's own pattern matcher answers the call: moto has one but does not connect it to TestEventPattern, so lab.py connects it and makes it compare numbers as written. The results above are the ones EventBridge's documentation gives for these patterns, but they did not come from EventBridge.
A pattern can also be right and in the wrong place. A rule only applies to events that arrive on its own event bus, and each Region has its own. GuardDuty runs separately in each Region, AWS recommends turning it on in all of them, and each finding goes to the default event bus in the Region that produced it, so a rule in us-east-1 never sees a finding from eu-west-1. That takes a rule in every Region where GuardDuty is on, or a rule in each one that forwards findings to a central Region, which EventBridge can do. Two more things decide what arrives. GuardDuty sends a new finding in near real time, but folds later occurrences of the same finding into one event every 6 hours, unless an administrator account shortens that to 1 hour or 15 minutes. And findings that a suppression rule archives are not sent at all. Exercise 5 checks every Region of the lab account.
Hands-on exercises
These are the questions people script most often. Write each one in ~/sdk-lab with the lab still running, as the auditor, and compare your output with the answer.
List every IAM user with an active access key that has not been used for 90 days. AWS Security Hub CSPM, AWS's cloud security posture management service, uses the same 90-day line in its control IAM.8. The calls you need are list_users, list_access_keys and get_access_key_last_used.
Show the answer
cat > stale_keys.py <<'EOF'
import datetime
import boto3
LIMIT = datetime.timedelta(days=90)
now = datetime.datetime.now(datetime.timezone.utc)
iam = boto3.client("iam")
for page in iam.get_paginator("list_users").paginate():
for user in page["Users"]:
name = user["UserName"]
for key_page in iam.get_paginator("list_access_keys").paginate(UserName=name):
for key in key_page["AccessKeyMetadata"]:
if key["Status"] != "Active":
continue
used = iam.get_access_key_last_used(AccessKeyId=key["AccessKeyId"])["AccessKeyLastUsed"]
if "LastUsedDate" in used:
idle, how = now - used["LastUsedDate"], "last used"
else:
idle, how = now - key["CreateDate"], "never used, created"
if idle > LIMIT:
print(f"{name}: {how} {idle.days} days ago")
EOF
python3 stale_keys.pybob: last used 120 days ago dave: never used, created 150 days ago
dave's key is the one a first attempt misses. For a key that has never been used, AWS leaves LastUsedDate out and sets ServiceName and Region to "N/A". So used["LastUsedDate"] crashes on it, which is loud and fine, while if used.get("LastUsedDate") and ... quietly treats a key that has sat unused for 150 days as not stale. A never-used key is measured from its CreateDate, which is why carol's five-day-old key is not on the list. dave's second key is inactive and is skipped, since it cannot sign anything until someone turns it back on. The times boto3 returns carry a time zone, so now must have one too (datetime.timezone.utc): subtracting a time without one from a time with one raises TypeError.
For a large account, IAM's credential report (generate_credential_report, then get_credential_report) gives the same dates for every user in one CSV (comma-separated values) file instead of three calls per key, and writes N/A where a key was never used. IAM makes a new report at most every four hours, so it can be up to four hours behind.
List every security group with an inbound rule open to the whole internet, in every enabled Region, with the protocol and port. Make the work a function that takes a boto3 session, because Exercise 4 reuses it.
Show the answer
cat > open_sgs.py <<'EOF'
import boto3
WORLD = {"0.0.0.0/0", "::/0"}
def describe(rule):
if rule["IpProtocol"] == "-1":
return "all traffic"
low, high = rule.get("FromPort"), rule.get("ToPort")
return f"{rule['IpProtocol']} {low if low == high else f'{low}-{high}'}"
def open_groups(session):
found = []
ec2 = session.client("ec2")
for region in sorted(r["RegionName"] for r in ec2.describe_regions()["Regions"]):
regional = session.client("ec2", region_name=region)
for page in regional.get_paginator("describe_security_groups").paginate():
for group in page["SecurityGroups"]:
for rule in group["IpPermissions"]:
sources = [r["CidrIp"] for r in rule.get("IpRanges", [])]
sources += [r["CidrIpv6"] for r in rule.get("Ipv6Ranges", [])]
for source in WORLD.intersection(sources):
found.append(f"{region} {group['GroupName']} ({group['GroupId']}): "
f"{describe(rule)} from {source}")
return sorted(found)
if __name__ == "__main__":
for line in open_groups(boto3.Session()):
print(line)
EOF
python3 open_sgs.pyap-southeast-2 ipv6-everything (sg-7febd3ce0102d6546): all traffic from ::/0 eu-west-1 legacy-rdp (sg-ddfad65ca6f049189): tcp 3389 from 0.0.0.0/0 me-central-1 temp-postgres (sg-be8767ea2416195ef): tcp 5432 from 0.0.0.0/0 us-east-1 debug-ssh (sg-c225ead533fca7440): tcp 22 from 0.0.0.0/0 us-east-1 web-public (sg-f3b1db538cdbb826c): tcp 443 from 0.0.0.0/0
Your group IDs will differ; moto makes new ones each time the lab starts. Three of the five are outside us-east-1, and the first is the one most scripts miss: its rule allows ::/0, the whole IPv6 internet, which the API returns in Ipv6Ranges, not in IpRanges. A script that reads only IpRanges reports four groups. The same rule uses protocol -1, which means every protocol and every port, and it has no FromPort at all, so rule["FromPort"] would crash there; rule.get() does not. Only IpPermissions, the inbound rules, is checked. IpPermissionsEgress holds the outbound rules, where allowing everything is the usual default.
WORLD.intersection(sources) keeps the sources that are in the set WORLD. The last two lines run only when the file is run as a script, not when another script imports its function, which Exercise 4 relies on. Whether web-public is a finding is a question for a person: port 443 open to everyone is normal for a public load balancer. The script's job is the list, and it has one gap to know about: a rule can take its sources from a managed prefix list (PrefixListIds), which this script does not expand, so check what your prefix lists contain.
List every S3 bucket that S3 Block Public Access does not fully protect. Each of the four settings can be on for the bucket, for the whole account, or both. Report which settings are off at both levels, and report any bucket you could not check.
Show the answer
cat > bpa.py <<'EOF'
import sys
import boto3
from botocore.exceptions import ClientError
SETTINGS = ["BlockPublicAcls", "IgnorePublicAcls", "BlockPublicPolicy", "RestrictPublicBuckets"]
session = boto3.Session()
account_id = session.client("sts").get_caller_identity()["Account"]
def missing(config):
return [name for name in SETTINGS if not config.get(name)]
try:
account = session.client("s3control").get_public_access_block(AccountId=account_id)
account_off = missing(account["PublicAccessBlockConfiguration"])
except ClientError as err:
if err.response["Error"]["Code"] != "NoSuchPublicAccessBlockConfiguration":
raise
account_off = SETTINGS
print("account level, off:", ", ".join(account_off) or "none")
s3 = session.client("s3")
not_checked = []
for page in s3.get_paginator("list_buckets").paginate():
for bucket in page["Buckets"]:
name = bucket["Name"]
try:
config = s3.get_public_access_block(Bucket=name)["PublicAccessBlockConfiguration"]
bucket_off = missing(config)
except ClientError as err:
code = err.response["Error"]["Code"]
if code != "NoSuchPublicAccessBlockConfiguration":
not_checked.append(f"{name} ({code})")
continue
bucket_off = SETTINGS
off_at_both = [setting for setting in bucket_off if setting in account_off]
if off_at_both:
print(f"{name}: off at both levels: {', '.join(off_at_both)}")
print("NOT CHECKED:", not_checked)
sys.exit(1 if not_checked else 0)
EOF
python3 bpa.py; echo "exit code: $?"account level, off: BlockPublicAcls, IgnorePublicAcls, BlockPublicPolicy, RestrictPublicBuckets csoh-lab-web-assets: off at both levels: BlockPublicAcls, IgnorePublicAcls, BlockPublicPolicy, RestrictPublicBuckets csoh-lab-build-artifacts: off at both levels: BlockPublicPolicy NOT CHECKED: ['csoh-lab-payroll-exports (AccessDenied)'] exit code: 1
S3 applies the most restrictive combination of the bucket's and the account's settings, so a setting is really off only when it is off at both levels. The account-level settings come from the S3 Control API (s3control), not from s3. One error code is an answer: NoSuchPublicAccessBlockConfiguration, from either level, means nothing is configured there, so all four settings are off at that level. Any other code means not checked. Turn on all four settings at the account level and the bucket lines disappear, because the account then covers every bucket.
S3 Block Public Access can also be set for a whole AWS Organizations organization through an S3 policy. That needs no extra call: account-level settings inherit it, and the account-level GetPublicAccessBlock returns the effective configuration, organization policy included. Settings that are off do not make a bucket public: they mean Block Public Access will not stop a bucket policy or ACL (access control list) that makes it public. AWS Security Hub CSPM's control S3.8 checks the bucket-level settings.
Run Exercise 2's check in every active account in the organization, assuming audit-readonly in each member account, and finish with the accounts you could not check.
Show the answer
cat > org_open_sgs.py <<'EOF'
import sys
import boto3
from botocore.exceptions import ClientError
from open_sgs import open_groups
home = boto3.Session()
my_account = home.client("sts").get_caller_identity()["Account"]
not_checked = []
for page in home.client("organizations").get_paginator("list_accounts").paginate():
for account in page["Accounts"]:
if account["State"] != "ACTIVE":
continue
try:
session = home
if account["Id"] != my_account:
creds = home.client("sts").assume_role(
RoleArn=f"arn:aws:iam::{account['Id']}:role/audit-readonly",
RoleSessionName="security-audit")["Credentials"]
session = boto3.Session(aws_access_key_id=creds["AccessKeyId"],
aws_secret_access_key=creds["SecretAccessKey"],
aws_session_token=creds["SessionToken"],
region_name=home.region_name)
for line in open_groups(session):
print(account["Name"], line)
except ClientError as err:
not_checked.append(f"{account['Name']} ({err.response['Error']['Code']})")
print("NOT CHECKED:", not_checked)
sys.exit(1 if not_checked else 0)
EOF
python3 org_open_sgs.py; echo "exit code: $?"management ap-southeast-2 ipv6-everything (sg-7febd3ce0102d6546): all traffic from ::/0 management eu-west-1 legacy-rdp (sg-ddfad65ca6f049189): tcp 3389 from 0.0.0.0/0 management me-central-1 temp-postgres (sg-be8767ea2416195ef): tcp 5432 from 0.0.0.0/0 management us-east-1 debug-ssh (sg-c225ead533fca7440): tcp 22 from 0.0.0.0/0 management us-east-1 web-public (sg-f3b1db538cdbb826c): tcp 443 from 0.0.0.0/0 prod us-west-2 prod-bastion (sg-efdb8f9beeb14faa8): tcp 22 from 0.0.0.0/0 NOT CHECKED: ['sandbox (AccessDenied)'] exit code: 1
from open_sgs import open_groups loads the function from Exercise 2's file, which is why that file keeps its own printing behind if __name__ == "__main__":. prod adds a bastion host with SSH (Secure Shell) open to the world in us-west-2, a Region no single-account, single-Region script would have looked in. sandbox has a group open to all traffic in us-east-1 that this run cannot see, and the last line is the only place that shows. That line is the point of the exercise: the report says which part of the organization it covers.
One refinement: if one Region fails inside open_groups(), for example because a service control policy (SCP) blocks that Region, the whole account lands in NOT CHECKED. Moving a try inside the Region loop would report the Region instead, and keep the rest of the account's results.
In every enabled Region where GuardDuty is turned on, find out whether a High finding would reach anything: an enabled rule whose pattern matches it, with at least one target. Test each rule's pattern with test_event_pattern rather than reading it, print one line per Region, and exit non-zero if any Region has no route or could not be checked. GuardDuty's list_detectors and get_detector say whether it is on in a Region.
Show the answer
cat > routes.py <<'EOF'
import json, sys
import boto3
from botocore.exceptions import ClientError
session = boto3.Session()
account = session.client("sts").get_caller_identity()["Account"]
def high_finding(region):
return json.dumps({
"version": "0", "id": "4e2b0c1a-6f3d-4c8e-9a71-0d5b2f8e7c19",
"detail-type": "GuardDuty Finding", "source": "aws.guardduty",
"account": account, "time": "2026-11-05T09:00:00Z", "region": region, "resources": [],
"detail": {"type": "UnauthorizedAccess:EC2/SSHBruteForce", "severity": 7.5}})
def routes(region):
guardduty = session.client("guardduty", region_name=region)
detectors = [d for page in guardduty.get_paginator("list_detectors").paginate()
for d in page["DetectorIds"]]
if not any(guardduty.get_detector(DetectorId=d)["Status"] == "ENABLED" for d in detectors):
return None
events = session.client("events", region_name=region)
found = []
for page in events.get_paginator("list_rules").paginate():
for rule in page["Rules"]:
if rule["State"] == "DISABLED" or "EventPattern" not in rule:
continue
if not events.test_event_pattern(EventPattern=rule["EventPattern"],
Event=high_finding(region))["Result"]:
continue
targets = [t for p in events.get_paginator("list_targets_by_rule").paginate(Rule=rule["Name"])
for t in p["Targets"]]
if targets:
found.append(f"{rule['Name']} -> {len(targets)} target(s)")
return found
unrouted, not_checked = [], []
ec2 = session.client("ec2")
for region in sorted(r["RegionName"] for r in ec2.describe_regions()["Regions"]):
try:
found = routes(region)
except ClientError as err:
not_checked.append(f"{region} ({err.response['Error']['Code']})")
continue
if found is None:
continue
if found:
print(f"{region}: {', '.join(found)}")
else:
unrouted.append(region)
print(f"{region}: NOT ROUTED")
print("NOT CHECKED:", not_checked)
sys.exit(1 if unrouted or not_checked else 0)
EOF
python3 routes.py; echo "exit code: $?"ap-southeast-2: NOT ROUTED eu-west-1: NOT ROUTED me-central-1: NOT ROUTED us-east-1: guardduty-high -> 1 target(s) us-west-2: NOT ROUTED NOT CHECKED: [] exit code: 1
Four of the five Regions where GuardDuty is on would drop a High finding, each for a different reason. me-central-1 has no rule at all. eu-west-1's rule has a good pattern and a target, but it is disabled. us-west-2's rule matches every GuardDuty finding and has no target, so it sends them nowhere. ap-southeast-2's rule is GuardDuty's [5, 8] example, which does not match 7.5. Only us-east-1's numeric rule passes the finding on. A script that only looked for aws.guardduty in each pattern would report four Regions covered, and none of the four gaps is an error anywhere in AWS.
A detector can exist and be suspended, so the script asks get_detector for its Status. A rule's State is ENABLED, DISABLED or ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS, and the last is enabled too, which is why the script skips DISABLED rather than keeping only ENABLED. A rule with no EventPattern runs on a schedule instead. list_rules lists the default event bus, the one GuardDuty sends to. [d for page in ... for d in page["DetectorIds"]] is a list comprehension with two for clauses: it builds one list from every page, as the nested loops in Exercise 1 do. One gap remains: a target that points at a function someone deleted still counts here, and finding that out takes a call to the target's own service.
Common mistakes
- Calling a list operation once. IAM's list calls page at 100, Organizations'
ListAccountsat 20 at most, and other services at sizes of their own. Use a paginator wherevercan_paginate()says one exists. - Hand-writing a pagination loop. Each service names its continuation field:
Markerin IAM andNextTokenin EC2 and Organizations, and S3 varies by operation. S3 usesContinuationTokenforListBucketsbutNextContinuationTokenforListObjectsV2. A loop that checks the wrong one stops after the first page, and one that stops on an empty or short page stops early. - Trusting
AWS_PROFILEwith keys in the environment. Environment variables win over it. Printget_caller_identity()at the top of the script, or passprofile_namein code. - Looking in one Region, or in a fixed list. Ask
describe_regions()every run, so opt-in Regions someone enabled last month are included. - Setting
AWS_REGIONfor a boto3 script. boto3 readsAWS_DEFAULT_REGIONand ignoresAWS_REGION, so the script quietly uses the profile's Region instead. except Exception: pass, orcontinue. It turns AccessDenied, throttling and network failures into "nothing found". CatchClientError, handle the codes that are answers, and report the rest.- Reading a field that might be missing with
.get()and treatingNoneas "fine". A never-used access key has noLastUsedDate, a rule for all traffic has noFromPort, and AWS said it would retire the accountStatusfield. Decide what a missing value means before you write the comparison. - Exiting 0 from an incomplete audit. A scheduled job can only see the exit code. Exit non-zero whenever anything was not checked.
- Trusting an event pattern nobody tested. A pattern that matches nothing raises no error and sends nothing. Test it with
TestEventPatternagainst sample events, compare severities withnumericrather than a list of exact values, and give every Region where GuardDuty runs a rule with a target. - Expecting a list call to return everything about each item.
list_rolesleaves out each role's last-used date, tags and permissions boundary;get_rolereturns them, one role per call.
Where next
- jq and JMESPath for one-off questions at the command line, where a script would be too much, including the AWS CLI's
--query. - Cloud Custodian policies for the stale-key, open security group and Block Public Access checks written as YAML policies instead of scripts.
- IAM policy languages for reading the policies these scripts list, starting with why a policy that says Allow can grant nothing.
- Panther Python detections for Python in a different job: one log event in, true or false out.
- The LocalStack AWS lab for a longer-lived pretend AWS, deployed with Terraform, to point these scripts at.
- The boto3 paginators guide, the Azure SDK for Python overview, Google's Python client library reference and moto's documentation.
