r/devops7 • • 8d ago

One script, one chore: a CI key leaked in a build log. Its own grants show 2 resources; a graph walk through 3 chained roles finds 10, 3 with customer data (real output)

Short one this week: one script, one chore, real output. (This sub is run by the SynapCores team.)

The chore

A CI job printed its env into a public build log, access key included. You rotate it now. Then: what could it reach, and which teams do you tell?

First look: the key's user in the IAM console. iam.txt has one "who how what" line per grant, group membership or AssumeRole, loaded into a plain SQL table:

SELECT how, what FROM d9_grants WHERE who = 'ci-builder' ORDER BY how

AKIAIOSFODNN7EXAMPLE is ci-builder's key. Its own grants:
  ecr:PushImage   app-images
  member-of       ci-runners
  s3:PutObject    build-artifacts

Two resources and a group. But the group can assume deploy-staging, staging can assume deploy-prod (the promote step), and prod can assume data-export (nightly export). Each hop is another console page.

Step 1: the same lines as a graph

The script loads each line as an edge with Cypher, same SynapCores endpoint as the SQL:

MERGE (a:d9_Iam {name: "ci-runners"}) MERGE (b:d9_Iam {name: "deploy-staging"}) MERGE (a)-[:CAN]->(b)

Owners and data classes go in a SQL table, d9_resources.

loaded 21 IAM lines, 14 resources

Step 2: walk from the key

MATCH p = (k:d9_Iam {name: 'AKIAIOSFODNN7EXAMPLE'})-[:CAN*1..8]->(x:d9_Iam)
RETURN x.name AS target, length(p) AS hops, [n IN nodes(p) | n.name] AS via

graph walk: 15 things reachable from the key

The shortest chain to each goes into a d9_reach table.

Step 3, the payoff: one join, worst first

SELECT s.data, s.env, s.kind, r.target, s.owner, s.channel, r.hops, r.via
FROM d9_reach r JOIN d9_resources s ON s.name = r.target
ORDER BY CASE s.data WHEN 'customer' THEN 1 WHEN 'credentials' THEN 2 ELSE 3 END,
         CASE s.env WHEN 'prod' THEN 1 ELSE 2 END, r.hops, r.target

python3 keyreach.py reach AKIAIOSFODNN7EXAMPLE on SynapCores 2.5.1:

  customer    prod    s3       customer-exports     data-platform #data-oncall
    via ci-builder > ci-runners > deploy-staging > deploy-prod > data-export
  customer    prod    dynamodb customers            crm           #crm-oncall
    via ci-builder > ci-runners > deploy-staging > deploy-prod > data-export
  customer    prod    rds      orders-db            orders        #orders-oncall
    via ci-builder > ci-runners > deploy-staging > deploy-prod > data-export
  credentials prod    secret   prod/orders-db-creds orders        #orders-oncall
    via ci-builder > ci-runners > deploy-staging > deploy-prod
  credentials staging secret   staging/db-creds     orders        #orders-oncall
    via ci-builder > ci-runners > deploy-staging
  internal    prod    ecs      prod-cluster         sre           #sre-oncall
    via ci-builder > ci-runners > deploy-staging > deploy-prod
  internal    prod    sqs      export-jobs          data-platform #data-oncall
    via ci-builder > ci-runners > deploy-staging > deploy-prod > data-export
  internal    ci      ecr      app-images           platform      #platform
    via ci-builder
  internal    ci      s3       build-artifacts      platform      #platform
    via ci-builder
  internal    staging ecs      staging-cluster      platform      #platform
    via ci-builder > ci-runners > deploy-staging

10 resources reachable (2 through its own grants), 3 with customer data
notify: #data-oncall, #crm-oncall, #orders-oncall, #sre-oncall, #platform

Own grants: 2 resources. Reachable: 10, and the top 3 are customer data in prod, all via data-export, three AssumeRoles away. Check CloudTrail for those AssumeRoles first, and tell #data-oncall, #crm-oncall and #orders-oncall before #platform.

