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

This commit is contained in:
Translator
2024-12-31 19:09:02 +00:00
parent 7770a50092
commit 4ecda9fe96
244 changed files with 8478 additions and 11318 deletions

View File

@@ -1,207 +1,198 @@
# GCP - Basic Information
# GCP - Основна інформація
{{#include ../../../banners/hacktricks-training.md}}
## **Resource hierarchy**
## **Ієрархія ресурсів**
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 використовує [Ієрархію ресурсів](https://cloud.google.com/resource-manager/docs/cloud-platform-resource-hierarchy), яка концептуально подібна до традиційної файлової системи. Це забезпечує логічний робочий процес батьків/дочок з конкретними точками прив'язки для політик і дозволів.
На високому рівні це виглядає так:
```
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.
Віртуальна машина (називається Обчислювальним екземпляром) є ресурсом. Ресурс знаходиться в проекті, ймовірно, поряд з іншими Обчислювальними екземплярами, сховищами, тощо.
<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**
## **Міграція проектів**
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).
Можливо **мігрувати проект без організації** до організації з правами `roles/resourcemanager.projectCreator` та `roles/resourcemanager.projectMover`. Якщо проект знаходиться в іншій організації, потрібно зв'язатися з підтримкою GCP, щоб **спочатку перемістити їх з організації**. Для отримання додаткової інформації перегляньте [**це**](https://medium.com/google-cloud/migrating-a-project-from-one-organization-to-another-gcp-4b37a86dd9e6).
## **Organization Policies**
## **Політики організації**
Allow to centralize control over your organization's cloud resources:
Дозволяють централізувати контроль над ресурсами хмари вашої організації:
- 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.
- Централізувати контроль для **налаштування обмежень** на те, як можуть використовуватися ресурси вашої організації.
- Визначити та встановити **обмеження** для ваших команд розробників, щоб залишатися в межах відповідності.
- Допомогти власникам проектів та їх командам швидко рухатися без побоювань про порушення відповідності.
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**.
Ці політики можуть бути створені для **впливу на всю організацію, папки або проекти**. Наслідники цільового вузла ієрархії ресурсів **успадковують політику організації**.
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**.
Щоб **визначити** політику організації, **ви вибираєте** [**обмеження**](https://cloud.google.com/resource-manager/docs/organization-policy/overview#constraints), яке є певним типом обмеження щодо або служби Google Cloud, або групи служб Google Cloud. Ви **налаштовуєте це обмеження з вашими бажаними обмеженнями**.
<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>
#### Загальні випадки використання <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
- Обмежити спільний доступ до ресурсів на основі домену.
- Обмежити використання облікових записів служби управління ідентифікацією та доступом.
- Обмежити фізичне розташування новостворених ресурсів.
- Вимкнути створення облікових записів служби.
<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)**.**
Є багато інших обмежень, які надають вам детальний контроль над ресурсами вашої організації. Для **додаткової інформації дивіться** [**список усіх обмежень служби політики організації**](https://cloud.google.com/resource-manager/docs/organization-policy/org-policy-constraints)**.**
### **Default Organization Policies**
### **Політики організації за замовчуванням**
<details>
<summary>These are the policies that Google will add by default when setting up your GCP organization:</summary>
<summary>Це політики, які Google додасть за замовчуванням при налаштуванні вашої організації GCP:</summary>
**Access Management Policies**
**Політики управління доступом**
- **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.
- **Обмежені контакти домену:** Запобігає додаванню користувачів до Основних контактів за межами ваших вказаних доменів. Це обмежує Основні контакти лише на управлінні ідентичностями користувачів у ваших вибраних доменах для отримання сповіщень платформи.
- **Обмежене спільне використання домену:** Запобігає додаванню користувачів до політик IAM за межами ваших вказаних доменів. Це обмежує політики IAM лише на управлінні ідентичностями користувачів у ваших вибраних доменах для доступу до ресурсів у цій організації.
- **Запобігання публічному доступу:** Запобігає відкриттю сховищ Cloud Storage для публіки. Це забезпечує, що розробник не може налаштувати сховища Cloud Storage для неавтентифікованого доступу в Інтернеті.
- **Уніфікований доступ на рівні сховища:** Запобігає спискам контролю доступу (ACL) на рівні об'єктів у сховищах Cloud Storage. Це спрощує управління доступом, застосовуючи політики IAM послідовно до всіх об'єктів у сховищах Cloud Storage.
- **Вимагати вхід в ОС:** Віртуальні машини, створені в нових проектах, матимуть увімкнений вхід в ОС. Це дозволяє вам керувати доступом SSH до ваших екземплярів, використовуючи IAM, без необхідності створювати та керувати окремими ключами SSH.
**Additional security policies for service accounts**
**Додаткові політики безпеки для облікових записів служби**
- **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.
- **Вимкнути автоматичні надання IAM:** Запобігає автоматичному наданню обліковим записам служби App Engine та Compute Engine ролі редактора IAM при створенні проекту. Це забезпечує, що облікові записи служби не отримують надто широкі ролі IAM при створенні.
- **Вимкнути створення ключів облікових записів служби:** Запобігає створенню публічних ключів облікових записів служби. Це допомагає зменшити ризик витоку постійних облікових даних.
- **Вимкнути завантаження ключів облікових записів служби:** Запобігає завантаженню публічних ключів облікових записів служби. Це допомагає зменшити ризик витоку або повторного використання матеріалів ключів.
**Secure VPC network configuration policies**
**Політики конфігурації безпечної мережі VPC**
- **Define allowed external IPs for VM instances**: Prevents the creation of Compute instances with a public IP, which can expose them to internet traffic.
- **Визначити дозволені зовнішні IP-адреси для екземплярів ВМ:** Запобігає створенню обчислювальних екземплярів з публічною IP-адресою, що може піддати їх інтернет-трафіку.
* **Disable VM nested virtualization**: Prevents the creation of nested VMs on Compute Engine VMs. This decreases the security risk of having unmonitored nested VMs.
* **Вимкнути вкладену віртуалізацію ВМ:** Запобігає створенню вкладених ВМ на ВМ Compute Engine. Це зменшує ризик безпеки, пов'язаний з наявністю непідконтрольних вкладених ВМ.
- **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.
- **Вимкнути серійний порт ВМ:** Запобігає доступу до серійного порту ВМ Compute Engine. Це запобігає введенню даних у серійний порт сервера за допомогою API Compute Engine.
* **Restrict authorized networks on Cloud SQL instances:** Prevents public or non-internal network ranges from accessing your Cloud SQL databases.
* **Обмежити авторизовані мережі на екземплярах Cloud SQL:** Запобігає доступу публічних або не внутрішніх мереж до ваших баз даних Cloud SQL.
- **Restrict Protocol Forwarding Based on type of IP Address:** Prevents VM protocol forwarding for external IP addresses.
- **Обмежити пересилання протоколів на основі типу IP-адреси:** Запобігає пересиланню протоколів ВМ для зовнішніх IP-адрес.
* **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.
* **Обмежити доступ до публічних IP на екземплярах Cloud SQL:** Запобігає створенню екземплярів Cloud SQL з публічною IP-адресою, що може піддати їх інтернет-трафіку.
- **Restrict shared VPC project lien removal:** Prevents the accidental deletion of Shared VPC host projects.
- **Обмежити видалення застави проекту спільної VPC:** Запобігає випадковому видаленню проектів-хостів спільної VPC.
* **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.
* **Встановити внутрішнє налаштування DNS для нових проектів на лише зональний DNS:** Запобігає використанню застарілого налаштування DNS, яке зменшило доступність служби.
- **Skip default network creation:** Prevents automatic creation of the default VPC network and related resources. This avoids overly-permissive default firewall rules.
- **Пропустити створення мережі за замовчуванням:** Запобігає автоматичному створенню мережі VPC за замовчуванням та пов'язаних ресурсів. Це уникає надто широких правил брандмауера за замовчуванням.
* **Disable VPC External IPv6 usage:** Prevents the creation of external IPv6 subnets, which can be exposed to unauthorized internet access.
* **Вимкнути використання зовнішнього IPv6 VPC:** Запобігає створенню зовнішніх підмереж IPv6, які можуть бути піддані несанкціонованому доступу в Інтернет.
</details>
## **IAM Roles**
## **Ролі IAM**
These are like IAM policies in AWS as **each role contains a set of permissions.**
Це схоже на політики IAM в AWS, оскільки **кожна роль містить набір дозволів.**
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.
Однак, на відміну від AWS, **немає централізованого репозиторію** ролей. Замість цього, **ресурси надають X ролей доступу Y принципалам**, і єдиний спосіб дізнатися, хто має доступ до ресурсу, - це використовувати **метод `get-iam-policy` для цього ресурсу**.\
Це може бути проблемою, оскільки це означає, що єдиний спосіб дізнатися, **які дозволи має принципал, - це запитати кожен ресурс, кому він надає дозволи**, і користувач може не мати дозволів, щоб отримати дозволи з усіх ресурсів.
There are **three types** of roles in IAM:
Є **три типи** ролей в 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.
- **Основні/примітивні ролі**, які включають ролі **Власника**, **Редактора** та **Переглядача**, що існували до впровадження IAM.
- **Попередньо визначені ролі**, які надають детальний доступ до конкретної служби та управляються Google Cloud. Є багато попередньо визначених ролей, ви можете **переглянути всі з них з привілеями, які вони мають** [**тут**](https://cloud.google.com/iam/docs/understanding-roles#predefined_roles).
- **Користувацькі ролі**, які надають детальний доступ відповідно до списку дозволів, вказаного користувачем.
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.
Є тисячі дозволів у GCP. Щоб перевірити, чи має роль дозволи, ви можете [**шукати дозвіл тут**](https://cloud.google.com/iam/docs/permissions-reference) і побачити, які ролі його мають.
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.**
Ви також можете [**шукати тут попередньо визначені ролі**](https://cloud.google.com/iam/docs/understanding-roles#product_specific_documentation) **пропоновані кожним продуктом.** Зверніть увагу, що деякі **ролі** не можуть бути прикріплені до користувачів і **тільки до СА через деякі дозволи**, які вони містять.\
Більше того, зверніть увагу, що **дозволи** набудуть **чинності** лише якщо вони **прикріплені до відповідної служби.**
Or check if a **custom role can use a** [**specific permission in here**](https://cloud.google.com/iam/docs/custom-roles-permissions-support)**.**
Або перевірте, чи може **користувацька роль використовувати** [**конкретний дозвіл тут**](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>
## Користувачі <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.
У **консолі GCP** немає управління Користувачами або Групами, це робиться в **Google Workspace**. Хоча ви можете синхронізувати інший постачальник ідентичності в Google Workspace.
You can access Workspaces **users and groups in** [**https://admin.google.com**](https://admin.google.com/).
Ви можете отримати доступ до користувачів і груп Workspace за адресою [**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** може бути **вимушена** для користувачів Workspace, однак **зловмисник** може використовувати токен для доступу до GCP **через cli, який не буде захищений MFA** (він буде захищений MFA лише тоді, коли користувач входить для його генерації: `gcloud auth login`).
## Groups
## Групи
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:
Коли створюється організація, кілька груп **рекомендується створити.** Якщо ви керуєте будь-якою з них, ви можете скомпрометувати всю або важливу частину організації:
<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>Група</strong></td><td><strong>Функція</strong></td></tr><tr><td><strong><code>gcp-organization-admins</code></strong><br><em>(група або індивідуальні облікові записи потрібні для контрольного списку)</em></td><td>Адміністрування будь-якого ресурсу, що належить організації. Призначайте цю роль обережно; адміністратори організації мають доступ до всіх ваших ресурсів Google Cloud. Альтернативно, оскільки ця функція має високі привілеї, розгляньте можливість використання індивідуальних облікових записів замість створення групи.</td></tr><tr><td><strong><code>gcp-network-admins</code></strong><br><em>(потрібно для контрольного списку)</em></td><td>Створення мереж, підмереж, правил брандмауера та мережевих пристроїв, таких як Cloud Router, Cloud VPN та балансувальники навантаження в хмарі.</td></tr><tr><td><strong><code>gcp-billing-admins</code></strong><br><em>(потрібно для контрольного списку)</em></td><td>Налаштування облікових записів для виставлення рахунків та моніторинг їх використання.</td></tr><tr><td><strong><code>gcp-developers</code></strong><br><em>(потрібно для контрольного списку)</em></td><td>Проектування, кодування та тестування додатків.</td></tr><tr><td><strong><code>gcp-security-admins</code></strong><br></td><td>Встановлення та управління політиками безпеки для всієї організації, включаючи управління доступом та <a href="https://cloud.google.com/resource-manager/docs/organization-policy/org-policy-constraints">політики обмежень організації</a>. Дивіться <a href="https://cloud.google.com/architecture/security-foundations/authentication-authorization#users_and_groups">посібник з основ безпеки Google Cloud</a> для отримання додаткової інформації про планування вашої інфраструктури безпеки Google Cloud.</td></tr><tr><td><strong><code>gcp-devops</code></strong></td><td>Створення або управління кінцевими конвеєрами, які підтримують безперервну інтеграцію та доставку, моніторинг та постачання систем.</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>(більше не за замовчуванням)</em></td><td>Моніторинг витрат на проекти. Типові учасники є частиною фінансової команди.</td></tr><tr><td><strong><code>gcp-platform-viewer</code></strong><br><em>(більше не за замовчуванням)</em></td><td>Перегляд інформації про ресурси в організації Google Cloud.</td></tr><tr><td><strong><code>gcp-security-reviewer</code></strong><br><em>(більше не за замовчуванням)</em></td><td>Перегляд безпеки хмари.</td></tr><tr><td><strong><code>gcp-network-viewer</code></strong><br><em>(більше не за замовчуванням)</em></td><td>Перегляд конфігурацій мережі.</td></tr><tr><td><strong><code>grp-gcp-audit-viewer</code></strong><br><em>(більше не за замовчуванням)</em></td><td>Перегляд журналів аудиту.</td></tr><tr><td><strong><code>gcp-scc-admin</code></strong><br><em>(більше не за замовчуванням)</em></td><td>Адміністрування Центру команд безпеки.</td></tr><tr><td><strong><code>gcp-secrets-admin</code></strong><br><em>(більше не за замовчуванням)</em></td><td>Управління секретами в Secret Manager.</td></tr></tbody></table>
## **Default Password Policy**
## **Політика паролів за замовчуванням**
- 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.
- Вимагати сильні паролі
- Від 8 до 100 символів
- Без повторного використання
- Без терміну дії
- Якщо людина отримує доступ до Workspace через стороннього постачальника, ці вимоги не застосовуються.
<figure><img src="../../../images/image (20).png" alt=""><figcaption></figcaption></figure>
<figure><img src="../../../images/image (22).png" alt=""><figcaption></figcaption></figure>
## **Service accounts**
## **Облікові записи служби**
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.
Це принципали, які **ресурси** можуть **мати** **прикріпленими** та доступом для легкого взаємодії з GCP. Наприклад, можливо отримати доступ до **токена автентифікації** облікового запису служби **прикріпленого до ВМ** в метаданих.\
Можливо зіткнутися з деякими **конфліктами** при використанні як **IAM, так і обсягів доступу**. Наприклад, ваш обліковий запис служби може мати роль IAM `compute.instanceAdmin`, але екземпляр, до якого ви отримали доступ, був обмежений обмеженням обсягу `https://www.googleapis.com/auth/compute.readonly`. Це завадить вам вносити будь-які зміни, використовуючи токен OAuth, який автоматично призначається вашому екземпляру.
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:
Це схоже на **ролі IAM з AWS**. Але не так, як в AWS, **будь-який** обліковий запис служби може бути **прикріплений до будь-якої служби** (не потрібно дозволяти це через політику).
Декілька облікових записів служби, які ви знайдете, насправді **автоматично генеруються GCP** при початку використання служби, як:
```
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:
Однак також можливо створювати та приєднуватися до ресурсів **кастомних облікових записів служби**, які виглядатимуть так:
```
SERVICE_ACCOUNT_NAME@PROJECT_NAME.iam.gserviceaccount.com
```
### **Ключі та Токени**
### **Keys & Tokens**
Існує 2 основні способи доступу до GCP як обліковий запис служби:
There are 2 main ways to access GCP as a service account:
- **Через OAuth токени**: Це токени, які ви отримаєте з таких місць, як кінцеві точки метаданих або шляхом викрадення http запитів, і вони обмежені **обсягами доступу**.
- **Ключі**: Це пари публічних і приватних ключів, які дозволять вам підписувати запити як обліковий запис служби і навіть генерувати OAuth токени для виконання дій як обліковий запис служби. Ці ключі небезпечні, оскільки їх складніше обмежити і контролювати, тому GCP рекомендує не генерувати їх.
- Зверніть увагу, що кожного разу, коли створюється SA, **GCP генерує ключ для облікового запису служби**, до якого користувач не має доступу (і який не буде вказано в веб-додатку). Згідно з [**цією темою**](https://www.reddit.com/r/googlecloud/comments/f0ospy/service_account_keys_observations/), цей ключ **використовується внутрішньо GCP** для надання доступу до кінцевих точок метаданих для генерації доступних OAuth токенів.
- **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.
### **Обсяги доступу**
### **Access scopes**
Обсяги доступу **прикріплені до згенерованих OAuth токенів** для доступу до кінцевих точок API GCP. Вони **обмежують дозволи** OAuth токена.\
Це означає, що якщо токен належить Власнику ресурсу, але не має в обсязі токена доступу до цього ресурсу, токен **не може бути використаний для (зловживання) цих привілеїв**.
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 насправді [рекомендує](https://cloud.google.com/compute/docs/access/service-accounts#service_account_permissions), щоб **обсяги доступу не використовувалися і щоб повністю покладатися на IAM**. Веб-портал управління насправді це забезпечує, але обсяги доступу все ще можуть бути застосовані до екземплярів за допомогою програмних облікових записів служби.
Ви можете побачити, які **обсяги** **призначені**, **запитуючи:**
```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"
}
```
Попередні **scopes** - це ті, що генеруються за **замовчуванням** за допомогою **`gcloud`** для доступу до даних. Це тому, що коли ви використовуєте **`gcloud`**, спочатку ви створюєте токен OAuth, а потім використовуєте його для зв'язку з кінцевими точками.
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.
Найважливіший scope з цих потенційно є **`cloud-platform`**, що в основному означає, що можливо **доступ до будь-якої служби в 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:
Ви можете **знайти список** [**усіх можливих scopes тут**](https://developers.google.com/identity/protocols/googlescopes)**.**
Якщо у вас є **`gcloud`** облікові дані браузера, можливо **отримати токен з іншими scopes,** зробивши щось на зразок:
```bash
# Maybe you can get a user token with other scopes changing the scopes array from ~/.config/gcloud/credentials.db
@@ -213,14 +204,13 @@ 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>"
```
## **Terraform IAM Policies, Bindings and Memberships**
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:
Як визначено terraform у [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), використовуючи terraform з GCP, існують різні способи надання доступу принципалу до ресурсу:
- **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).
- **Memberships**: Ви встановлюєте **принципалів як членів ролей** **без обмежень** щодо ролі або принципалів. Ви можете призначити користувача членом ролі, а потім призначити групу членом тієї ж ролі, а також встановити цих принципалів (користувача та групу) членами інших ролей.
- **Bindings**: Кілька **принципалів можуть бути прив'язані до ролі**. Ці **принципали все ще можуть бути прив'язані або бути членами інших ролей**. Однак, якщо принципал, який не прив'язаний до ролі, встановлений як **член прив'язаної ролі**, наступного разу, коли **прив'язка буде застосована, членство зникне**.
- **Policies**: Політика є **авторитетною**, вона вказує ролі та принципалів, і тоді **ці принципали не можуть мати більше ролей, а ці ролі не можуть мати більше принципалів**, якщо ця політика не буде змінена (навіть в інших політиках, прив'язках або членствах). Тому, коли роль або принципал вказані в політиці, всі їхні привілеї є **обмеженими цією політикою**. Очевидно, це можна обійти, якщо принципалу надано можливість змінювати політику або права на ескалацію привілеїв (наприклад, створити нового принципала та прив'язати його до нової ролі).
## References
@@ -228,7 +218,3 @@ As defined by terraform in [https://registry.terraform.io/providers/hashicorp/go
- [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

@@ -6,10 +6,9 @@
### 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:**
Щоб надати **доступ до Github Actions** з репозиторію Github до **облікового запису сервісу** GCP, необхідно виконати наступні кроки:
- **Створіть обліковий запис сервісу** для доступу з github actions з **бажаними правами:**
```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**:
- Створіть **новий пул ідентичності робочого навантаження**:
```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):
- Створіть новий **workload identity pool OIDC provider**, який **довіряє** github actions (за назвою org/repo в цьому сценарії):
```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:
- Нарешті, **дозвольте принципалу** з постачальника використовувати сервісний принципал:
```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).
> Зверніть увагу, що в попередньому члені ми вказуємо **`org-name/repo-name`** як умови для доступу до облікового запису служби (інші параметри, які роблять його **більш обмежувальним**, такі як гілка, також можуть бути використані).
>
> However it's also possible to **allow all github to access** the service account creating a provider such the following using a wildcard:
> Однак також можливо **дозволити всім github доступ** до облікового запису служби, створивши провайдера, подібного до наступного, використовуючи підстановочний знак:
<pre class="language-bash"><code class="lang-bash"># Create a Workload Identity Pool
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="Demo provider" \
--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>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:
> У цьому випадку будь-хто міг би отримати доступ до облікового запису служби з github actions, тому важливо завжди **перевіряти, як визначено члена**.\
> Це завжди повинно бути щось на зразок цього:
>
> `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:
Не забудьте змінити **`${providerId}`** та **`${saId}`** на їх відповідні значення:
```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}}