Communitygithub.com

审计GCP IAM权限

审计Google Cloud Platform IAM权限,识别过于宽松的访问权限。

审计GCP IAM权限 是什么?

此技能用于对 Google Cloud Platform (GCP) 组织或项目级 IAM 配置进行安全审计。它通过枚举所有 IAM 绑定、审查服务账号及其密钥、利用 IAM Recommender 发现超额权限、使用 Policy Analyzer 分析有效权限,并检查域范围委派和模拟风险,帮助用户识别过度授权、不安全的原语角色、未使用的密钥以及潜在的安全隐患。该技能适用于 gcloud CLI 环境,支持 Cloud Asset、IAM Recommender 和 Policy Analyzer API,最终生成详细的审计报告并提供权限缩减的补救措施,适用于安全评估、合规审查和攻击面缩小场景。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mukul975/Anthropic-Cybersecurity-Skills/tree/main/skills/auditing-gcp-iam-permissions

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

审计GCP IAM权限 是做什么的?

何时使用

  • 对 GCP 组织或项目的 IAM 配置进行安全评估时
  • 识别具有过多权限或未使用访问权限的服务账号时
  • 合规要求对访问控制和角色分配进行审查时
  • 调查因 IAM 配置不当导致的潜在横向移动时
  • 通过缩小权限范围来降低已泄露凭证的爆炸半径时

不要使用于 VPC 防火墙规则审计(请使用网络安全工具)、GKE RBAC 审计(请使用 Kubernetes 专属 RBAC 工具),或用于 IAM 操作的实时威胁检测(请使用 SCC Event Threat Detection)。

前提条件

  • 具有 roles/iam.securityReviewer 和 roles/cloudAsset.viewer 角色的 GCP 组织或项目
  • 已通过适当权限认证的 gcloud CLI
  • 已启用 Cloud Asset API(gcloud services enable cloudasset.googleapis.com)
  • 已启用 IAM Recommender API(gcloud services enable recommender.googleapis.com)
  • 已启用 Policy Analyzer API(gcloud services enable policyanalyzer.googleapis.com)

工作流程

步骤 1:枚举整个组织的 IAM 绑定

列出组织、文件夹和项目级别的所有 IAM 绑定,以全面了解访问权限情况。

# 组织级别 IAM 绑定
gcloud organizations get-iam-policy ORG_ID \
  --format=json > org-iam-policy.json

# 搜索整个组织的所有 IAM 策略
gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --format="table(resource, policy.bindings.role, policy.bindings.members)" \
  --limit=500

# 查找所有具有 Owner 角色的用户和服务账号
gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --query="policy:roles/owner" \
  --format="table(resource, policy.bindings.members)"

# 查找所有使用原语角色(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}')
"

步骤 2:审计服务账号及其密钥

识别具有过多权限的服务账号、用户管理的密钥以及未使用的账号。

# 列出项目中的所有服务账号
gcloud iam service-accounts list \
  --project=PROJECT_ID \
  --format="table(email, displayName, disabled)"

# 检查用户管理的密钥(应尽可能少)
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

# 查找所有项目中具有管理员角色的服务账号
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)"

# 检查服务账号 IAM 策略(谁可以模拟)
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
done

步骤 3:使用 IAM Recommender 识别超额权限

利用 GCP 的 IAM Recommender 查找授予了超出实际使用权限的角色。

# 列出项目的 IAM 角色建议
gcloud recommender recommendations list \
  --project=PROJECT_ID \
  --recommender=google.iam.policy.Recommender \
  --location=global \
  --format="table(name, description, priority, stateInfo.state)"

# 获取详细建议
gcloud recommender recommendations describe RECOMMENDATION_ID \
  --project=PROJECT_ID \
  --recommender=google.iam.policy.Recommender \
  --location=global \
  --format=json

# 列出有关 IAM 使用的洞察
gcloud recommender insights list \
  --project=PROJECT_ID \
  --insight-type=google.iam.policy.Insight \
  --location=global \
  --format="table(name, description, severity, category)"

# 应用建议(经过审查后)
gcloud recommender recommendations mark-claimed RECOMMENDATION_ID \
  --project=PROJECT_ID \
  --recommender=google.iam.policy.Recommender \
  --location=global \
  --etag=ETAG

步骤 4:使用 Policy Analyzer 分析有效权限

使用 Policy Analyzer 确定特定主体或资源的有效访问权限。

# 检查谁有权访问特定资源
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)"

# 检查特定用户可以访问哪些资源
gcloud asset analyze-iam-policy \
  --organization=ORG_ID \
  --identity="user:[email protected]" \
  --format="table(accessControlLists.resources.fullResourceName, accessControlLists.accesses.role)"

# 检查谁可以执行特定操作
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)"

