
Auditing Gcp Iam Permissions
- 191 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Auditing GCP IAM permissions is an agent skill that guides systematic review of Google Cloud IAM roles and bindings to reduce over-privileged access.
About
Auditing GCP IAM permissions is an agent skill for solo builders and small teams running workloads on Google Cloud who need repeatable identity reviews without a dedicated cloud security hire. It guides structured inspection of IAM roles, bindings, service accounts, and inherited organization policies so you can spot standing admin access, stale principals, and cross-project privilege sprawl before customers or auditors ask. Use it when you are shipping a new environment, onboarding contractors, or rotating keys after an incident. The skill fits the Security discipline in Prism and pairs with broader compliance work when you later need evidence of access governance. Expect checklist-style analysis rather than live API automation unless your agent is wired to gcloud—treat outputs as a review draft you validate against your console and policy baselines.
- Maps GCP IAM roles, bindings, and service accounts to least-privilege findings
- Supports systematic review of project, folder, and organization-level policies
- Aligns with cloud identity audit workflows for indie SaaS on Google Cloud
- Produces actionable gaps for overly broad admin or custom role assignments
Auditing Gcp Iam Permissions by the numbers
- 191 all-time installs (skills.sh)
- +9 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #790 of 2,203 Security skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill auditing-gcp-iam-permissionsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 191 |
|---|---|
| repo stars | ★ 27.3k |
| Security audit | 3 / 3 scanners passed |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Audit Google Cloud IAM bindings and over-privileged roles before production or after org changes.
Who is it for?
SaaS or side projects on GCP that need a first-pass IAM review before production or SOC-style questions.
Skip if: Skip if you're without Google Cloud assets or developers and only need generic OWASP app scanning with no IAM surface.
When should I use this skill?
User asks to review, audit, or harden Google Cloud IAM roles, bindings, or service account permissions.
What you get
You get a structured IAM audit narrative with prioritized permission risks to remediate before launch or during access reviews.
- IAM finding list with severity-oriented permission gaps
- Remediation-oriented notes for role binding changes
Files
Auditing GCP IAM Permissions
When to Use
- When performing security assessments of GCP organization or project IAM configurations
- When identifying service accounts with excessive permissions or unused access
- When compliance requirements mandate review of access controls and role assignments
- When investigating potential lateral movement through IAM misconfigurations
- When reducing the blast radius of compromised credentials by scoping down permissions
Do not use for VPC firewall rule auditing (use network security tools), for GKE RBAC auditing (use Kubernetes-specific RBAC tools), or for real-time threat detection on IAM actions (use SCC Event Threat Detection).
Prerequisites
- GCP organization or project with
roles/iam.securityReviewerandroles/cloudAsset.viewer - gcloud CLI authenticated with appropriate permissions
- Cloud Asset API enabled (
gcloud services enable cloudasset.googleapis.com) - IAM Recommender API enabled (
gcloud services enable recommender.googleapis.com) - Policy Analyzer API enabled (
gcloud services enable policyanalyzer.googleapis.com)
Workflow
Step 1: Enumerate IAM Bindings Across the Organization
List all IAM bindings at organization, folder, and project levels to understand the full access landscape.
# Organization-level IAM bindings
gcloud organizations get-iam-policy ORG_ID \
--format=json > org-iam-policy.json
# Search all IAM policies across the organization
gcloud asset search-all-iam-policies \
--scope=organizations/ORG_ID \
--format="table(resource, policy.bindings.role, policy.bindings.members)" \
--limit=500
# Find all users and service accounts with Owner role
gcloud asset search-all-iam-policies \
--scope=organizations/ORG_ID \
--query="policy:roles/owner" \
--format="table(resource, policy.bindings.members)"
# Find all bindings using primitive roles (Owner, Editor, Viewer)
gcloud asset search-all-iam-policies \
--scope=organizations/ORG_ID \
--query="policy:roles/owner OR policy:roles/editor" \
--format=json | python3 -c "
import json, sys
data = json.load(sys.stdin)
for result in data:
resource = result.get('resource', '')
for binding in result.get('policy', {}).get('bindings', []):
role = binding.get('role', '')
if role in ['roles/owner', 'roles/editor']:
for member in binding.get('members', []):
print(f'{resource} | {role} | {member}')
"Step 2: Audit Service Accounts and Their Keys
Identify service accounts with excessive permissions, user-managed keys, and unused accounts.
# List all service accounts in a project
gcloud iam service-accounts list \
--project=PROJECT_ID \
--format="table(email, displayName, disabled)"
# Check for user-managed keys (should be minimized)
for sa in $(gcloud iam service-accounts list --project=PROJECT_ID --format="value(email)"); do
keys=$(gcloud iam service-accounts keys list \
--iam-account="$sa" \
--managed-by=user \
--format="table(name.basename(),validAfterTime,validBeforeTime)")
if [ -n "$keys" ]; then
echo "=== $sa ==="
echo "$keys"
fi
done
# Find service accounts with admin roles across all projects
gcloud asset search-all-iam-policies \
--scope=organizations/ORG_ID \
--query="policy.bindings.members:serviceAccount AND (policy:roles/owner OR policy:roles/editor OR policy:admin)" \
--format="table(resource, policy.bindings.role, policy.bindings.members)"
# Check service account IAM policies (who can impersonate)
for sa in $(gcloud iam service-accounts list --project=PROJECT_ID --format="value(email)"); do
echo "=== $sa ==="
gcloud iam service-accounts get-iam-policy "$sa" --format=json 2>/dev/null
doneStep 3: Use IAM Recommender to Identify Excess Permissions
Leverage GCP's IAM Recommender to find roles that grant more access than actually used.
# List IAM role recommendations for a project
gcloud recommender recommendations list \
--project=PROJECT_ID \
--recommender=google.iam.policy.Recommender \
--location=global \
--format="table(name, description, priority, stateInfo.state)"
# Get detailed recommendation
gcloud recommender recommendations describe RECOMMENDATION_ID \
--project=PROJECT_ID \
--recommender=google.iam.policy.Recommender \
--location=global \
--format=json
# List insights about IAM usage
gcloud recommender insights list \
--project=PROJECT_ID \
--insight-type=google.iam.policy.Insight \
--location=global \
--format="table(name, description, severity, category)"
# Apply a recommendation (after review)
gcloud recommender recommendations mark-claimed RECOMMENDATION_ID \
--project=PROJECT_ID \
--recommender=google.iam.policy.Recommender \
--location=global \
--etag=ETAGStep 4: Analyze Effective Permissions with Policy Analyzer
Use Policy Analyzer to determine effective access for specific principals or resources.
# Check who has access to a specific resource
gcloud asset analyze-iam-policy \
--organization=ORG_ID \
--full-resource-name="//storage.googleapis.com/projects/_/buckets/sensitive-data-bucket" \
--format="table(identityList.identities, accessControlLists.accesses.role)"
# Check what resources a specific user can access
gcloud asset analyze-iam-policy \
--organization=ORG_ID \
--identity="user:developer@company.com" \
--format="table(accessControlLists.resources.fullResourceName, accessControlLists.accesses.role)"
# Check who can perform a specific action
gcloud asset analyze-iam-policy \
--organization=ORG_ID \
--full-resource-name="//cloudresourcemanager.googleapis.com/projects/PROJECT_ID" \
--permissions="iam.serviceAccounts.actAs,iam.serviceAccountKeys.create" \
--format="table(identityList.identities, accessControlLists.accesses.permission)"
# Find all principals with allUsers or allAuthenticatedUsers access
gcloud asset search-all-iam-policies \
--scope=organizations/ORG_ID \
--query="policy:allUsers OR policy:allAuthenticatedUsers" \
--format="table(resource, policy.bindings.role, policy.bindings.members)"Step 5: Check for Domain-Wide Delegation and Impersonation Risks
Identify service accounts with domain-wide delegation and impersonation capabilities.
# Check for service accounts with domain-wide delegation
# (Requires Admin SDK access to list delegated accounts)
gcloud iam service-accounts list --project=PROJECT_ID --format=json | python3 -c "
import json, sys
accounts = json.load(sys.stdin)
for sa in accounts:
email = sa.get('email', '')
# Check if the SA has domain-wide delegation enabled
# This requires Admin SDK API access
print(f'SA: {email} - Check admin.google.com for delegation status')
"
# Find service accounts that other identities can impersonate
for sa in $(gcloud iam service-accounts list --project=PROJECT_ID --format="value(email)"); do
policy=$(gcloud iam service-accounts get-iam-policy "$sa" --format=json 2>/dev/null)
if echo "$policy" | python3 -c "
import json, sys
p = json.load(sys.stdin)
for b in p.get('bindings', []):
if b['role'] in ['roles/iam.serviceAccountTokenCreator', 'roles/iam.serviceAccountUser']:
print(f' {b[\"role\"]}: {b[\"members\"]}')
" 2>/dev/null; then
echo "=== Impersonation risk: $sa ==="
fi
doneStep 6: Generate Audit Report and Apply Remediation
Compile findings and implement recommended permission reductions.
# Remove primitive role and replace with predefined role
gcloud projects remove-iam-policy-binding PROJECT_ID \
--member="user:developer@company.com" \
--role="roles/editor"
gcloud projects add-iam-policy-binding PROJECT_ID \
--member="user:developer@company.com" \
--role="roles/compute.viewer"
gcloud projects add-iam-policy-binding PROJECT_ID \
--member="user:developer@company.com" \
--role="roles/storage.objectViewer"
# Delete unused service account keys
gcloud iam service-accounts keys delete KEY_ID \
--iam-account=SA_EMAIL
# Disable unused service accounts
gcloud iam service-accounts disable SA_EMAIL --project=PROJECT_IDKey Concepts
| Term | Definition |
|---|---|
| Primitive Role | Legacy GCP roles (Owner, Editor, Viewer) that grant broad permissions across all services, not recommended for production |
| Predefined Role | GCP-managed role scoped to specific services and actions, providing more granular access than primitive roles |
| IAM Recommender | GCP ML-based service that analyzes actual permission usage and suggests role reductions to achieve least privilege |
| Policy Analyzer | Tool for analyzing effective IAM access across the organization hierarchy, answering who-can-access-what queries |
| Service Account Key | User-managed credential for service account authentication, a security risk as keys can be exported and do not auto-expire |
| Domain-Wide Delegation | Grants a service account the ability to impersonate any user in the Google Workspace domain, a significant privilege escalation risk |
Tools & Systems
- gcloud CLI: Primary tool for querying and managing GCP IAM policies, service accounts, and role bindings
- IAM Recommender: ML-based recommendation engine for reducing excessive permissions based on actual usage
- Policy Analyzer: Organization-wide effective access analysis tool for understanding who can access what
- Cloud Asset Inventory: Cross-project search for IAM policies and resource metadata
- ScoutSuite: Multi-cloud auditing tool with GCP IAM-specific checks for role assignments and service accounts
Common Scenarios
Scenario: Reducing Primitive Role Usage Across a GCP Organization
Context: An audit reveals that 60% of IAM bindings across the organization use primitive roles (Owner/Editor). The security team needs to migrate to predefined roles without disrupting developer workflows.
Approach: 1. Run gcloud asset search-all-iam-policies to inventory all primitive role bindings 2. Use IAM Recommender to get ML-based suggestions for replacement predefined roles 3. For each binding, use Policy Analyzer to understand what the principal actually accesses 4. Create a mapping document: primitive role -> specific predefined roles needed 5. Apply predefined roles alongside primitive roles for a testing period 6. Monitor for access denied errors using Cloud Audit Logs 7. Remove primitive roles after confirming no access issues over 2 weeks
Pitfalls: Primitive roles include permissions across all GCP services, so replacing them requires multiple predefined roles. The Recommender may suggest overly restrictive roles if the observation period does not capture all use cases. Custom roles can fill gaps where no predefined role matches the exact permission set needed.
Output Format
GCP IAM Permissions Audit Report
===================================
Organization: acme-org (ORG_ID: 123456789)
Projects Audited: 25
Audit Date: 2026-02-23
IAM BINDING SUMMARY:
Total bindings: 342
Using primitive roles: 205 (60%)
Using predefined roles: 112 (33%)
Using custom roles: 25 (7%)
CRITICAL FINDINGS:
[IAM-001] Service Account with Owner Role
SA: admin-sa@prod-project.iam.gserviceaccount.com
Role: roles/owner on project prod-project
User-Managed Keys: 3 (oldest: 14 months)
Remediation: Replace with specific predefined roles, delete old keys
[IAM-002] allAuthenticatedUsers Binding
Resource: gs://public-data-bucket
Role: roles/storage.objectViewer
Risk: Any Google account holder can read bucket contents
Remediation: Restrict to specific user groups or service accounts
SERVICE ACCOUNT HEALTH:
Total service accounts: 67
With user-managed keys: 23
Keys older than 90 days: 18
Unused accounts (90+ days): 12
With domain-wide delegation: 2
RECOMMENDER SUGGESTIONS:
Total recommendations: 45
Priority HIGH: 12
Estimated permissions reduced: 2,847 individual permissions
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Auditing GCP IAM Permissions
google-cloud-asset
Search All IAM Policies
from google.cloud import asset_v1
client = asset_v1.AssetServiceClient()
request = asset_v1.SearchAllIamPoliciesRequest(
scope="organizations/ORG_ID",
query="policy:roles/owner",
page_size=500,
)
for result in client.search_all_iam_policies(request=request):
print(result.resource, result.policy.bindings)Analyze IAM Policy (Who Can Access What)
request = asset_v1.AnalyzeIamPolicyRequest(
analysis_query=asset_v1.IamPolicyAnalysisQuery(
scope="organizations/ORG_ID",
identity_selector=asset_v1.IamPolicyAnalysisQuery.IdentitySelector(
identity="user:dev@company.com"
),
)
)
response = client.analyze_iam_policy(request=request)google-cloud-iam (Service Accounts)
from google.cloud import iam_admin_v1
client = iam_admin_v1.IAMClient()
# List service accounts
request = iam_admin_v1.ListServiceAccountsRequest(name="projects/PROJECT_ID")
for sa in client.list_service_accounts(request=request):
print(sa.email, sa.disabled)
# List user-managed keys
key_req = iam_admin_v1.ListServiceAccountKeysRequest(
name=sa.name,
key_types=[iam_admin_v1.ListServiceAccountKeysRequest.KeyType.USER_MANAGED],
)google-cloud-resource-manager
from google.cloud import resourcemanager_v3
client = resourcemanager_v3.ProjectsClient()
policy = client.get_iam_policy(request={"resource": "projects/PROJECT_ID"})
for binding in policy.bindings:
print(binding.role, list(binding.members))Key GCP IAM Roles to Flag
| Role | Risk Level |
|---|---|
roles/owner | Critical (full control) |
roles/editor | High (write access all services) |
roles/iam.serviceAccountTokenCreator | High (impersonation) |
roles/iam.serviceAccountKeyAdmin | High (key creation) |
References
- google-cloud-asset: https://pypi.org/project/google-cloud-asset/
- google-cloud-iam: https://pypi.org/project/google-cloud-iam/
- google-cloud-resource-manager: https://pypi.org/project/google-cloud-resource-manager/
- GCP IAM docs: https://cloud.google.com/iam/docs
#!/usr/bin/env python3
"""Agent for auditing GCP IAM permissions using google-cloud libraries."""
import json
import argparse
from datetime import datetime
from google.cloud import asset_v1
from google.cloud import resourcemanager_v3
def search_iam_policies(scope, query=""):
"""Search IAM policies across the GCP organization."""
client = asset_v1.AssetServiceClient()
request = asset_v1.SearchAllIamPoliciesRequest(scope=scope, query=query, page_size=500)
results = []
for result in client.search_all_iam_policies(request=request):
for binding in result.policy.bindings:
results.append({
"resource": result.resource,
"role": binding.role,
"members": list(binding.members),
})
return results
def find_primitive_roles(scope):
"""Find all IAM bindings using primitive roles (Owner, Editor)."""
query = "policy:roles/owner OR policy:roles/editor"
return search_iam_policies(scope, query)
def find_public_bindings(scope):
"""Find resources accessible to allUsers or allAuthenticatedUsers."""
query = "policy:allUsers OR policy:allAuthenticatedUsers"
return search_iam_policies(scope, query)
def list_service_accounts(project_id):
"""List all service accounts in a project with key info."""
from google.cloud import iam_admin_v1
client = iam_admin_v1.IAMClient()
request = iam_admin_v1.ListServiceAccountsRequest(name=f"projects/{project_id}")
accounts = []
for sa in client.list_service_accounts(request=request):
sa_info = {
"email": sa.email,
"display_name": sa.display_name,
"disabled": sa.disabled,
"user_managed_keys": [],
}
key_request = iam_admin_v1.ListServiceAccountKeysRequest(
name=sa.name,
key_types=[iam_admin_v1.ListServiceAccountKeysRequest.KeyType.USER_MANAGED],
)
keys = client.list_service_account_keys(request=key_request)
for key in keys.keys:
sa_info["user_managed_keys"].append({
"name": key.name.split("/")[-1],
"valid_after": str(key.valid_after_time),
"valid_before": str(key.valid_before_time),
})
accounts.append(sa_info)
return accounts
def get_project_iam_policy(project_id):
"""Get IAM policy for a specific project."""
client = resourcemanager_v3.ProjectsClient()
request = {"resource": f"projects/{project_id}"}
policy = client.get_iam_policy(request=request)
bindings = []
for binding in policy.bindings:
bindings.append({"role": binding.role, "members": list(binding.members)})
return bindings
def analyze_permissions(scope, identity):
"""Analyze what resources an identity can access."""
client = asset_v1.AssetServiceClient()
request = asset_v1.AnalyzeIamPolicyRequest(
analysis_query=asset_v1.IamPolicyAnalysisQuery(
scope=scope,
identity_selector=asset_v1.IamPolicyAnalysisQuery.IdentitySelector(
identity=identity
),
)
)
response = client.analyze_iam_policy(request=request)
results = []
for entry in response.main_analysis.analysis_results:
for acl in entry.access_control_lists:
resources = [r.full_resource_name for r in acl.resources]
accesses = [a.role for a in acl.accesses]
results.append({"resources": resources, "roles": accesses})
return results
def classify_risk(bindings):
"""Classify risk for IAM bindings."""
critical = []
high = []
for b in bindings:
role = b.get("role", "")
members = b.get("members", [])
if "allUsers" in members or "allAuthenticatedUsers" in members:
critical.append(b)
elif role in ("roles/owner", "roles/editor"):
for m in members:
if "serviceAccount" in m:
critical.append(b)
break
else:
high.append(b)
return {"critical": critical, "high": high}
def main():
parser = argparse.ArgumentParser(description="GCP IAM Permissions Audit Agent")
parser.add_argument("--org-id", help="GCP Organization ID")
parser.add_argument("--project-id", help="GCP Project ID")
parser.add_argument("--identity", help="Identity to analyze (user:email or serviceAccount:email)")
parser.add_argument("--output", default="gcp_iam_audit.json")
parser.add_argument("--action", choices=[
"primitive_roles", "public_access", "service_accounts",
"analyze_identity", "full_audit"
], default="full_audit")
args = parser.parse_args()
scope = f"organizations/{args.org_id}" if args.org_id else f"projects/{args.project_id}"
report = {"audit_date": datetime.utcnow().isoformat(), "scope": scope, "findings": {}}
if args.action in ("primitive_roles", "full_audit"):
primitives = find_primitive_roles(scope)
report["findings"]["primitive_roles"] = primitives
print(f"[+] Primitive role bindings: {len(primitives)}")
if args.action in ("public_access", "full_audit"):
public = find_public_bindings(scope)
report["findings"]["public_access"] = public
print(f"[+] Public access bindings: {len(public)}")
if args.action in ("service_accounts", "full_audit") and args.project_id:
sas = list_service_accounts(args.project_id)
report["findings"]["service_accounts"] = sas
keys_count = sum(len(sa["user_managed_keys"]) for sa in sas)
print(f"[+] Service accounts: {len(sas)}, user-managed keys: {keys_count}")
if args.action == "analyze_identity" and args.identity:
access = analyze_permissions(scope, args.identity)
report["findings"]["identity_access"] = access
print(f"[+] Resources accessible by {args.identity}: {len(access)}")
with open(args.output, "w") as f:
json.dump(report, f, indent=2, default=str)
print(f"[+] Report saved to {args.output}")
if __name__ == "__main__":
main()
Related skills
How it compares
Use for GCP identity posture review, not as a substitute for runtime vulnerability scanning or MCP market-data tools.
FAQ
Who is auditing-gcp-iam-permissions for?
Developers shipping on Google Cloud who must validate IAM without a full-time cloud security team.
When should I use auditing-gcp-iam-permissions?
During ship security hardening, before granting production access, after org restructuring, or when preparing compliance evidence about access control.
Is auditing-gcp-iam-permissions safe to install?
Review the Security Audits panel on this Prism page for published audit results; treat any cloud-related skill as requiring careful scoping of credentials and agent permissions.