mirror of
https://github.com/HackTricks-wiki/hacktricks-cloud.git
synced 2026-01-08 11:21:00 -08:00
Translated ['src/README.md', 'src/banners/hacktricks-training.md', 'src/
This commit is contained in:
@@ -1,331 +1,319 @@
|
||||
# AWS - Basic Information
|
||||
# AWS - Основна інформація
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Organization Hierarchy
|
||||
## Ієрархія організації
|
||||
|
||||
.png>)
|
||||
|
||||
### Accounts
|
||||
### Облікові записи
|
||||
|
||||
In AWS there is a **root account,** which is the **parent container for all the accounts** for your **organization**. However, you don't need to use that account to deploy resources, you can create **other accounts to separate different AWS** infrastructures between them.
|
||||
В AWS є **кореневий обліковий запис**, який є **батьківським контейнером для всіх облікових записів** вашої **організації**. Однак вам не потрібно використовувати цей обліковий запис для розгортання ресурсів, ви можете створити **інші облікові записи, щоб розділити різні AWS** інфраструктури між ними.
|
||||
|
||||
This is very interesting from a **security** point of view, as **one account won't be able to access resources from other account** (except bridges are specifically created), so this way you can create boundaries between deployments.
|
||||
Це дуже цікаво з точки зору **безпеки**, оскільки **один обліковий запис не зможе отримати доступ до ресурсів з іншого облікового запису** (якщо спеціально не створені мости), таким чином ви можете створити межі між розгортаннями.
|
||||
|
||||
Therefore, there are **two types of accounts in an organization** (we are talking about AWS accounts and not User accounts): a single account that is designated as the management account, and one or more member accounts.
|
||||
Отже, в організації є **два типи облікових записів** (ми говоримо про облікові записи AWS, а не про облікові записи користувачів): один обліковий запис, який призначений як обліковий запис управління, і один або кілька облікових записів учасників.
|
||||
|
||||
- The **management account (the root account)** is the account that you use to create the organization. From the organization's management account, you can do the following:
|
||||
- **Обліковий запис управління (кореневий обліковий запис)** - це обліковий запис, який ви використовуєте для створення організації. З облікового запису управління організації ви можете зробити наступне:
|
||||
|
||||
- Create accounts in the organization
|
||||
- Invite other existing accounts to the organization
|
||||
- Remove accounts from the organization
|
||||
- Manage invitations
|
||||
- Apply policies to entities (roots, OUs, or accounts) within the organization
|
||||
- Enable integration with supported AWS services to provide service functionality across all of the accounts in the organization.
|
||||
- It's possible to login as the root user using the email and password used to create this root account/organization.
|
||||
- Створити облікові записи в організації
|
||||
- Запросити інші існуючі облікові записи в організацію
|
||||
- Видалити облікові записи з організації
|
||||
- Керувати запрошеннями
|
||||
- Застосовувати політики до сутностей (корені, ОУ або облікові записи) в межах організації
|
||||
- Увімкнути інтеграцію з підтримуваними AWS сервісами для надання функціональності сервісу для всіх облікових записів в організації.
|
||||
- Можливо увійти як кореневий користувач, використовуючи електронну пошту та пароль, які використовувалися для створення цього кореневого облікового запису/організації.
|
||||
|
||||
The management account has the **responsibilities of a payer account** and is responsible for paying all charges that are accrued by the member accounts. You can't change an organization's management account.
|
||||
|
||||
- **Member accounts** make up all of the rest of the accounts in an organization. An account can be a member of only one organization at a time. You can attach a policy to an account to apply controls to only that one account.
|
||||
- Member accounts **must use a valid email address** and can have a **name**, in general they wont be able to manage the billing (but they might be given access to it).
|
||||
Обліковий запис управління має **обов'язки облікового запису платника** і відповідає за оплату всіх витрат, які накопичуються учасниками облікових записів. Ви не можете змінити обліковий запис управління організації.
|
||||
|
||||
- **Облікові записи учасників** складають всі інші облікові записи в організації. Обліковий запис може бути учасником лише однієї організації одночасно. Ви можете прикріпити політику до облікового запису, щоб застосувати контролі лише до цього одного облікового запису.
|
||||
- Облікові записи учасників **повинні використовувати дійсну електронну адресу** і можуть мати **ім'я**, загалом вони не зможуть керувати виставленням рахунків (але їм можуть надати доступ до цього).
|
||||
```
|
||||
aws organizations create-account --account-name testingaccount --email testingaccount@lalala1233fr.com
|
||||
```
|
||||
### **Організаційні одиниці**
|
||||
|
||||
### **Organization Units**
|
||||
|
||||
Accounts can be grouped in **Organization Units (OU)**. This way, you can create **policies** for the Organization Unit that are going to be **applied to all the children accounts**. Note that an OU can have other OUs as children.
|
||||
|
||||
Облікові записи можна групувати в **Організаційні одиниці (OU)**. Таким чином, ви можете створювати **політики** для Організаційної одиниці, які будуть **застосовані до всіх дочірніх облікових записів**. Зверніть увагу, що OU може мати інші OU як дочірні.
|
||||
```bash
|
||||
# You can get the root id from aws organizations list-roots
|
||||
aws organizations create-organizational-unit --parent-id r-lalala --name TestOU
|
||||
```
|
||||
|
||||
### Service Control Policy (SCP)
|
||||
|
||||
A **service control policy (SCP)** is a policy that specifies the services and actions that users and roles can use in the accounts that the SCP affects. SCPs are **similar to IAM** permissions policies except that they **don't grant any permissions**. Instead, SCPs specify the **maximum permissions** for an organization, organizational unit (OU), or account. When you attach a SCP to your organization root or an OU, the **SCP limits permissions for entities in member accounts**.
|
||||
**Політика контролю послуг (SCP)** - це політика, яка визначає послуги та дії, які користувачі та ролі можуть використовувати в облікових записах, на які впливає SCP. SCP є **схожими на політики дозволів IAM**, за винятком того, що вони **не надають жодних дозволів**. Натомість SCP визначають **максимальні дозволи** для організації, організаційної одиниці (OU) або облікового запису. Коли ви прикріплюєте SCP до кореня вашої організації або OU, **SCP обмежує дозволи для суб'єктів у членських облікових записах**.
|
||||
|
||||
This is the ONLY way that **even the root user can be stopped** from doing something. For example, it could be used to stop users from disabling CloudTrail or deleting backups.\
|
||||
The only way to bypass this is to compromise also the **master account** that configures the SCPs (master account cannot be blocked).
|
||||
Це є ЄДИНИМ способом, яким **навіть кореневий користувач може бути зупинений** від виконання певних дій. Наприклад, його можна використовувати, щоб зупинити користувачів від вимкнення CloudTrail або видалення резервних копій.\
|
||||
Єдиний спосіб обійти це - також скомпрометувати **майстер-обліковий запис**, який налаштовує SCP (майстер-обліковий запис не може бути заблокований).
|
||||
|
||||
> [!WARNING]
|
||||
> Note that **SCPs only restrict the principals in the account**, so other accounts are not affected. This means having an SCP deny `s3:GetObject` will not stop people from **accessing a public S3 bucket** in your account.
|
||||
> Зверніть увагу, що **SCP лише обмежують суб'єктів у обліковому записі**, тому інші облікові записи не підлягають впливу. Це означає, що наявність SCP, яка забороняє `s3:GetObject`, не зупинить людей від **доступу до публічного S3 бакету** у вашому обліковому записі.
|
||||
|
||||
SCP examples:
|
||||
Приклади SCP:
|
||||
|
||||
- Deny the root account entirely
|
||||
- Only allow specific regions
|
||||
- Only allow white-listed services
|
||||
- Deny GuardDuty, CloudTrail, and S3 Public Block Access from
|
||||
- Повна заборона кореневого облікового запису
|
||||
- Дозволити лише конкретні регіони
|
||||
- Дозволити лише білий список послуг
|
||||
- Заборонити GuardDuty, CloudTrail та S3 Public Block Access від
|
||||
|
||||
being disabled
|
||||
вимкнення
|
||||
|
||||
- Deny security/incident response roles from being deleted or
|
||||
- Заборонити ролі безпеки/реагування на інциденти від видалення або
|
||||
|
||||
modified.
|
||||
модифікації.
|
||||
|
||||
- Deny backups from being deleted.
|
||||
- Deny creating IAM users and access keys
|
||||
- Заборонити видалення резервних копій.
|
||||
- Заборонити створення користувачів IAM та ключів доступу
|
||||
|
||||
Find **JSON examples** in [https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps_examples.html](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps_examples.html)
|
||||
Знайдіть **приклади JSON** в [https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps_examples.html](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps_examples.html)
|
||||
|
||||
### ARN
|
||||
|
||||
**Amazon Resource Name** is the **unique name** every resource inside AWS has, its composed like this:
|
||||
|
||||
**Ідентифікатор ресурсу Amazon (ARN)** - це **унікальна назва**, яку має кожен ресурс всередині AWS, вона складається ось так:
|
||||
```
|
||||
arn:partition:service:region:account-id:resource-type/resource-id
|
||||
arn:aws:elasticbeanstalk:us-west-1:123456789098:environment/App/Env
|
||||
```
|
||||
|
||||
Note that there are 4 partitions in AWS but only 3 ways to call them:
|
||||
Зверніть увагу, що в AWS є 4 розділи, але лише 3 способи їх виклику:
|
||||
|
||||
- AWS Standard: `aws`
|
||||
- AWS China: `aws-cn`
|
||||
- AWS US public Internet (GovCloud): `aws-us-gov`
|
||||
- AWS Secret (US Classified): `aws`
|
||||
|
||||
## IAM - Identity and Access Management
|
||||
## IAM - Управління ідентифікацією та доступом
|
||||
|
||||
IAM is the service that will allow you to manage **Authentication**, **Authorization** and **Access Control** inside your AWS account.
|
||||
IAM - це сервіс, який дозволяє вам керувати **Аутентифікацією**, **Авторизацією** та **Контролем доступу** у вашому обліковому записі AWS.
|
||||
|
||||
- **Authentication** - Process of defining an identity and the verification of that identity. This process can be subdivided in: Identification and verification.
|
||||
- **Authorization** - Determines what an identity can access within a system once it's been authenticated to it.
|
||||
- **Access Control** - The method and process of how access is granted to a secure resource
|
||||
- **Аутентифікація** - Процес визначення особи та перевірки цієї особи. Цей процес можна поділити на: Ідентифікацію та перевірку.
|
||||
- **Авторизація** - Визначає, до чого може отримати доступ особа в системі після її аутентифікації.
|
||||
- **Контроль доступу** - Метод і процес надання доступу до захищеного ресурсу.
|
||||
|
||||
IAM can be defined by its ability to manage, control and govern authentication, authorization and access control mechanisms of identities to your resources within your AWS account.
|
||||
IAM можна визначити за його здатністю керувати, контролювати та регулювати механізми аутентифікації, авторизації та контролю доступу осіб до ваших ресурсів у вашому обліковому записі AWS.
|
||||
|
||||
### [AWS account root user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html) <a href="#id_root" id="id_root"></a>
|
||||
### [Кореневий користувач облікового запису AWS](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html) <a href="#id_root" id="id_root"></a>
|
||||
|
||||
When you first create an Amazon Web Services (AWS) account, you begin with a single sign-in identity that has **complete access to all** AWS services and resources in the account. This is the AWS account _**root user**_ and is accessed by signing in with the **email address and password that you used to create the account**.
|
||||
Коли ви вперше створюєте обліковий запис Amazon Web Services (AWS), ви починаєте з єдиної особи для входу, яка має **повний доступ до всіх** сервісів та ресурсів AWS в обліковому записі. Це _**кореневий користувач**_ облікового запису AWS, до якого отримують доступ, увійшовши за **електронною адресою та паролем, які ви використовували для створення облікового запису**.
|
||||
|
||||
Note that a new **admin user** will have **less permissions that the root user**.
|
||||
Зверніть увагу, що новий **адміністратор** матиме **менше прав, ніж кореневий користувач**.
|
||||
|
||||
From a security point of view, it's recommended to create other users and avoid using this one.
|
||||
З точки зору безпеки рекомендується створити інших користувачів і уникати використання цього.
|
||||
|
||||
### [IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) <a href="#id_iam-users" id="id_iam-users"></a>
|
||||
### [Користувачі IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) <a href="#id_iam-users" id="id_iam-users"></a>
|
||||
|
||||
An IAM _user_ is an entity that you create in AWS to **represent the person or application** that uses it to **interact with AWS**. A user in AWS consists of a name and credentials (password and up to two access keys).
|
||||
Користувач IAM - це сутність, яку ви створюєте в AWS, щоб **представити особу або додаток**, який використовує його для **взаємодії з AWS**. Користувач в AWS складається з імені та облікових даних (пароль та до двох ключів доступу).
|
||||
|
||||
When you create an IAM user, you grant it **permissions** by making it a **member of a user group** that has appropriate permission policies attached (recommended), or by **directly attaching policies** to the user.
|
||||
Коли ви створюєте користувача IAM, ви надаєте йому **права** шляхом включення його до **групи користувачів**, яка має відповідні політики прав, або **безпосередньо прикріплюючи політики** до користувача.
|
||||
|
||||
Users can have **MFA enabled to login** through the console. API tokens of MFA enabled users aren't protected by MFA. If you want to **restrict the access of a users API keys using MFA** you need to indicate in the policy that in order to perform certain actions MFA needs to be present (example [**here**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html)).
|
||||
Користувачі можуть мати **увімкнене MFA для входу** через консоль. API токени користувачів з увімкненим MFA не захищені MFA. Якщо ви хочете **обмежити доступ ключів API користувачів за допомогою MFA**, вам потрібно вказати в політиці, що для виконання певних дій MFA має бути присутнім (приклад [**тут**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html)).
|
||||
|
||||
#### CLI
|
||||
|
||||
- **Access Key ID**: 20 random uppercase alphanumeric characters like AKHDNAPO86BSHKDIRYT
|
||||
- **Secret access key ID**: 40 random upper and lowercase characters: S836fh/J73yHSb64Ag3Rkdi/jaD6sPl6/antFtU (It's not possible to retrieve lost secret access key IDs).
|
||||
- **ID ключа доступу**: 20 випадкових великих алфавітно-цифрових символів, таких як AKHDNAPO86BSHKDIRYT
|
||||
- **ID секретного ключа доступу**: 40 випадкових великих і малих символів: S836fh/J73yHSb64Ag3Rkdi/jaD6sPl6/antFtU (неможливо відновити втрачені ID секретного ключа доступу).
|
||||
|
||||
Whenever you need to **change the Access Key** this is the process you should follow:\
|
||||
Коли вам потрібно **змінити ключ доступу**, це процес, який ви повинні виконати:\
|
||||
&#xNAN;_Create a new access key -> Apply the new key to system/application -> mark original one as inactive -> Test and verify new access key is working -> Delete old access key_
|
||||
|
||||
### MFA - Multi Factor Authentication
|
||||
### MFA - Багатофакторна аутентифікація
|
||||
|
||||
It's used to **create an additional factor for authentication** in addition to your existing methods, such as password, therefore, creating a multi-factor level of authentication.\
|
||||
You can use a **free virtual application or a physical device**. You can use apps like google authentication for free to activate a MFA in AWS.
|
||||
Вона використовується для **створення додаткового фактора для аутентифікації** на додаток до ваших існуючих методів, таких як пароль, тим самим створюючи багатофакторний рівень аутентифікації.\
|
||||
Ви можете використовувати **безкоштовний віртуальний додаток або фізичний пристрій**. Ви можете безкоштовно використовувати такі додатки, як Google Authenticator, щоб активувати MFA в AWS.
|
||||
|
||||
Policies with MFA conditions can be attached to the following:
|
||||
Політики з умовами MFA можуть бути прикріплені до наступного:
|
||||
|
||||
- An IAM user or group
|
||||
- A resource such as an Amazon S3 bucket, Amazon SQS queue, or Amazon SNS topic
|
||||
- The trust policy of an IAM role that can be assumed by a user
|
||||
|
||||
If you want to **access via CLI** a resource that **checks for MFA** you need to call **`GetSessionToken`**. That will give you a token with info about MFA.\
|
||||
Note that **`AssumeRole` credentials don't contain this information**.
|
||||
- Користувача або групи IAM
|
||||
- Ресурсу, такому як кошик Amazon S3, черга Amazon SQS або тема Amazon SNS
|
||||
- Політики довіри ролі IAM, яку може прийняти користувач
|
||||
|
||||
Якщо ви хочете **отримати доступ через CLI** до ресурсу, який **перевіряє MFA**, вам потрібно викликати **`GetSessionToken`**. Це надасть вам токен з інформацією про MFA.\
|
||||
Зверніть увагу, що **облікові дані `AssumeRole` не містять цю інформацію**.
|
||||
```bash
|
||||
aws sts get-session-token --serial-number <arn_device> --token-code <code>
|
||||
```
|
||||
Як [**вказано тут**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html), існує багато різних випадків, коли **MFA не може бути використано**.
|
||||
|
||||
As [**stated here**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html), there are a lot of different cases where **MFA cannot be used**.
|
||||
### [IAM групи користувачів](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) <a href="#id_iam-groups" id="id_iam-groups"></a>
|
||||
|
||||
### [IAM user groups](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) <a href="#id_iam-groups" id="id_iam-groups"></a>
|
||||
IAM [група користувачів](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) — це спосіб **прикріпити політики до кількох користувачів** одночасно, що може спростити управління дозволами для цих користувачів. **Ролі та групи не можуть бути частиною групи**.
|
||||
|
||||
An IAM [user group](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) is a way to **attach policies to multiple users** at one time, which can make it easier to manage the permissions for those users. **Roles and groups cannot be part of a group**.
|
||||
Ви можете прикріпити **політику на основі ідентичності до групи користувачів**, щоб всі **користувачі** в групі користувачів **отримали дозволи політики**. Ви **не можете** ідентифікувати **групу користувачів** як **`Principal`** у **політиці** (такій як політика на основі ресурсу), оскільки групи стосуються дозволів, а не аутентифікації, а принципи є аутентифікованими сутностями IAM.
|
||||
|
||||
You can attach an **identity-based policy to a user group** so that all of the **users** in the user group **receive the policy's permissions**. You **cannot** identify a **user group** as a **`Principal`** in a **policy** (such as a resource-based policy) because groups relate to permissions, not authentication, and principals are authenticated IAM entities.
|
||||
Ось деякі важливі характеристики груп користувачів:
|
||||
|
||||
Here are some important characteristics of user groups:
|
||||
- **Група користувачів** може **містити багато користувачів**, а **користувач** може **належати до кількох груп**.
|
||||
- **Групи користувачів не можуть бути вкладеними**; вони можуть містити лише користувачів, а не інші групи користувачів.
|
||||
- **Не існує групи користувачів за замовчуванням, яка автоматично включає всіх користувачів в обліковому записі AWS**. Якщо ви хочете мати таку групу користувачів, ви повинні створити її та призначити кожного нового користувача до неї.
|
||||
- Кількість і розмір ресурсів IAM в обліковому записі AWS, таких як кількість груп і кількість груп, до яких може належати користувач, обмежені. Для отримання додаткової інформації див. [Квоти IAM та AWS STS](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html).
|
||||
|
||||
- A user **group** can **contain many users**, and a **user** can **belong to multiple groups**.
|
||||
- **User groups can't be nested**; they can contain only users, not other user groups.
|
||||
- There is **no default user group that automatically includes all users in the AWS account**. If you want to have a user group like that, you must create it and assign each new user to it.
|
||||
- The number and size of IAM resources in an AWS account, such as the number of groups, and the number of groups that a user can be a member of, are limited. For more information, see [IAM and AWS STS quotas](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html).
|
||||
### [IAM ролі](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) <a href="#id_iam-roles" id="id_iam-roles"></a>
|
||||
|
||||
### [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) <a href="#id_iam-roles" id="id_iam-roles"></a>
|
||||
IAM **роль** дуже **схожа** на **користувача**, оскільки це **ідентичність з політиками дозволів, які визначають, що** вона може і не може робити в AWS. Однак роль **не має жодних облікових даних** (пароль або ключі доступу), пов'язаних з нею. Замість того, щоб бути унікально пов'язаною з однією особою, роль призначена для того, щоб її **могли приймати будь-хто, хто її потребує (і має достатні дозволи)**. **Користувач IAM може прийняти роль, щоб тимчасово** отримати різні дозволи для конкретного завдання. Роль може бути **призначена** [**федеративному користувачу**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html), який входить, використовуючи зовнішнього постачальника ідентичності замість IAM.
|
||||
|
||||
An IAM **role** is very **similar** to a **user**, in that it is an **identity with permission policies that determine what** it can and cannot do in AWS. However, a role **does not have any credentials** (password or access keys) associated with it. Instead of being uniquely associated with one person, a role is intended to be **assumable by anyone who needs it (and have enough perms)**. An **IAM user can assume a role to temporarily** take on different permissions for a specific task. A role can be **assigned to a** [**federated user**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html) who signs in by using an external identity provider instead of IAM.
|
||||
IAM роль складається з **двох типів політик**: **політики довіри**, яка не може бути порожньою, що визначає, **хто може прийняти** роль, і **політики дозволів**, яка не може бути порожньою, що визначає, **до чого вона може отримати доступ**.
|
||||
|
||||
An IAM role consists of **two types of policies**: A **trust policy**, which cannot be empty, defining **who can assume** the role, and a **permissions policy**, which cannot be empty, defining **what it can access**.
|
||||
#### AWS Служба безпечних токенів (STS)
|
||||
|
||||
#### AWS Security Token Service (STS)
|
||||
AWS Служба безпечних токенів (STS) — це веб-сервіс, який полегшує **видачу тимчасових, обмежених привілеїв облікових даних**. Він спеціально розроблений для:
|
||||
|
||||
AWS Security Token Service (STS) is a web service that facilitates the **issuance of temporary, limited-privilege credentials**. It is specifically tailored for:
|
||||
### [Тимчасові облікові дані в IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) <a href="#id_temp-creds" id="id_temp-creds"></a>
|
||||
|
||||
### [Temporary credentials in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) <a href="#id_temp-creds" id="id_temp-creds"></a>
|
||||
**Тимчасові облікові дані в основному використовуються з IAM ролями**, але є й інші використання. Ви можете запитати тимчасові облікові дані, які мають більш обмежений набір дозволів, ніж ваш стандартний користувач IAM. Це **запобігає** вам **випадковому виконанню завдань, які не дозволені** більш обмеженими обліковими даними. Перевагою тимчасових облікових даних є те, що вони автоматично закінчуються після встановленого періоду часу. Ви контролюєте тривалість, протягом якої облікові дані є дійсними.
|
||||
|
||||
**Temporary credentials are primarily used with IAM roles**, but there are also other uses. You can request temporary credentials that have a more restricted set of permissions than your standard IAM user. This **prevents** you from **accidentally performing tasks that are not permitted** by the more restricted credentials. A benefit of temporary credentials is that they expire automatically after a set period of time. You have control over the duration that the credentials are valid.
|
||||
### Політики
|
||||
|
||||
### Policies
|
||||
#### Дозволи політики
|
||||
|
||||
#### Policy Permissions
|
||||
Використовуються для призначення дозволів. Є 2 типи:
|
||||
|
||||
Are used to assign permissions. There are 2 types:
|
||||
|
||||
- AWS managed policies (preconfigured by AWS)
|
||||
- Customer Managed Policies: Configured by you. You can create policies based on AWS managed policies (modifying one of them and creating your own), using the policy generator (a GUI view that helps you granting and denying permissions) or writing your own..
|
||||
|
||||
By **default access** is **denied**, access will be granted if an explicit role has been specified.\
|
||||
If **single "Deny" exist, it will override the "Allow"**, except for requests that use the AWS account's root security credentials (which are allowed by default).
|
||||
- Політики, керовані AWS (попередньо налаштовані AWS)
|
||||
- Політики, керовані клієнтом: Налаштовані вами. Ви можете створювати політики на основі політик, керованих AWS (модифікуючи одну з них і створюючи свою), використовуючи генератор політик (GUI, який допомагає вам надавати та відмовляти в дозволах) або написавши свої власні.
|
||||
|
||||
За **замовчуванням доступ** **заборонено**, доступ буде надано, якщо вказано явну роль.\
|
||||
Якщо **існує єдине "Заперечення", воно переважатиме "Дозволити"**, за винятком запитів, які використовують кореневі облікові дані безпеки облікового запису AWS (які за замовчуванням дозволені).
|
||||
```javascript
|
||||
{
|
||||
"Version": "2012-10-17", //Version of the policy
|
||||
"Statement": [ //Main element, there can be more than 1 entry in this array
|
||||
{
|
||||
"Sid": "Stmt32894y234276923" //Unique identifier (optional)
|
||||
"Effect": "Allow", //Allow or deny
|
||||
"Action": [ //Actions that will be allowed or denied
|
||||
"ec2:AttachVolume",
|
||||
"ec2:DetachVolume"
|
||||
],
|
||||
"Resource": [ //Resource the action and effect will be applied to
|
||||
"arn:aws:ec2:*:*:volume/*",
|
||||
"arn:aws:ec2:*:*:instance/*"
|
||||
],
|
||||
"Condition": { //Optional element that allow to control when the permission will be effective
|
||||
"ArnEquals": {"ec2:SourceInstanceARN": "arn:aws:ec2:*:*:instance/instance-id"}
|
||||
}
|
||||
}
|
||||
]
|
||||
"Version": "2012-10-17", //Version of the policy
|
||||
"Statement": [ //Main element, there can be more than 1 entry in this array
|
||||
{
|
||||
"Sid": "Stmt32894y234276923" //Unique identifier (optional)
|
||||
"Effect": "Allow", //Allow or deny
|
||||
"Action": [ //Actions that will be allowed or denied
|
||||
"ec2:AttachVolume",
|
||||
"ec2:DetachVolume"
|
||||
],
|
||||
"Resource": [ //Resource the action and effect will be applied to
|
||||
"arn:aws:ec2:*:*:volume/*",
|
||||
"arn:aws:ec2:*:*:instance/*"
|
||||
],
|
||||
"Condition": { //Optional element that allow to control when the permission will be effective
|
||||
"ArnEquals": {"ec2:SourceInstanceARN": "arn:aws:ec2:*:*:instance/instance-id"}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
The [глобальні поля, які можна використовувати для умов у будь-якій службі, задокументовані тут](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourceaccount).\
|
||||
[Специфічні поля, які можна використовувати для умов для кожної служби, задокументовані тут](https://docs.aws.amazon.com/service-authorization/latest/reference/reference_policies_actions-resources-contextkeys.html).
|
||||
|
||||
The [global fields that can be used for conditions in any service are documented here](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourceaccount).\
|
||||
The [specific fields that can be used for conditions per service are documented here](https://docs.aws.amazon.com/service-authorization/latest/reference/reference_policies_actions-resources-contextkeys.html).
|
||||
#### Вбудовані політики
|
||||
|
||||
#### Inline Policies
|
||||
Цей вид політик **безпосередньо призначається** користувачу, групі або ролі. Тоді вони не з'являються у списку політик, оскільки інші не можуть їх використовувати.\
|
||||
Вбудовані політики корисні, якщо ви хочете **підтримувати строгі однозначні відносини між політикою та ідентичністю**, до якої вона застосовується. Наприклад, ви хочете бути впевненими, що дозволи в політиці не призначені ненавмисно іншій ідентичності, окрім тієї, для якої вони призначені. Коли ви використовуєте вбудовану політику, дозволи в політиці не можуть бути ненавмисно прикріплені до неправильної ідентичності. Крім того, коли ви використовуєте AWS Management Console для видалення цієї ідентичності, політики, вбудовані в ідентичність, також видаляються. Це тому, що вони є частиною основної сутності.
|
||||
|
||||
This kind of policies are **directly assigned** to a user, group or role. Then, they do not appear in the Policies list as any other one can use them.\
|
||||
Inline policies are useful if you want to **maintain a strict one-to-one relationship between a policy and the identity** that it's applied to. For example, you want to be sure that the permissions in a policy are not inadvertently assigned to an identity other than the one they're intended for. When you use an inline policy, the permissions in the policy cannot be inadvertently attached to the wrong identity. In addition, when you use the AWS Management Console to delete that identity, the policies embedded in the identity are deleted as well. That's because they are part of the principal entity.
|
||||
#### Політики ресурсних кошиків
|
||||
|
||||
#### Resource Bucket Policies
|
||||
Це **політики**, які можна визначити в **ресурсах**. **Не всі ресурси AWS підтримують їх**.
|
||||
|
||||
These are **policies** that can be defined in **resources**. **Not all resources of AWS supports them**.
|
||||
Якщо у основної сутності немає явного заборони на них, і політика ресурсу надає їм доступ, тоді їм дозволено.
|
||||
|
||||
If a principal does not have an explicit deny on them, and a resource policy grants them access, then they are allowed.
|
||||
### Межі IAM
|
||||
|
||||
### IAM Boundaries
|
||||
Межі IAM можна використовувати для **обмеження дозволів, до яких користувач або роль повинні мати доступ**. Таким чином, навіть якщо інший набір дозволів надається користувачу **іншою політикою**, операція **не вдасться**, якщо він спробує їх використати.
|
||||
|
||||
IAM boundaries can be used to **limit the permissions a user or role should have access to**. This way, even if a different set of permissions are granted to the user by a **different policy** the operation will **fail** if he tries to use them.
|
||||
Межа - це просто політика, прикріплена до користувача, яка **вказує максимальний рівень дозволів, які користувач або роль можуть мати**. Отже, **навіть якщо у користувача є доступ адміністратора**, якщо межа вказує, що він може лише читати S· кошики, це максимальне, що він може зробити.
|
||||
|
||||
A boundary is just a policy attached to a user which **indicates the maximum level of permissions the user or role can have**. So, **even if the user has Administrator access**, if the boundary indicates he can only read S· buckets, that's the maximum he can do.
|
||||
**Це**, **SCP** та **дотримання принципу найменших привілеїв** - це способи контролю, щоб користувачі не мали більше дозволів, ніж їм потрібно.
|
||||
|
||||
**This**, **SCPs** and **following the least privilege** principle are the ways to control that users doesn't have more permissions than the ones he needs.
|
||||
### Політики сесії
|
||||
|
||||
### Session Policies
|
||||
|
||||
A session policy is a **policy set when a role is assumed** somehow. This will be like an **IAM boundary for that session**: This means that the session policy doesn't grant permissions but **restrict them to the ones indicated in the policy** (being the max permissions the ones the role has).
|
||||
|
||||
This is useful for **security meassures**: When an admin is going to assume a very privileged role he could restrict the permission to only the ones indicated in the session policy in case the session gets compromised.
|
||||
Політика сесії - це **політика, встановлена, коли роль приймається** якимось чином. Це буде як **межа IAM для цієї сесії**: Це означає, що політика сесії не надає дозволів, а **обмежує їх до тих, що вказані в політиці** (максимальні дозволи - це ті, які має роль).
|
||||
|
||||
Це корисно для **заходів безпеки**: Коли адміністратор збирається прийняти дуже привілейовану роль, він може обмежити дозволи лише тими, що вказані в політиці сесії, у разі, якщо сесія буде скомпрометована.
|
||||
```bash
|
||||
aws sts assume-role \
|
||||
--role-arn <value> \
|
||||
--role-session-name <value> \
|
||||
[--policy-arns <arn_custom_policy1> <arn_custom_policy2>]
|
||||
[--policy <file://policy.json>]
|
||||
--role-arn <value> \
|
||||
--role-session-name <value> \
|
||||
[--policy-arns <arn_custom_policy1> <arn_custom_policy2>]
|
||||
[--policy <file://policy.json>]
|
||||
```
|
||||
Зверніть увагу, що за замовчуванням **AWS може додавати політики сесії до сесій**, які будуть згенеровані з інших причин. Наприклад, у [неавтентифікованих ролях, що припускають Cognito](../aws-services/aws-cognito-enum/cognito-identity-pools.md#accessing-iam-roles) за замовчуванням (використовуючи розширену автентифікацію), AWS згенерує **облікові дані сесії з політикою сесії**, яка обмежує сервіси, до яких може отримати доступ ця сесія [**до наступного списку**](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies-scope-down-services).
|
||||
|
||||
Note that by default **AWS might add session policies to sessions** that are going to be generated because of third reasons. For example, in [unauthenticated cognito assumed roles](../aws-services/aws-cognito-enum/cognito-identity-pools.md#accessing-iam-roles) by default (using enhanced authentication), AWS will generate **session credentials with a session policy** that limits the services that session can access [**to the following list**](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies-scope-down-services).
|
||||
Отже, якщо в якийсь момент ви зіткнетеся з помилкою "... тому що жодна політика сесії не дозволяє ...", і роль має доступ для виконання дії, це тому, що **існує політика сесії, яка цьому заважає**.
|
||||
|
||||
Therefore, if at some point you face the error "... because no session policy allows the ...", and the role has access to perform the action, it's because **there is a session policy preventing it**.
|
||||
### Федерація ідентичності
|
||||
|
||||
### Identity Federation
|
||||
Федерація ідентичності **дозволяє користувачам з постачальників ідентичності, які є зовнішніми** для AWS, безпечно отримувати доступ до ресурсів AWS без необхідності надавати облікові дані користувача AWS з дійсного облікового запису IAM.\
|
||||
Прикладом постачальника ідентичності може бути ваш власний корпоративний **Microsoft Active Directory** (через **SAML**) або **OpenID** сервіси (як **Google**). Федеративний доступ дозволить користувачам всередині нього отримувати доступ до AWS.
|
||||
|
||||
Identity federation **allows users from identity providers which are external** to AWS to access AWS resources securely without having to supply AWS user credentials from a valid IAM user account.\
|
||||
An example of an identity provider can be your own corporate **Microsoft Active Directory** (via **SAML**) or **OpenID** services (like **Google**). Federated access will then allow the users within it to access AWS.
|
||||
Щоб налаштувати це довір'я, створюється **постачальник ідентичності IAM (SAML або OAuth)**, який буде **довіряти** **іншій платформі**. Потім принаймні одна **роль IAM призначається (довіряє) постачальнику ідентичності**. Якщо користувач з довіреної платформи отримує доступ до AWS, він буде отримувати доступ як зазначена роль.
|
||||
|
||||
To configure this trust, an **IAM Identity Provider is generated (SAML or OAuth)** that will **trust** the **other platform**. Then, at least one **IAM role is assigned (trusting) to the Identity Provider**. If a user from the trusted platform access AWS, he will be accessing as the mentioned role.
|
||||
|
||||
However, you will usually want to give a **different role depending on the group of the user** in the third party platform. Then, several **IAM roles can trust** the third party Identity Provider and the third party platform will be the one allowing users to assume one role or the other.
|
||||
Однак зазвичай ви захочете надати **іншу роль в залежності від групи користувача** на сторонній платформі. Тоді кілька **ролей IAM можуть довіряти** сторонньому постачальнику ідентичності, а стороння платформа буде тією, що дозволяє користувачам приймати одну роль або іншу.
|
||||
|
||||
<figure><img src="../../../images/image (247).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
### IAM Identity Center
|
||||
### IAM Центр ідентичності
|
||||
|
||||
AWS IAM Identity Center (successor to AWS Single Sign-On) expands the capabilities of AWS Identity and Access Management (IAM) to provide a **central plac**e that brings together **administration of users and their access to AWS** accounts and cloud applications.
|
||||
AWS IAM Центр ідентичності (наступник AWS Single Sign-On) розширює можливості AWS Identity and Access Management (IAM), щоб забезпечити **централізоване місце**, яке об'єднує **адміністрування користувачів та їх доступ до облікових записів AWS** та хмарних додатків.
|
||||
|
||||
The login domain is going to be something like `<user_input>.awsapps.com`.
|
||||
Домен для входу буде чимось на зразок `<user_input>.awsapps.com`.
|
||||
|
||||
To login users, there are 3 identity sources that can be used:
|
||||
Для входу користувачів можна використовувати 3 джерела ідентичності:
|
||||
|
||||
- Identity Center Directory: Regular AWS users
|
||||
- Active Directory: Supports different connectors
|
||||
- External Identity Provider: All users and groups come from an external Identity Provider (IdP)
|
||||
- Директорія Центру ідентичності: Звичайні користувачі AWS
|
||||
- Active Directory: Підтримує різні конектори
|
||||
- Зовнішній постачальник ідентичності: Всі користувачі та групи походять від зовнішнього постачальника ідентичності (IdP)
|
||||
|
||||
<figure><img src="../../../images/image (279).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
In the simplest case of Identity Center directory, the **Identity Center will have a list of users & groups** and will be able to **assign policies** to them to **any of the accounts** of the organization.
|
||||
У найпростішому випадку директорії Центру ідентичності, **Центр ідентичності матиме список користувачів і груп** і зможе **призначати політики** їм для **будь-якого з облікових записів** організації.
|
||||
|
||||
In order to give access to a Identity Center user/group to an account a **SAML Identity Provider trusting the Identity Center will be created**, and a **role trusting the Identity Provider with the indicated policies will be created** in the destination account.
|
||||
Щоб надати доступ користувачу/групі Центру ідентичності до облікового запису, буде створено **постачальника ідентичності SAML, який довіряє Центру ідентичності**, і **роль, що довіряє постачальнику ідентичності з вказаними політиками, буде створена** в цільовому обліковому записі.
|
||||
|
||||
#### AwsSSOInlinePolicy
|
||||
|
||||
It's possible to **give permissions via inline policies to roles created via IAM Identity Center**. The roles created in the accounts being given **inline policies in AWS Identity Center** will have these permissions in an inline policy called **`AwsSSOInlinePolicy`**.
|
||||
Можливо **надавати дозволи через вбудовані політики для ролей, створених через IAM Центр ідентичності**. Ролі, створені в облікових записах, яким надаються **вбудовані політики в AWS Центрі ідентичності**, матимуть ці дозволи у вбудованій політиці під назвою **`AwsSSOInlinePolicy`**.
|
||||
|
||||
Therefore, even if you see 2 roles with an inline policy called **`AwsSSOInlinePolicy`**, it **doesn't mean it has the same permissions**.
|
||||
Отже, навіть якщо ви бачите 2 ролі з вбудованою політикою під назвою **`AwsSSOInlinePolicy`**, це **не означає, що вони мають однакові дозволи**.
|
||||
|
||||
### Cross Account Trusts and Roles
|
||||
### Довірчі відносини та ролі між обліковими записами
|
||||
|
||||
**A user** (trusting) can create a Cross Account Role with some policies and then, **allow another user** (trusted) to **access his account** but only **having the access indicated in the new role policies**. To create this, just create a new Role and select Cross Account Role. Roles for Cross-Account Access offers two options. Providing access between AWS accounts that you own, and providing access between an account that you own and a third party AWS account.\
|
||||
It's recommended to **specify the user who is trusted and not put some generic thing** because if not, other authenticated users like federated users will be able to also abuse this trust.
|
||||
**Користувач** (довіряючий) може створити роль між обліковими записами з деякими політиками, а потім **дозволити іншому користувачу** (довіреному) **отримати доступ до свого облікового запису**, але лише **маючи доступ, вказаний у нових політиках ролі**. Щоб створити це, просто створіть нову роль і виберіть Роль між обліковими записами. Ролі для доступу між обліковими записами пропонують два варіанти. Надання доступу між обліковими записами AWS, які ви володієте, і надання доступу між обліковим записом, яким ви володієте, та стороннім обліковим записом AWS.\
|
||||
Рекомендується **вказати користувача, який є довіреним, а не ставити щось загальне**, оскільки в іншому випадку інші автентифіковані користувачі, такі як федеративні користувачі, також зможуть зловживати цією довірою.
|
||||
|
||||
### AWS Simple AD
|
||||
|
||||
Not supported:
|
||||
Не підтримується:
|
||||
|
||||
- Trust Relations
|
||||
- AD Admin Center
|
||||
- Full PS API support
|
||||
- AD Recycle Bin
|
||||
- Group Managed Service Accounts
|
||||
- Schema Extensions
|
||||
- No Direct access to OS or Instances
|
||||
- Довірчі відносини
|
||||
- Центр адміністрування AD
|
||||
- Повна підтримка PS API
|
||||
- Кошик для переробки AD
|
||||
- Групові керовані облікові записи служб
|
||||
- Розширення схеми
|
||||
- Немає прямого доступу до ОС або екземплярів
|
||||
|
||||
#### Web Federation or OpenID Authentication
|
||||
#### Веб-федерація або автентифікація OpenID
|
||||
|
||||
The app uses the AssumeRoleWithWebIdentity to create temporary credentials. However, this doesn't grant access to the AWS console, just access to resources within AWS.
|
||||
Додаток використовує AssumeRoleWithWebIdentity для створення тимчасових облікових даних. Однак це не надає доступ до консолі AWS, лише доступ до ресурсів у AWS.
|
||||
|
||||
### Other IAM options
|
||||
### Інші варіанти IAM
|
||||
|
||||
- You can **set a password policy setting** options like minimum length and password requirements.
|
||||
- You can **download "Credential Report"** with information about current credentials (like user creation time, is password enabled...). You can generate a credential report as often as once every **four hours**.
|
||||
- Ви можете **встановити параметри політики паролів**, такі як мінімальна довжина та вимоги до паролів.
|
||||
- Ви можете **завантажити "Звіт про облікові дані"** з інформацією про поточні облікові дані (такі як час створення користувача, чи увімкнено пароль...). Ви можете генерувати звіт про облікові дані так часто, як раз на **чотири години**.
|
||||
|
||||
AWS Identity and Access Management (IAM) provides **fine-grained access control** across all of AWS. With IAM, you can specify **who can access which services and resources**, and under which conditions. With IAM policies, you manage permissions to your workforce and systems to **ensure least-privilege permissions**.
|
||||
AWS Identity and Access Management (IAM) забезпечує **точний контроль доступу** по всьому AWS. З IAM ви можете вказати, **хто може отримати доступ до яких сервісів і ресурсів**, і за яких умов. За допомогою політик IAM ви керуєте дозволами для вашої робочої сили та систем, щоб **забезпечити найменші привілеї**.
|
||||
|
||||
### IAM ID Prefixes
|
||||
### Префікси IAM ID
|
||||
|
||||
In [**this page**](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids) you can find the **IAM ID prefixe**d of keys depending on their nature:
|
||||
На [**цій сторінці**](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids) ви можете знайти **префікси IAM ID** ключів залежно від їх природи:
|
||||
|
||||
| ABIA | [AWS STS service bearer token](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_bearer.html) |
|
||||
| ABIA | [Токен носія служби AWS STS](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_bearer.html) |
|
||||
| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| ACCA | Context-specific credential |
|
||||
| AGPA | User group |
|
||||
| AIDA | IAM user |
|
||||
| AIPA | Amazon EC2 instance profile |
|
||||
| AKIA | Access key |
|
||||
| ANPA | Managed policy |
|
||||
| ANVA | Version in a managed policy |
|
||||
| APKA | Public key |
|
||||
| AROA | Role |
|
||||
| ASCA | Certificate |
|
||||
| ASIA | [Temporary (AWS STS) access key IDs](https://docs.aws.amazon.com/STS/latest/APIReference/API_Credentials.html) use this prefix, but are unique only in combination with the secret access key and the session token. |
|
||||
| ACCA | Контекстно-специфічні облікові дані |
|
||||
| AGPA | Група користувачів |
|
||||
| AIDA | Користувач IAM |
|
||||
| AIPA | Профіль екземпляра Amazon EC2 |
|
||||
| AKIA | Ключ доступу |
|
||||
| ANPA | Керована політика |
|
||||
| ANVA | Версія в керованій політиці |
|
||||
| APKA | Публічний ключ |
|
||||
| AROA | Роль |
|
||||
| ASCA | Сертифікат |
|
||||
| ASIA | [Тимчасові (AWS STS) ідентифікатори ключів доступу](https://docs.aws.amazon.com/STS/latest/APIReference/API_Credentials.html) використовують цей префікс, але є унікальними лише в комбінації з секретним ключем доступу та токеном сесії. |
|
||||
|
||||
### Recommended permissions to audit accounts
|
||||
### Рекомендовані дозволи для аудиту облікових записів
|
||||
|
||||
The following privileges grant various read access of metadata:
|
||||
Наступні привілеї надають різний доступ для читання метаданих:
|
||||
|
||||
- `arn:aws:iam::aws:policy/SecurityAudit`
|
||||
- `arn:aws:iam::aws:policy/job-function/ViewOnlyAccess`
|
||||
@@ -336,14 +324,13 @@ The following privileges grant various read access of metadata:
|
||||
- `directconnect:DescribeConnections`
|
||||
- `dynamodb:ListTables`
|
||||
|
||||
## Misc
|
||||
## Різне
|
||||
|
||||
### CLI Authentication
|
||||
|
||||
In order for a regular user authenticate to AWS via CLI you need to have **local credentials**. By default you can configure them **manually** in `~/.aws/credentials` or by **running** `aws configure`.\
|
||||
In that file you can have more than one profile, if **no profile** is specified using the **aws cli**, the one called **`[default]`** in that file will be used.\
|
||||
Example of credentials file with more than 1 profile:
|
||||
### CLI автентифікація
|
||||
|
||||
Щоб звичайний користувач міг автентифікуватися в AWS через CLI, вам потрібно мати **локальні облікові дані**. За замовчуванням ви можете налаштувати їх **вручну** в `~/.aws/credentials` або **запустивши** `aws configure`.\
|
||||
У цьому файлі ви можете мати більше ніж один профіль, якщо **жоден профіль** не вказано за допомогою **aws cli**, буде використано той, що називається **`[default]`** в цьому файлі.\
|
||||
Приклад файлу облікових даних з більш ніж 1 профілем:
|
||||
```
|
||||
[default]
|
||||
aws_access_key_id = AKIA5ZDCUJHF83HDTYUT
|
||||
@@ -354,12 +341,10 @@ aws_access_key_id = AKIA8YDCu7TGTR356SHYT
|
||||
aws_secret_access_key = uOcdhof683fbOUGFYEQuR2EIHG34UY987g6ff7
|
||||
region = eu-west-2
|
||||
```
|
||||
Якщо вам потрібно отримати доступ до **різних облікових записів AWS** і вашому профілю було надано доступ до **прийняття ролі в цих облікових записах**, вам не потрібно вручну викликати STS щоразу (`aws sts assume-role --role-arn <role-arn> --role-session-name sessname`) і налаштовувати облікові дані.
|
||||
|
||||
If you need to access **different AWS accounts** and your profile was given access to **assume a role inside those accounts**, you don't need to call manually STS every time (`aws sts assume-role --role-arn <role-arn> --role-session-name sessname`) and configure the credentials.
|
||||
|
||||
You can use the `~/.aws/config` file to[ **indicate which roles to assume**](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-role.html), and then use the `--profile` param as usual (the `assume-role` will be performed in a transparent way for the user).\
|
||||
A config file example:
|
||||
|
||||
Ви можете використовувати файл `~/.aws/config`, щоб [**вказати, які ролі приймати**](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-role.html), а потім використовувати параметр `--profile` як зазвичай (прийняття ролі буде виконано прозоро для користувача).\
|
||||
Приклад конфігураційного файлу:
|
||||
```
|
||||
[profile acc2]
|
||||
region=eu-west-2
|
||||
@@ -368,23 +353,16 @@ role_session_name = <session_name>
|
||||
source_profile = <profile_with_assume_role>
|
||||
sts_regional_endpoints = regional
|
||||
```
|
||||
|
||||
With this config file you can then use aws cli like:
|
||||
|
||||
З цим файлом конфігурації ви можете використовувати aws cli, як:
|
||||
```
|
||||
aws --profile acc2 ...
|
||||
```
|
||||
Якщо ви шукаєте щось **схоже** на це, але для **браузера**, ви можете перевірити **розширення** [**AWS Extend Switch Roles**](https://chrome.google.com/webstore/detail/aws-extend-switch-roles/jpmkfafbacpgapdghgdpembnojdlgkdl?hl=en).
|
||||
|
||||
If you are looking for something **similar** to this but for the **browser** you can check the **extension** [**AWS Extend Switch Roles**](https://chrome.google.com/webstore/detail/aws-extend-switch-roles/jpmkfafbacpgapdghgdpembnojdlgkdl?hl=en).
|
||||
|
||||
## References
|
||||
## Посилання
|
||||
|
||||
- [https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html)
|
||||
- [https://aws.amazon.com/iam/](https://aws.amazon.com/iam/)
|
||||
- [https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,84 +4,81 @@
|
||||
|
||||
## SAML
|
||||
|
||||
For info about SAML please check:
|
||||
Для отримання інформації про SAML, будь ласка, перевірте:
|
||||
|
||||
{{#ref}}
|
||||
https://book.hacktricks.xyz/pentesting-web/saml-attacks
|
||||
{{#endref}}
|
||||
|
||||
In order to configure an **Identity Federation through SAML** you just need to provide a **name** and the **metadata XML** containing all the SAML configuration (**endpoints**, **certificate** with public key)
|
||||
Щоб налаштувати **Ідентифікаційну Федерацію через SAML**, вам потрібно лише надати **ім'я** та **метадані XML**, що містять усю конфігурацію SAML (**кінцеві точки**, **сертифікат** з публічним ключем)
|
||||
|
||||
## OIDC - Github Actions Abuse
|
||||
|
||||
In order to add a github action as Identity provider:
|
||||
|
||||
1. For _Provider type_, select **OpenID Connect**.
|
||||
2. For _Provider URL_, enter `https://token.actions.githubusercontent.com`
|
||||
3. Click on _Get thumbprint_ to get the thumbprint of the provider
|
||||
4. For _Audience_, enter `sts.amazonaws.com`
|
||||
5. Create a **new role** with the **permissions** the github action need and a **trust policy** that trust the provider like:
|
||||
- ```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"Federated": "arn:aws:iam::0123456789:oidc-provider/token.actions.githubusercontent.com"
|
||||
},
|
||||
"Action": "sts:AssumeRoleWithWebIdentity",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"token.actions.githubusercontent.com:sub": [
|
||||
"repo:ORG_OR_USER_NAME/REPOSITORY:pull_request",
|
||||
"repo:ORG_OR_USER_NAME/REPOSITORY:ref:refs/heads/main"
|
||||
],
|
||||
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
6. Note in the previous policy how only a **branch** from **repository** of an **organization** was authorized with a specific **trigger**.
|
||||
7. The **ARN** of the **role** the github action is going to be able to **impersonate** is going to be the "secret" the github action needs to know, so **store** it inside a **secret** inside an **environment**.
|
||||
8. Finally use a github action to configure the AWS creds to be used by the workflow:
|
||||
Щоб додати github action як постачальника ідентифікації:
|
||||
|
||||
1. Для _Типу постачальника_ виберіть **OpenID Connect**.
|
||||
2. Для _URL постачальника_ введіть `https://token.actions.githubusercontent.com`
|
||||
3. Натисніть _Отримати відбиток_ для отримання відбитка постачальника
|
||||
4. Для _Аудиторії_ введіть `sts.amazonaws.com`
|
||||
5. Створіть **нову роль** з **дозволами**, які потрібні github action, та **політикою довіри**, яка довіряє постачальнику, як:
|
||||
- ```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"Federated": "arn:aws:iam::0123456789:oidc-provider/token.actions.githubusercontent.com"
|
||||
},
|
||||
"Action": "sts:AssumeRoleWithWebIdentity",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"token.actions.githubusercontent.com:sub": [
|
||||
"repo:ORG_OR_USER_NAME/REPOSITORY:pull_request",
|
||||
"repo:ORG_OR_USER_NAME/REPOSITORY:ref:refs/heads/main"
|
||||
],
|
||||
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
6. Зверніть увагу в попередній політиці, як лише **гілка** з **репозиторію** **організації** була авторизована з конкретним **тригером**.
|
||||
7. **ARN** **ролі**, яку github action зможе **використовувати**, буде "секретом", який github action потрібно знати, тому **зберігайте** його в **секреті** всередині **середовища**.
|
||||
8. Нарешті, використовуйте github action для налаштування AWS облікових даних, які будуть використовуватися робочим процесом:
|
||||
```yaml
|
||||
name: "test AWS Access"
|
||||
|
||||
# The workflow should only trigger on pull requests to the main branch
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
# Required to get the ID Token that will be used for OIDC
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: read # needed for private repos to checkout
|
||||
id-token: write
|
||||
contents: read # needed for private repos to checkout
|
||||
|
||||
jobs:
|
||||
aws:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
aws:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Configure AWS Credentials
|
||||
uses: aws-actions/configure-aws-credentials@v1
|
||||
with:
|
||||
aws-region: eu-west-1
|
||||
role-to-assume:${{ secrets.READ_ROLE }}
|
||||
role-session-name: OIDCSession
|
||||
- name: Configure AWS Credentials
|
||||
uses: aws-actions/configure-aws-credentials@v1
|
||||
with:
|
||||
aws-region: eu-west-1
|
||||
role-to-assume:${{ secrets.READ_ROLE }}
|
||||
role-session-name: OIDCSession
|
||||
|
||||
- run: aws sts get-caller-identity
|
||||
shell: bash
|
||||
- run: aws sts get-caller-identity
|
||||
shell: bash
|
||||
```
|
||||
|
||||
## OIDC - EKS Abuse
|
||||
|
||||
## OIDC - Зловживання EKS
|
||||
```bash
|
||||
# Crate an EKS cluster (~10min)
|
||||
eksctl create cluster --name demo --fargate
|
||||
@@ -91,43 +88,34 @@ eksctl create cluster --name demo --fargate
|
||||
# Create an Identity Provider for an EKS cluster
|
||||
eksctl utils associate-iam-oidc-provider --cluster Testing --approve
|
||||
```
|
||||
|
||||
It's possible to generate **OIDC providers** in an **EKS** cluster simply by setting the **OIDC URL** of the cluster as a **new Open ID Identity provider**. This is a common default policy:
|
||||
|
||||
Можливо створити **OIDC providers** у кластері **EKS**, просто встановивши **OIDC URL** кластера як **нового постачальника ідентичності Open ID**. Це звичайна стандартна політика:
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"Federated": "arn:aws:iam::123456789098:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B"
|
||||
},
|
||||
"Action": "sts:AssumeRoleWithWebIdentity",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"oidc.eks.us-east-1.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B:aud": "sts.amazonaws.com"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"Federated": "arn:aws:iam::123456789098:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B"
|
||||
},
|
||||
"Action": "sts:AssumeRoleWithWebIdentity",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"oidc.eks.us-east-1.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B:aud": "sts.amazonaws.com"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
Ця політика правильно вказує, що **тільки** **EKS кластер** з **id** `20C159CDF6F2349B68846BEC03BE031B` може приймати роль. Однак, вона не вказує, який обліковий запис служби може її приймати, що означає, що **будь-який обліковий запис служби з веб-ідентифікаційним токеном** зможе **приймати** роль.
|
||||
|
||||
This policy is correctly indicating than **only** the **EKS cluster** with **id** `20C159CDF6F2349B68846BEC03BE031B` can assume the role. However, it's not indicting which service account can assume it, which means that A**NY service account with a web identity token** is going to be **able to assume** the role.
|
||||
|
||||
In order to specify **which service account should be able to assume the role,** it's needed to specify a **condition** where the **service account name is specified**, such as:
|
||||
|
||||
Щоб вказати, **який обліковий запис служби повинен мати можливість приймати роль,** потрібно вказати **умову**, де **вказується ім'я облікового запису служби**, наприклад:
|
||||
```bash
|
||||
"oidc.eks.region-code.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B:sub": "system:serviceaccount:default:my-service-account",
|
||||
```
|
||||
|
||||
## References
|
||||
## Посилання
|
||||
|
||||
- [https://www.eliasbrange.dev/posts/secure-aws-deploys-from-github-actions-with-oidc/](https://www.eliasbrange.dev/posts/secure-aws-deploys-from-github-actions-with-oidc/)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user