Translated ['.github/pull_request_template.md', 'src/pentesting-cloud/az

This commit is contained in:
Translator
2024-12-31 18:54:26 +00:00
parent 7770a50092
commit 192d97f7b7
244 changed files with 8835 additions and 11676 deletions

View File

@@ -1,207 +1,198 @@
# GCP - Basic Information
# GCP - Información Básica
{{#include ../../../banners/hacktricks-training.md}}
## **Resource hierarchy**
## **Jerarquía de recursos**
Google Cloud uses a [Resource hierarchy](https://cloud.google.com/resource-manager/docs/cloud-platform-resource-hierarchy) that is similar, conceptually, to that of a traditional filesystem. This provides a logical parent/child workflow with specific attachment points for policies and permissions.
At a high level, it looks like this:
Google Cloud utiliza una [Jerarquía de recursos](https://cloud.google.com/resource-manager/docs/cloud-platform-resource-hierarchy) que es similar, conceptualmente, a la de un sistema de archivos tradicional. Esto proporciona un flujo de trabajo lógico de padre/hijo con puntos de adjunto específicos para políticas y permisos.
A un alto nivel, se ve así:
```
Organization
--> Folders
--> Projects
--> Resources
--> Projects
--> Resources
```
A virtual machine (called a Compute Instance) is a resource. A resource resides in a project, probably alongside other Compute Instances, storage buckets, etc.
Una máquina virtual (llamada una Compute Instance) es un recurso. Un recurso reside en un proyecto, probablemente junto a otras Compute Instances, buckets de almacenamiento, etc.
<figure><img src="../../../images/image (1) (1) (1) (1) (1) (1) (1).png" alt=""><figcaption><p><a href="https://cloud.google.com/static/resource-manager/img/cloud-hierarchy.svg">https://cloud.google.com/static/resource-manager/img/cloud-hierarchy.svg</a></p></figcaption></figure>
## **Projects Migration**
## **Migración de Proyectos**
It's possible to **migrate a project without any organization** to an organization with the permissions `roles/resourcemanager.projectCreator` and `roles/resourcemanager.projectMover`. If the project is inside other organization, it's needed to contact GCP support to **move them out of the organization first**. For more info check [**this**](https://medium.com/google-cloud/migrating-a-project-from-one-organization-to-another-gcp-4b37a86dd9e6).
Es posible **migrar un proyecto sin ninguna organización** a una organización con los permisos `roles/resourcemanager.projectCreator` y `roles/resourcemanager.projectMover`. Si el proyecto está dentro de otra organización, es necesario contactar al soporte de GCP para **moverlo fuera de la organización primero**. Para más información, consulta [**esto**](https://medium.com/google-cloud/migrating-a-project-from-one-organization-to-another-gcp-4b37a86dd9e6).
## **Organization Policies**
## **Políticas de Organización**
Allow to centralize control over your organization's cloud resources:
Permiten centralizar el control sobre los recursos en la nube de tu organización:
- Centralize control to **configure restrictions** on how your organizations resources can be used.
- Define and establish **guardrails** for your development teams to stay within compliance boundaries.
- Help project owners and their teams move quickly without worry of breaking compliance.
- Centralizar el control para **configurar restricciones** sobre cómo se pueden utilizar los recursos de tu organización.
- Definir y establecer **límites** para que tus equipos de desarrollo se mantengan dentro de los límites de cumplimiento.
- Ayudar a los propietarios de proyectos y sus equipos a moverse rápidamente sin preocuparse por romper el cumplimiento.
These policies can be created to **affect the complete organization, folder(s) or project(s)**. Descendants of the targeted resource hierarchy node **inherit the organization policy**.
Estas políticas pueden ser creadas para **afectar a la organización completa, carpeta(s) o proyecto(s)**. Los descendientes del nodo de jerarquía de recursos objetivo **heredan la política de organización**.
In order to **define** an organization policy, **you choose a** [**constraint**](https://cloud.google.com/resource-manager/docs/organization-policy/overview#constraints), which is a particular type of restriction against either a Google Cloud service or a group of Google Cloud services. You **configure that constraint with your desired restrictions**.
Para **definir** una política de organización, **eliges un** [**constraint**](https://cloud.google.com/resource-manager/docs/organization-policy/overview#constraints), que es un tipo particular de restricción contra un servicio de Google Cloud o un grupo de servicios de Google Cloud. **Configuras esa restricción con tus restricciones deseadas**.
<figure><img src="../../../images/image (217).png" alt=""><figcaption><p><a href="https://cloud.google.com/resource-manager/img/org-policy-concepts.svg">https://cloud.google.com/resource-manager/img/org-policy-concepts.svg</a></p></figcaption></figure>
#### Common use cases <a href="#common_use_cases" id="common_use_cases"></a>
#### Casos de uso comunes <a href="#common_use_cases" id="common_use_cases"></a>
- Limit resource sharing based on domain.
- Limit the usage of Identity and Access Management service accounts.
- Restrict the physical location of newly created resources.
- Disable service account creation
- Limitar el uso compartido de recursos según el dominio.
- Limitar el uso de cuentas de servicio de Identity and Access Management.
- Restringir la ubicación física de los recursos recién creados.
- Deshabilitar la creación de cuentas de servicio.
<figure><img src="../../../images/image (172).png" alt=""><figcaption></figcaption></figure>
There are many more constraints that give you fine-grained control of your organization's resources. For **more information, see the** [**list of all Organization Policy Service constraints**](https://cloud.google.com/resource-manager/docs/organization-policy/org-policy-constraints)**.**
Hay muchas más restricciones que te dan un control detallado sobre los recursos de tu organización. Para **más información, consulta la** [**lista de todas las restricciones del Servicio de Políticas de Organización**](https://cloud.google.com/resource-manager/docs/organization-policy/org-policy-constraints)**.**
### **Default Organization Policies**
### **Políticas de Organización Predeterminadas**
<details>
<summary>These are the policies that Google will add by default when setting up your GCP organization:</summary>
<summary>Estas son las políticas que Google añadirá por defecto al configurar tu organización GCP:</summary>
**Access Management Policies**
**Políticas de Gestión de Acceso**
- **Domain restricted contacts:** Prevents adding users to Essential Contacts outside your specified domains. This limits Essential Contacts to only allow managed user identities in your selected domains to receive platform notifications.
- **Domain restricted sharing:** Prevents adding users to IAM policies outside your specified domains. This limits IAM policies to only allow managed user identities in your selected domains to access resources inside this organization.
- **Public access prevention:** Prevents Cloud Storage buckets from being exposed to the public. This ensures that a developer can't configure Cloud Storage buckets to have unauthenticated internet access.
- **Uniform bucket level access:** Prevents object-level access control lists (ACLs) in Cloud Storage buckets. This simplifies your access management by applying IAM policies consistently across all objects in Cloud Storage buckets.
- **Require OS login:** VMs created in new projects will have OS Login enabled. This lets you manage SSH access to your instances using IAM without needing to create and manage individual SSH keys.
- **Contactos restringidos por dominio:** Previene agregar usuarios a Contactos Esenciales fuera de tus dominios especificados. Esto limita los Contactos Esenciales a permitir solo identidades de usuario gestionadas en tus dominios seleccionados para recibir notificaciones de la plataforma.
- **Compartición restringida por dominio:** Previene agregar usuarios a políticas de IAM fuera de tus dominios especificados. Esto limita las políticas de IAM a permitir solo identidades de usuario gestionadas en tus dominios seleccionados para acceder a recursos dentro de esta organización.
- **Prevención de acceso público:** Previene que los buckets de Cloud Storage sean expuestos al público. Esto asegura que un desarrollador no pueda configurar buckets de Cloud Storage para tener acceso a internet no autenticado.
- **Acceso uniforme a nivel de bucket:** Previene listas de control de acceso (ACLs) a nivel de objeto en buckets de Cloud Storage. Esto simplifica tu gestión de acceso aplicando políticas de IAM de manera consistente en todos los objetos en los buckets de Cloud Storage.
- **Requerir inicio de sesión en el SO:** Las VMs creadas en nuevos proyectos tendrán habilitado el inicio de sesión en el SO. Esto te permite gestionar el acceso SSH a tus instancias usando IAM sin necesidad de crear y gestionar claves SSH individuales.
**Additional security policies for service accounts**
**Políticas de seguridad adicionales para cuentas de servicio**
- **Disable automatic IAM grants**: Prevents the default App Engine and Compute Engine service accounts from automatically being granted the Editor IAM role on a project at creation. This ensures service accounts don't receive overly-permissive IAM roles upon creation.
- **Disable service account key creation**: Prevents the creation of public service account keys. This helps reduce the risk of exposing persistent credentials.
- **Disable service account key upload**: Prevents the uploading of public service account keys. This helps reduce the risk of leaked or reused key material.
- **Deshabilitar concesiones automáticas de IAM:** Previene que las cuentas de servicio predeterminadas de App Engine y Compute Engine sean automáticamente otorgadas el rol de Editor de IAM en un proyecto al crearse. Esto asegura que las cuentas de servicio no reciban roles de IAM excesivamente permisivos al crearse.
- **Deshabilitar la creación de claves de cuentas de servicio:** Previene la creación de claves de cuentas de servicio públicas. Esto ayuda a reducir el riesgo de exponer credenciales persistentes.
- **Deshabilitar la carga de claves de cuentas de servicio:** Previene la carga de claves de cuentas de servicio públicas. Esto ayuda a reducir el riesgo de material de clave filtrado o reutilizado.
**Secure VPC network configuration policies**
**Políticas de configuración de red VPC segura**
- **Define allowed external IPs for VM instances**: Prevents the creation of Compute instances with a public IP, which can expose them to internet traffic.
- **Definir IPs externas permitidas para instancias de VM:** Previene la creación de instancias Compute con una IP pública, lo que puede exponerlas al tráfico de internet.
* **Disable VM nested virtualization**: Prevents the creation of nested VMs on Compute Engine VMs. This decreases the security risk of having unmonitored nested VMs.
* **Deshabilitar virtualización anidada de VM:** Previene la creación de VMs anidadas en VMs de Compute Engine. Esto disminuye el riesgo de seguridad de tener VMs anidadas no monitoreadas.
- **Disable VM serial port:** Prevents serial port access to Compute Engine VMs. This prevents input to a servers serial port using the Compute Engine API.
- **Deshabilitar puerto serie de VM:** Previene el acceso al puerto serie de VMs de Compute Engine. Esto previene la entrada al puerto serie de un servidor usando la API de Compute Engine.
* **Restrict authorized networks on Cloud SQL instances:** Prevents public or non-internal network ranges from accessing your Cloud SQL databases.
* **Restringir redes autorizadas en instancias de Cloud SQL:** Previene que rangos de red públicos o no internos accedan a tus bases de datos de Cloud SQL.
- **Restrict Protocol Forwarding Based on type of IP Address:** Prevents VM protocol forwarding for external IP addresses.
- **Restringir el reenvío de protocolos según el tipo de dirección IP:** Previene el reenvío de protocolos de VM para direcciones IP externas.
* **Restrict Public IP access on Cloud SQL instances:** Prevents the creation of Cloud SQL instances with a public IP, which can expose them to internet traffic.
* **Restringir el acceso IP público en instancias de Cloud SQL:** Previene la creación de instancias de Cloud SQL con una IP pública, lo que puede exponerlas al tráfico de internet.
- **Restrict shared VPC project lien removal:** Prevents the accidental deletion of Shared VPC host projects.
- **Restringir la eliminación de gravámenes de proyectos VPC compartidos:** Previene la eliminación accidental de proyectos anfitriones de VPC compartidos.
* **Sets the internal DNS setting for new projects to Zonal DNS Only:** Prevents the use of a legacy DNS setting that has reduced service availability.
* **Establece la configuración de DNS interno para nuevos proyectos a Solo DNS Zonal:** Previene el uso de una configuración de DNS heredada que ha reducido la disponibilidad del servicio.
- **Skip default network creation:** Prevents automatic creation of the default VPC network and related resources. This avoids overly-permissive default firewall rules.
- **Omitir la creación de red predeterminada:** Previene la creación automática de la red VPC predeterminada y recursos relacionados. Esto evita reglas de firewall predeterminadas excesivamente permisivas.
* **Disable VPC External IPv6 usage:** Prevents the creation of external IPv6 subnets, which can be exposed to unauthorized internet access.
* **Deshabilitar el uso de IPv6 externo en VPC:** Previene la creación de subredes IPv6 externas, que pueden ser expuestas a accesos no autorizados a internet.
</details>
## **IAM Roles**
## **Roles de IAM**
These are like IAM policies in AWS as **each role contains a set of permissions.**
Estos son como las políticas de IAM en AWS ya que **cada rol contiene un conjunto de permisos.**
However, unlike in AWS, there is **no centralized repo** of roles. Instead of that, **resources give X access roles to Y principals**, and the only way to find out who has access to a resource is to use the **`get-iam-policy` method over that resource**.\
This could be a problem because this means that the only way to find out **which permissions a principal has is to ask every resource who is it giving permissions to**, and a user might not have permissions to get permissions from all resources.
Sin embargo, a diferencia de AWS, **no hay un repositorio centralizado** de roles. En lugar de eso, **los recursos dan X roles de acceso a Y principales**, y la única forma de averiguar quién tiene acceso a un recurso es usar el **método `get-iam-policy` sobre ese recurso**.\
Esto podría ser un problema porque esto significa que la única forma de averiguar **qué permisos tiene un principal es preguntar a cada recurso a quién le está dando permisos**, y un usuario podría no tener permisos para obtener permisos de todos los recursos.
There are **three types** of roles in IAM:
Hay **tres tipos** de roles en IAM:
- **Basic/Primitive roles**, which include the **Owner**, **Editor**, and **Viewer** roles that existed prior to the introduction of IAM.
- **Predefined roles**, which provide granular access for a specific service and are managed by Google Cloud. There are a lot of predefined roles, you can **see all of them with the privileges they have** [**here**](https://cloud.google.com/iam/docs/understanding-roles#predefined_roles).
- **Custom roles**, which provide granular access according to a user-specified list of permissions.
- **Roles básicos/primarios**, que incluyen los roles de **Propietario**, **Editor** y **Visualizador** que existían antes de la introducción de IAM.
- **Roles predefinidos**, que proporcionan acceso granular para un servicio específico y son gestionados por Google Cloud. Hay muchos roles predefinidos, puedes **ver todos ellos con los privilegios que tienen** [**aquí**](https://cloud.google.com/iam/docs/understanding-roles#predefined_roles).
- **Roles personalizados**, que proporcionan acceso granular de acuerdo a una lista de permisos especificada por el usuario.
There are thousands of permissions in GCP. In order to check if a role has a permissions you can [**search the permission here**](https://cloud.google.com/iam/docs/permissions-reference) and see which roles have it.
Hay miles de permisos en GCP. Para verificar si un rol tiene un permiso, puedes [**buscar el permiso aquí**](https://cloud.google.com/iam/docs/permissions-reference) y ver qué roles lo tienen.
You can also [**search here predefined roles**](https://cloud.google.com/iam/docs/understanding-roles#product_specific_documentation) **offered by each product.** Note that some **roles** cannot be attached to users and **only to SAs because some permissions** they contain.\
Moreover, note that **permissions** will only **take effect** if they are **attached to the relevant service.**
También puedes [**buscar aquí roles predefinidos**](https://cloud.google.com/iam/docs/understanding-roles#product_specific_documentation) **ofrecidos por cada producto.** Ten en cuenta que algunos **roles** no pueden ser asignados a usuarios y **solo a cuentas de servicio debido a algunos permisos** que contienen.\
Además, ten en cuenta que los **permisos** solo **tendrán efecto** si están **adjuntos al servicio relevante.**
Or check if a **custom role can use a** [**specific permission in here**](https://cloud.google.com/iam/docs/custom-roles-permissions-support)**.**
O verifica si un **rol personalizado puede usar un** [**permiso específico aquí**](https://cloud.google.com/iam/docs/custom-roles-permissions-support)**.**
{{#ref}}
../gcp-services/gcp-iam-and-org-policies-enum.md
{{#endref}}
## Users <a href="#default-credentials" id="default-credentials"></a>
## Usuarios <a href="#default-credentials" id="default-credentials"></a>
In **GCP console** there **isn't any Users or Groups** management, that is done in **Google Workspace**. Although you could synchronize a different identity provider in Google Workspace.
En **la consola de GCP** no **hay gestión de Usuarios o Grupos**, eso se hace en **Google Workspace**. Aunque podrías sincronizar un proveedor de identidad diferente en Google Workspace.
You can access Workspaces **users and groups in** [**https://admin.google.com**](https://admin.google.com/).
Puedes acceder a los **usuarios y grupos de Workspaces en** [**https://admin.google.com**](https://admin.google.com/).
**MFA** can be **forced** to Workspaces users, however, an **attacker** could use a token to access GCP **via cli which won't be protected by MFA** (it will be protected by MFA only when the user logins to generate it: `gcloud auth login`).
**MFA** puede ser **forzada** a los usuarios de Workspaces, sin embargo, un **atacante** podría usar un token para acceder a GCP **a través de cli que no estará protegido por MFA** (estará protegido por MFA solo cuando el usuario inicie sesión para generarlo: `gcloud auth login`).
## Groups
## Grupos
When an organisation is created several groups are **strongly suggested to be created.** If you manage any of them you might have compromised all or an important part of the organization:
Cuando se crea una organización, se **sugiere encarecidamente crear varios grupos.** Si gestionas alguno de ellos, podrías haber comprometido toda o una parte importante de la organización:
<table data-header-hidden><thead><tr><th width="299.3076923076923"></th><th></th></tr></thead><tbody><tr><td><strong>Group</strong></td><td><strong>Function</strong></td></tr><tr><td><strong><code>gcp-organization-admins</code></strong><br><em>(group or individual accounts required for checklist)</em></td><td>Administering any resource that belongs to the organization. Assign this role sparingly; org admins have access to all of your Google Cloud resources. Alternatively, because this function is highly privileged, consider using individual accounts instead of creating a group.</td></tr><tr><td><strong><code>gcp-network-admins</code></strong><br><em>(required for checklist)</em></td><td>Creating networks, subnets, firewall rules, and network devices such as Cloud Router, Cloud VPN, and cloud load balancers.</td></tr><tr><td><strong><code>gcp-billing-admins</code></strong><br><em>(required for checklist)</em></td><td>Setting up billing accounts and monitoring their usage.</td></tr><tr><td><strong><code>gcp-developers</code></strong><br><em>(required for checklist)</em></td><td>Designing, coding, and testing applications.</td></tr><tr><td><strong><code>gcp-security-admins</code></strong><br></td><td>Establishing and managing security policies for the entire organization, including access management and <a href="https://cloud.google.com/resource-manager/docs/organization-policy/org-policy-constraints">organization constraint policies</a>. See the <a href="https://cloud.google.com/architecture/security-foundations/authentication-authorization#users_and_groups">Google Cloud security foundations guide</a> for more information about planning your Google Cloud security infrastructure.</td></tr><tr><td><strong><code>gcp-devops</code></strong></td><td>Creating or managing end-to-end pipelines that support continuous integration and delivery, monitoring, and system provisioning.</td></tr><tr><td><strong><code>gcp-logging-admins</code></strong></td><td></td></tr><tr><td><strong><code>gcp-logging-viewers</code></strong></td><td></td></tr><tr><td><strong><code>gcp-monitor-admins</code></strong></td><td></td></tr><tr><td><strong><code>gcp-billing-viewer</code></strong><br><em>(no longer by default)</em></td><td>Monitoring the spend on projects. Typical members are part of the finance team.</td></tr><tr><td><strong><code>gcp-platform-viewer</code></strong><br><em>(no longer by default)</em></td><td>Reviewing resource information across the Google Cloud organization.</td></tr><tr><td><strong><code>gcp-security-reviewer</code></strong><br><em>(no longer by default)</em></td><td>Reviewing cloud security.</td></tr><tr><td><strong><code>gcp-network-viewer</code></strong><br><em>(no longer by default)</em></td><td>Reviewing network configurations.</td></tr><tr><td><strong><code>grp-gcp-audit-viewer</code></strong><br><em>(no longer by default)</em></td><td>Viewing audit logs.</td></tr><tr><td><strong><code>gcp-scc-admin</code></strong><br><em>(no longer by default)</em></td><td>Administering Security Command Center.</td></tr><tr><td><strong><code>gcp-secrets-admin</code></strong><br><em>(no longer by default)</em></td><td>Managing secrets in Secret Manager.</td></tr></tbody></table>
<table data-header-hidden><thead><tr><th width="299.3076923076923"></th><th></th></tr></thead><tbody><tr><td><strong>Grupo</strong></td><td><strong>Funcn</strong></td></tr><tr><td><strong><code>gcp-organization-admins</code></strong><br><em>(se requieren cuentas de grupo o individuales para la lista de verificación)</em></td><td>Administrar cualquier recurso que pertenezca a la organización. Asigna este rol con moderación; los administradores de la organización tienen acceso a todos tus recursos de Google Cloud. Alternativamente, dado que esta función tiene privilegios altos, considera usar cuentas individuales en lugar de crear un grupo.</td></tr><tr><td><strong><code>gcp-network-admins</code></strong><br><em>(requerido para la lista de verificación)</em></td><td>Crear redes, subredes, reglas de firewall y dispositivos de red como Cloud Router, Cloud VPN y balanceadores de carga en la nube.</td></tr><tr><td><strong><code>gcp-billing-admins</code></strong><br><em>(requerido para la lista de verificación)</em></td><td>Configurar cuentas de facturación y monitorear su uso.</td></tr><tr><td><strong><code>gcp-developers</code></strong><br><em>(requerido para la lista de verificación)</em></td><td>Diseñar, codificar y probar aplicaciones.</td></tr><tr><td><strong><code>gcp-security-admins</code></strong><br></td><td>Establecer y gestionar políticas de seguridad para toda la organización, incluyendo gestión de acceso y <a href="https://cloud.google.com/resource-manager/docs/organization-policy/org-policy-constraints">políticas de restricciones de organización</a>. Consulta la <a href="https://cloud.google.com/architecture/security-foundations/authentication-authorization#users_and_groups">guía de fundamentos de seguridad de Google Cloud</a> para más información sobre la planificación de tu infraestructura de seguridad en Google Cloud.</td></tr><tr><td><strong><code>gcp-devops</code></strong></td><td>Crear o gestionar pipelines de extremo a extremo que soporten integración y entrega continuas, monitoreo y aprovisionamiento de sistemas.</td></tr><tr><td><strong><code>gcp-logging-admins</code></strong></td><td></td></tr><tr><td><strong><code>gcp-logging-viewers</code></strong></td><td></td></tr><tr><td><strong><code>gcp-monitor-admins</code></strong></td><td></td></tr><tr><td><strong><code>gcp-billing-viewer</code></strong><br><em>(ya no por defecto)</em></td><td>Monitorear el gasto en proyectos. Los miembros típicos son parte del equipo de finanzas.</td></tr><tr><td><strong><code>gcp-platform-viewer</code></strong><br><em>(ya no por defecto)</em></td><td>Revisar información de recursos a través de la organización de Google Cloud.</td></tr><tr><td><strong><code>gcp-security-reviewer</code></strong><br><em>(ya no por defecto)</em></td><td>Revisar la seguridad en la nube.</td></tr><tr><td><strong><code>gcp-network-viewer</code></strong><br><em>(ya no por defecto)</em></td><td>Revisar configuraciones de red.</td></tr><tr><td><strong><code>grp-gcp-audit-viewer</code></strong><br><em>(ya no por defecto)</em></td><td>Ver registros de auditoría.</td></tr><tr><td><strong><code>gcp-scc-admin</code></strong><br><em>(ya no por defecto)</em></td><td>Administrar el Centro de Comando de Seguridad.</td></tr><tr><td><strong><code>gcp-secrets-admin</code></strong><br><em>(ya no por defecto)</em></td><td>Gestionar secretos en Secret Manager.</td></tr></tbody></table>
## **Default Password Policy**
## **Política de Contraseñas Predeterminada**
- Enforce strong passwords
- Between 8 and 100 characters
- No reuse
- No expiration
- If people is accessing Workspace through a third party provider, these requirements aren't applied.
- Hacer cumplir contraseñas fuertes
- Entre 8 y 100 caracteres
- Sin reutilización
- Sin expiración
- Si las personas acceden a Workspace a través de un proveedor de terceros, estos requisitos no se aplican.
<figure><img src="../../../images/image (20).png" alt=""><figcaption></figcaption></figure>
<figure><img src="../../../images/image (22).png" alt=""><figcaption></figcaption></figure>
## **Service accounts**
## **Cuentas de servicio**
These are the principals that **resources** can **have** **attached** and access to interact easily with GCP. For example, it's possible to access the **auth token** of a Service Account **attached to a VM** in the metadata.\
It is possible to encounter some **conflicts** when using both **IAM and access scopes**. For example, your service account may have the IAM role of `compute.instanceAdmin` but the instance you've breached has been crippled with the scope limitation of `https://www.googleapis.com/auth/compute.readonly`. This would prevent you from making any changes using the OAuth token that's automatically assigned to your instance.
Estos son los principales que **los recursos** pueden **tener** **adjuntos** y acceso para interactuar fácilmente con GCP. Por ejemplo, es posible acceder al **token de autenticación** de una Cuenta de Servicio **adjunta a una VM** en los metadatos.\
Es posible encontrar algunos **conflictos** al usar tanto **IAM como scopes de acceso**. Por ejemplo, tu cuenta de servicio puede tener el rol de IAM de `compute.instanceAdmin`, pero la instancia que has comprometido ha sido limitada con la restricción de scope de `https://www.googleapis.com/auth/compute.readonly`. Esto te impediría hacer cualquier cambio usando el token OAuth que se asigna automáticamente a tu instancia.
It's similar to **IAM roles from AWS**. But not like in AWS, **any** service account can be **attached to any service** (it doesn't need to allow it via a policy).
Several of the service accounts that you will find are actually **automatically generated by GCP** when you start using a service, like:
Es similar a **los roles de IAM de AWS**. Pero a diferencia de AWS, **cualquier** cuenta de servicio puede ser **adjunta a cualquier servicio** (no necesita permitirlo a través de una política).
Varias de las cuentas de servicio que encontrarás son en realidad **generadas automáticamente por GCP** cuando comienzas a usar un servicio, como:
```
PROJECT_NUMBER-compute@developer.gserviceaccount.com
PROJECT_ID@appspot.gserviceaccount.com
```
However, it's also possible to create and attach to resources **custom service accounts**, which will look like this:
Sin embargo, también es posible crear y adjuntar a recursos **cuentas de servicio personalizadas**, que se verán así:
```
SERVICE_ACCOUNT_NAME@PROJECT_NAME.iam.gserviceaccount.com
```
### **Claves y Tokens**
### **Keys & Tokens**
Hay 2 formas principales de acceder a GCP como una cuenta de servicio:
There are 2 main ways to access GCP as a service account:
- **A través de tokens OAuth**: Estos son tokens que obtendrás de lugares como puntos finales de metadatos o robando solicitudes http y están limitados por los **alcances de acceso**.
- **Claves**: Estos son pares de claves públicas y privadas que te permitirán firmar solicitudes como la cuenta de servicio e incluso generar tokens OAuth para realizar acciones como la cuenta de servicio. Estas claves son peligrosas porque son más complicadas de limitar y controlar, por eso GCP recomienda no generarlas.
- Ten en cuenta que cada vez que se crea una SA, **GCP genera una clave para la cuenta de servicio** a la que el usuario no puede acceder (y no se listará en la aplicación web). Según [**este hilo**](https://www.reddit.com/r/googlecloud/comments/f0ospy/service_account_keys_observations/), esta clave es **utilizada internamente por GCP** para dar acceso a los puntos finales de metadatos para generar los tokens OAuth accesibles.
- **Via OAuth tokens**: These are tokens that you will get from places like metadata endpoints or stealing http requests and they are limited by the **access scopes**.
- **Keys**: These are public and private key pairs that will allow you to sign requests as the service account and even generate OAuth tokens to perform actions as the service account. These keys are dangerous because they are more complicated to limit and control, that's why GCP recommend to not generate them.
- Note that every-time a SA is created, **GCP generates a key for the service account** that the user cannot access (and won't be listed in the web application). According to [**this thread**](https://www.reddit.com/r/googlecloud/comments/f0ospy/service_account_keys_observations/) this key is **used internally by GCP** to give metadata endpoints access to generate the accesible OAuth tokens.
### **Alcances de acceso**
### **Access scopes**
Los alcances de acceso están **adjuntos a los tokens OAuth generados** para acceder a los puntos finales de la API de GCP. **Restringen los permisos** del token OAuth.\
Esto significa que si un token pertenece a un Propietario de un recurso pero no tiene en el alcance del token acceso a ese recurso, el token **no puede ser utilizado para (ab)usar esos privilegios**.
Access scope are **attached to generated OAuth tokens** to access the GCP API endpoints. They **restrict the permissions** of the OAuth token.\
This means that if a token belongs to an Owner of a resource but doesn't have the in the token scope to access that resource, the token **cannot be used to (ab)use those privileges**.
Google actually [recommends](https://cloud.google.com/compute/docs/access/service-accounts#service_account_permissions) that **access scopes are not used and to rely totally on IAM**. The web management portal actually enforces this, but access scopes can still be applied to instances using custom service accounts programmatically.
You can see what **scopes** are **assigned** by **querying:**
Google de hecho [recomienda](https://cloud.google.com/compute/docs/access/service-accounts#service_account_permissions) que **no se utilicen alcances de acceso y que se confíe totalmente en IAM**. El portal de gestión web de hecho hace cumplir esto, pero los alcances de acceso aún se pueden aplicar a instancias utilizando cuentas de servicio personalizadas programáticamente.
Puedes ver qué **alcances** están **asignados** consultando:
```bash
curl 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=<access_token>'
{
"issued_to": "223044615559.apps.googleusercontent.com",
"audience": "223044615559.apps.googleusercontent.com",
"user_id": "139746512919298469201",
"scope": "openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/sqlservice.login https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/accounts.reauth",
"expires_in": 2253,
"email": "username@testing.com",
"verified_email": true,
"access_type": "offline"
"issued_to": "223044615559.apps.googleusercontent.com",
"audience": "223044615559.apps.googleusercontent.com",
"user_id": "139746512919298469201",
"scope": "openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/sqlservice.login https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/accounts.reauth",
"expires_in": 2253,
"email": "username@testing.com",
"verified_email": true,
"access_type": "offline"
}
```
Los **alcances** anteriores son los que se generan por **defecto** utilizando **`gcloud`** para acceder a datos. Esto se debe a que cuando usas **`gcloud`** primero creas un token de OAuth y luego lo usas para contactar los endpoints.
The previous **scopes** are the ones generated by **default** using **`gcloud`** to access data. This is because when you use **`gcloud`** you first create an OAuth token, and then use it to contact the endpoints.
El alcance más importante de esos potencialmente es **`cloud-platform`**, que básicamente significa que es posible **acceder a cualquier servicio en GCP**.
The most important scope of those potentially is **`cloud-platform`**, which basically means that it's possible to **access any service in GCP**.
You can **find a list of** [**all the possible scopes in here**](https://developers.google.com/identity/protocols/googlescopes)**.**
If you have **`gcloud`** browser credentials, it's possible to **obtain a token with other scopes,** doing something like:
Puedes **encontrar una lista de** [**todos los posibles alcances aquí**](https://developers.google.com/identity/protocols/googlescopes)**.**
Si tienes credenciales de navegador de **`gcloud`**, es posible **obtener un token con otros alcances,** haciendo algo como:
```bash
# Maybe you can get a user token with other scopes changing the scopes array from ~/.config/gcloud/credentials.db
@@ -213,22 +204,17 @@ gcloud auth application-default print-access-token
# To use this token with some API you might need to use curl to indicate the project header with --header "X-Goog-User-Project: <project-name>"
```
## **Políticas, Vinculaciones y Membresías de IAM en Terraform**
## **Terraform IAM Policies, Bindings and Memberships**
Como se define en terraform en [https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/google_project_iam](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/google_project_iam), al usar terraform con GCP hay diferentes formas de otorgar acceso a un principal sobre un recurso:
As defined by terraform in [https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/google_project_iam](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/google_project_iam) using terraform with GCP there are different ways to grant a principal access over a resource:
- **Membresías**: Estableces **principales como miembros de roles** **sin restricciones** sobre el rol o los principales. Puedes poner un usuario como miembro de un rol y luego poner un grupo como miembro del mismo rol y también establecer esos principales (usuario y grupo) como miembros de otros roles.
- **Vinculaciones**: Varios **principales pueden estar vinculados a un rol**. Esos **principales aún pueden estar vinculados o ser miembros de otros roles**. Sin embargo, si un principal que no está vinculado al rol se establece como **miembro de un rol vinculado**, la próxima vez que se **aplique la vinculación, la membresía desaparecerá**.
- **Políticas**: Una política es **autoritativa**, indica roles y principales y luego, **esos principales no pueden tener más roles y esos roles no pueden tener más principales** a menos que esa política sea modificada (ni siquiera en otras políticas, vinculaciones o membresías). Por lo tanto, cuando un rol o principal se especifica en la política, todos sus privilegios están **limitados por esa política**. Obviamente, esto puede ser eludido en caso de que al principal se le dé la opción de modificar la política o permisos de escalada de privilegios (como crear un nuevo principal y vincularlo a un nuevo rol).
- **Memberships**: You set **principals as members of roles** **without restrictions** over the role or the principals. You can put a user as a member of a role and then put a group as a member of the same role and also set those principals (user and group) as member of other roles.
- **Bindings**: Several **principals can be binded to a role**. Those **principals can still be binded or be members of other roles**. However, if a principal which isnt binded to the role is set as **member of a binded role**, the next time the **binding is applied, the membership will disappear**.
- **Policies**: A policy is **authoritative**, it indicates roles and principals and then, **those principals cannot have more roles and those roles cannot have more principals** unless that policy is modified (not even in other policies, bindings or memberships). Therefore, when a role or principal is specified in policy all its privileges are **limited by that policy**. Obviously, this can be bypassed in case the principal is given the option to modify the policy or privilege escalation permissions (like create a new principal and bind him a new role).
## References
## Referencias
- [https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/](https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/)
- [https://cloud.google.com/resource-manager/docs/cloud-platform-resource-hierarchy](https://cloud.google.com/resource-manager/docs/cloud-platform-resource-hierarchy)
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -1,15 +1,14 @@
# GCP - Federation Abuse
# GCP - Abuso de Federación
{{#include ../../../banners/hacktricks-training.md}}
## OIDC - Github Actions Abuse
## OIDC - Abuso de Github Actions
### GCP
In order to give **access to the Github Actions** from a Github repo to a GCP **service account** the following steps are needed:
- **Create the Service Account** to access from github actions with the **desired permissions:**
Para dar **acceso a las Github Actions** desde un repositorio de Github a una **cuenta de servicio** de GCP, se necesitan los siguientes pasos:
- **Crear la Cuenta de Servicio** para acceder desde las acciones de github con los **permisos deseados:**
```bash
projectId=FIXME
gcloud config set project $projectId
@@ -24,134 +23,121 @@ gcloud services enable iamcredentials.googleapis.com
# Give permissions to SA
gcloud projects add-iam-policy-binding $projectId \
--member="serviceAccount:$saId" \
--role="roles/iam.securityReviewer"
--member="serviceAccount:$saId" \
--role="roles/iam.securityReviewer"
```
- Generate a **new workload identity pool**:
- Generar un **nuevo grupo de identidades de carga de trabajo**:
```bash
# Create a Workload Identity Pool
poolName=wi-pool
gcloud iam workload-identity-pools create $poolName \
--location global \
--display-name $poolName
--location global \
--display-name $poolName
poolId=$(gcloud iam workload-identity-pools describe $poolName \
--location global \
--format='get(name)')
--location global \
--format='get(name)')
```
- Generate a new **workload identity pool OIDC provider** that **trusts** github actions (by org/repo name in this scenario):
- Generar un nuevo **proveedor OIDC de grupo de identidades de carga de trabajo** que **confíe** en las acciones de github (por nombre de org/repo en este escenario):
```bash
attributeMappingScope=repository # could be sub (GitHub repository and branch) or repository_owner (GitHub organization)
gcloud iam workload-identity-pools providers create-oidc $poolName \
--location global \
--workload-identity-pool $poolName \
--display-name $poolName \
--attribute-mapping "google.subject=assertion.${attributeMappingScope},attribute.actor=assertion.actor,attribute.aud=assertion.aud,attribute.repository=assertion.repository" \
--issuer-uri "https://token.actions.githubusercontent.com"
--location global \
--workload-identity-pool $poolName \
--display-name $poolName \
--attribute-mapping "google.subject=assertion.${attributeMappingScope},attribute.actor=assertion.actor,attribute.aud=assertion.aud,attribute.repository=assertion.repository" \
--issuer-uri "https://token.actions.githubusercontent.com"
providerId=$(gcloud iam workload-identity-pools providers describe $poolName \
--location global \
--workload-identity-pool $poolName \
--format='get(name)')
--location global \
--workload-identity-pool $poolName \
--format='get(name)')
```
- Finally, **allow the principal** from the provider to use a service principal:
- Finalmente, **permita que el principal** del proveedor use un principal de servicio:
```bash
gitHubRepoName="repo-org/repo-name"
gcloud iam service-accounts add-iam-policy-binding $saId \
--role "roles/iam.workloadIdentityUser" \
--member "principalSet://iam.googleapis.com/${poolId}/attribute.${attributeMappingScope}/${gitHubRepoName}"
--role "roles/iam.workloadIdentityUser" \
--member "principalSet://iam.googleapis.com/${poolId}/attribute.${attributeMappingScope}/${gitHubRepoName}"
```
> [!WARNING]
> Note how in the previous member we are specifying the **`org-name/repo-name`** as conditions to be able to access the service account (other params that makes it **more restrictive** like the branch could also be used).
> Nota cómo en el miembro anterior estamos especificando el **`org-name/repo-name`** como condiciones para poder acceder a la cuenta de servicio (otros parámetros que la hacen **más restrictiva** como la rama también podrían ser utilizados).
>
> However it's also possible to **allow all github to access** the service account creating a provider such the following using a wildcard:
> Sin embargo, también es posible **permitir que todos en github accedan** a la cuenta de servicio creando un proveedor como el siguiente usando un comodín:
<pre class="language-bash"><code class="lang-bash"># Create a Workload Identity Pool
<pre class="language-bash"><code class="lang-bash"># Crear un Pool de Identidad de Carga de Trabajo
poolName=wi-pool2
gcloud iam workload-identity-pools create $poolName \
--location global \
--display-name $poolName
--location global \
--display-name $poolName
poolId=$(gcloud iam workload-identity-pools describe $poolName \
--location global \
--format='get(name)')
--location global \
--format='get(name)')
gcloud iam workload-identity-pools providers create-oidc $poolName \
--project="${projectId}" \
--location="global" \
--workload-identity-pool="$poolName" \
--display-name="Demo provider" \
--attribute-mapping="google.subject=assertion.sub,attribute.actor=assertion.actor,attribute.aud=assertion.aud" \
--issuer-uri="https://token.actions.githubusercontent.com"
--project="${projectId}" \
--location="global" \
--workload-identity-pool="$poolName" \
--display-name="Proveedor de demostración" \
--attribute-mapping="google.subject=assertion.sub,attribute.actor=assertion.actor,attribute.aud=assertion.aud" \
--issuer-uri="https://token.actions.githubusercontent.com"
providerId=$(gcloud iam workload-identity-pools providers describe $poolName \
--location global \
--workload-identity-pool $poolName \
--format='get(name)')
--location global \
--workload-identity-pool $poolName \
--format='get(name)')
<strong># CHECK THE WILDCARD
<strong># VERIFICAR EL COMODÍN
</strong>gcloud iam service-accounts add-iam-policy-binding "${saId}" \
--project="${projectId}" \
--role="roles/iam.workloadIdentityUser" \
--project="${projectId}" \
--role="roles/iam.workloadIdentityUser" \
<strong> --member="principalSet://iam.googleapis.com/${poolId}/*"
</strong></code></pre>
> [!WARNING]
> In this case anyone could access the service account from github actions, so it's important always to **check how the member is defined**.\
> It should be always something like this:
> En este caso, cualquiera podría acceder a la cuenta de servicio desde github actions, por lo que es importante siempre **verificar cómo está definido el miembro**.\
> Siempre debería ser algo como esto:
>
> `attribute.{custom_attribute}`:`principalSet://iam.googleapis.com/projects/{project}/locations/{location}/workloadIdentityPools/{pool}/attribute.{custom_attribute}/{value}`
### Github
Remember to change **`${providerId}`** and **`${saId}`** for their respective values:
Recuerda cambiar **`${providerId}`** y **`${saId}`** por sus respectivos valores:
```yaml
name: Check GCP action
on:
workflow_dispatch:
pull_request:
branches:
- main
workflow_dispatch:
pull_request:
branches:
- main
permissions:
id-token: write
id-token: write
jobs:
Get_OIDC_ID_token:
runs-on: ubuntu-latest
steps:
- id: "auth"
name: "Authenticate to GCP"
uses: "google-github-actions/auth@v2.1.3"
with:
create_credentials_file: "true"
workload_identity_provider: "${providerId}" # In the providerId, the numerical project ID (12 digit number) should be used
service_account: "${saId}" # instead of the alphanumeric project ID. ex:
activate_credentials_file: true # projects/123123123123/locations/global/workloadIdentityPools/iam-lab-7-gh-pool/providers/iam-lab-7-gh-pool-oidc-provider'
- id: "gcloud"
name: "gcloud"
run: |-
gcloud config set project <project-id>
gcloud config set account '${saId}'
gcloud auth login --brief --cred-file="${{ steps.auth.outputs.credentials_file_path }}"
gcloud auth list
gcloud projects list
gcloud secrets list
Get_OIDC_ID_token:
runs-on: ubuntu-latest
steps:
- id: "auth"
name: "Authenticate to GCP"
uses: "google-github-actions/auth@v2.1.3"
with:
create_credentials_file: "true"
workload_identity_provider: "${providerId}" # In the providerId, the numerical project ID (12 digit number) should be used
service_account: "${saId}" # instead of the alphanumeric project ID. ex:
activate_credentials_file: true # projects/123123123123/locations/global/workloadIdentityPools/iam-lab-7-gh-pool/providers/iam-lab-7-gh-pool-oidc-provider'
- id: "gcloud"
name: "gcloud"
run: |-
gcloud config set project <project-id>
gcloud config set account '${saId}'
gcloud auth login --brief --cred-file="${{ steps.auth.outputs.credentials_file_path }}"
gcloud auth list
gcloud projects list
gcloud secrets list
```
{{#include ../../../banners/hacktricks-training.md}}