Auditing a GCP IAM policy: a repeatable checklist

A one-hour audit procedure for Google Cloud IAM: snapshot the policies, run eight targeted queries, triage what you find, and keep the result diffable.

Published

Updated

Reading time

13 min

Access in Google Cloud is the sum of the grants on a resource and on every one of its ancestors, plus grants on individual buckets, secrets and service accounts that no project-level page will ever list. The console shows one resource at a time, so an audit that starts there checks a slice of the picture and calls it the whole. The procedure below works from an organization-wide snapshot instead: use it when you take over an unfamiliar Google Cloud organization, or when a quarter has passed since the last review. It assumes the access model is already designed; if it is not, start with least privilege in practice and come back here to measure how far reality has drifted.

What an audit has to answer#

An audit is a set of questions with queryable answers. Mine are these:

  • Who outside the organization can get in? Public principals, external domains, deleted principals that could be recreated.
  • Where is access broader than a job needs? Basic roles, individual users, project-wide grants of sensitive roles.
  • Which identities can become another identity? Impersonation chains are how a small grant turns into a large one.
  • Which credentials never expire? User-managed service account keys.
  • What is granted but never used? Dormant accounts and unused roles.
  • Is the control plane itself guarded? Organization policies that stop the same mistakes from coming back.

The constraints on the method are practical. It has to run in about an hour on an organization I do not know. It has to produce output I can diff against last quarter's. It must not require paid tooling, and it must be read-only, so I can run it with a viewer identity and nobody has to worry about the audit itself changing anything.

Options for collecting the data#

ApproachCovers inherited and resource-level grantsRepeatableCostWeakness
Console IAM pages, project by projectNoNoFreeMisses resource-level bindings; depends on who looks
gcloud projects get-iam-policy in a loopNo (project level only)YesFreeSame blind spot as the console, only faster
Cloud Asset Inventory search and exportYesYesFree to call; storage for exports is yoursSearch results are a snapshot with some lag
Policy Analyzer queriesYes, with group and role expansionYesFree tier is limited per dayDaily query quota per organization; allow policies only
Third-party posture scannerYesYesLicence feeAnother system with read access to everything

I combine the third and fourth rows. Cloud Asset Inventory gives me a bulk, diffable snapshot and cheap searches. Policy Analyzer answers the few questions that need group expansion or "through any path" reasoning. The Policy Analyzer documentation states a limit of 20 queries per day per organization unless you have the Premium or Enterprise tier of Security Command Center, so I spend those queries deliberately instead of exploring with them.

One snapshot, a fixed set of queries, a triage step, and a diff against the previous run.

Snapshot first, then fixed questions#

Take a snapshot first, then ask fixed questions of live search, then triage. The snapshot is the evidence: it is what I attach to the audit record and what next quarter's run is compared with. The searches are the working tool. Triage sorts findings into three buckets only, because more buckets means nothing gets fixed: fix now (public access, leaked-credential risk), fix this quarter (broad roles, individual users), and accepted with a written reason and a review date.

The ten passes#

Replace ORG_ID, project and bucket names with your own. The identity running these needs read access across the organization. The access control page names Cloud Asset Viewer (roles/cloudasset.viewer) for the asset permissions and Service Usage Consumer (roles/serviceusage.serviceUsageConsumer) for the API call itself, and the Cloud Asset Inventory API must be enabled in the project the calls are billed to.

0. Snapshot every IAM policy#

Export the IAM policy of every asset under the organization to a Cloud Storage object. The export command writes one JSON line per asset.

terminalbash
gcloud asset export \
  --organization=ORG_ID \
  --content-type=iam-policy \
  --output-path="gs://audit-evidence-example/iam/$(date +%F).json"

The call is asynchronous. It returns an operation, and gcloud asset operations describe reports when it finishes. Keep the files; the diff in step 9 needs them. If you prefer SQL, the same command can write to BigQuery with --bigquery-table instead.

1. Public principals#

This is the only check where one hit is an incident, not a finding. allUsers means anyone on the internet, allAuthenticatedUsers means anyone with any Google account, including a free personal one.

terminalbash
gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --query="memberTypes:(allUsers OR allAuthenticatedUsers)" \
  --format="table(resource, assetType)"

A public bucket that serves a website is a legitimate answer. A public bucket you cannot explain is not. For each hit, write down who owns it and why it is public, or fix it.

2. Basic roles and individual users#

terminalbash
gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --query="roles:(roles/owner OR roles/editor)" \
  --asset-types="cloudresourcemanager.*" \
  --flatten="policy.bindings[].members[]" \
  --format="table(resource, policy.bindings.role, policy.bindings.members)"
 
gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --query="memberTypes:user" \
  --format="table(resource, assetType)"