# 查找所有具有 allUsers 或 allAuthenticatedUsers 访问权限的主体
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)"

步骤 5:检查域范围委派和模拟风险

识别具有域范围委派和模拟能力的服务账号。

# 检查具有域范围委派的服务账号
# (需要 Admin SDK 访问权限才能列出委派账号)
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', '')
    # 检查服务账号是否启用了域范围委派
    # 这需要 Admin SDK API 访问权限
    print(f'SA: {email} - 请检查 admin.google.com 上的委派状态')
"

# 查找其他身份可以模拟的服务账号
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 "=== 模拟风险: $sa ==="
  fi
done

步骤 6:生成审计报告并应用修复

汇总发现的问题并实施建议的权限缩减。

# 移除原语角色并替换为预定义角色
gcloud projects remove-iam-policy-binding PROJECT_ID \
  --member="user:[email protected]" \
  --role="roles/editor"

gcloud projects add-iam-policy-binding PROJECT_ID \
  --member="user:[email protected]" \
  --role="roles/compute.viewer"

gcloud projects add-iam-policy-binding PROJECT_ID \
  --member="user:[email protected]" \
  --role="roles/storage.objectViewer"

# 删除未使用的服务账号密钥
gcloud iam service-accounts keys delete KEY_ID \
  --iam-account=SA_EMAIL

# 禁用未使用的服务账号
gcloud iam service-accounts disable SA_EMAIL --project=PROJECT_ID

关键概念

术语定义
原语角色传统的 GCP 角色(Owner, Editor, Viewer),在所有服务中授予广泛的权限,不推荐用于生产环境
预定义角色GCP 管理的角色,范围限定在特定服务和操作,提供比原语角色更细粒度的访问控制
IAM RecommenderGCP 基于机器学习的服务,分析实际权限使用情况并建议角色缩减以实现最小权限原则
Policy Analyzer用于分析组织层级结构中有效 IAM 访问权限的工具,回答谁可以访问什么的问题
服务账号密钥用户管理的服务账号身份验证凭据,由于密钥可被导出且不会自动过期,存在安全风险
域范围委派授予服务账号模拟 Google Workspace 域中任何用户的能力,是严重的权限提升风险

工具与系统

  • gcloud CLI: 查询和管理 GCP IAM 策略、服务账号和角色绑定的主要工具
  • IAM Recommender: 基于机器学习的推荐引擎,根据实际使用情况减少过多权限
  • Policy Analyzer: 整个组织的有效访问分析工具,用于了解谁可以访问什么
  • Cloud Asset Inventory: 跨项目搜索 IAM 策略和资源元数据
  • ScoutSuite: 多云审计工具,包含针对 GCP IAM 的角色分配和服务账号检查

常见场景

场景:减少整个 GCP 组织中的原语角色使用

背景:审计显示整个组织中 60% 的 IAM 绑定使用原语角色(Owner/Editor)。安全团队需要在不中断开发人员工作流程的情况下迁移到预定义角色。

方法:

  1. 运行 gcloud asset search-all-iam-policies 盘点所有原语角色绑定
  2. 使用 IAM Recommender 获取基于机器学习的替代预定义角色建议
  3. 对于每个绑定,使用 Policy Analyzer 了解主体实际访问的内容
  4. 创建映射文档:原语角色 -> 所需的特定预定义角色
  5. 在测试期内同时应用预定义角色和原语角色
  6. 使用 Cloud Audit Logs 监控访问拒绝错误
  7. 确认两周内无访问问题后移除原语角色

陷阱:原语角色包含所有 GCP 服务的权限,因此替换它们需要多个预定义角色。如果观察期未捕获所有使用场景,Recommender 可能会建议过于严格的角色。在没有预定义角色匹配确切权限集时,自定义角色可以填补空白。

输出格式

GCP IAM 权限审计报告
===================================
组织: acme-org (ORG_ID: 123456789)
审计项目数: 25
审计日期: 2026-02-23

IAM 绑定摘要:
  总绑定数:                    342
  使用原语角色:             205 (60%)
  使用预定义角色:           112 (33%)
  使用自定义角色:             25 (7%)

严重发现:
[IAM-001] 具有 Owner 角色的服务账号
  SA: [email protected]
  角色: roles/owner on project prod-project
  用户管理密钥: 3 (最旧: 14 个月)
  修复措施: 替换为特定的预定义角色,删除旧密钥

[IAM-002] allAuthenticatedUsers 绑定
  资源: gs://public-data-bucket
  角色: roles/storage.objectViewer
  风险: 任何 Google 账号持有者均可读取存储桶内容
  修复措施: 限制为特定用户组或服务账号

服务账号健康状况:
  总服务账号数:                67
  具有用户管理密钥:           23
  密钥超过 90 天:              18
  未使用账号 (90+ 天):         12
  具有域范围委派:              2

