SECURITY ENGINEERING · PART 3 · SCRIPTING AND AUTOMATION · PYTHON · 42 OF 229

Security Automation With Python and Cloud APIs

Most security work at scale is a script asking an API a question on a schedule: which access keys are older than 90 days, which buckets are public, which repositories lack branch protection. How to write those checks with boto3 and requests, with pagination, rate limits, read-only credentials, a dry-run mode, alerts to chat, and safe automatic fixes.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 9
  9. 10
  10. 11
  11. 12
  12. 13
  13. 14
  14. 15
  15. 16
  16. 17
  17. 18
  18. 19
  19. 20
  20. 21
  21. 22
  22. 23
  23. 24
  24. 25
  25. 26
  26. 27
  27. 28
  28. 29
  29. 30
  30. 31
  31. 32
  32. 33
  33. 34
  34. 35
  35. 36
  36. 37
  37. 38
  38. 39
  39. 40
  40. 41
  41. 42
  42. 43
  43. 44
  44. 45
  45. 46
  46. 47
  47. 48
  48. 49
  49. 50
  50. 51
  51. 52
  52. 53
  53. 54
  54. 55
  55. 56
  56. 57
  57. 58
  58. 59
  59. 60
  60. 61
  61. 62
  62. 63
  63. 64
  64. 106
  65. 107
  66. 108
  67. 109
  68. 110
  69. 111
  70. 112
  71. 113
  72. 114
  73. 115
  74. 116
  75. 117
  76. 118
  77. 119
  78. 120
  79. 121
  80. 122
  81. 123
  82. 124
  83. 125
  84. 126
  85. 127
  86. 128
  87. 129
  88. 130
  89. 131
  90. 132
  91. 133
  92. 134
  93. 135
  94. 136
  95. 137
  96. 138
  97. 139
  98. 140
  99. 141
  100. 142
  101. 143
  102. 144
1 / 14

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Ask, compare, report, repeat
  • read-only short-lived access
  • paginate and respect rate limits
  • owners
  • careful auto-fix

Notes

The pattern

Every automated check follows the same four steps. Ask an API for the current state. Compare it with a rule, such as no access key older than ninety days. Report whatever breaks the rule to someone who can fix it. And run again tomorrow, because the state will have changed. That loop is policy as code in its simplest form. Once you have written one check, the next ten are small variations on it.

Ask, compare, report, repeat
  • 1 ask an API for the current state
  • 2 compare it with the rule ("no key older than 90 days")
  • 3 report what breaks the rule, to someone who can fix it
  • 4 run again tomorrow
  • this is "policy as code" in its simplest form

Access first

Before any code, decide what the script may do. Give it a dedicated role, not a person's account. Make that role read-only; clouds provide ready-made audit policies for this. Use short-lived credentials from an assumed role or from your pipeline's identity, so there is no long-lived key to leak. And if you later add automatic fixes, give those a separate, narrow role. A checking script that can only read cannot become the incident.

Credentials for automation
  • a dedicated role, not a person's account
  • read-only: SecurityAudit or ViewOnlyAccess style policy
  • short-lived credentials: an assumed role or OIDC from the pipeline, no stored keys
  • separate role for anything that fixes
  • every call is logged

Check 1 · Old keys

First check: access keys that should have been rotated. With the AWS library for Python, boto three, you list every user, list each user's access keys, and compute the age of each from its creation date. Anything over ninety days is reported. Notice the paginator. Cloud APIs return results a page at a time, and a script that reads only the first page silently checks the first hundred users and reports that everything is fine.

boto3: stale IAM access keys
iam = boto3.client("iam")
now = datetime.now(timezone.utc)
pages = iam.get_paginator("list_users")
for page in pages.paginate():
  for u in page["Users"]:
    name = u["UserName"]
    keys = iam.list_access_keys(
        UserName=name)
    for k in keys["AccessKeyMetadata"]:
      age = (now - k["CreateDate"]).days
      if age > 90: report(name, age)

Check 2 · Public data

Second check: storage that could be public. For each bucket we read its public access block settings, four switches that together stop a bucket being exposed. If all four are on, the bucket passes. If the settings do not exist at all, the API raises an error, and the script treats that as a failure rather than skipping it. That is fail closed from Part zero, applied to your own tooling: when a check cannot tell, it must not report success.

boto3: public access block
s3 = boto3.client("s3")
for b in s3.list_buckets()["Buckets"]:
  name = b["Name"]
  try:
    cfg = s3.get_public_access_block(
      Bucket=name)[
      "PublicAccessBlockConfiguration"]
    ok = all(cfg.values())
  except ClientError:
    ok = False     # no block set
  if not ok: report(name)

Check 3 · Repositories

Third check, on a code platform. Branch protection is what forces a review before code reaches the main branch, which is separation of duties in practice. The script asks the API for the protection settings of each repository's main branch. A 404 answer means none are set, so the repository is reported. Any other error raises an exception. The token comes from the environment, there is a timeout, and the token needs only read access.

requests: branch protection
H = {"Authorization":
     "Bearer " + os.environ["GH_TOKEN"]}
url = f"{API}/repos/{org}/{repo}"
url += "/branches/main/protection"
r = requests.get(url, headers=H,
                 timeout=10)
if r.status_code == 404:
    report(repo, "no protection")
else:
    r.raise_for_status()

APIs push back

Real APIs push back, and good scripts expect it. Always follow pagination to the last page. Honour rate limits: when the API answers with status four twenty nine, wait as long as it tells you and retry, with a little randomness so parallel jobs do not retry in step. Put a timeout on every call. Distinguish a real no from a could not check. Make the script safe to run twice. And log each run, so you can prove the check happened.