The first query is adapted from the official examples for searching by role, with --asset-types limiting the output to the resource-manager hierarchy so that you see organization, folder and project grants first. Treat the flattened rows with care: the flatten expands every member of a matching policy, so the role column shows each binding in that policy, not only the Owner or Editor one. Filter the table or read the role column when triaging.

Owner and Editor on a production project are fix-this-quarter findings at minimum. Individual users are a style finding until the user is someone who has left, at which point it is an access finding; cross-check against your directory.

3. Deleted principals#

When you delete a user or a service account, the bindings that named them stay in the policy with a deleted: prefix, and deleted service accounts carry a ?uid= suffix, as the IAM policy reference describes. They grant nothing today. They are still noise that hides real findings, and for user identities they are a reminder that a recreated address is a different principal than the old one.

terminalbash
gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --flatten="policy.bindings[].members[]" \
  --filter="policy.bindings.members:deleted" \
  --format="table(resource, policy.bindings.role, policy.bindings.members)"

Removing them is low risk and high reward: the list that remains is shorter and every row is real.

4. Who can become a service account#

A service account is only as small as the set of people who can use it. Two roles matter most. Service Account User lets a principal attach the account to a resource such as a Cloud Run service, so code running there gets its credentials. Service Account Token Creator lets a principal mint short-lived tokens for the account directly and enables --impersonate-service-account. Both are described on the service account permissions page, which also tells you to be careful granting Service Account User on highly privileged accounts.

terminalbash
gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --query="roles:(roles/iam.serviceAccountUser OR roles/iam.serviceAccountTokenCreator OR roles/iam.serviceAccountKeyAdmin)" \
  --flatten="policy.bindings[].members[]" \
  --format="table(resource, policy.bindings.role, policy.bindings.members)"
 
gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --query="policy.role.permissions:iam.serviceAccounts.actAs" \
  --format="table(resource, assetType)"

The second query catches custom roles and other roles that include the iam.serviceAccounts.actAs permission, which the role-name search would miss. Any of these roles bound on a project or folder, rather than on one service account, is the finding to look for: it grants the ability to use every service account below that point. Then ask Policy Analyzer the question that matters, for the most privileged account you found:

terminalbash
gcloud asset analyze-iam-policy \
  --organization=ORG_ID \
  --full-resource-name="//iam.googleapis.com/projects/app-prod/serviceAccounts/deployer@app-prod.iam.gserviceaccount.com" \
  --permissions="iam.serviceAccounts.actAs" \
  --expand-groups

This lists who can act as that account, with groups expanded. Spend one of the daily queries per high-privilege account, not per account. The flag --analyze-service-account-impersonation follows chains from one account to the next, but the documentation warns that it runs one query per service account in the result, so I use it only on a single account I already suspect.

5. Default service accounts holding broad roles#

Older projects often run workloads as the Compute Engine default service account, and older organizations automatically granted that account Editor. Search for it by suffix:

terminalbash
gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --asset-types="cloudresourcemanager.*" \
  --flatten="policy.bindings[].members[]" \
  --filter="policy.bindings.members:compute@developer.gserviceaccount.com" \
  --format="table(resource, policy.bindings.role, policy.bindings.members)"

Every row with a basic role is a finding with a known fix: create a dedicated service account for the workload, move the workload, then remove the grant. Do it in that order, because removing the grant first breaks whatever still runs as the default account.

6. Service account keys#

A user-managed key is a bearer credential that does not expire unless you set it to. The monitoring page calls user-managed keys extremely powerful credentials. List them per account, filtering out the system-managed keys that Google rotates for you:

terminalbash
for project in $(gcloud projects list --format="value(projectId)"); do
  for sa in $(gcloud iam service-accounts list --project="$project" --format="value(email)"); do
    gcloud iam service-accounts keys list \
      --iam-account="$sa" --managed-by=user \
      --format="csv[no-heading](name.basename(), validAfterTime, validBeforeTime)" \
      | sed "s|^|$sa,|"
  done
done

Each output line is a service account, a key ID, a creation time and an expiry. The loop makes one call per service account, so on a large organization run it from a scheduled job and keep the output with the snapshot. For each key, find out where it is used. The metric iam.googleapis.com/service_account/key/authn_events_count shows authentication events per key, but Monitoring keeps it for six weeks, and the documentation notes it can include failed calls, so a key that never shows up in the window is a candidate for deletion, not proof of safety. Disable first, wait one cycle, then delete.

7. Dormant identities and unused grants#

Two Google tools do the heavy lifting here. Service account insights flags accounts with no authentication in the last 90 days, as described on the monitoring page above. The IAM recommender suggests roles to remove or shrink based on observed permission usage:

terminalbash
gcloud recommender recommendations list \
  --project=app-prod --location=global \
  --recommender=google.iam.policy.Recommender \
  --format="table(description, stateInfo.state)"