推荐建议:
  总建议数:                    45
  优先级高:                    12
  预计减少的权限:              2,847 个单独权限

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

abusing-dpapi-for-credential-access

Extract and decrypt Windows DPAPI-protected secrets (Credential Manager, browser logins/cookies, Wi-Fi credentials, KeePass keys) online or offline using SharpDPAPI, SharpChrome, Mimikatz, or Impacket

abusing-shadow-credentials-for-privesc

Take over Active Directory accounts by writing attacker-controlled public keys to msDS-KeyCredentialLink (Shadow Credentials) with pyWhisker, Whisker, or Certipy, then authenticate via PKINIT to recover the target

achieving-cmmc-level-2-compliance

>-

acquiring-disk-image-with-dd-and-dcfldd

Create forensically sound bit-for-bit disk images with dd or dcfldd on a Linux forensic workstation, preserving evidence integrity through hash verification (MD5/SHA) during acquisition. Use when imaging a suspect drive, USB device, or memory card for investigation, preserving volatile disk evidence during incident response, or producing a verified copy for legal or law-enforcement proceedings before any destructive analysis.

analyzing-active-directory-acl-abuse

Detect dangerous ACL misconfigurations in Active Directory using ldap3

analyzing-android-malware-with-apktool

Perform static analysis of Android APK malware using apktool for resource decompilation, jadx for Java source recovery, and androguard for manifest inspection, dangerous permission-combination detection, and identification of obfuscated code, dynamic code loading, and reflection-based API calls. Use to statically triage a suspicious APK without executing it or to build mobile malware detection rules.

analyzing-api-gateway-access-logs

Parses API Gateway access logs (AWS API Gateway, Kong, Nginx) to detect

analyzing-apt-group-with-mitre-navigator

Query ATT&CK data with attackcti, mitreattack-python, and stix2, then build MITRE ATT&CK Navigator layers and multi-layer heatmap overlays mapping one or more APT groups

analyzing-azure-activity-logs-for-threats

Queries Azure Monitor activity logs and sign-in logs via azure-monitor-query

analyzing-bootkit-and-rootkit-samples

Analyzes bootkit and advanced rootkit malware infecting the Master

analyzing-browser-forensics-with-hindsight

Parse Chromium-based browser databases with Hindsight to extract and correlate browsing history, downloads, cookies, cached content, autofill data, saved passwords, and extensions from Chrome, Edge, Brave, Opera, and Vivaldi into a unified timeline (XLSX, JSON, or SQLite output). Use during incident response, insider-threat investigations, or criminal cases when you need to reconstruct a user

analyzing-campaign-attribution-evidence

Systematically evaluate cyber-campaign evidence to attribute an operation to a threat actor, using the Diamond Model and Analysis of Competing Hypotheses (ACH) to weigh infrastructure overlaps, TTP consistency, malware code similarity, and timing/language artifacts into confidence-weighted attribution assessments. Use when an incident investigation needs a defensible attribution confidence level.

analyzing-certificate-transparency-for-phishing

Monitor Certificate Transparency logs using crt.sh and Certstream to

analyzing-cloud-storage-access-patterns

Detect abnormal access in AWS S3, GCS, and Azure Blob Storage by analyzing CloudTrail Data Events, GCS audit logs, and Azure Storage Analytics for after-hours bulk downloads, new-IP access, and API-call spikes (e.g. GetObject) via statistical baselines and time-series anomaly detection. Use when investigating suspected cloud data exfiltration or building related detection rules.

analyzing-cobalt-strike-beacon-configuration

Extract and analyze Cobalt Strike beacon configuration from PE files

analyzing-cobaltstrike-malleable-c2-profiles

Parse and analyze Cobalt Strike Malleable C2 profiles with dissect.cobaltstrike (profiles and beacon-payload configs) and pyMalleableC2 (AST parsing) to extract HTTP/DNS transforms, URIs, headers, sleep/jitter, and injection behavior, then generate network detection signatures. Use when reverse-engineering a captured malleable profile or building detections against Cobalt Strike Beacon traffic.

analyzing-command-and-control-communication

Analyzes malware C2 communication over HTTP, HTTPS, DNS, and custom

analyzing-cyber-kill-chain

Analyzes intrusion activity against the Lockheed Martin Cyber Kill Chain

analyzing-disk-image-with-autopsy

Perform comprehensive forensic analysis of raw (dd), E01, or AFF disk images with Autopsy and The Sleuth Kit, recovering deleted files, examining metadata and embedded artifacts, keyword searching, and building investigation timelines with visual reports. Use for structured analysis of a forensic disk image or when stakeholders need visual reports from evidence.

analyzing-dns-logs-for-exfiltration

Analyzes DNS query logs to detect data exfiltration via DNS tunneling,

相关技能