Writing against real APIs
  • pagination: always loop until there is no next page
  • rate limits: honour HTTP 429 and Retry-After; back off and retry with jitter
  • timeouts on every call
  • distinguish "no" from "could not check"
  • idempotent: safe to run twice
  • log each run: what, when, how many

Report it well

A finding that nobody receives never gets fixed. So each one should say what is wrong, where, why it matters, how to fix it and who owns it. Find the owner from resource tags or a service catalogue, and deliver the finding where that owner already works, a ticket queue or a team chat channel. Keep state, so the same finding is not sent again every hour until people mute the channel. And measure how long fixes take; that number tells you if the programme works.

From finding to fix
  • one finding = what, where, why it matters, how to fix, who owns it
  • find the owner from tags or a service catalogue
  • send it where the owner works: a ticket, a chat channel
  • do not repeat the same alert every hour: track state
  • measure time to fix

Fixing automatically

The next temptation is to have the script fix what it finds. That is powerful, and it is also how a script takes down production at three in the morning. Earn it in steps. Report only. Then report with a one-click fix that a person approves. Then fix automatically, but only for low-risk, reversible cases, such as switching on a public access block. Always with a dry-run mode, a list of approved exceptions, a log of every change and a way to undo it.

Auto-remediation, safely
  • step 1: report only step 2: report + a one-click fix for a human
  • step 3: fix automatically, for low-risk, reversible cases
  • always: --dry-run, an allow list of exceptions, a log of every change, a way to undo
  • never auto-delete data

Where it runs

Where the script runs matters. On your laptop it is a habit that ends when you go on holiday. As a scheduled job, in a pipeline, a serverless function or cron, it is a control. Better still, trigger it on events, so a new bucket is checked seconds after it is created. Keep the code in git with review and tests like any other software. And monitor the monitor: alert when the job fails or silently stops running, because a check that died looks exactly like good news.

Run it properly
  • on a schedule: a CI workflow, a serverless function, a cron job
  • or on an event: "bucket created" triggers the check
  • code in git, reviewed, tested
  • secrets from the platform, never in the repo
  • alert if the job itself fails or stops running

Build or buy

Before writing your own, know what exists. Prowler and ScoutSuite run hundreds of ready-made cloud checks for free. Steampipe lets you query cloud APIs using SQL. Cloud Custodian expresses rules with actions. Each cloud has a native policy service, and commercial platforms such as Wiz go much further. So why learn to write checks? Because every company has rules that are its own, and because you cannot judge or extend these tools until you understand what they do underneath.

Tools that do this already
  • Prowler, ScoutSuite: hundreds of cloud checks, free
  • Steampipe: query cloud APIs with SQL
  • Cloud Custodian: rules with actions
  • cloud-native: AWS Config, Azure Policy, GCP org policy
  • commercial: Wiz and others
  • write your own for rules that are yours alone

Common mistakes

Mistakes. Reading only the first page of results and reporting a clean bill of health. Running a read-only check with an administrator token. Treating an error as a pass. Alerts that reach no owner. The same alert repeated hourly until everyone ignores the channel. Automatic fixes with no dry-run mode and no undo. And the quiet one: a scheduled job that stopped months ago, while everyone assumed that no alerts meant no problems.

Avoid these
  • reading only the first page
  • an admin token for a read-only job
  • errors treated as "passed"
  • alerts with no owner
  • the same alert every hour
  • auto-fix with no dry run
  • a job that stopped months ago and nobody noticed

Say it like this

In the interview, describe one real automation end to end. For example: a scheduled Python check running with a read-only role that lists access keys, flags any older than ninety days, finds the owner from tags and opens a ticket. Mention the engineering: it paginates, respects rate limits, fails closed on errors and alerts if the job itself stops. Then give the outcome, such as the time to fix falling from weeks to days. Outcomes are what interviewers remember.

In the interview
  • "A scheduled Python check with a read-only role that lists
  • IAM access keys, flags any older than 90 days, finds the owner from tags and opens a ticket. It paginates, handles
  • rate limits, fails closed and alerts if the job stops. Fix
  • time dropped from weeks to days."

Interview questions

Q1What is the basic pattern of a security automation check?

Query an API for current state, compare it with a rule, report violations to the responsible owner, and repeat on a schedule or on events. This is policy as code in its simplest form.

Q2What credentials should an automated security check use?

A dedicated, read-only role with short-lived credentials, for example an assumed role or OIDC federation from the CI system, rather than a personal account or long-lived keys. Any remediation should use a separate, narrowly scoped role.

Q3Why is pagination important when calling cloud APIs?

APIs return results in pages. A script that reads only the first page checks a subset and may report no problems while most resources were never examined. Paginators or next-token loops ensure every item is covered.

Q4How should a script handle API rate limits?

Detect throttling responses such as HTTP 429, honour the Retry-After header, and retry with exponential backoff and jitter, with an upper bound. This avoids hammering the API and prevents synchronised retries from parallel jobs.

Q5What does fail closed mean for a security check?

If the script cannot determine the answer, because of an error, missing permission or timeout, it must not report success. It should report the item as failed or unknown and surface the error, so gaps are visible.

Q6How do you make findings actionable?

Include what is wrong, where, why it matters, how to fix it and who owns it; route it to the owner’s ticket queue or chat channel; avoid duplicate alerts by tracking state; and measure time to remediation.

Q7When is automatic remediation appropriate?

For low-risk, reversible fixes with a clear rule, after a period of report-only operation. It needs a dry-run mode, an exception allow list, logging of every change, a rollback path, and should never delete data automatically.

Q8Which existing tools automate cloud security checks?

Open-source tools such as Prowler, ScoutSuite, Steampipe and Cloud Custodian; native services such as AWS Config, Azure Policy and GCP organisation policies; and commercial CNAPP platforms. Custom scripts fill in organisation-specific rules.