Treat recommendations as input to review, not as an automatic change list. A role used once a year for the audit itself will look unused for eleven months. Mark those explicitly as accepted so the same recommendation does not reappear in every report.

8. Guardrails: the org policies that stop recurrence#

Finding problems is half the work; the other half is making the next audit shorter. Read the effective org policy for the constraints that map to the findings above:

terminalbash
gcloud org-policies describe iam.disableServiceAccountKeyCreation \
  --organization=ORG_ID --effective
 
gcloud org-policies describe iam.allowedPolicyMemberDomains \
  --organization=ORG_ID --effective

The first blocks new user-managed keys. The second, domain restricted sharing, stops grants to principals outside the organization; the documentation notes you have to include your own organization or Workspace customer ID in the allowed values, and that its managed equivalent is iam.managed.allowedPolicyMembers. If describe reports the constraint is not set, that is itself a finding. Set the policies after you have cleaned the existing bindings, not before, because enforcement applies to future grants and a half-clean state is hard to reason about.

9. Diff against last time#

This is the step that turns an audit into a process. With both snapshots downloaded, flatten each to one line per binding and compare:

terminalbash
for d in previous current; do
  jq -r '.name as $r | .iam_policy.bindings[]? | .role as $role | .members[] | [$r, $role, .] | @tsv' \
    "$d.json" | sort > "$d.tsv"
done
diff previous.tsv current.tsv

The field names follow the asset export format: each line has a name and an iam_policy object with bindings. Check one line of your own export with head -1 current.json before you rely on the filter, because the exact casing depends on how the file was produced. Conditional bindings carry a condition object; the filter above drops it, so a binding that gained or lost an expiry will not show in the diff, and you should extend the filter if you rely on time-bound grants. Added lines are new grants since last time. For each one you should be able to point at a pull request. A grant with no pull request is the most valuable thing an audit can find.

CostWhat an audit costs

IAM, groups and org policies are free. According to the Cloud Asset Inventory pricing page, use of the service itself is free of charge, and you pay for the storage of the data it produces, for example the exported files in Cloud Storage or tables in BigQuery. Check the Cloud Storage pricing page for current rates. An organization-wide IAM export is a text file whose size scales with the number of resources, so for a small organization it is small. The real constraint is the Policy Analyzer daily query limit mentioned earlier, which is a quota, not a charge, until you need more than the default.

Where the audit can mislead you#

  • Search is not instantaneous. Results come from an index, and recent changes may be missing. The Policy Analyzer documentation says the same about its data. Do not audit five minutes after a migration and call it clean.
  • Allow policies only. Neither Policy Analyzer nor a policy export reflects IAM deny policies. If you use deny policies, review them separately.
  • Conditions are easy to lose. When reading or writing a policy with conditions through the API, request policy version 3 and include the etag. A version 1 read hides the condition and shows a role name with a _withcond_ suffix, and a version 1 write without the etag can silently remove every condition, as the IAM policy reference explains. Never fix findings by editing exported JSON and writing it back.
  • Groups hide members. A clean binding to engineers@ tells you nothing about who is in it. Run the Policy Analyzer with group expansion on sensitive resources and review group owners separately, since group expansion is capped at 1,000 members per group.
  • Audits that only look at the organization root miss other organizations. Projects outside your org, in a separate Cloud Identity tenant, will not appear in any of these queries. Ask whether any exist.
  • Fixing everything at once breaks things. Each removed grant is a possible outage. Fix in the order: public, keys, impersonation, basic roles, then the rest; and land each fix as a separate Terraform change so one revert undoes one risk.
  • Findings without owners rot. If a row in the findings list has no named owner and no date, it will still be there next quarter.

Checklist

  • IAM policies are exported for the whole organization to a retained location, dated
  • No unexplained allUsers or allAuthenticatedUsers bindings anywhere
  • Owner and Editor appear only where a written reason exists
  • Individual users are limited to named exceptions; everyone else comes in through groups
  • Deleted principals are removed from bindings
  • Service Account User, Token Creator and Key Admin are bound on specific service accounts, not on projects or folders
  • Default service accounts hold no basic roles
  • Every user-managed service account key is listed, owned and either rotated or scheduled for deletion
  • Dormant service accounts and unused role recommendations are reviewed and each is removed or marked accepted
  • Key creation is blocked by org policy and domain restricted sharing is enabled
  • The new snapshot is diffed against the previous one and every added grant maps to a pull request

When a lighter review is enough#

If your organization is a single project with two people, this procedure is more process than you need. Run the first two queries and the key listing, delete what you cannot explain, and move on. Likewise, if you already pay for a posture-management product that covers these checks and someone owns its findings, do not build a parallel pipeline; spend the hour verifying that the product sees resource-level bindings and impersonation paths, which are the checks most often missing. And do not run an audit at all if nobody has the authority to remove access afterwards. A list of findings that no one can act on is a liability, not a control.

Share
All articles →