Why one database? In plain SQL the walk is a recursive CTE that carries the path by hand; a separate graph store means syncing owners into it. Here the walk and the join hit the same database.

keyreach.py (stdlib only) and the sample files are in the comments.

Free Community Edition: https://synapcores.com/download?utm_source=reddit&utm_medium=owned&utm_campaign=devops7-one-script-9

Quick one: do you know, today, which of your CI roles can assume a prod role?

1 Upvotes

2 comments sorted by

1

u/Alternative_Pin9598 8d ago

keyreach.py (standard library only; set SC_URL and SC_TOKEN). Run: python3 keyreach.py load iam.txt resources.txt, then python3 keyreach.py reach <access key id>.

"""keyreach.py: an access key leaked. Before you rotate it: what can it actually reach, and who do you tell?
IAM edges live in a graph, resource owners live in a SQL table, same SynapCores database.
usage: python3 keyreach.py load iam.txt resources.txt
       python3 keyreach.py reach AKIAIOSFODNN7EXAMPLE
  iam.txt        one "who how what" per line: key-of, member-of, sts:AssumeRole, or an action on a resource
  resources.txt  one "name kind env data owner channel" per line
"""
import json, os, sys, time, urllib.error, urllib.request

BASE = os.environ["SC_URL"]      # e.g. http://localhost:<port> of your SynapCores
TOKEN = os.environ["SC_TOKEN"]   # from POST /v1/auth/login


def run(q, tries=5):
    req = urllib.request.Request(BASE + "/v1/query/execute", method="POST",
                                 data=json.dumps({"sql": q, "database": "main"}).encode(),
                                 headers={"Authorization": "Bearer " + TOKEN, "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=120) as r:
            return json.load(r)["data"].get("rows", [])
    except urllib.error.HTTPError as e:  # server busy: wait a second, try again
        if tries > 1 and (e.code in (429, 503) or "retry" in e.read().decode().lower()):
            time.sleep(1)
            return run(q, tries - 1)
        raise


def load(iam, resources):
    edges = [l.split() for l in open(iam) if l.strip()]
    # the same lines twice: a plain SQL table (what the IAM console shows you, one principal at a time) ...
    run("CREATE TABLE d9_grants (who TEXT, how TEXT, what TEXT)")
    run("INSERT INTO d9_grants VALUES " + ",".join(f"('{a}', '{h}', '{b}')" for a, h, b in edges))
    # ... and a graph (Cypher, same endpoint): one CAN edge per line, whatever the "how"
    for a, h, b in edges:
        run(f'MERGE (a:d9_Iam {{name: "{a}"}}) MERGE (b:d9_Iam {{name: "{b}"}}) MERGE (a)-[:CAN]->(b)')
    # what each resource holds and who owns it (SQL)
    run("CREATE TABLE d9_resources (name TEXT PRIMARY KEY, kind TEXT, env TEXT, data TEXT, owner TEXT, channel TEXT)")
    rows = [l.split() for l in open(resources) if l.strip()]
    run("INSERT INTO d9_resources VALUES " + ",".join("(" + ", ".join(f"'{v}'" for v in r) + ")" for r in rows))
    run("CREATE TABLE d9_reach (target TEXT, hops INTEGER, via TEXT)")
    print(f"loaded {len(edges)} IAM lines, {len(rows)} resources")


# 1. what you see when you open the key's user: its own grants
OWN = "SELECT how, what FROM d9_grants WHERE who = '{user}' ORDER BY how"

# 2. the graph walk: everything the key reaches in 1 to 8 hops (groups, roles it can assume, their roles, their grants)
WALK = """MATCH p = (k:d9_Iam {{name: '{key}'}})-[:CAN*1..8]->(x:d9_Iam)
RETURN x.name AS target, length(p) AS hops, [n IN nodes(p) | n.name] AS via"""

# 3. one SQL join: the walk against the resources table, customer data and prod first
RANK = """SELECT s.data, s.env, s.kind, r.target, s.owner, s.channel, r.hops, r.via
FROM d9_reach r JOIN d9_resources s ON s.name = r.target
ORDER BY CASE s.data WHEN 'customer' THEN 1 WHEN 'credentials' THEN 2 ELSE 3 END,
         CASE s.env WHEN 'prod' THEN 1 ELSE 2 END, r.hops, r.target"""


def reach(key):
    user = run(f"SELECT what FROM d9_grants WHERE who = '{key}' AND how = 'key-of'")[0][0]
    own = run(OWN.format(user=user))
    print(f"{key} is {user}'s key. Its own grants:")
    for how, what in own:
        print(f"  {how:<15} {what}")
    shortest = {}  # keep the shortest chain to each target: the principals between the key and it
    for target, hops, via in sorted(run(WALK.format(key=key)), key=lambda p: p[1]):
        shortest.setdefault(target, (hops, " > ".join(via[1:-1])))
    run("DELETE FROM d9_reach")
    run("INSERT INTO d9_reach VALUES " + ",".join(f"('{t}', {h}, '{v}')" for t, (h, v) in shortest.items()))
    print(f"\ngraph walk: {len(shortest)} things reachable from the key\n")
    rows = run(RANK)
    for data, env, kind, target, owner, channel, hops, via in rows:
        print(f"  {data:<11} {env:<7} {kind:<8} {target:<20} {owner:<13} {channel}\n    via {via}")
    direct = [what for how, what in own if what in {r[3] for r in rows}]
    customer = [r[3] for r in rows if r[0] == "customer"]
    notify = list(dict.fromkeys(r[5] for r in rows))
    print(f"\n{len(rows)} resources reachable ({len(direct)} through its own grants), {len(customer)} with customer data")
    print(f"notify: {', '.join(notify)}")


if __name__ == "__main__":
    if sys.argv[1] == "load":
        load(sys.argv[2], sys.argv[3])
    else:
        reach(sys.argv[2])

iam.txt and resources.txt are in the reply below.

Graph hops and SQL in one query, step by step: SQLv2 Lesson 5 (graph hops + meaning search): https://www.reddit.com/r/SQLv2/comments/1xq8g8l/

1

u/Alternative_Pin9598 8d ago

iam.txt (made up; one "who how what" per line):

AKIAIOSFODNN7EXAMPLE key-of ci-builder
ci-builder member-of ci-runners
ci-builder s3:PutObject build-artifacts
ci-builder ecr:PushImage app-images
ci-runners sts:AssumeRole deploy-staging
deploy-staging ecs:UpdateService staging-cluster
deploy-staging secretsmanager:GetSecretValue staging/db-creds
deploy-staging sts:AssumeRole deploy-prod
deploy-prod ecs:UpdateService prod-cluster
deploy-prod secretsmanager:GetSecretValue prod/orders-db-creds
deploy-prod sts:AssumeRole data-export
data-export s3:GetObject customer-exports
data-export rds:StartExportTask orders-db
data-export dynamodb:Scan customers
data-export sqs:SendMessage export-jobs
alice member-of analysts
analysts sts:AssumeRole analytics-ro
analytics-ro s3:GetObject clickstream-raw
payments-svc secretsmanager:GetSecretValue payments/stripe-key
hr-sync s3:GetObject hr-documents
billing-api sqs:SendMessage billing-events

resources.txt (name kind env data owner channel):

build-artifacts s3 ci internal platform #platform
app-images ecr ci internal platform #platform
staging-cluster ecs staging internal platform #platform
staging/db-creds secret staging credentials orders #orders-oncall
prod-cluster ecs prod internal sre #sre-oncall
prod/orders-db-creds secret prod credentials orders #orders-oncall
customer-exports s3 prod customer data-platform #data-oncall
orders-db rds prod customer orders #orders-oncall
customers dynamodb prod customer crm #crm-oncall
export-jobs sqs prod internal data-platform #data-oncall
clickstream-raw s3 prod customer analytics #analytics
payments/stripe-key secret prod credentials payments #payments-oncall
hr-documents s3 prod employee people-ops #people-ops
billing-events sqs prod internal billing #billing-oncall